(() => {
  const ROOT = document.documentElement;
  // 每次注入都寫標記（方便偵測）；監聽器只掛一次
  ROOT.dataset.haixunExtension = "1";
  ROOT.dataset.haixunExtensionVersion = "4";

  function readPageAccessToken() {
    try {
      const legacy = localStorage.getItem("haixun.access_token");
      if (legacy) return legacy;
      const raw = localStorage.getItem("hb_live_tokens");
      if (!raw) return "";
      const parsed = JSON.parse(raw);
      return String(parsed?.access_token ?? "");
    } catch {
      return "";
    }
  }

  function announceReady() {
    window.postMessage(
      { type: "HAIXUN_EXTENSION_READY", version: 4, origin: location.origin },
      "*",
    );
  }

  if (!globalThis.__HAIXUN_THREADS_BRIDGE__) {
    globalThis.__HAIXUN_THREADS_BRIDGE__ = true;

    window.addEventListener("message", (event) => {
      if (event.source !== window) return;

      if (event.data?.type === "HAIXUN_PING_EXTENSION") {
        announceReady();
        return;
      }

      // 只收集 cookies，回傳 storageState 給網頁（網頁用自己的 JWT 上傳）
      if (event.data?.type === "HAIXUN_REQUEST_THREADS_COLLECT") {
        chrome.runtime
          .sendMessage({ action: "collect" })
          .then((result) => {
            window.postMessage(
              {
                type: "HAIXUN_THREADS_COLLECT_RESULT",
                ...(result ?? {}),
              },
              "*",
            );
          })
          .catch((error) => {
            const message =
              chrome.runtime.lastError?.message ??
              (error instanceof Error ? error.message : "收集失敗");
            window.postMessage(
              {
                type: "HAIXUN_THREADS_COLLECT_RESULT",
                success: false,
                message,
              },
              "*",
            );
          });
        return;
      }

      if (event.data?.type !== "HAIXUN_REQUEST_THREADS_SYNC") return;

      const accessToken =
        String(event.data.accessToken ?? "").trim() || readPageAccessToken();

      chrome.runtime
        .sendMessage({
          action: "sync",
          serverUrl: event.data.serverUrl ?? window.location.origin,
          accountId: String(event.data.accountId ?? "").trim(),
          accessToken,
          apiVersion: event.data.apiVersion ?? "go-v1",
        })
        .then((result) => {
          window.postMessage(
            {
              type: "HAIXUN_THREADS_SYNC_RESULT",
              ...(result ?? {}),
            },
            "*",
          );
        })
        .catch((error) => {
          const message =
            chrome.runtime.lastError?.message ??
            (error instanceof Error ? error.message : "同步失敗");
          window.postMessage(
            {
              type: "HAIXUN_THREADS_SYNC_RESULT",
              success: false,
              valid: false,
              message,
            },
            "*",
          );
        });
    });
  }

  announceReady();
  setTimeout(announceReady, 500);
  setTimeout(announceReady, 2000);
})();
