// 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())
  );
});

// ---- Push: anomalie-meldingen van de baan -----------------------------
self.addEventListener('push', (e) => {
  let d = {};
  try { d = e.data ? e.data.json() : {}; } catch (_) { d = { body: e.data ? e.data.text() : '' }; }
  const title = d.title || 'ModelRailPro';
  e.waitUntil(self.registration.showNotification(title, {
    body: d.body || '',
    tag: d.tag || 'mrp',
    icon: 'icon.svg',
    badge: 'icon.svg',
    data: { url: d.url || '/app/' },
    vibrate: [80, 40, 80],
  }));
});
self.addEventListener('notificationclick', (e) => {
  e.notification.close();
  const url = (e.notification.data && e.notification.data.url) || '/app/';
  e.waitUntil(self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((cs) => {
    for (const c of cs) { if ('focus' in c) return c.focus(); }
    if (self.clients.openWindow) return self.clients.openWindow(url);
  }));
});

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')))
  );
});
