<!doctype html>
<html lang="es">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
    <meta name="description" content="DatesFox — Sistema de gestión de citas inteligente para negocios de servicios." />
    <meta name="theme-color" content="#FF6600" />

    <!-- PWA / Instalación -->
    <link rel="manifest" href="/manifest.json" />

    <!-- iOS / Safari PWA — mobile-web-app-capable es el estándar actual -->
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <meta name="apple-mobile-web-app-title" content="DatesFox" />
    <link rel="apple-touch-icon" href="/logo.png" />

    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="/logoico.ico" />

    <title>DatesFox | Gestión de Citas</title>

    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&display=swap" rel="stylesheet" />
    <script type="module" crossorigin src="/assets/index-CSb5BMwF.js"></script>
    <link rel="stylesheet" crossorigin href="/assets/index-CgekJpwf.css">
  </head>
  <body>
    <div id="root"></div>

    <!-- SW: limpia caches corruptos y registra nueva versión -->
    <script>
      // Versión del SW — debe coincidir con CACHE_VER en sw.js
      const SW_VERSION = 'v7';

      (async () => {
        if (!('serviceWorker' in navigator)) return;

        // Desactivar SW en entorno de desarrollo local para evitar conflictos con HMR (Vite)
        const isLocal = ['localhost', '127.0.0.1', '0.0.0.0', '::1'].includes(window.location.hostname) || window.location.hostname.startsWith('192.168.');
        if (isLocal) {
          const registrations = await navigator.serviceWorker.getRegistrations();
          for (const registration of registrations) {
            await registration.unregister();
            console.log('[SW] Unregistered existing SW for local development');
          }
          return;
        }

        try {
          // 1. Borrar TODOS los caches que no sean de la versión actual
          const keys = await caches.keys();
          await Promise.all(
            keys
              .filter(k => !k.includes(SW_VERSION))
              .map(k => {
                console.log('[SW-Cleanup] Borrando cache viejo:', k);
                return caches.delete(k);
              })
          );

          // 2. Registrar/actualizar el SW
          const reg = await navigator.serviceWorker.register('/sw.js', {
            updateViaCache: 'none' // Siempre verifica nueva versión en red
          });

          // 3. Forzar activación inmediata si hay nuevo SW esperando
          if (reg.waiting) {
            reg.waiting.postMessage({ type: 'SKIP_WAITING' });
          }

          reg.addEventListener('updatefound', () => {
            const w = reg.installing;
            if (!w) return;
            w.addEventListener('statechange', () => {
              if (w.state === 'installed') {
                // Nuevo SW instalado: forzar activación sin esperar tabs
                w.postMessage({ type: 'SKIP_WAITING' });
              }
            });
          });

          // 4. Recargar una vez cuando el nuevo SW tome control (Evitar bucles en dev/localhost)
          let refreshing = false;
          navigator.serviceWorker.addEventListener('controllerchange', () => {
            if (refreshing) return;
            const isLocal = ['localhost', '127.0.0.1', '0.0.0.0'].includes(window.location.hostname) || window.location.hostname.startsWith('192.168.');
            if (isLocal) return;
            refreshing = true;
            window.location.reload();
          });

        } catch (err) {
          console.warn('[SW] Error:', err);
        }
      })();
    </script>
  </body>
</html>
