const CACHE = 'homesynchub-v9.4.0';
const APP_SHELL = [
  './', './index.php', './offline.html', './manifest.json',
  './assets/css/app.css?v=9.4.0', './assets/js/app.js?v=9.4.0',
  './assets/icons/icon-192.png', './assets/icons/icon-512.png',
  './assets/brand/app-brand-mark.svg', './assets/brand/brand-text-logo.svg',
  './assets/brand/home-sync-hub-dashboard-banner-default.png',
  './assets/brand/home-sync-hub-footer-banner-default.png',
  './assets/brand/family-schedule-commandcenter-integrated.png',
  './assets/brand/high-tech-auth-bg.svg',
  './assets/meals/tapsilog.png', './assets/meals/chicken_adobo.png',
  './assets/meals/turon.png', './assets/meals/sinigang_na_baboy.png',
  './assets/meals/custom_meal.png' // full menu images cache dynamically on first view
];
self.addEventListener('install', event => {
  event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(APP_SHELL)).then(() => 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 request = event.request;
  const accept = request.headers.get('accept') || '';
  const isNavigation = request.mode === 'navigate' || accept.includes('text/html');

  if (isNavigation) {
    event.respondWith(
      fetch(request)
        .then(response => {
          const copy = response.clone();
          caches.open(CACHE).then(cache => cache.put(request, copy)).catch(() => {});
          return response;
        })
        .catch(() => caches.match(request).then(cached => cached || caches.match('./offline.html')))
    );
    return;
  }

  event.respondWith(
    caches.match(request).then(cached => cached || fetch(request).then(response => {
      const copy = response.clone();
      caches.open(CACHE).then(cache => cache.put(request, copy)).catch(() => {});
      return response;
    }).catch(() => caches.match('./offline.html')))
  );
});
