/* CA Automator — service worker.
   The shell is cached on install so the app opens with no connection at all.
   API responses are never cached: offline data lives in IndexedDB, which the app
   owns, so a stale cached JSON response would only confuse the sync logic. */
const CACHE = 'ca-automator-v89';
const SHELL = ['/', '/index.html', '/style.css', '/landing.js', '/chatbot.js', '/engines.js', '/tp_engines.js', '/forensic_engines.js', '/corporate_engines.js', '/business_engines.js', '/ipo_engines.js', '/tax_advisory_engines.js', '/audit_execution_engines.js', '/acct_engines.js', '/app.js', '/manifest.webmanifest', '/hero-bg.jpg', '/favicon.ico', '/favicon-32.png', '/favicon-16.png', '/apple-touch-icon.png', '/logo-mark.png'];

self.addEventListener('install', e => {
  e.waitUntil(caches.open(CACHE).then(c => c.addAll(SHELL)).then(() => self.skipWaiting()));
});

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

self.addEventListener('fetch', e => {
  const url = new URL(e.request.url);
  if (url.pathname.startsWith('/api/')) return;           // always live
  if (e.request.method !== 'GET') return;

  e.respondWith(
    caches.match(e.request).then(hit => {
      const live = fetch(e.request).then(res => {
        if (res && res.status === 200 && res.type === 'basic') {
          const copy = res.clone();
          caches.open(CACHE).then(c => c.put(e.request, copy));
        }
        return res;
      }).catch(() => hit || caches.match('/index.html'));
      return hit || live;
    })
  );
});
