/**
 * STONK KOC - Session Sync (ISOLATED world)
 * Đồng bộ TikTok session cookies lên server mỗi 3 phút
 */
(function () {
  const SYNC_INTERVAL = 3 * 60 * 1000; // 3 minutes

  const sync = async () => {
    try {
      const urlParams = new URLSearchParams(window.location.search);
      const shopId =
        urlParams.get("shop_id") ||
        urlParams.get("shopId") ||
        localStorage.getItem("current_shop_id") ||
        "";

      const cookie = document.cookie;
      const ttToken =
        localStorage.getItem("x-tt-token") ||
        localStorage.getItem("tt_token") ||
        "";

      if (!cookie) return;

      chrome.runtime.sendMessage({
        action: { type: "event", name: "uploadShopCookie" },
        data: { cookie, ttToken, shopId },
      }, res => {
        if (chrome.runtime.lastError) return;
        if (res?.success) {
          console.log("[STONK KOC] Session synced ✓");
        }
      });
    } catch (err) {
      console.warn("[STONK KOC] Session sync error:", err.message);
    }
  };

  // Run on load
  if (document.readyState === "complete") {
    sync();
  } else {
    window.addEventListener("load", sync);
  }

  // Periodic sync
  setInterval(sync, SYNC_INTERVAL);

  console.log("[STONK KOC] Session Sync Active — every 3 minutes");
})();
