import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import { ToastProvider } from './components/ui/Toast';
import './index.css';
import { dispatchUpdateAvailable } from './utils/cacheRefresh';

// 🔍 Enhanced diagnostics for debugging reloads
console.log('🚀 [Main] App starting at:', Date.now());
console.log('🔍 [Main] Environment:', import.meta.env.MODE);
console.log('🔍 [Main] Previous load time:', (window as any).__APP_LOAD_TIME__);

// Check if this is a fresh load or potential unwanted reload
const lastRoute = localStorage.getItem('app_last_route');
const lastRouteTime = localStorage.getItem('app_last_route_time');
if (lastRoute && lastRouteTime) {
  const timeSinceLastRoute = Date.now() - parseInt(lastRouteTime);
  console.log('🔍 [Main] Last route was:', lastRoute, 'saved', Math.round(timeSinceLastRoute / 1000), 'seconds ago');
  
  // If we have a recent route saved, this might be an unwanted reload
  if (timeSinceLastRoute < 30000) { // Less than 30 seconds
    console.warn('⚠️ [Main] Possible unwanted reload detected - route was saved recently');
  }
}

// 🔄 Service Worker: registro con auto-actualización.
// - En preview/iframe de Lovable: desregistrar para no servir builds viejos.
// - En producción (PWA real): registrar y, al detectar nueva versión, recargar
//   automáticamente para que los operadores siempre tengan el código más reciente
//   sin tener que cerrar/abrir la app manualmente.
const isInIframe = (() => {
  try { return window.self !== window.top; } catch { return true; }
})();
const isPreviewHost =
  window.location.hostname.includes('id-preview--') ||
  window.location.hostname.includes('lovableproject.com') ||
  window.location.hostname.includes('lovable.dev');

if (isPreviewHost || isInIframe) {
  // Preview: nunca registrar SW; limpiar cualquier registro previo.
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations()
      .then((regs) => regs.forEach((r) => r.unregister()))
      .catch(() => {});
  }
  if ('caches' in window) {
    caches.keys().then((names) => names.forEach((n) => caches.delete(n))).catch(() => {});
  }
} else if ('serviceWorker' in navigator) {
  // Producción: registrar SW con auto-update + reload inmediato cuando llega
  // un SW nuevo, y version-check inmediato + periódico contra /version.json
  // para detectar deploys aunque la pestaña ya esté abierta.
  let reloaded = false;
  const safeReload = () => {
    if (reloaded) return;
    reloaded = true;
    // Cache-bust en URL para garantizar HTML fresco aún si el SW viejo intercepta.
    const u = new URL(window.location.href);
    u.searchParams.set('_v', Date.now().toString());
    window.location.replace(u.toString());
  };

  // Chequeo inmediato de versión ANTES de registrar el SW: si el bundle
  // cargado no coincide con el publicado, limpia caches y recarga ya.
  (async () => {
    try {
      const res = await fetch('/version.json', { cache: 'no-store' });
      if (!res.ok) return;
      const { build } = await res.json();
      if (build && typeof __BUILD_ID__ !== 'undefined' && build !== __BUILD_ID__) {
        console.log('[SW] Versión obsoleta al arranque:', __BUILD_ID__, '->', build);
        dispatchUpdateAvailable(build);
      }
    } catch { /* noop */ }
  })();

  // Cuando el SW nuevo toma control del cliente, recarga una sola vez para
  // que el HTML/JS servido sea de la versión nueva (sin esperar a que el
  // usuario cierre/abra la app).
  navigator.serviceWorker.addEventListener('controllerchange', () => {
    safeReload();
  });

  import('virtual:pwa-register')
    .then(({ registerSW }) => {
      const updateSW = registerSW({
        immediate: true,
        onNeedRefresh() {
          // Activa el SW en waiting; el listener de controllerchange recargará.
          updateSW(true).catch(() => safeReload());
        },
        onRegisteredSW(_swUrl, registration) {
          if (!registration) return;
          const checkSW = () => registration.update().catch(() => {});

          // Comparar build id del bundle vs el publicado en /version.json.
          const checkVersion = async () => {
            try {
              const res = await fetch('/version.json', { cache: 'no-store' });
              if (!res.ok) return;
              const { build } = await res.json();
              if (build && typeof __BUILD_ID__ !== 'undefined' && build !== __BUILD_ID__) {
                console.log('[SW] Nueva versión detectada:', build, 'vs', __BUILD_ID__);
                await checkSW();
                // En vez de recargar automáticamente (que interrumpe formularios
                // en curso), avisamos al usuario con un toast persistente que
                // incluye un botón "Refrescar ahora" para limpiar caché.
                dispatchUpdateAvailable(build);
              }
            } catch { /* noop */ }
          };

          // Chequeo inicial + periódico + en focus/visibility (más agresivo).
          checkVersion();
          setInterval(checkSW, 5 * 60 * 1000);
          setInterval(checkVersion, 60 * 1000);
          window.addEventListener('focus', () => { checkSW(); checkVersion(); });
          document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'visible') {
              checkSW();
              checkVersion();
            }
          });
          // iOS standalone PWA: los timers se congelan en background y
          // focus/visibilitychange no siempre disparan al volver a la app.
          // 'pageshow' cubre el restore desde bfcache (incl. persisted) y
          // 'online' cubre la reconexión tras estar sin señal — ambos son
          // los momentos en que un repartidor retoma la app tras un deploy.
          window.addEventListener('pageshow', () => { checkSW(); checkVersion(); });
          window.addEventListener('online', () => { checkSW(); checkVersion(); });
        },
      });
    })
    .catch((e) => console.warn('[SW] registro falló:', e));
}

try {
  const rootElement = document.getElementById('root');
  if (!rootElement) {
    throw new Error('Root element not found');
  }

  createRoot(rootElement).render(
    <StrictMode>
      <ToastProvider>
        <App />
      </ToastProvider>
    </StrictMode>
  );
} catch (error) {
  console.error('Error initializing app:', error);
  const rootElement = document.getElementById('root');
  if (rootElement) {
    rootElement.innerHTML = `
      <div style="display: flex; align-items: center; justify-content: center; height: 100vh; padding: 20px; font-family: system-ui, -apple-system, sans-serif;">
        <div style="text-align: center; max-width: 400px;">
          <h1 style="color: #dc2626; margin-bottom: 16px;">Error al cargar la aplicación</h1>
          <p style="color: #6b7280; margin-bottom: 24px;">Por favor, intenta recargar la página. Si el problema persiste, intenta limpiar el caché del navegador.</p>
          <button onclick="window.location.reload()" style="background: #2563eb; color: white; padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; font-size: 16px;">
            Recargar
          </button>
        </div>
      </div>
    `;
  }
}
