/* ============================================================
   COPPER_AGENT_CARTRIDGE — service-worker.js
   Created: 2026-06-26  Reason: offline-first caching so the
   cartridge runs with ZERO network requests after first load.
   Byte-identical across all three targets: precaches the common
   core, then runtime-caches any same-origin GET (this picks up
   each target's differently-named adapter without naming it).
   ============================================================ */
// 2026-06-26 LAUNCH PATCH: scope cache cleanup to THIS cartridge only.
// Reason: a blanket "delete every cache except current" would wipe sibling
// cartridge caches (calculator, fertility, secure-nodes, etc.). Cleanup below
// now deletes only old copper- versions.
var CACHE_PREFIX='copper-';
var CACHE=CACHE_PREFIX+'static-v1.1';
var CORE=['./','index.html','styles.css','content.js','app.js','direct-platform-adapter.js','cartridge.manifest.json','service-worker.js','assets/icon.svg'];

self.addEventListener('install',function(e){
  self.skipWaiting();
  e.waitUntil(caches.open(CACHE).then(function(c){
    return Promise.all(CORE.map(function(u){return c.add(u).catch(function(){});}));
  }));
});

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

self.addEventListener('fetch',function(e){
  var req=e.request;
  if(req.method!=='GET'){return;}
  if(new URL(req.url).origin!==self.location.origin){return;}
  e.respondWith(
    caches.match(req).then(function(hit){
      if(hit)return hit;
      return fetch(req).then(function(res){
        if(res&&res.status===200&&res.type==='basic'){
          var copy=res.clone();
          caches.open(CACHE).then(function(c){c.put(req,copy);});
        }
        return res;
      }).catch(function(){return caches.match('index.html');});
    })
  );
});
