(() => {
  if (window.MMWQianchuanTakeoverController) return;

  function createTakeoverController(options = {}) {
    const host = document.createElement("div");
    host.className = "mmw-qca-takeover";
    host.hidden = true;
    host.setAttribute("role", "status");
    host.setAttribute("aria-live", "polite");
    host.innerHTML = `
      <span class="mmw-qca-takeover-pulse" aria-hidden="true"></span>
      <div><strong>AI 接管 · 盯盘中</strong><span data-takeover-status>正在识别当前页面</span></div>
      <button type="button" data-takeover-stop>停止并夺回控制</button>`;
    document.documentElement.appendChild(host);
    const status = host.querySelector("[data-takeover-status]");
    const stop = host.querySelector("[data-takeover-stop]");
    let operationActive = false;
    let monitoringActive = false;
    let monitoringLabel = "当前账户与场景正在盯盘";
    let monitoringPhase = "monitoring";
    let onStop = null;

    const agentEnabled = () => options.isEnabled?.() === true;

    const requestStop = async () => {
      if (!operationActive && !monitoringActive) return;
      if (monitoringActive && typeof options.onUserStop === "function") {
        stop.disabled = true;
        try {
          await options.onUserStop();
        } finally {
          stop.disabled = false;
        }
        return;
      }
      const callback = onStop;
      operationActive = false;
      onStop = null;
      syncVisual();
      callback?.("用户已停止 AI 接管");
    };
    stop.addEventListener("click", () => void requestStop());
    window.addEventListener("keydown", (event) => {
      if ((operationActive || monitoringActive) && event.key === "Escape") void requestStop();
    }, true);

    function activate({ mode = "confirm", label = "正在执行已确认操作", stop: stopHandler } = {}) {
      if (!agentEnabled()) {
        operationActive = false;
        onStop = null;
        syncVisual();
        return false;
      }
      operationActive = true;
      onStop = typeof stopHandler === "function" ? stopHandler : null;
      host.dataset.mode = mode;
      host.dataset.state = "executing";
      host.querySelector("strong").textContent = "AI 接管 · 执行中";
      status.textContent = label;
      stop.textContent = "停止盯盘";
      syncVisual();
      return true;
    }

    function update(value) {
      if (operationActive) status.textContent = String(value || "正在重新识别页面").slice(0, 160);
    }

    function deactivate() {
      operationActive = false;
      onStop = null;
      syncVisual();
    }

    function setMonitoring(enabled, label = "", phase = "monitoring") {
      monitoringActive = enabled === true && agentEnabled();
      if (label) monitoringLabel = String(label).slice(0, 160);
      monitoringPhase = ["monitoring", "observing", "executing", "verifying", "attention"].includes(phase)
        ? phase
        : "monitoring";
      syncVisual();
    }

    function syncVisual() {
      const visible = agentEnabled() && (operationActive || monitoringActive);
      host.hidden = !visible;
      document.documentElement.classList.toggle("mmw-qca-is-taken-over", visible && operationActive);
      document.documentElement.classList.toggle("mmw-qca-managed-loop", visible && monitoringActive);
      if (!visible || operationActive) return;
      const titles = {
        monitoring: "AI 接管 · 盯盘中",
        observing: "AI 接管 · 观察中",
        executing: "AI 接管 · 执行中",
        verifying: "AI 接管 · 验证中",
        attention: "AI 接管 · 需处理"
      };
      host.dataset.mode = "monitoring";
      host.dataset.state = monitoringPhase;
      host.querySelector("strong").textContent = titles[monitoringPhase];
      status.textContent = monitoringLabel;
      stop.textContent = "关闭盯盘";
    }

    return Object.freeze({
      activate,
      update,
      deactivate,
      requestStop,
      setMonitoring,
      get active() { return operationActive; },
      get monitoring() { return monitoringActive; }
    });
  }

  window.MMWQianchuanTakeoverController = Object.freeze({ createTakeoverController });
})();
