/* AUDITSITE-WIA — Service Worker (PWA) */
const CACHE = 'auditsite-wia-v3';
const APP_SHELL = [
  './',
  './index.html',
  './app.js',
  './offline.html',
  './manifest.json',
  './icons/favicon.svg',
  './icons/icon-192.png',
  './icons/icon-512.png',
];

// Installation : pré-cache de l'app shell
self.addEventListener('install', (e) => {
  e.waitUntil(
    caches.open(CACHE).then((c) => c.addAll(APP_SHELL)).then(() => self.skipWaiting())
  );
});

// Activation : nettoyage des anciens caches
self.addEventListener('activate', (e) => {
  e.waitUntil(
    caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
      .then(() => self.clients.claim())
  );
});

self.addEventListener('fetch', (e) => {
  const req = e.request;
  if (req.method !== 'GET') return;
  const url = new URL(req.url);

  // Ne jamais mettre en cache les appels d'API (analyse en temps réel)
  if (url.pathname.endsWith('/api.php') || url.pathname.endsWith('api.php')) {
    e.respondWith(fetch(req).catch(() =>
      new Response(JSON.stringify({ ok:false, error:'Vous êtes hors ligne. Reconnectez-vous pour lancer un audit.' }),
        { headers: { 'Content-Type': 'application/json' }, status: 503 })
    ));
    return;
  }

  // Pages, scripts, styles, manifeste : RÉSEAU d'abord (les mises à jour arrivent
  // toujours), repli sur le cache hors-ligne. Évite de servir un vieux app.js.
  const isShell = req.mode === 'navigate' || /\.(html|js|css|json)(\?|$)/i.test(url.pathname);
  if (url.origin === location.origin && isShell) {
    e.respondWith(
      fetch(req).then((res) => {
        const copy = res.clone();
        caches.open(CACHE).then((c) => c.put(req, copy)).catch(()=>{});
        return res;
      }).catch(() => caches.match(req).then((cached) => cached || caches.match('./offline.html')))
    );
    return;
  }

  // Autres ressources same-origin (icônes, images) : cache d'abord
  if (url.origin === location.origin) {
    e.respondWith(
      caches.match(req).then((cached) => cached || fetch(req).then((res) => {
        const copy = res.clone();
        caches.open(CACHE).then((c) => c.put(req, copy)).catch(()=>{});
        return res;
      }).catch(() => caches.match('./offline.html')))
    );
    return;
  }

  // Ressources externes (CDN, polices) : réseau d'abord, repli cache
  e.respondWith(
    fetch(req).then((res) => {
      const copy = res.clone();
      caches.open(CACHE).then((c) => c.put(req, copy)).catch(()=>{});
      return res;
    }).catch(() => caches.match(req))
  );
});
