// Application entry point
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { initStandaloneApp } from "./lib/standaloneApp";

// Home-screen (installed PWA) app-shell behavior
initStandaloneApp();

// Recovery: after a new release, an old cached page can point at app files
// that no longer exist, which shows a blank screen. Clear caches once and reload.
(() => {
  const RECOVER_KEY = "lumera_chunk_recover_at";
  const isChunkError = (msg?: string) =>
    !!msg &&
    /Importing a module script failed|Failed to fetch dynamically imported module|error loading dynamically imported module|Unable to preload CSS/i.test(
      msg
    );

  const recover = async () => {
    const last = Number(sessionStorage.getItem(RECOVER_KEY) || 0);
    if (Date.now() - last < 30000) return; // never loop
    sessionStorage.setItem(RECOVER_KEY, String(Date.now()));
    try {
      if ("caches" in window) {
        const keys = await caches.keys();
        await Promise.all(keys.map((k) => caches.delete(k)));
      }
      if ("serviceWorker" in navigator) {
        const regs = await navigator.serviceWorker.getRegistrations();
        await Promise.all(regs.map((r) => r.unregister()));
      }
    } catch {
      /* ignore */
    }
    window.location.reload();
  };

  window.addEventListener("error", (e) => {
    if (isChunkError(e.message)) recover();
  });
  window.addEventListener("unhandledrejection", (e) => {
    const reason: any = e.reason;
    if (isChunkError(typeof reason === "string" ? reason : reason?.message)) recover();
  });
})();

// Detect if running as native app (iOS/Android via Capacitor)
// Use dynamic check to avoid import issues that break React initialization
const isNativePlatform = (() => {
  try {
    // Check for Capacitor bridge without importing the module directly
    return !!(window as any).Capacitor?.isNativePlatform?.();
  } catch {
    return false;
  }
})();

// Detect if running in Lovable preview (to avoid update noise during dev)
const isLovablePreview = typeof window !== 'undefined' && (
  window.location.hostname.includes('lovableproject.com') ||
  window.location.hostname.startsWith('id-preview--') ||
  window.location.hostname.startsWith('preview--')
);

// Register Service Worker ONLY for web PWA (not native apps, not preview)
// Native apps don't need SW and it causes reload issues
if ('serviceWorker' in navigator && !isNativePlatform && !isLovablePreview) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then(registration => {
        console.log('[PWA] Service Worker registered:', registration.scope);
        
        // Check for updates
        registration.addEventListener('updatefound', () => {
          const newWorker = registration.installing;
          if (newWorker) {
            newWorker.addEventListener('statechange', () => {
              if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                // Silent update: activate in background, applied on next app launch.
                console.log('[PWA] New content available (silent)');
                newWorker.postMessage({ type: 'SKIP_WAITING' });
              }
            });
          }
        });
      })
      .catch(error => {
        console.log('[PWA] Service Worker registration failed:', error);
      });
  });

  // NO automatic reload on controllerchange - avoids mid-session reloads
}


// Performance monitoring in development
if (import.meta.env.DEV && 'PerformanceObserver' in window) {
  try {
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (entry.duration > 50) {
          console.warn('[Performance] Long task:', Math.round(entry.duration), 'ms');
        }
      }
    });
    observer.observe({ entryTypes: ['longtask'] });
  } catch {
    // Long task observer not supported in this browser
  }
}

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