import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";

// Defer non-critical CSS (scrollbar, high-contrast) until after first paint
if (typeof window !== 'undefined') {
  const loadDeferred = () => import("./styles/deferred.css");
  if ('requestIdleCallback' in window) {
    requestIdleCallback(loadDeferred, { timeout: 2000 });
  } else {
    setTimeout(loadDeferred, 1000);
  }
}
import { captureUtmParams } from "./utils/utm";
import { captureAttribution } from "./utils/attribution";
import { startCallRailMonitor } from "./utils/callrailMonitor";

const STALE_IMPORT_RELOAD_FLAG = "lovable:stale-import-reloaded";

const isStaleDynamicImportError = (error: unknown) => {
  if (!(error instanceof Error)) return false;
  return /Failed to fetch dynamically imported module/i.test(error.message);
};

const recoverFromStaleImport = async () => {
  try {
    if (sessionStorage.getItem(STALE_IMPORT_RELOAD_FLAG)) return;
    sessionStorage.setItem(STALE_IMPORT_RELOAD_FLAG, "1");
  } catch {
    // ignore storage failures and still attempt recovery
  }

  try {
    if ("serviceWorker" in navigator) {
      const registrations = await navigator.serviceWorker.getRegistrations();
      await Promise.all(registrations.map((registration) => registration.unregister().catch(() => false)));
    }
  } catch {
    // ignore SW cleanup failures
  }

  try {
    if ("caches" in window) {
      const cacheKeys = await caches.keys();
      await Promise.all(cacheKeys.map((key) => caches.delete(key).catch(() => false)));
    }
  } catch {
    // ignore cache cleanup failures
  }

  const url = new URL(window.location.href);
  url.searchParams.set("_v", Date.now().toString(36));
  window.location.replace(url.toString());
};

if (typeof window !== "undefined") {
  window.addEventListener("error", (event) => {
    if (isStaleDynamicImportError(event.error)) {
      void recoverFromStaleImport();
    }
  });

  window.addEventListener("unhandledrejection", (event) => {
    if (isStaleDynamicImportError(event.reason)) {
      event.preventDefault();
      void recoverFromStaleImport();
    }
  });
}

// Capture UTM parameters from the landing URL
captureUtmParams();
// Capture lead attribution (first-touch + last-touch + channel + geo)
captureAttribution();

// Start CallRail swap.js server-side telemetry (idle-deferred)
startCallRailMonitor();

// Register service worker for caching and offline support
if ('serviceWorker' in navigator && import.meta.env.PROD) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js').then((registration) => {
      // Check for updates every 30 minutes
      setInterval(() => registration.update(), 30 * 60 * 1000);

      // When a new SW is waiting, tell it to activate immediately
      registration.addEventListener('updatefound', () => {
        const newWorker = registration.installing;
        if (newWorker) {
          newWorker.addEventListener('statechange', () => {
            if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
              newWorker.postMessage({ type: 'SKIP_WAITING' });
            }
          });
        }
      });
    }).catch(() => {
      // Service worker registration failed silently
    });

    // Reload when the new SW takes over
    navigator.serviceWorker.addEventListener('controllerchange', () => {
      window.location.reload();
    });
  });
}

// Post-publish version check: detect when the deployed bundle no longer
// matches the version baked into this running script and force a refresh.
if (import.meta.env.PROD && typeof window !== 'undefined') {
  import('./lib/version-check').then(({ startVersionCheck }) => {
    startVersionCheck();
  });
}

// Initialize Core Web Vitals monitoring after the app is interactive
if (typeof window !== 'undefined') {
  window.addEventListener('load', () => {
    // Defer web vitals to after all critical work is done
    if ('requestIdleCallback' in window) {
      window.requestIdleCallback(() => {
        import('./lib/web-vitals').then(({ initWebVitals }) => {
          initWebVitals();
        });
      }, { timeout: 5000 });
    } else {
      setTimeout(() => {
        import('./lib/web-vitals').then(({ initWebVitals }) => {
          initWebVitals();
        });
      }, 3000);
    }
  });
}

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