/* Ashley Timer SW - Enhanced */
const VERSION = 'at-v3-' + (self.registration ? self.registration.scope : Math.random());
const APP_SHELL = [
  '/ashleytimer/',
  '/ashleytimer/index.html',
  '/ashleytimer/site.webmanifest',
  '/ashleytimer/icons/icon-192.png',
  '/ashleytimer/icons/icon-512.png',
  '/ashleytimer/icons/icon-512-maskable.png',
  '/ashleytimer/assets/rain-soft.mp3',
  '/ashleytimer/three.min.js'
];

self.addEventListener('install', (e) => {
  console.log('Service Worker installing');
  e.waitUntil(
    caches.open(VERSION)
      .then((cache) => {
        console.log('Caching app shell');
        return cache.addAll(APP_SHELL);
      })
      .then(() => {
        console.log('Skip waiting');
        return self.skipWaiting();
      })
      .catch(err => console.error('Install failed:', err))
  );
});

self.addEventListener('activate', (e) => {
  console.log('Service Worker activating');
  e.waitUntil(
    (async () => {
      const keys = await caches.keys();
      await Promise.all(
        keys.filter(k => k !== VERSION)
          .map(k => {
            console.log('Deleting old cache:', k);
            return caches.delete(k);
          })
      );
      console.log('Claiming clients');
      await self.clients.claim();
    })()
  );
});

self.addEventListener('fetch', (e) => {
  const req = e.request;
  
  // Skip non-GET requests
  if (req.method !== 'GET') return;

  // HTML: network-first
  if (req.mode === 'navigate') {
    e.respondWith(
      (async () => {
        try {
          const networkResponse = await fetch(req);
          const cache = await caches.open(VERSION);
          cache.put(req, networkResponse.clone());
          return networkResponse;
        } catch (error) {
          const cached = await caches.match('/ashleytimer/index.html');
          return cached || new Response('Offline', { status: 503 });
        }
      })()
    );
    return;
  }

  // Static assets: cache-first
  if (APP_SHELL.some(url => req.url.includes(url))) {
    e.respondWith(
      caches.match(req).then(cached => {
        return cached || fetch(req).then(networkResponse => {
          const cacheCopy = networkResponse.clone();
          caches.open(VERSION).then(cache => cache.put(req, cacheCopy));
          return networkResponse;
        });
      })
    );
    return;
  }

  // Other: network-first
  e.respondWith(
    fetch(req).catch(() => caches.match(req))
  );
});

// Background sync for timer persistence
self.addEventListener('sync', (event) => {
  if (event.tag === 'timer-sync') {
    console.log('Background sync for timer');
    event.waitUntil(
      Promise.resolve().then(() => {
        return self.clients.matchAll().then(clients => {
          clients.forEach(client => {
            client.postMessage({
              type: 'TIMER_SYNC',
              timestamp: Date.now()
            });
          });
        });
      })
    );
  }
});

// Handle messages from main app
self.addEventListener('message', (e) => {
  if (e.data === 'SKIP_WAITING') {
    self.skipWaiting().then(() => {
      self.clients.claim().then(() => {
        self.clients.matchAll().then(clients => {
          clients.forEach(client => client.postMessage({ type: 'RELOAD_PAGE' }));
        });
      });
    });
  }
  
  if (e.data.type === 'REGISTER_BG_SYNC') {
    self.registration.sync.register('timer-sync')
      .then(() => console.log('Background sync registered'))
      .catch(err => console.warn('Background sync failed:', err));
  }
});