// Cincinnati Fire Department Portal — Service Worker
const CACHE_NAME = 'cfd-portal-v1';
const STATIC_ASSETS = [
  '/assets/css/app.css',
  '/assets/css/ticker.css',
  '/assets/css/toasts.css',
  '/assets/js/app.js',
  '/assets/js/weather.js',
  '/assets/js/ticker.js',
  '/assets/js/toasts.js',
  '/assets/js/radio.js',
  '/assets/img/city-logo.png',
  '/assets/img/cfd-logo.png',
];

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

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

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

  // API calls: network-first
  if (url.pathname.startsWith('/api/')) {
    event.respondWith(
      fetch(event.request).catch(() => caches.match(event.request))
    );
    return;
  }

  // Static assets: cache-first
  event.respondWith(
    caches.match(event.request).then(cached => cached || fetch(event.request))
  );
});
