import { createRoot } from "react-dom/client";
import { HelmetProvider } from "react-helmet-async";
import App from "./App.tsx";
import { BUILD_ID } from "./lib/buildInfo";
import { assertSupabaseEnv } from "./lib/env";
import { safeSetSeen as markSplashSeen } from "./lib/splashSession";
import "./index.css";



// =============================================================================
// Service Worker policy — KILL SWITCH ONLY
// =============================================================================
// The app no longer caches anything in a service worker. `public/sw.js` is a
// kill-switch worker whose only job is to purge legacy caches (Workbox
// precache + the old `pt-assets-*` buckets) and unregister itself.
//
// - Production: register `/sw.js` once so returning browsers that still hold a
//   stale worker receive the replacement and get cleaned up.
// - Lovable preview / any iframe / dev: never register. Instead we actively
//   unregister EVERY worker, delete every app-owned cache, and hard-reload once
//   so the editor preview can never be pinned to an outdated build.
// =============================================================================

const isInIframe = (() => {
  try {
    return window.self !== window.top;
  } catch {
    return true;
  }
})();

const host = window.location.hostname;
const isPreviewHost =
  host.startsWith("id-preview--") ||
  host.startsWith("preview--") ||
  host === "lovableproject.com" ||
  host.endsWith(".lovableproject.com") ||
  host === "lovableproject-dev.com" ||
  host.endsWith(".lovableproject-dev.com") ||
  host.endsWith(".lovable.app") ||
  host.endsWith(".beta.lovable.dev") ||
  host === "localhost" ||
  host === "127.0.0.1";

const isSwDisabledByFlag = new URLSearchParams(window.location.search).has("sw")
  ? new URLSearchParams(window.location.search).get("sw") === "off"
  : false;

// Build stamp — lets you confirm at a glance which build the preview is showing.
console.info(`[PoultryTrackers] build ${BUILD_ID}`);

// Fail loudly (in the console) if a hosting-dashboard env var has hijacked the
// backend target. See src/lib/env.ts.
assertSupabaseEnv();



// Render IMMEDIATELY — never block first paint on SW work.
createRoot(document.getElementById("root")!).render(
  <HelmetProvider>
    <App />
  </HelmetProvider>
);

// SW registration runs after first paint, idle-scheduled.
const idle: typeof requestIdleCallback =
  typeof requestIdleCallback === "function"
    ? requestIdleCallback
    : ((cb: IdleRequestCallback) =>
        setTimeout(() => cb({ didTimeout: false, timeRemaining: () => 50 } as IdleDeadline), 1) as unknown as number);

const RELOAD_FLAG = "__pt_sw_purged";

// iOS Safari (private mode / ITP) can throw on sessionStorage access. If we
// cannot persist the guard flag we must NOT reload at all — an unguarded
// reload becomes an infinite boot loop (the symptom clients saw as the splash
// screen "restarting" several times before the homepage appeared).
const storageAvailable = (() => {
  try {
    sessionStorage.setItem("__pt_probe", "1");
    sessionStorage.removeItem("__pt_probe");
    return true;
  } catch {
    return false;
  }
})();

const purgeAppCaches = async () => {
  if (!("caches" in window)) return false;
  const names = await caches.keys();
  const appOwned = names.filter(
    (n) => /^pt-assets-/.test(n) || /(^|-)precache-v\d+-|(^|-)runtime-|(^|-)workbox-/.test(n),
  );
  await Promise.allSettled(appOwned.map((n) => caches.delete(n)));
  return appOwned.length > 0;
};

idle(async () => {
  if (!("serviceWorker" in navigator)) return;
  try {
    const regs = await navigator.serviceWorker.getRegistrations();

    if (isInIframe || isPreviewHost || isSwDisabledByFlag || !import.meta.env.PROD) {
      // Preview / iframe / dev / ?sw=off: never register. Evict everything so
      // the editor preview can never be pinned to a stale build.
      await Promise.allSettled(regs.map((r) => r.unregister()));
      const hadCaches = await purgeAppCaches();
      const needsReload = regs.length > 0 || hadCaches;
      if (needsReload && storageAvailable && sessionStorage.getItem(RELOAD_FLAG) !== "1") {
        sessionStorage.setItem(RELOAD_FLAG, "1");
        // App-controlled reload — never let it replay the splash.
        markSplashSeen();
        window.location.reload();
      }

      return;
    }

    // Production: install the kill-switch worker so returning browsers holding
    // a legacy worker get cleaned up. `/sw.js` unregisters itself on activate.
    await navigator.serviceWorker.register("/sw.js", { scope: "/" });
  } catch {
    /* no-op */
  }
});


