function init() {
  console.log("Xiaozhi script loaded");
  const token = localStorage.getItem("token");
  if (token) {
    chrome.runtime.sendMessage({ type: "XIAOZHI_TOKEN", token }, () => {
      void chrome.runtime.lastError;
    });
  } else {
    monitorPage();
  }
  window.addEventListener("message", (event) => {
    if (event.source !== window) return; // 只处理本页面消息
    if (event.data?.type === "userLogout") {
      chrome.runtime.sendMessage({ type: "XIAOZHI_TOKEN", token: "" }, () => {
        void chrome.runtime.lastError;
      });
    } else if (event.data?.type === "userLogin") {
      const token = localStorage.getItem("token");
      chrome.runtime.sendMessage({ type: "XIAOZHI_TOKEN", token }, () => {
        void chrome.runtime.lastError;
      });
    }
  });
}

function monitorPage() {
  // 每500ms检查一次
  const interval = setInterval(() => {
    const token = localStorage.getItem("token");
    if (token) {
      chrome.runtime.sendMessage({ type: "XIAOZHI_TOKEN", token }, () => {
        void chrome.runtime.lastError;
      });
      clearInterval(interval);
    }
  }, 500);
}

init();
