// Service Worker — CochranBlock offline-first caching
const CACHE = 'cb-v1';
const ASSETS = ['/', '/assets/css/main.css?v=3', '/assets/favicon.svg?v=9', '/assets/cochranblock-logo.svg?v=9', '/assets/cochranblock-hero-logo.svg?v=9'];

self.addEventListener('install', e => {
  e.waitUntil(caches.open(CACHE).then(c => c.addAll(ASSETS)).then(() => self.skipWaiting()));
});

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

self.addEventListener('fetch', e => {
  if (e.request.method !== 'GET') return;
  e.respondWith(
    caches.match(e.request).then(r => r || fetch(e.request).then(res => {
      if (res.ok && res.type === 'basic') {
        const cl = res.clone();
        caches.open(CACHE).then(c => c.put(e.request, cl));
      }
      return res;
    }).catch(() => caches.match('/')))
  );
});
