const CACHE = 'fleetlume-ui-v6-dark-sticky-20260622';
const STATIC_ASSETS = [
  './assets/css/app.css',
  './assets/css/app-v3.css?v=3.0.1',
  './assets/css/app-v4.css?v=4.0.0',
  './assets/css/app-v5.css?v=5.0.0',
  './assets/css/app-v6.css?v=6.0.0',
  './assets/js/app.js',
  './assets/js/app-v3.js?v=3.0.1',
  './assets/js/app-v4.js?v=4.0.0',
  './assets/js/app-v5.js?v=5.0.0',
  './assets/js/app-v6.js?v=6.0.0',
  './assets/images/fleetlume-mark.png',
  './assets/images/icon-192.png',
  './assets/images/icon-512.png'
];

self.addEventListener('install', event => {
  event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(STATIC_ASSETS)).catch(() => {}));
  self.skipWaiting();
});

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

self.addEventListener('fetch', event => {
  if (event.request.method !== 'GET') return;
  const requestUrl = new URL(event.request.url);
  const isStaticAsset = requestUrl.origin === self.location.origin && requestUrl.pathname.includes('/assets/');
  if (!isStaticAsset) return;

  // Network first keeps UI releases fresh while retaining an offline fallback.
  event.respondWith(
    fetch(event.request).then(response => {
      if (response.ok) {
        const copy = response.clone();
        caches.open(CACHE).then(cache => cache.put(event.request, copy));
      }
      return response;
    }).catch(() => caches.match(event.request))
  );
});
