// socialmediamanager/public/service-worker.js
const CACHE = "smm-phase3-v1";
const ASSETS = [
  "./index.php",
  "./manifest.webmanifest",
  "./assets/css/style.css",
  "./assets/js/app.js",
  "./assets/icons/icon-192.png",
  "./assets/icons/icon-512.png",
];

self.addEventListener("install",(e)=>e.waitUntil((async()=>{
  const c=await caches.open(CACHE);
  await c.addAll(ASSETS);
  self.skipWaiting();
})()));

self.addEventListener("activate",(e)=>e.waitUntil((async()=>{
  const keys=await caches.keys();
  await Promise.all(keys.map(k=>k===CACHE?null:caches.delete(k)));
  self.clients.claim();
})()));

self.addEventListener("fetch",(e)=>{
  const url=new URL(e.request.url);
  if(url.pathname.includes("/api/")){
    e.respondWith(fetch(e.request).catch(()=>caches.match(e.request)));
    return;
  }
  e.respondWith((async()=>{
    const cached=await caches.match(e.request);
    if(cached) return cached;
    const fresh=await fetch(e.request);
    const c=await caches.open(CACHE);
    c.put(e.request, fresh.clone());
    return fresh;
  })());
});
