const CACHE_NAME = 'chets-schedule-v6';
const CORE_ASSETS = [
  '/',
  '/index.html',
  '/daily.html',
  '/timesheet.html',
  '/stt.html',
  '/vacations.html',
  '/districts.html',
  '/problems.html',
  '/needs.html',
  '/archive.html',
  '/editor.html',
  '/emergency.html',
  '/install.html',
  '/voice.html',
  '/manifest.json',
  '/assets/site-operations.json',
  '/assets/app-icon.svg',
  '/assets/app-icon-192.png',
  '/assets/app-icon-512.png',
  '/assets/save-page.js',
  '/assets/header-left.jpg',
  '/assets/header-right.jpg',
  '/assets/trolleybus-center.jpg'
];

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

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

async function networkFirst(request) {
  const cache = await caches.open(CACHE_NAME);
  try {
    const response = await fetch(request);
    if (response && response.ok) cache.put(request, response.clone()).catch(() => null);
    return response;
  } catch (err) {
    const cached = await caches.match(request);
    return cached || caches.match('/') || new Response('Офлайн: сторінка ще не кешована.', {status: 503, headers: {'Content-Type': 'text/plain; charset=utf-8'}});
  }
}

async function cacheFirst(request) {
  const cached = await caches.match(request);
  if (cached) return cached;
  const cache = await caches.open(CACHE_NAME);
  const response = await fetch(request);
  if (response && response.ok) cache.put(request, response.clone()).catch(() => null);
  return response;
}

self.addEventListener('fetch', event => {
  if (event.request.method !== 'GET') return;
  const url = new URL(event.request.url);
  if (url.origin !== location.origin) return;
  if (url.pathname.match(/\.(png|jpg|jpeg|svg|webp|css|js|json)$/i)) {
    event.respondWith(cacheFirst(event.request));
    return;
  }
  event.respondWith(networkFirst(event.request));
});
