(() => {
  const MODE_LABELS = {
    overall: ["全域投放"],
    multiplier: ["乘方", "千川乘方"]
  };
  const TARGET_LABELS = {
    product: ["推商品", "商品"],
    live_room: ["推直播间", "直播"]
  };

  function createConfirmationCode() {
    const bytes = new Uint32Array(1);
    crypto.getRandomValues(bytes);
    return String(100000 + (bytes[0] % 900000));
  }

  async function navigateToScene(payload, doc = document, currentContext = {}, sendRuntime = null, isCancelled = () => false) {
    assertNotCancelled(isCancelled);
    if (payload?.destination === "tools_account_violations") {
      await clickNavigationLabel(doc, ["工具"], "navigate_tools_account_violations", sendRuntime);
      const entry = await waitForUniqueNavigationControl(
        doc,
        ["账户违规管理", "账号违规管理"],
        3000,
        isCancelled
      );
      await realNavigationClick(entry, "navigate_tools_account_violations", sendRuntime);
      const verified = await waitForDestination(
        doc,
        ["账户违规管理", "账号违规管理"],
        5000,
        isCancelled
      );
      if (!verified) {
        throw new Error("页面变化后未验证到账户违规管理，已停止继续导航。");
      }
      return "已打开工具 · 账户违规管理。";
    }
    const deliveryMode = ["current", "overall", "multiplier"].includes(payload?.delivery_mode)
      ? payload.delivery_mode
      : "current";
    const promotionTarget = ["current", "product", "live_room"].includes(payload?.promotion_target)
      ? payload.promotion_target
      : "current";
    if (deliveryMode === "current" && promotionTarget === "current") {
      throw new Error("没有可执行的页面切换目标。");
    }
    if (deliveryMode !== "current" && deliveryMode !== currentContext.deliveryMode) {
      const modeControl = findUniqueNavigationControl(doc, MODE_LABELS[deliveryMode]);
      await realNavigationClick(modeControl, "navigate_scene", sendRuntime);
      await wait(900);
      assertNotCancelled(isCancelled);
    }
    if (promotionTarget !== "current") {
      const targetControl = await waitForUniqueNavigationControl(
        doc,
        TARGET_LABELS[promotionTarget],
        3000,
        isCancelled
      );
      await realNavigationClick(targetControl, "navigate_scene", sendRuntime);
      await wait(500);
      assertNotCancelled(isCancelled);
    }
    const detected = window.MMWQianchuanPageContext?.detectPageContext?.(doc, location) || {};
    if (deliveryMode !== "current" && detected.deliveryMode !== deliveryMode) {
      throw new Error("页面变化后未验证到目标产品线，已停止继续导航。");
    }
    if (promotionTarget !== "current" && detected.promotionTarget !== promotionTarget) {
      throw new Error("页面变化后未验证到目标推广对象，已停止继续导航。");
    }
    const modeLabel = deliveryMode === "current" ? "当前产品线" : MODE_LABELS[deliveryMode][0];
    const targetLabel = promotionTarget === "current" ? "当前推广对象" : TARGET_LABELS[promotionTarget][0];
    return `已切换到${modeLabel} · ${targetLabel}，页面数据加载后会重新识别场景。`;
  }

  function findUniqueNavigationControl(doc, labels) {
    const candidates = [];
    const seen = new Set();
    for (const node of doc.querySelectorAll("a,button,[role='tab'],[role='menuitem'],li,span,div")) {
      if (node.closest?.("#mmw-qianchuan-agent-root") || !labels.includes(compactText(node.innerText || node.textContent))) continue;
      const control = node.closest?.("a,button,[role='tab'],[role='menuitem'],li") || node;
      if (seen.has(control) || !isVisible(control)) continue;
      seen.add(control);
      candidates.push({ control, score: navigationScore(control) });
    }
    candidates.sort((left, right) => right.score - left.score);
    if (!candidates.length || candidates[0].score < 20) {
      throw new Error(`当前页面未找到“${labels[0]}”导航入口。`);
    }
    if (candidates[1] && candidates[0].score === candidates[1].score
      && navigationIdentity(candidates[0].control) !== navigationIdentity(candidates[1].control)) {
      throw new Error(`页面上存在多个“${labels[0]}”入口，为避免误点已停止切换。`);
    }
    return candidates[0].control;
  }

  function navigationScore(node) {
    let score = 0;
    if (node.matches?.("[role='tab']")) score += 60;
    if (node.matches?.("a,button,[role='menuitem']")) score += 40;
    if (node.closest?.("nav,header,[role='tablist'],[class*='nav'],[class*='menu'],[class*='tab']")) score += 25;
    const rect = node.getBoundingClientRect?.();
    if (rect && rect.top >= 0 && rect.top < 260) score += 15;
    if (rect && rect.left >= 0 && rect.left < 360) score += 4;
    if (node.closest?.("[role='tablist']")) score += 12;
    if (node.getAttribute?.("aria-selected") === "true" || /active|selected|current/i.test(String(node.className || ""))) score += 5;
    return score;
  }

  async function clickNavigationLabel(doc, labels, businessAction, sendRuntime) {
    const control = findUniqueNavigationControl(doc, labels);
    await realNavigationClick(control, businessAction, sendRuntime);
  }

  async function waitForUniqueNavigationControl(doc, labels, timeoutMs, isCancelled) {
    const deadline = Date.now() + timeoutMs;
    let lastError = null;
    do {
      assertNotCancelled(isCancelled);
      try {
        return findUniqueNavigationControl(doc, labels);
      } catch (error) {
        if (/多个/.test(String(error?.message || ""))) throw error;
        lastError = error;
      }
      await wait(150);
    } while (Date.now() < deadline);
    throw lastError || new Error(`当前页面未找到“${labels[0]}”导航入口。`);
  }

  async function waitForDestination(doc, labels, timeoutMs, isCancelled) {
    const deadline = Date.now() + timeoutMs;
    do {
      assertNotCancelled(isCancelled);
      if (isDestinationActive(doc, labels)) return true;
      await wait(150);
    } while (Date.now() < deadline);
    return false;
  }

  async function realNavigationClick(control, businessAction, sendRuntime) {
    if (typeof sendRuntime !== "function") throw new Error("千川真实导航通道未加载。");
    control.scrollIntoView?.({ block: "center", inline: "nearest", behavior: "auto" });
    const rect = control.getBoundingClientRect();
    const x = Math.round(rect.left + rect.width / 2);
    const y = Math.round(rect.top + rect.height / 2);
    const hit = control.ownerDocument?.elementFromPoint?.(x, y);
    if (!hit || !(hit === control || control.contains?.(hit))) throw new Error("导航入口被遮挡，已停止切换。");
    const response = await sendRuntime({
      type: "QIANCHUAN_AGENT_REAL_ACTION",
      business_action: businessAction,
      action: "click",
      payload: { x, y }
    });
    if (response?.payload?.clicked !== true) throw new Error("浏览器未确认真实导航点击。");
  }

  function navigationIdentity(node) {
    return `${node.tagName}:${node.getAttribute?.("href") || ""}:${compactText(node.innerText || node.textContent)}`;
  }

  function isDestinationActive(doc, labels) {
    if (/(?:violation|punish|account-risk)/i.test(String(doc.defaultView?.location?.href || ""))) return true;
    if (labels.some((label) => compactText(doc.title).includes(label))) return true;
    return Array.from(doc.querySelectorAll("h1,h2,h3,[role='heading'],[aria-current='page'],[aria-selected='true'],.active,.selected,.is-active"))
      .filter(isVisible)
      .some((node) => labels.includes(compactText(node.innerText || node.textContent)));
  }

  function assertNotCancelled(isCancelled) {
    if (isCancelled?.()) throw new Error("用户已停止 AI 接管。");
  }

  function formatConfirmationMessage(proposal, code, scopeLabel) {
    const payload = proposal?.payload || {};
    const actionLabels = { open_target: "打开计划", pause: "暂停", resume: "恢复", set_budget: "调整预算", set_roi: "调整 ROI" };
    const lines = [
      "【千川 Agent 待确认】",
      `范围：${scopeLabel || "当前场景"}`,
      `操作：${actionLabels[payload.action] || payload.action || "未知"}`,
      `对象：${payload.target_name || payload.target_id || "当前目标"}`
    ];
    if (payload.action === "set_budget") lines.push(`新预算：${Number(payload.new_budget ?? payload.newBudget)} 元`);
    if (payload.action === "set_roi") lines.push(`新 ROI：${Number(payload.new_roi ?? payload.newRoi)}`);
    if (payload.reason) lines.push(`原因：${String(payload.reason).slice(0, 300)}`);
    lines.push(`5 分钟内发送“确认 ${code}”执行，或发送“取消 ${code}”。`);
    return lines.join("\n");
  }

  function compactText(value) {
    return String(value || "").replace(/\s+/g, " ").trim();
  }

  function isVisible(node) {
    const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
    const rect = node.getBoundingClientRect?.() || { width: 1, height: 1 };
    return (!style || (style.display !== "none" && style.visibility !== "hidden")) && rect.width > 0 && rect.height > 0;
  }

  function wait(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  const api = { createConfirmationCode, formatConfirmationMessage, navigateToScene };
  if (typeof window !== "undefined") window.MMWQianchuanRemoteControl = api;
  if (typeof module !== "undefined" && module.exports) module.exports = api;
})();
