const CACHE_NAME = 'Agora-v1.5.5';
const STATIC_ASSETS = [
  '/style.css',
  '/app.auth.js',
  '/app.js',
  '/manifest.json',
  '/images/icone-192.png',
  '/images/icone-512.png',
  '/images/logo_transparent.png',
  '/lucide.min.js'
];

// 1. INSTALLATION
self.addEventListener('install', event => {
  self.skipWaiting();
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      console.log('[SW] Mise en cache des fichiers statiques');
      return cache.addAll(STATIC_ASSETS);
    })
  );
});

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cache => {
          if (cache !== CACHE_NAME) {
            console.log('[SW] Suppression ancien cache:', cache);
            return caches.delete(cache);
          }
        })
      );
    })
  );
  return self.clients.claim();
});

self.addEventListener('fetch', event => {
  const url = new URL(event.request.url);

  const isStaticAsset = url.pathname.endsWith('.css') ||
    url.pathname.endsWith('.js') ||
    url.pathname.endsWith('.png') ||
    url.pathname.endsWith('.json');

  if (!isStaticAsset || event.request.method !== 'GET' || !url.protocol.startsWith('http')) {
    return;
  }

  // Stratégie Network-First : on tente le réseau, et on met à jour le cache. Sinon, fallback sur le cache.
  event.respondWith(
    fetch(event.request)
      .then(response => {
        if (response && response.status === 200) {
          const responseCopy = response.clone();
          caches.open(CACHE_NAME).then(cache => {
            cache.put(event.request, responseCopy);
          });
        }
        return response;
      })
      .catch(() => {
        return caches.match(event.request);
      })
  );
});