(() => {
  "use strict";

  // The manifest controls the exact workbench origins where this bridge is injected.
  const allowedOrigin = /^https?:\/\//i.test(location.origin);
  if (!allowedOrigin || window.__sdmExtensionBridgeInstalled) return;
  window.__sdmExtensionBridgeInstalled = true;

  const postEvent = message => window.postMessage({ type: "SDM_EXTENSION_EVENT", message }, location.origin);

  async function sendRuntimeMessage(message) {
    const runtime = globalThis.chrome?.runtime;
    if (typeof runtime?.sendMessage !== "function") throw new Error("易联跨境扩展通信未就绪，请重新加载扩展");
    return runtime.sendMessage(message);
  }

  window.addEventListener("message", async event => {
    if (event.source !== window || event.origin !== location.origin || event.data?.type !== "SDM_EXTENSION_REQUEST") return;
    const requestId = String(event.data.requestId || "");
    const message = event.data.message;
    if (!requestId || !message || typeof message !== "object") return;
    window.postMessage({ type: "SDM_EXTENSION_ACK", requestId }, location.origin);
    try {
      const response = await sendRuntimeMessage(message);
      window.postMessage({ type: "SDM_EXTENSION_RESPONSE", requestId, response }, location.origin);
    } catch (error) {
      window.postMessage({ type: "SDM_EXTENSION_RESPONSE", requestId, error: error?.message || String(error) }, location.origin);
    }
  });

  chrome.runtime.onMessage.addListener(message => {
    if (message?.type === "AI_TASK_RESULT" || message?.type === "GOOGLE_TRANSLATE_RESULT") postEvent(message);
  });

  chrome.storage.onChanged.addListener((changes, areaName) => {
    if (areaName !== "local") return;
    if (changes.lastAiTaskResult?.newValue) postEvent(changes.lastAiTaskResult.newValue);
    if (changes.lastGoogleTranslateResult?.newValue) postEvent(changes.lastGoogleTranslateResult.newValue);
  });
})();
