// Service worker for WakeUpYourSoul.
//
// Strategy:
//   - On install: precache the core shell (HTML, CSS, JS, lang, icons).
//   - On fetch:   cache-first for precached items, network-first for everything
//                 else (so new music tracks load when online, fallback to cache
//                 when offline).
//   - On activate: delete any cache whose name doesn't match CACHE_VERSION.
//
// To force every client to refresh after a deploy, bump CACHE_VERSION below.
// The activate step will purge old caches and the page will start using new
// content within one reload (or two on iOS, where SW updates lag).

const CACHE_VERSION = "wuys-v16";
const CORE_ASSETS = [
  "./",
  "./index.html",
  "./styles.css?v=7",
  "./i18n.js?v=6",
  "./galaxy.js",
  "./emotions.js",
  "./app.js?v=2",
  "./music.js",
  "./lang/en.js?v=1",
  "./lang/da.js?v=3",
  "./lang/fr.js?v=9",
  "./icons/icon-192.png",
  "./icons/icon-512.png",
  "./icons/apple-touch-icon.png",
  "./icons/favicon-32.png",
  "./manifest.json"
];

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE_VERSION)
      .then((cache) => cache.addAll(CORE_ASSETS))
      .then(() => self.skipWaiting())
  );
});

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

self.addEventListener("fetch", (event) => {
  const req = event.request;
  if (req.method !== "GET") return;
  // Only handle same-origin requests so we don't break analytics/CDN calls.
  const url = new URL(req.url);
  if (url.origin !== self.location.origin) return;

  // Network-first for music files so users get fresh streams when online,
  // cache-first for everything else (the shell + lang + icons).
  const isMusic = url.pathname.includes("/music/");
  if (isMusic) {
    event.respondWith(
      fetch(req)
        .then((res) => {
          const copy = res.clone();
          caches.open(CACHE_VERSION).then((c) => c.put(req, copy));
          return res;
        })
        .catch(() => caches.match(req))
    );
    return;
  }

  event.respondWith(
    caches.match(req).then((cached) => {
      if (cached) return cached;
      return fetch(req).then((res) => {
        // Cache successful same-origin responses so subsequent visits work offline.
        if (res && res.ok) {
          const copy = res.clone();
          caches.open(CACHE_VERSION).then((c) => c.put(req, copy));
        }
        return res;
      }).catch(() => cached);
    })
  );
});
