(() => {
  if (window.__MMW_QIANCHUAN_BILLING_BRIDGE__) return;
  window.__MMW_QIANCHUAN_BILLING_BRIDGE__ = true;

  const REQUEST_SOURCE = "mmw-qianchuan-billing-main";
  const RESPONSE_SOURCE = "mmw-qianchuan-billing-extension";
  const ACTIONS = new Set(["status", "authorize", "report"]);

  window.addEventListener("message", (event) => {
    if (event.source !== window || event.origin !== location.origin) return;
    const message = event.data;
    if (!message || message.source !== REQUEST_SOURCE || !ACTIONS.has(message.action)) return;
    const requestId = String(message.requestId || "");
    if (!requestId) return;
    chrome.runtime.sendMessage({
      type: "QIANCHUAN_BILLING_REQUEST",
      action: message.action,
      ...(message.payload && typeof message.payload === "object" ? message.payload : {})
    }, (response) => {
      const runtimeError = chrome.runtime.lastError;
      window.postMessage({
        source: RESPONSE_SOURCE,
        requestId,
        response: runtimeError
          ? { ok: false, error: runtimeError.message || "插件通信失败" }
          : (response || { ok: false, error: "插件未返回千川计费结果" })
      }, location.origin);
    });
  });
})();
