import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { QueryClientProvider } from '@tanstack/react-query'
import './index.css'
import App from './App.jsx'
import { queryClient } from './queryClient.js'
import { applyAdminPwaBranding } from './utils/pwaBranding.js'

// Inicialización inmediata de metadatos según la ruta (antes del render de React)
if (typeof window !== 'undefined') {
  const path = window.location.pathname || '';
  if (!path.startsWith('/my-card/') && !path.startsWith('/c/')) {
    applyAdminPwaBranding('Loyalty Pulse');
  }
}

// Captura global de beforeinstallprompt diferenciando vista de tarjeta vs administración
window.deferredInstallPrompt = null;
window.addEventListener('beforeinstallprompt', (e) => {
  const ua = (typeof navigator !== 'undefined' ? navigator.userAgent : '') || '';
  const isMobile = /Android|iPhone|iPad|iPod/i.test(ua);
  const path = (typeof window !== 'undefined' ? window.location.pathname : '') || '';

  // No capturar prompt en el formulario de registro (/c/:slug) para evitar instalar el formulario
  if (path.startsWith('/c/')) return;

  const isCardView = path.startsWith('/my-card/');
  if (isMobile || isCardView) {
    e.preventDefault();
    try {
      e.__lpRouteType = isCardView ? 'card' : 'admin';
    } catch {}
    window.deferredInstallPrompt = e;
    window.dispatchEvent(new Event('pwa-prompt-available'));
  }
});

// Registro de Service Worker en la raíz ('/') para interceptar /manifest-card.json y /card-logo-* en DEV y PROD
if ('serviceWorker' in navigator) {
  const hadController = Boolean(navigator.serviceWorker.controller);
  let refreshingSw = false;

  navigator.serviceWorker.addEventListener('controllerchange', () => {
    if (!hadController || refreshingSw) return;
    refreshingSw = true;
    window.location.reload();
  });

  const registerRootSw = () => {
    // Limpiar registros antiguos con scope restringido a /my-card/ si existieran
    navigator.serviceWorker.getRegistrations().then((registrations) => {
      registrations.forEach((reg) => {
        if (reg.scope && reg.scope.endsWith('/my-card/')) {
          reg.unregister().catch(() => {});
        }
      });
    }).catch(() => {});

    navigator.serviceWorker
      .register('/sw.js', { scope: '/' })
      .then((registration) => {
        registration.update().catch(() => {});
      })
      .catch((error) => {
        console.warn('[PWA] Error al registrar Service Worker:', error);
      });
  };

  registerRootSw();
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </StrictMode>,
)
