/* Progressive Web App Service Worker */
const CACHE_NAME = "mystery-pwa-v1760682590";
const APP_ASSETS = [
  "./index.html",
  "./manifest.webmanifest",
  "./files/sw.js",
  "./files/02_DE-IOEB-Logo_kurz.svg",
  "./files/artikel.jpg",
  "./files/container.png",
  "./files/exports_interactive_from_user_data.html",
  "./files/bootstrap.min.css",
  "./files/bootstrap.bundle.min.js",
  "./files/karte.jpg",
  "./files/start.jpg",
  "./files/start2.png"
];

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

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    const keys = await caches.keys();
    await Promise.all(keys.map((k) => (k !== CACHE_NAME ? caches.delete(k) : Promise.resolve())));
    await self.clients.claim();
  })());
});

self.addEventListener('fetch', (event) => {
  const req = event.request;
  if (req.mode === 'navigate') {
    event.respondWith((async () => {
      const cache = await caches.open(CACHE_NAME);
      const cached = await cache.match('./index.html');
      return cached || fetch(req);
    })());
    return;
  }
  event.respondWith((async () => {
    const cache = await caches.open(CACHE_NAME);
    const cached = await cache.match(req);
    if (cached) return cached;
    try {
      const res = await fetch(req);
      cache.put(req, res.clone());
      return res;
    } catch (err) {
      const fallback = await cache.match('./index.html');
      return fallback || new Response('Offline', { status: 503, statusText: 'Offline' });
    }
  })());
});
