const CACHE_NAME = 'cfc-v21';
const STATIC_ASSETS = [
  '/assets/css/style.css?v=20260718-20',
  '/assets/js/audio-messages.js?v=20260718-20',
  '/assets/js/internal-messages.js?v=20260718-20',
  '/assets/img/vehicle-cutout.png'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => cache.addAll(STATIC_ASSETS)).catch(() => null)
  );
  self.skipWaiting();
});

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

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

  if (request.mode === 'navigate') {
    event.respondWith(fetch(request).catch(() => caches.match((new URL('./index.php?r=home', self.location)).pathname + '?r=home')));
    return;
  }

  // Ícone e manifesto precisam vir sempre atualizados quando o admin troca a logo.
  if (url.pathname.endsWith('/manifest.php') || url.pathname.endsWith('/pwa-icon.php')) {
    event.respondWith(fetch(request).catch(() => caches.match(request)));
    return;
  }

  event.respondWith(
    caches.match(request).then(cached => {
      const network = fetch(request).then(response => {
        if (response && response.status === 200) {
          const copy = response.clone();
          caches.open(CACHE_NAME).then(cache => cache.put(request, copy));
        }
        return response;
      }).catch(() => cached);
      return cached || network;
    })
  );
});
