/* MediCore Service Worker — static asset caching + offline fallback */
const CACHE = 'medicore-v1';
const STATIC = [
  'assets/style.css',
  'assets/offline.js',
];

self.addEventListener('install', e => {
  e.waitUntil(
    caches.open(CACHE)
      .then(c => c.addAll(STATIC))
      .catch(() => {}) // non-fatal — SW still installs even if cache fails
  );
  self.skipWaiting();
});

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

self.addEventListener('fetch', e => {
  const url = e.request.url;

  // Never intercept POST (API calls) — handled by offline.js in the page
  if (e.request.method !== 'GET') return;

  // PHP pages — network only (always fresh from server)
  if (url.includes('.php')) return;

  // Static assets — cache first, network fallback
  if (url.match(/\.(css|js|woff2?|ttf|png|svg|ico)$/)) {
    e.respondWith(
      caches.match(e.request).then(cached => {
        if (cached) return cached;
        return fetch(e.request).then(res => {
          if (res.ok) {
            const clone = res.clone();
            caches.open(CACHE).then(c => c.put(e.request, clone));
          }
          return res;
        }).catch(() => cached || new Response('', { status: 503 }));
      })
    );
  }
});
