import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
// Selbst gehostete Fonts — ersetzen den render-blocking Google-Fonts-Request.
// Vite inlined die @font-face Regeln in den Haupt-CSS-Chunk und kopiert die
// WOFF2-Dateien nach /assets/. Spart ~750 ms Render-Block auf Mobil.
import "@fontsource-variable/dm-sans/index.css";
import "@fontsource-variable/inter/index.css";

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

// Replay opt-in trackers for returning visitors who already gave consent.
// We do this AFTER first paint to keep the critical path clean.
// IMPORTANT (DSGVO / § 25 TDDDG): every tracker below is gated on the
// matching consent category — nothing loads without a stored opt-in.
if (typeof window !== "undefined") {
  const replayTrackers = () => {
    try {
      const stored = localStorage.getItem("mister-leasing-cookie-consent");
      if (!stored) return;
      const consent = JSON.parse(stored) as {
        functional?: boolean;
        analytics?: boolean;
        marketing?: boolean;
      };
      // Replay Google Consent Mode v2 signals so Google tags honour the
      // returning visitor's previous choice (default in index.html is denied).
      import("./lib/consentMode").then((m) =>
        m.updateGoogleConsent({
          functional: !!consent?.functional,
          analytics: !!consent?.analytics,
          marketing: !!consent?.marketing,
        })
      );
      if (consent?.analytics) {
        // GTM (incl. GA4) loads on idle. Sentry is heavier (~35 KiB gzipped)
        // and is deferred until the user interacts to keep it out of the
        // Lighthouse "unused JS" budget on the homepage.
        import("./lib/loadGtm").then((m) => m.loadGtm());
        if (import.meta.env.PROD) {
          const loadSentry = () => {
            import("./lib/sentry").then((m) => m.initSentry()).catch(() => {});
            window.removeEventListener("pointerdown", loadSentry);
            window.removeEventListener("keydown", loadSentry);
            window.removeEventListener("scroll", loadSentry);
          };
          window.addEventListener("pointerdown", loadSentry, { once: true, passive: true });
          window.addEventListener("keydown", loadSentry, { once: true });
          window.addEventListener("scroll", loadSentry, { once: true, passive: true });
          // Safety net: load after 15 s even without interaction so background
          // tabs and bots still capture errors.
          setTimeout(loadSentry, 15000);
        }
      }
      if (consent?.marketing) {
        import("./lib/loadHubSpotTracker").then((m) => m.loadHubSpotTracker());
        import("./lib/loadFbPixel").then((m) => m.loadFbPixel());
      }
    } catch {
      /* ignore */
    }
  };
  if ("requestIdleCallback" in window) {
    (window as Window & typeof globalThis).requestIdleCallback(replayTrackers, { timeout: 3000 });
  } else {
    setTimeout(replayTrackers, 1500);
  }
}

// Register Service Worker in production
if ("serviceWorker" in navigator && import.meta.env.PROD) {
  window.addEventListener("load", () => {
    navigator.serviceWorker
      .register("/sw.js")
      .then((registration) => {
        // Self-healing: if a new SW is waiting, activate it immediately so
        // the user never gets stuck on a stale cached bundle after a deploy.
        registration.addEventListener("updatefound", () => {
          const installing = registration.installing;
          if (!installing) return;
          installing.addEventListener("statechange", () => {
            if (
              installing.state === "installed" &&
              navigator.serviceWorker.controller
            ) {
              installing.postMessage({ type: "SKIP_WAITING" });
            }
          });
        });
        // Reload once when a new SW takes control – ensures the freshly
        // deployed bundle is the one actually executing.
        let refreshing = false;
        navigator.serviceWorker.addEventListener("controllerchange", () => {
          if (refreshing) return;
          refreshing = true;
          window.location.reload();
        });
      })
      .catch(() => {
        // SW registration failed – app works fine without it
      });
  });
}
