// public/service-worker.js
const CACHE_NAME = 'sociowire-v9';
const PRECACHE = [
  '/icons/icon-192x192.png',
  '/icons/icon-512x512.png',
  '/icons/apple-touch-icon.png',
  '/icons/og-image.png'
];

self.addEventListener('install', event => {
  self.skipWaiting();
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      return cache.addAll(PRECACHE);
    })
  );
});

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(keys.map(key => (key === CACHE_NAME ? null : caches.delete(key))))
    ).then(() => self.clients.claim())
  );
});

self.addEventListener('fetch', event => {
  const url = new URL(event.request.url);

  // Never cache API calls or auth endpoints - always fetch fresh data
  const isAPI = url.pathname.startsWith('/api/') || url.pathname.startsWith('/ws') || url.pathname.startsWith('/auth');
  if (isAPI) {
    event.respondWith(fetch(event.request));
    return;
  }

  const isAsset = url.pathname.startsWith('/assets/');
  if (isAsset) {
    event.respondWith(fetch(event.request));
    return;
  }
  if (event.request.mode === 'navigate') {
    event.respondWith(
      fetch(event.request)
        .catch(() => caches.match('/'))
    );
    return;
  }

  event.respondWith(
    caches.match(event.request).then(response => response || fetch(event.request))
  );
});
