// Service worker — NETWERK-EERST, zodat updates altijd binnenkomen.
// (De vorige versie was cache-first en bleef oude bestanden tonen.)
const CACHE = 'modelrailpro-v1';
const ASSETS = ['.', 'index.html', 'style.css', 'app.js', 'i18n.js', 'qrcode.js', 'schema.js', 'beheer.js', 'manifest.webmanifest', 'icon.svg'];

self.addEventListener('install', (e) => {
  // nieuwe SW meteen activeren
  self.skipWaiting();
  e.waitUntil(caches.open(CACHE).then((c) => c.addAll(ASSETS)).catch(() => {}));
});

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) => {
  const u = new URL(e.request.url);
  if (e.request.method !== 'GET') return;
  if (u.pathname.startsWith('/api/') || e.request.headers.get('upgrade') === 'websocket') return;
  // Netwerk-eerst: altijd verse versie proberen, cache alleen als terugval (offline).
  e.respondWith(
    fetch(e.request)
      .then((res) => { const copy = res.clone(); caches.open(CACHE).then((c) => c.put(e.request, copy)).catch(() => {}); return res; })
      .catch(() => caches.match(e.request).then((r) => r || caches.match('index.html')))
  );
});
