(() => {
  let lastToken = '';

  async function syncDashboardSession() {
    let token = '';
    try {
      token = String(localStorage.getItem('token') || '').trim();
    } catch (_) {
      return;
    }
    if (!token || token === lastToken) return;
    const response = await chrome.runtime.sendMessage({
      action: 'syncDashboardSessionFromPage',
      token,
    }).catch(() => {});
    if (response?.success) lastToken = token;
  }

  void syncDashboardSession();
  const timer = window.setInterval(() => void syncDashboardSession(), 3000);
  window.addEventListener('pagehide', () => window.clearInterval(timer), { once: true });
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') void syncDashboardSession();
  });

  // 供后台快速读取当前页面 token：后台会话恢复时优先走消息（已在页面的内容脚本
  // 立刻应答），而不是对后台节流的页面逐个 executeScript 注入（每个可能耗时数秒）。
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message?.action !== 'getDashboardSessionToken') return;
    try {
      sendResponse({ token: String(localStorage.getItem('token') || '').trim() });
    } catch (_) {
      sendResponse({ token: '' });
    }
  });
})();
