const CACHE_VERSION = 'hontech-portal-pwa-v20260313';
const PRECACHE_URLS = [
  './offline.html',
  './manifest.json',
  './apple-touch-icon.png',
  './pwa-icons/icon-72x72.png',
  './pwa-icons/icon-96x96.png',
  './pwa-icons/icon-128x128.png',
  './pwa-icons/icon-144x144.png',
  './pwa-icons/icon-152x152.png',
  './pwa-icons/icon-180x180.png',
  './pwa-icons/icon-192x192.png',
  './pwa-icons/icon-256x256.png',
  './pwa-icons/icon-384x384.png',
  './pwa-icons/icon-512x512.png'
];
const STATIC_FILE = /\.(?:css|js|png|jpg|jpeg|svg|gif|webp|ico|woff2?|ttf)$/i;

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

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    const keys = await caches.keys();
    await Promise.all(keys.map((key) => key !== CACHE_VERSION ? caches.delete(key) : Promise.resolve()));
    await self.clients.claim();
  })());
});

self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

self.addEventListener('fetch', (event) => {
  const request = event.request;
  if (request.method !== 'GET') return;

  const url = new URL(request.url);
  if (url.origin !== self.location.origin) return;

  const isNavigation = request.mode === 'navigate' || (request.headers.get('accept') || '').includes('text/html');
  const isManifest = url.pathname.endsWith('/manifest.json') || url.pathname.endsWith('manifest.json');
  const isIcon = url.pathname.includes('/pwa-icons/') || url.pathname.endsWith('/apple-touch-icon.png');
  const isStatic = STATIC_FILE.test(url.pathname) || isManifest || isIcon;

  if (isNavigation) {
    event.respondWith((async () => {
      try {
        return await fetch(request, { cache: 'no-store' });
      } catch (error) {
        const cachedOffline = await caches.match('./offline.html');
        return cachedOffline || new Response('Offline', { status: 200, headers: { 'Content-Type': 'text/plain; charset=UTF-8' } });
      }
    })());
    return;
  }

  if (isStatic) {
    event.respondWith((async () => {
      const cached = await caches.match(request);
      const networkFetch = fetch(request).then((response) => {
        if (response && response.ok) {
          caches.open(CACHE_VERSION).then((cache) => cache.put(request, response.clone())).catch(() => undefined);
        }
        return response;
      }).catch(() => cached);
      return cached || networkFetch;
    })());
  }
});
