/* ═════════════════════════════════════════
   Service Worker — Listen & Read
   Offline-first for local assets, cache for audio
   ═════════════════════════════════════════ */

const CACHE = 'listen-read-v1';
const ASSETS = [
  './',
  './index.html',
  './builder.html',
  './stories.js',
  './manifest.json',
  './icon.svg'
];

/* Install — cache core assets */
self.addEventListener('install', e => {
  e.waitUntil(
    caches.open(CACHE)
      .then(c => c.addAll(ASSETS))
      .then(() => self.skipWaiting())
  );
});

/* Activate — clean old caches */
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())
  );
});

/* Fetch — smart caching */
self.addEventListener('fetch', e => {
  const req = e.request;
  if (req.method !== 'GET') return;

  const url = new URL(req.url);
  const isAudio = /\.(mp3|wav|m4a|ogg)$/i.test(url.pathname);
  const isLocal = url.origin === self.location.origin;

  /* Audio: cache first (big files, don't re-download) */
  if (isAudio) {
    e.respondWith(
      caches.match(req).then(hit =>
        hit || fetch(req).then(res => {
          const clone = res.clone();
          caches.open(CACHE).then(c => c.put(req, clone));
          return res;
        }).catch(() => new Response('', { status: 404 }))
      )
    );
    return;
  }

  /* Local assets: network first, fallback to cache */
  if (isLocal) {
    e.respondWith(
      fetch(req).then(res => {
        const clone = res.clone();
        caches.open(CACHE).then(c => c.put(req, clone));
        return res;
      }).catch(() =>
        caches.match(req).then(hit => hit || caches.match('./index.html'))
      )
    );
    return;
  }

  /* External (fonts, CDN): cache first */
  e.respondWith(
    caches.match(req).then(hit =>
      hit || fetch(req).then(res => {
        const clone = res.clone();
        caches.open(CACHE).then(c => c.put(req, clone));
        return res;
      }).catch(() => hit)
    )
  );
});