// FM1 Free Music v2.1 — scoped cache; same-origin only; never cache Spotify/YouTube
var CACHE_PREFIX = 'fm1-v2.1-';
var CACHE_NAME = CACHE_PREFIX + 'static';
var ASSETS = [
  './',
  'index.html',
  'styles.css',
  'fm-pack1.css',
  'fm-v21.css',
  'app.js',
  'tracks.json',
  'download_rights.json',
  'update_catalog_schema.json',
  'cartridge.manifest.json',
  'manifest.json',
  'service-worker.js',
  'feeling-the-energy-64.m4a',
  'feeling-the-energy-96.m4a',
  'god-make-it-my-day-64.m4a',
  'god-make-it-my-day-96.m4a',
  'bootees-boobees-64.m4a',
  'bootees-boobees-96.m4a',
  'feeling-the-energy-cover.png',
  'god-make-it-my-day-cover.jpg',
  'bootees-boobees-cover.png',
  'feeling-the-energy-lyrics.txt',
  'god-make-it-my-day-lyrics.txt',
  'bootees-boobees-lyrics.txt',
  'bootees-boobees-lyrics.png'
];

self.addEventListener('install', function (event) {
  event.waitUntil(
    caches.open(CACHE_NAME).then(function (cache) {
      return Promise.all(ASSETS.map(function (u) {
        return cache.add(u).catch(function () {});
      }));
    }).then(function () { return self.skipWaiting(); })
  );
});

self.addEventListener('activate', function (event) {
  event.waitUntil(
    caches.keys().then(function (keys) {
      return Promise.all(keys.map(function (key) {
        if (key.indexOf(CACHE_PREFIX) === 0 && key !== CACHE_NAME) {
          return caches.delete(key);
        }
      }));
    }).then(function () { return self.clients.claim(); })
  );
});

self.addEventListener('fetch', function (event) {
  if (event.request.method !== 'GET') return;
  var url = new URL(event.request.url);
  if (url.origin !== self.location.origin) return;
  // never cache cross-origin (spotify/youtube) — already returned above
  event.respondWith(
    caches.match(event.request).then(function (cached) {
      if (cached) return cached;
      return fetch(event.request).then(function (resp) {
        if (resp && resp.status === 200 && resp.type === 'basic') {
          var copy = resp.clone();
          caches.open(CACHE_NAME).then(function (c) { c.put(event.request, copy); });
        }
        return resp;
      }).catch(function () {
        return caches.match('index.html');
      });
    })
  );
});
