import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { startVersionSync, checkVersionNow, purgeCachesAndVerify } from "./lib/versionSync";
import { supabase } from "./integrations/supabase/client";
import { installDiagnosticsBuffer } from "./utils/diagnosticsBuffer";

installDiagnosticsBuffer();

const PWA_RESET_VERSION = "2026-04-19-preview-sw-disable";
const RESET_MARKER_KEY = `workitect-pwa-reset-${PWA_RESET_VERSION}`;

function shouldEnableServiceWorker() {
  const { hostname } = window.location;

  return !(
    hostname === "localhost" ||
    hostname === "127.0.0.1" ||
    hostname.includes("lovableproject.com") ||
    hostname.startsWith("id-preview--")
  );
}

async function resetStalePwaCachesIfNeeded(): Promise<boolean> {
  try {
    if (window.localStorage.getItem(RESET_MARKER_KEY) === "done") return false;

    if ("serviceWorker" in navigator) {
      const registrations = await navigator.serviceWorker.getRegistrations();
      await Promise.all(registrations.map((r) => r.unregister()));
    }
    if ("caches" in window) {
      const cacheKeys = await window.caches.keys();
      await Promise.all(cacheKeys.map((k) => window.caches.delete(k)));
    }

    window.localStorage.setItem(RESET_MARKER_KEY, "done");
    return true;
  } catch {
    return false;
  }
}

async function bootstrap() {
  const enableServiceWorker = shouldEnableServiceWorker();
  const didReset = await resetStalePwaCachesIfNeeded();

  if (didReset && !sessionStorage.getItem("workitect-post-reset-reload")) {
    sessionStorage.setItem("workitect-post-reset-reload", "1");
    window.location.reload();
    return;
  }

  const hideSplash = () => {
    const splash = document.getElementById("pwa-splash");
    if (!splash) return;
    splash.style.opacity = "0";
    setTimeout(() => splash.remove(), 300);
  };

  let hidden = false;
  const hideOnce = () => { if (hidden) return; hidden = true; hideSplash(); };

  // For non-/app routes (landing, marketing, public pages) the splash adds
  // no value — hide it as soon as the JS bundle starts executing so users
  // see content immediately as React mounts.
  const isAppRoute = window.location.pathname.startsWith("/app");
  if (!isAppRoute) {
    requestAnimationFrame(hideOnce);
  }

  createRoot(document.getElementById("root")!).render(<App />);

  // Background version sync — detects new deployments and hard-reloads
  // exactly once when a mismatch is found. Safe in iframes/preview.
  startVersionSync();

  // Force a fresh check whenever the auth state changes (login/logout/refresh)
  // so users land on the latest build immediately after signing in.
  // On login: purge SW + Cache Storage, then verify build version.
  // On token refresh: just re-check version (no need to purge again).
  supabase.auth.onAuthStateChange((event) => {
    if (event === "SIGNED_IN") {
      void purgeCachesAndVerify();
    } else if (event === "TOKEN_REFRESHED") {
      void checkVersionNow();
    }
  });

  // /app waits for the ready signal (auth + initial data); hard cap at 3s.
  window.addEventListener("workitect-app-ready", hideOnce, { once: true });
  setTimeout(hideOnce, 3000);

  if (enableServiceWorker && "serviceWorker" in navigator) {
    let reloading = false;
    navigator.serviceWorker.addEventListener("controllerchange", () => {
      if (reloading) return;
      reloading = true;
      window.location.reload();
    });
    navigator.serviceWorker.addEventListener("message", (event) => {
      if (event.data?.type === "SW_UPDATED" && !reloading) {
        reloading = true;
        window.location.reload();
      }
    });

    window.addEventListener("load", () => {
      navigator.serviceWorker
        .register("/sw.js", { updateViaCache: "none" })
        .then((registration) => {
          registration.update();
          // Poll for updates every 60s so long-lived tabs pick up new builds.
          setInterval(() => registration.update().catch(() => {}), 60_000);
          registration.addEventListener("updatefound", () => {
            const installing = registration.installing;
            if (!installing) return;
            installing.addEventListener("statechange", () => {
              if (installing.state === "installed" && navigator.serviceWorker.controller) {
                // New SW ready — activate immediately.
                installing.postMessage({ type: "SKIP_WAITING" });
              }
            });
          });
        })
        .catch(() => {});
    });
  }
}

bootstrap();
