// FILE: /digitalpremium/pwa/sw.js
const CACHE_NAME = 'dp-pwa-v1';
const ASSETS = [
  '/digitalpremium/',
  'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css',
  'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css',
  'https://code.jquery.com/jquery-3.7.0.min.js'
];

self.addEventListener('install', e=>{
  e.waitUntil(caches.open(CACHE_NAME).then(cache=>cache.addAll(ASSETS)));
});

self.addEventListener('activate', e=>{
  e.waitUntil(
    caches.keys().then(keys=>Promise.all(
      keys.filter(k=>k!==CACHE_NAME).map(k=>caches.delete(k))
    ))
  );
});

self.addEventListener('fetch', e=>{
  const req = e.request;
  // Strategy: Stale-While-Revalidate for GET
  if (req.method !== 'GET') return;
  e.respondWith(
    caches.match(req).then(cached=>{
      const fetchPromise = fetch(req).then(resp=>{
        const clone = resp.clone();
        caches.open(CACHE_NAME).then(cache=>cache.put(req, clone));
        return resp;
      }).catch(()=>cached);
      return cached || fetchPromise;
    })
  );
});
