(() => {
  if (globalThis.__HAIXUN_THREADS_BRIDGE__) return;
  globalThis.__HAIXUN_THREADS_BRIDGE__ = true;

  const ROOT = document.documentElement;
  ROOT.dataset.haixunExtension = "1";
  ROOT.dataset.haixunExtensionVersion = "2";

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

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

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

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

    chrome.runtime
      .sendMessage({
        action: "sync",
        serverUrl: event.data.serverUrl ?? window.location.origin,
        accountId: event.data.accountId,
        accessToken: event.data.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();
})();