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

  const LABELS = { pause: "暂停", resume: "恢复" };
  const SWITCH_SELECTORS = [
    "[role='switch']",
    "[aria-checked='true'],[aria-checked='false']",
    ".ovui-switch",
    ".oc-switch",
    ".ant-switch",
    ".semi-switch"
  ];
  const CHECKED_CLASSES = [
    "ovui-switch--checked",
    "ant-switch-checked",
    "semi-switch-checked",
    "is-checked",
    "checked"
  ];
  const OVERALL_SCOPES = new Set(["overall_promotion", "live_room"]);
  const CONTROL_PROFILES = Object.freeze({
    overall: Object.freeze({
      roiLabelPattern: /(?:净成交ROI目标|ROI\s*目标)/i,
      roiTargetSelector: ".cell-ecp-pay-roi .setting-item.reference-setting-item",
      roiEditorSelector: ".oc-popover-operate__content",
      switchSelector: ".col-status-switch .ovui-switch"
    }),
    multiplier: Object.freeze({
      roiLabelPattern: /(?:综合营销ROI目标|ROI\s*目标|目标投产)/i,
      roiTargetSelector: ".setting-item.reference-setting-item",
      roiEditorSelector: "[role='dialog'],.ant-modal,.semi-modal,.ovui-dialog,.ovui-drawer",
      switchSelector: ""
    })
  });
  const VALUE_LABEL_PATTERNS = {
    set_budget: /(?:每日预算|预算)/,
    set_roi: /(?:净成交ROI目标|综合营销ROI目标|ROI\s*目标|目标投产)/i
  };
  const CONFIRM_BUTTON_PATTERN = /^(?:确定|确认|保存|提交|确认调整|确认保存|继续)$/;
  const CANCEL_BUTTON_PATTERN = /^(?:再想想|取消|返回|暂不|稍后)$/;
  const PLATFORM_CONFIRM_PATTERNS = {
    pause: /(?:确定|确认)(?:关闭|暂停).{0,24}(?:投放|计划)|关闭后.{0,120}(?:手动恢复|不恢复)/,
    resume: /(?:确定|确认)(?:开启|恢复).{0,24}(?:投放|计划)|为保证投放的唯一性.{0,800}(?:放量投放|全域投放|标准投放|乘方投放).{0,800}终止后不可恢复/
  };

  function resolvePauseResumeControl(row, action, scope = "") {
    if (!row || !LABELS[action]) throw new Error("不支持的计划开关操作。");
    const label = LABELS[action];
    const textControls = visible(row.querySelectorAll("button,a,[role='button']"))
      .filter((node) => compactText(node.innerText) === label);
    if (textControls.length > 1) throw new Error(`找到多个“${label}”入口，本次未执行。`);
    if (textControls.length === 1) {
      return { element: textControls[0], kind: "text", checked: null, label };
    }

    const element = findUniqueSwitch(row, controlProfile(scope).switchSelector);
    if (!element) throw new Error(`未在目标计划行识别到唯一的“${label}”开关，本次未执行。`);
    if (isDisabled(element)) throw new Error(`目标计划的“${label}”开关已禁用，本次未执行。`);
    const checked = readSwitchState(element);
    if (checked === null) throw new Error(`无法确认目标计划开关的当前状态，本次未执行。`);
    if (action === "pause" && !checked) throw new Error("目标计划已经处于暂停状态，本次未重复操作。");
    if (action === "resume" && checked) throw new Error("目标计划当前仍在投放，本次未重复恢复。");
    return { element, kind: "visual-switch", checked, label };
  }

  async function clickPauseResume({ row, action, targetId, scope = "", sendRuntime }) {
    if (typeof sendRuntime !== "function") throw new Error("真实点击通道未加载，本次未执行。");
    const target = resolvePauseResumeControl(row, action, scope);
    target.element.scrollIntoView?.({ block: "center", inline: "nearest", behavior: "auto" });
    const point = verifiedCenterPoint(row, target.element);
    const response = await sendRuntime({
      type: "QIANCHUAN_AGENT_REAL_CLICK",
      action,
      target_id: String(targetId || ""),
      x: point.x,
      y: point.y
    });
    const result = response?.payload || response?.result || {};
    if (result.clicked !== true) throw new Error("浏览器未确认真实点击，本次未执行。");
    return { ...target, point, engine: result.engine || "browser-pointer" };
  }

  async function clickOpenTarget({ row, targetId, targetName, sendRuntime }) {
    if (typeof sendRuntime !== "function") throw new Error("真实点击通道未加载，本次未打开计划。");
    const target = resolveOpenTargetControl(row, targetId, targetName);
    target.element.scrollIntoView?.({ block: "center", inline: "nearest", behavior: "auto" });
    const point = verifiedCenterPoint(row, target.element);
    const response = await sendRuntime({
      type: "QIANCHUAN_AGENT_REAL_CLICK",
      action: "open_target",
      target_id: String(targetId || ""),
      x: point.x,
      y: point.y
    });
    const result = response?.payload || response?.result || {};
    if (result.clicked !== true) throw new Error("浏览器未确认计划入口点击，本次未打开计划。");
    return { ...target, point, engine: result.engine || "browser-pointer" };
  }

  function observeOperation({ row, action, desiredValue, targetId, targetName, scope = "" }) {
    let dialogs = visible(document.querySelectorAll("[role='dialog'],.ant-modal,.semi-modal,.ovui-dialog,.ovui-drawer"))
      .filter((node) => !node.closest?.("#mmw-qianchuan-agent-root"));
    let dialog = dialogs.length === 1 ? dialogs[0] : null;
    if (!dialogs.length) {
      const platformConfirmation = resolvePlatformConfirmationSurface(action);
      if (platformConfirmation) {
        dialog = platformConfirmation;
        dialogs = [platformConfirmation];
      }
    }
    const valueEditor = (action === "set_budget" || action === "set_roi")
      ? resolveValueEditorSurface(action, dialog, scope)
      : null;
    if (!dialog && valueEditor?.surface) {
      dialog = valueEditor.surface;
      dialogs = [dialog];
    }
    const dialogText = compactText(dialog?.innerText).slice(0, 1800);
    const pageSecurityText = /login|passport|verify/i.test(location.href)
      ? compactText(document.body?.innerText).slice(0, 2400)
      : compactText(document.body?.innerText).slice(0, 6000).match(/.{0,80}(?:验证码|滑块验证|扫码登录|重新登录|安全校验|风险验证|人脸验证).{0,80}/)?.[0] || "";
    const securityText = /验证码|滑块验证|扫码登录|重新登录|安全校验|风险验证|人脸验证/.test(`${dialogText} ${pageSecurityText}`)
      ? compactText(`${dialogText} ${pageSecurityText}`).slice(0, 2400)
      : "";
    const observation = {
      action,
      scope,
      url: location.href,
      rowText: compactText(row?.innerText).slice(0, 1200),
      dialogCount: dialogs.length,
      dialog,
      dialogText,
      securityText,
      desiredValue: Number(desiredValue),
      candidates: [],
      _candidateElements: Object.create(null)
    };
    if (action === "pause" || action === "resume") {
      registerCandidates(observation, "control", pauseResumeCandidates(row, action, scope), row);
      try {
        const control = resolvePauseResumeControl(row, action, scope);
        observation.control = control.element;
        observation.controlContainer = row;
        observation.checked = control.checked;
        observation.controlKind = control.kind;
      } catch (error) {
        observation.controlError = error.message || "未识别到状态开关";
      }
    }
    if (action === "open_target") {
      registerCandidates(observation, "control", openTargetCandidates(row, targetId, targetName).map((item) => item.element), row);
      try {
        const control = resolveOpenTargetControl(row, targetId, targetName);
        observation.control = control.element;
        observation.controlContainer = row;
      } catch {}
    }
    if (action === "set_budget" || action === "set_roi") {
      const labelPattern = valueLabelPattern(action, scope);
      const valueTargets = resolveValueTargets(row, action, scope);
      registerCandidates(observation, "value", valueTargets, row);
      observation.hoverTargetCount = valueTargets.length;
      if (valueTargets.length === 1) {
        observation.hoverTarget = valueTargets[0];
        observation.hoverContainer = row;
      }
      const triggers = resolveValueEditTriggers(valueTargets);
      registerCandidates(observation, "trigger", triggers, row);
      observation.triggerCount = triggers.length;
      if (triggers.length === 1) {
        observation.trigger = triggers[0];
        observation.triggerContainer = row;
      }
      if (dialog) {
        const inputs = valueEditor?.input ? [{ element: valueEditor.input, score: 100 }] : visible(dialog.querySelectorAll("input[type='number'],input"))
          .filter((node) => !isDisabled(node) && !node.readOnly)
          .map((element) => ({ element, score: inputScore(element, labelPattern) }))
          .sort((left, right) => right.score - left.score);
        registerCandidates(observation, "input", inputs.map((item) => item.element), dialog);
        if (inputs.length && (!inputs[1] || inputs[0].score > inputs[1].score || inputs.length === 1)) {
          observation.input = inputs[0].element;
          observation.inputContainer = dialog;
          observation.currentValue = Number(inputs[0].element.value);
        }
      }
    }
    if (dialog) {
      const buttons = visible(dialog.querySelectorAll("button,[role='button']"))
        .filter((node) => CONFIRM_BUTTON_PATTERN.test(compactText(node.innerText || node.textContent)))
        .filter((node) => !isDisabled(node));
      registerCandidates(observation, "confirm", buttons, dialog);
      observation.confirmButtonCount = buttons.length;
      if (buttons.length === 1) {
        observation.confirmButton = buttons[0];
        observation.confirmContainer = dialog;
      }
    }
    observation.pageFingerprint = fingerprint([
      location.origin,
      location.pathname,
      scope,
      action,
      targetId,
      observation.rowText,
      observation.dialogText,
      observation.checked,
      observation.currentValue
    ].join("|"));
    return observation;
  }

  function resolvePlatformConfirmationSurface(action, doc = document) {
    const titlePattern = PLATFORM_CONFIRM_PATTERNS[action];
    if (!titlePattern) return null;
    const surfaces = [];
    const confirms = visible(doc.querySelectorAll("button,[role='button']"))
      .filter((node) => !node.closest?.("#mmw-qianchuan-agent-root"))
      .filter((node) => CONFIRM_BUTTON_PATTERN.test(compactText(node.innerText || node.textContent)))
      .filter((node) => !isDisabled(node));
    for (const confirm of confirms) {
      let surface = confirm.parentElement;
      for (let depth = 0; surface && surface !== doc.body && depth < 10; depth += 1, surface = surface.parentElement) {
        const text = compactText(surface.innerText || surface.textContent);
        if (!titlePattern.test(text) || text.length > 2000 || /删除|充值|创建|支付|验证码|登录|风险校验/.test(text)) continue;
        const buttons = visible(surface.querySelectorAll("button,[role='button']")).filter((node) => !isDisabled(node));
        const safeConfirms = buttons.filter((node) => CONFIRM_BUTTON_PATTERN.test(compactText(node.innerText || node.textContent)));
        const cancels = buttons.filter((node) => CANCEL_BUTTON_PATTERN.test(compactText(node.innerText || node.textContent)));
        if (safeConfirms.length === 1 && cancels.length >= 1) surfaces.push(surface);
        break;
      }
    }
    const unique = uniqueElements(surfaces);
    return unique.length === 1 ? unique[0] : null;
  }

  async function performRealStep({ step, observation, businessAction, sendRuntime }) {
    if (typeof sendRuntime !== "function") throw new Error("真实操作通道未加载。");
    if (step.type === "click_control") {
      const target = candidateTarget(observation, step.candidateId, "control", observation.control, observation.controlContainer);
      return realClick(target.element, target.container, businessAction, sendRuntime);
    }
    if (step.type === "click_trigger") {
      const target = candidateTarget(observation, step.candidateId, "trigger", observation.trigger, observation.triggerContainer);
      return realClick(target.element, target.container, businessAction, sendRuntime);
    }
    if (step.type === "hover_value") {
      const target = candidateTarget(observation, step.candidateId, "value", observation.hoverTarget, observation.hoverContainer);
      const point = verifiedCenterPoint(target.container, target.element);
      const response = await sendRuntime({
        type: "QIANCHUAN_AGENT_REAL_ACTION",
        business_action: businessAction,
        action: "move",
        payload: { x: point.x, y: point.y }
      });
      const result = response?.payload || response?.result || {};
      if (result.moved !== true) throw new Error("浏览器未确认真实悬停。");
      return { moved: true, point, engine: result.engine || "browser-debugger" };
    }
    if (step.type === "confirm_platform") {
      const target = candidateTarget(observation, step.candidateId, "confirm", observation.confirmButton, observation.confirmContainer);
      return realClick(target.element, target.container, "confirm_platform", sendRuntime);
    }
    if (step.type === "type_value") {
      const target = candidateTarget(observation, step.candidateId, "input", observation.input, observation.inputContainer);
      const point = verifiedCenterPoint(target.container, target.element);
      const response = await sendRuntime({
        type: "QIANCHUAN_AGENT_REAL_ACTION",
        business_action: businessAction,
        action: "type",
        payload: { x: point.x, y: point.y, text: String(step.value), clear: true }
      });
      const result = response?.payload || response?.result || {};
      if (result.typed !== true) throw new Error("浏览器未确认真实输入。");
      return { typed: true, point, engine: result.engine || "browser-debugger" };
    }
    throw new Error("不支持的千川接管单步操作。");
  }

  async function typeAndSubmit({ element, text, businessAction = "search_target", sendRuntime }) {
    if (!element || typeof sendRuntime !== "function") throw new Error("真实搜索通道未加载。");
    element.scrollIntoView?.({ block: "center", inline: "nearest", behavior: "auto" });
    const point = verifiedCenterPoint(element, element);
    const typed = await sendRuntime({
      type: "QIANCHUAN_AGENT_REAL_ACTION",
      business_action: businessAction,
      action: "type",
      payload: { x: point.x, y: point.y, text: String(text || "").slice(0, 128), clear: true }
    });
    if (typed?.payload?.typed !== true && typed?.result?.typed !== true) {
      throw new Error("浏览器未确认搜索内容输入。");
    }
    const submitted = await sendRuntime({
      type: "QIANCHUAN_AGENT_REAL_ACTION",
      business_action: businessAction,
      action: "key",
      payload: { key: "Enter" }
    });
    if (String(submitted?.payload?.key || submitted?.result?.key || "") !== "Enter") {
      throw new Error("浏览器未确认搜索提交。");
    }
    return { typed: true, submitted: true, point, engine: typed?.payload?.engine || "browser-debugger" };
  }

  async function realClick(element, container, businessAction, sendRuntime) {
    if (!element || !container) throw new Error("页面目标已变化，请重新识别。");
    element.scrollIntoView?.({ block: "center", inline: "nearest", behavior: "auto" });
    const point = verifiedCenterPoint(container, element);
    const response = await sendRuntime({
      type: "QIANCHUAN_AGENT_REAL_ACTION",
      business_action: businessAction,
      action: "click",
      payload: { x: point.x, y: point.y }
    });
    const result = response?.payload || response?.result || {};
    if (result.clicked !== true) throw new Error("浏览器未确认真实点击。");
    return { clicked: true, point, engine: result.engine || "browser-debugger" };
  }

  function fingerprint(value) {
    let hash = 2166136261;
    const text = String(value || "");
    for (let index = 0; index < text.length; index += 1) {
      hash ^= text.charCodeAt(index);
      hash = Math.imul(hash, 16777619);
    }
    return `qc-${(hash >>> 0).toString(16).padStart(8, "0")}`;
  }

  function inputScore(element, labelPattern) {
    const parts = [
      element.placeholder,
      element.getAttribute?.("aria-label")
    ];
    let current = element.parentElement;
    for (let depth = 0; current && current !== document.body && depth < 12; depth += 1, current = current.parentElement) {
      const nearby = compactText(current.innerText || current.textContent);
      if (nearby && nearby.length <= 2400) parts.push(nearby);
      if (current.matches?.("[role='dialog'],.ant-modal,.semi-modal,.ovui-dialog,.ovui-drawer")) break;
    }
    const text = compactText(parts.join(" "));
    return (labelPattern.test(text) ? 10 : 0) + (element.type === "number" ? 2 : 0);
  }

  function resolveValueTargets(row, action, scope = "") {
    if (!row || !VALUE_LABEL_PATTERNS[action]) return [];
    const labelPattern = valueLabelPattern(action, scope);
    const preferredSelectors = action === "set_roi"
      ? [controlProfile(scope).roiTargetSelector, ".setting-item.reference-setting-item"]
      : [".setting-item:not(.reference-setting-item)"];
    for (const selector of uniqueStrings(preferredSelectors)) {
      const preferred = visible(row.querySelectorAll(selector))
        .filter((node) => labelPattern.test(compactText(node.innerText || node.textContent)));
      if (preferred.length) return uniqueElements(preferred);
    }
    const fallback = visible(row.querySelectorAll(".setting-item,[class*='roi'],[class*='budget']"))
      .filter((node) => labelPattern.test(compactText(node.innerText || node.textContent)))
      .map((node) => node.closest?.(".setting-item") || node);
    return uniqueElements(fallback);
  }

  function resolveValueEditTriggers(valueTargets) {
    const candidates = uniqueElements((valueTargets || []).flatMap((target) => {
      const scope = target?.closest?.(".setting-item") || target;
      if (!scope?.querySelectorAll) return [];
      return visible(scope.querySelectorAll(
        ".edit-icon,.hover-show,[class*='edit'],[class*='Edit'],[class*='icon'],[class*='Icon'],button,a,[role='button'],[aria-label],[title],svg"
      ))
        .filter((node) => !isDisabled(node))
        .filter(isCompactValueTrigger);
    }));
    return collapseEquivalentValueTriggers(candidates);
  }

  function isCompactValueTrigger(node) {
    const rect = node?.getBoundingClientRect?.();
    if (!rect || rect.width < 4 || rect.height < 4 || rect.width > 56 || rect.height > 56) return false;
    const text = compactText(node.innerText || node.textContent);
    if (text.length > 24) return false;
    return true;
  }

  function collapseEquivalentValueTriggers(elements) {
    const sorted = uniqueElements(elements).sort((left, right) => rectArea(left) - rectArea(right));
    const selected = [];
    for (const element of sorted) {
      const rect = element.getBoundingClientRect?.();
      if (!rect) continue;
      const duplicate = selected.some((existing) => {
        if (existing.contains?.(element) || element.contains?.(existing)) return true;
        const other = existing.getBoundingClientRect?.();
        if (!other) return false;
        const centerDistance = Math.abs(rect.left + rect.width / 2 - other.left - other.width / 2)
          + Math.abs(rect.top + rect.height / 2 - other.top - other.height / 2);
        return centerDistance <= 6;
      });
      if (!duplicate) selected.push(element);
    }
    return selected;
  }

  function rectArea(element) {
    const rect = element?.getBoundingClientRect?.();
    return rect ? Math.max(0, rect.width) * Math.max(0, rect.height) : Number.MAX_SAFE_INTEGER;
  }

  function resolveValueEditorSurface(action, knownDialog = null, scope = "") {
    if (!VALUE_LABEL_PATTERNS[action]) return null;
    const labelPattern = valueLabelPattern(action, scope);
    const inputs = visible(document.querySelectorAll("input[type='number'],input"))
      .filter((node) => !node.closest?.("#mmw-qianchuan-agent-root") && !isDisabled(node) && !node.readOnly)
      .map((element) => ({ element, score: inputScore(element, labelPattern) }))
      .filter((item) => item.score >= 10)
      .sort((left, right) => right.score - left.score);
    if (!inputs.length || (inputs[1] && inputs[0].score === inputs[1].score)) return null;
    const input = inputs[0].element;
    if (knownDialog?.contains?.(input)) return { surface: knownDialog, input };
    if (action === "set_roi") {
      const preferredSurface = input.closest?.(controlProfile(scope).roiEditorSelector);
      if (preferredSurface && visible([preferredSurface]).length === 1) {
        const confirms = visible(preferredSurface.querySelectorAll("button,[role='button']"))
          .filter((node) => CONFIRM_BUTTON_PATTERN.test(compactText(node.innerText || node.textContent)))
          .filter((node) => !isDisabled(node));
        if (confirms.length === 1) return { surface: preferredSurface, input };
      }
    }
    let surface = input.parentElement;
    while (surface && surface !== document.body) {
      const text = compactText(surface.innerText || surface.textContent);
      const confirms = visible(surface.querySelectorAll("button,[role='button']"))
        .filter((node) => CONFIRM_BUTTON_PATTERN.test(compactText(node.innerText || node.textContent)))
        .filter((node) => !isDisabled(node));
      if (labelPattern.test(text) && confirms.length === 1) return { surface, input };
      surface = surface.parentElement;
    }
    return null;
  }

  function uniqueElements(elements) {
    return Array.from(new Set(elements.filter(Boolean)));
  }

  function resolveOpenTargetControl(row, targetId, targetName) {
    if (!row) throw new Error("没有可打开的目标计划行。");
    const candidates = openTargetCandidates(row, targetId, targetName);
    if (!candidates.length) throw new Error("未在目标计划行识别到可打开的计划名称或详情入口。");
    if (candidates[1] && candidates[0].score === candidates[1].score) {
      throw new Error("目标计划行内存在多个同等入口，为避免误点，本次未打开计划。");
    }
    return candidates[0];
  }

  function openTargetCandidates(row, targetId, targetName) {
    if (!row) return [];
    const id = compactText(targetId);
    const name = compactText(targetName);
    return visible(row.querySelectorAll("a,button,[role='button'],[data-testid*='name']"))
      .filter((node) => !isDisabled(node))
      .filter((node) => !/暂停|恢复|预算|删除|复制|更多/.test(compactText(node.innerText || node.textContent)))
      .map((element) => {
        const text = compactText(element.innerText || element.textContent);
        let score = 0;
        if (name && text === name) score = 100;
        else if (id && text === id) score = 95;
        else if (name && name.length >= 2 && text.includes(name)) score = 85;
        else if (id && text.includes(id)) score = 80;
        else if (/^(?:查看详情|查看|详情|编辑|进入)$/.test(text)) score = 60;
        return { element, text, score, kind: "plan-entry" };
      })
      .filter((item) => item.score > 0)
      .sort((left, right) => right.score - left.score);
  }

  function pauseResumeCandidates(row, action, scope = "") {
    if (!row || !LABELS[action]) return [];
    const label = LABELS[action];
    const textControls = visible(row.querySelectorAll("button,a,[role='button']"))
      .filter((node) => compactText(node.innerText || node.textContent) === label && !isDisabled(node));
    const preferredSelector = controlProfile(scope).switchSelector;
    const preferredSwitches = preferredSelector
      ? visible(row.querySelectorAll(preferredSelector)).filter((node) => !isDisabled(node))
      : [];
    const switches = preferredSwitches.length ? preferredSwitches : SWITCH_SELECTORS.flatMap((selector) =>
      visible(row.querySelectorAll(selector)).filter((node) => !isNestedSwitchDuplicate(node, selector) && !isDisabled(node))
    );
    return uniqueElements([...textControls, ...switches]);
  }

  function registerCandidates(observation, role, elements, container) {
    if (!observation || !container) return;
    uniqueElements(elements).slice(0, 12).forEach((element, index) => {
      const id = `${role}-${index + 1}`;
      const rect = element.getBoundingClientRect?.();
      const ownText = compactText(element.innerText || element.textContent);
      const nearbyText = ownText || compactText(element.parentElement?.innerText || element.parentElement?.textContent).slice(0, 180);
      observation.candidates.push({
        id,
        role,
        text: nearbyText.slice(0, 240),
        ariaLabel: compactText(element.getAttribute?.("aria-label")).slice(0, 160),
        title: compactText(element.getAttribute?.("title")).slice(0, 160),
        tag: String(element.tagName || "").toLowerCase(),
        disabled: isDisabled(element),
        rect: rect ? { left: rect.left, top: rect.top, width: rect.width, height: rect.height } : null
      });
      observation._candidateElements[id] = { role, element, container };
    });
  }

  function candidateTarget(observation, candidateId, role, fallbackElement, fallbackContainer) {
    const id = String(candidateId || "").trim();
    if (!id) return { element: fallbackElement, container: fallbackContainer };
    const candidate = observation?._candidateElements?.[id];
    if (!candidate || candidate.role !== role || !candidate.element?.isConnected || !candidate.container?.contains?.(candidate.element)) {
      throw new Error("模型选择的页面候选已变化，AI 接管已停止。");
    }
    return candidate;
  }

  function findUniqueSwitch(row, preferredSelector = "") {
    if (preferredSelector) {
      const preferred = visible(row.querySelectorAll(preferredSelector));
      if (preferred.length > 1) throw new Error("目标计划行内存在多个状态开关，本次未执行。");
      if (preferred.length === 1) return preferred[0];
    }
    for (const selector of SWITCH_SELECTORS) {
      const matches = visible(row.querySelectorAll(selector)).filter((node) => !isNestedSwitchDuplicate(node, selector));
      if (matches.length > 1) throw new Error("目标计划行内存在多个状态开关，本次未执行。");
      if (matches.length === 1) return matches[0];
    }
    return null;
  }

  function isNestedSwitchDuplicate(node, selector) {
    if (selector !== ".oc-switch") return false;
    return Boolean(node.querySelector?.(".ovui-switch,[role='switch'],[aria-checked]"));
  }

  function readSwitchState(element) {
    const ariaChecked = element?.getAttribute?.("aria-checked");
    if (ariaChecked === "true" || ariaChecked === "false") return ariaChecked === "true";
    const dataState = String(element?.getAttribute?.("data-state") || element?.dataset?.state || "").toLowerCase();
    if (["checked", "on", "true", "active"].includes(dataState)) return true;
    if (["unchecked", "off", "false", "inactive"].includes(dataState)) return false;
    const className = String(element?.className || "");
    if (CHECKED_CLASSES.some((name) => element?.classList?.contains?.(name))) return true;
    if (/\b(?:ovui|ant|semi)?-?switch\b|\boc-switch\b/i.test(className)) return false;
    return null;
  }

  function verifiedCenterPoint(row, element) {
    const rect = element.getBoundingClientRect();
    if (!(rect.width > 0 && rect.height > 0)) throw new Error("目标计划控件当前不可见，本次未执行。");
    const x = Math.round(rect.left + rect.width / 2);
    const y = Math.round(rect.top + rect.height / 2);
    const doc = element.ownerDocument || document;
    const view = doc.defaultView || window;
    if (x < 0 || y < 0 || x >= view.innerWidth || y >= view.innerHeight) {
      throw new Error("目标计划控件不在当前画面内，本次未执行。");
    }
    const hit = doc.elementFromPoint?.(x, y);
    const hitInsideControl = hit && (hit === element || element.contains?.(hit));
    if (!hitInsideControl || !row.contains?.(hit)) {
      throw new Error("目标计划控件被其他界面遮挡，本次未执行。");
    }
    return { x, y };
  }

  function visible(nodes) {
    return Array.from(nodes || []).filter((node) => {
      const rect = node.getBoundingClientRect?.();
      const view = node.ownerDocument?.defaultView || window;
      const style = view.getComputedStyle?.(node);
      return rect?.width > 0 && rect?.height > 0 && style?.display !== "none" && style?.visibility !== "hidden";
    });
  }

  function isDisabled(element) {
    return Boolean(element?.disabled || element?.hasAttribute?.("disabled") || element?.getAttribute?.("aria-disabled") === "true");
  }

  function normalizePlanStatus(value) {
    const text = compactText(value).toLowerCase();
    if (!text) return "";
    if (/(?:已暂停|暂停中|已关闭|未开启|已停止|停止投放)/.test(text) || /\b(?:paused|inactive|off|stopped)\b/.test(text)) {
      return "paused";
    }
    if (/(?:投放中|生效中|已开启|开启中)/.test(text) || /\b(?:active|running|on)\b/.test(text)) {
      return "active";
    }
    return "";
  }

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

  function controlProfile(scope = "") {
    return OVERALL_SCOPES.has(String(scope || "")) ? CONTROL_PROFILES.overall : CONTROL_PROFILES.multiplier;
  }

  function valueLabelPattern(action, scope = "") {
    return action === "set_roi" ? controlProfile(scope).roiLabelPattern : VALUE_LABEL_PATTERNS[action];
  }

  function uniqueStrings(values) {
    return Array.from(new Set((values || []).filter(Boolean)));
  }

  window.MMWQianchuanActionExecutor = Object.freeze({
    clickOpenTarget,
    clickPauseResume,
    observeOperation,
    performRealStep,
    typeAndSubmit,
    normalizePlanStatus,
    controlProfile,
    readSwitchState,
    resolvePlatformConfirmationSurface,
    resolveOpenTargetControl,
    resolvePauseResumeControl,
    resolveValueEditorSurface,
    resolveValueTargets,
    resolveValueEditTriggers
  });
})();
