'use strict';
const VERSION='v100rc1-distribution';
const STATIC_CACHE=`ds-calisthenie-static-${VERSION}`;
const RUNTIME_CACHE=`ds-calisthenie-runtime-${VERSION}`;
const OFFLINE_CACHE=`ds-calisthenie-offline-${VERSION}`;
const CORE=[
  './','index.html','styles-v100rc1.css?v=100rc1-distribution','app-v100rc1.js?v=100rc1-distribution','manifest.webmanifest',
  'assets/icons/icon-192.png','assets/icons/icon-512.png','assets/muscle-map-male.jpg','assets/hero-duo-clean.jpg'
];
self.addEventListener('install',event=>{
  event.waitUntil(caches.open(STATIC_CACHE).then(c=>c.addAll(CORE)).then(()=>self.skipWaiting()));
});
self.addEventListener('activate',event=>{
  event.waitUntil((async()=>{
    const keep=new Set([STATIC_CACHE,RUNTIME_CACHE,OFFLINE_CACHE]);
    for(const key of await caches.keys()) if(key.startsWith('ds-calisthenie-')&&!keep.has(key)) await caches.delete(key);
    await self.clients.claim();
  })());
});
self.addEventListener('fetch',event=>{
  const req=event.request;if(req.method!=='GET')return;
  const url=new URL(req.url);if(url.origin!==self.location.origin)return;
  if(req.destination==='video'){
    event.respondWith((async()=>{
      const cached=await caches.match(req);if(cached)return cached;
      try{return await fetch(req);}catch{return new Response('',{status:503,statusText:'Vidéo non disponible hors connexion'});}
    })());return;
  }
  if(req.mode==='navigate'){
    event.respondWith((async()=>{
      try{
        const net=await fetch(req);
        const c=await caches.open(RUNTIME_CACHE);c.put('index.html',net.clone());
        return net;
      }catch{
        return (await caches.match('index.html'))||(await caches.match('./'));
      }
    })());return;
  }
  event.respondWith((async()=>{
    const cached=await caches.match(req);if(cached)return cached;
    try{
      const net=await fetch(req);
      if(net.ok){const c=await caches.open(RUNTIME_CACHE);c.put(req,net.clone());}
      return net;
    }catch{return new Response('',{status:503,statusText:'Indisponible hors connexion'});}
  })());
});
async function cacheUrls(urls){
  const cache=await caches.open(OFFLINE_CACHE);
  for(const raw of urls||[]){
    const url=new URL(raw,self.location.href).href;
    const res=await fetch(url,{cache:'reload'});
    if(!res.ok)throw new Error(`HTTP ${res.status} pour ${raw}`);
    await cache.put(url,res.clone());
  }
  return (urls||[]).length;
}
async function checkUrls(urls){
  const missing=[];
  for(const raw of urls||[]){
    const url=new URL(raw,self.location.href).href;
    const hit=await caches.match(url);
    if(!hit)missing.push(raw);
  }
  return {complete:missing.length===0,missing};
}
self.addEventListener('message',event=>{
  const port=event.ports?.[0],type=event.data?.type;
  if(!['CACHE_URLS','CHECK_URLS'].includes(type))return;
  event.waitUntil((async()=>{
    try{
      if(type==='CACHE_URLS'){
        const count=await cacheUrls(event.data.urls||[]);
        port?.postMessage({ok:true,count});
      }else{
        const result=await checkUrls(event.data.urls||[]);
        port?.postMessage({ok:true,...result});
      }
    }catch(e){port?.postMessage({ok:false,error:String(e.message||e)});}
  })());
});
