/* MyKollectOr® — Service Worker PWA v1.0 */

const CACHE_NAME = 'mykollector-v1.0';
const ASSETS = [
  './',
  './app.html',
  './index.html',
  './forgot.html',
  './manifest.json',
  './js/auth.js',
  './js/api.js',
  './images/MyKollectOr-LOGO-LOWPOLY-2025-V02.png',
  './images/icon-192.png',
  './images/icon-512.png'
];

self.addEventListener('install', function(e){
  e.waitUntil(
    caches.open(CACHE_NAME).then(function(cache){
      return cache.addAll(ASSETS);
    })
  );
  self.skipWaiting();
});

self.addEventListener('activate', function(e){
  e.waitUntil(
    caches.keys().then(function(keys){
      return Promise.all(
        keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k))
      );
    })
  );
  self.clients.claim();
});

self.addEventListener('fetch', function(e){
  var url = e.request.url;

  // Ne jamais intercepter les appels API ni les fonts
  if(url.includes('api.mykollector.com') || url.includes('fonts.googleapis') || url.includes('fonts.gstatic')){
    e.respondWith(fetch(e.request));
    return;
  }

  // Network-first pour app.html — toujours la dernière version
  if(url.includes('app.html') || url.endsWith('/')){
    e.respondWith(
      fetch(e.request).then(function(response){
        var clone = response.clone();
        caches.open(CACHE_NAME).then(function(cache){ cache.put(e.request, clone); });
        return response;
      }).catch(function(){
        return caches.match(e.request);
      })
    );
    return;
  }

  // Cache-first pour les autres assets statiques
  e.respondWith(
    caches.match(e.request).then(function(cached){
      return cached || fetch(e.request);
    })
  );
});

