const CACHE = 'jarvis-v1';
const SHELL = [
  '/static/style.css',
  '/static/app.js',
  '/static/icon.png',
  '/static/logo.png',
];

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

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

self.addEventListener('fetch', e => {
  const url = new URL(e.request.url);
  if (url.pathname.startsWith('/static/')) {
    // Cache-first for static assets
    e.respondWith(
      caches.match(e.request).then(r => r || fetch(e.request))
    );
  } else {
    // Network-first for everything else (pages, API)
    e.respondWith(
      fetch(e.request).catch(() => caches.match(e.request))
    );
  }
});
