// HR Pro Service Worker v2.0
const CACHE_NAME = 'hrpro-v13';
const STATIC_ASSETS = [
  '/hr/login.html',
  '/hr/admin.html',
  '/hr/contacts.html',
  '/hr/manifest.json',
  '/hr/manifest-admin.json',
  '/hr/index.html',
  '/hr/att_sound.mp3',
  '/hr/favicon.ico',
  '/hr/hrpro-theme.css',
  '/hr/hrpro-theme.js',
  '/hr/admin-page.js',
  '/hr/login-page.js',
];

self.addEventListener('install', (e) => {
  e.waitUntil(
    caches.open(CACHE_NAME).then(cache =>
      // FIX: allSettled بدل addAll — لو ملف واحد فشل الباقي بيتحفظ عادي
      Promise.allSettled(
        STATIC_ASSETS.map(url =>
          cache.add(url).catch(err => console.warn('[SW] Failed to cache:', url, err))
        )
      )
    )
  );
  self.skipWaiting();
});

self.addEventListener('message', (e) => {
  const d = e.data;
  if (d && d.type === 'HRPRO_SKIP_WAITING') {
    self.skipWaiting();
  }
});

self.addEventListener('activate', (e) => {
  e.waitUntil(
    caches.keys().then(keys =>
      Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
    )
  );
  self.clients.claim();
  e.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {
      for (const c of clients) {
        try {
          c.postMessage({ type: 'HRPRO_SW_UPDATED', cache: CACHE_NAME });
        } catch (err) { /* ignore */ }
      }
    })
  );
});

self.addEventListener('fetch', (e) => {
  const url = new URL(e.request.url);
  // Always go network for API calls
  if (url.pathname.includes('api.php')) {
    e.respondWith(fetch(e.request));
    return;
  }

  // For navigation + app shell assets: prefer network (fresh) with cache fallback.
  const isNav = e.request.mode === 'navigate';
  const dest = e.request.destination || '';
  const isShellAsset = isNav || dest === 'script' || dest === 'style' || dest === 'document';

  if (isShellAsset) {
    e.respondWith(
      fetch(e.request, { cache: 'no-cache' })
        .then((res) => {
          const copy = res.clone();
          caches.open(CACHE_NAME).then((cache) => cache.put(e.request, copy)).catch(() => {});
          return res;
        })
        .catch(() => caches.match(e.request))
    );
    return;
  }

  // Everything else: cache-first for speed.
  e.respondWith(
    caches.match(e.request).then((cached) =>
      cached || fetch(e.request, { cache: 'no-cache' })
    )
  );
});

self.addEventListener('push', (e) => {
  let data = { title: 'HR Pro', body: '', url: '/hr/admin.html?hrpro_pwa=admin' };
  if (e.data) {
    try {
      const parsed = e.data.json();
      if (parsed && typeof parsed === 'object') data = { ...data, ...parsed };
    } catch (err) {
      try {
        const t = e.data.text();
        if (t) data.body = t.slice(0, 200);
      } catch (e2) { /* ignore */ }
    }
  }
  const openUrl = data.url || '/hr/admin.html?hrpro_pwa=admin';
  e.waitUntil(
    self.registration.showNotification(data.title || 'HR Pro', {
      body: data.body || '',
      icon: '/hr/favicon.ico',
      badge: '/hr/favicon.ico',
      tag: String(data.tag || 'hrpro-push'),
      renotify: true,
      requireInteraction: !!data.requireInteraction,
      silent: false,
      vibrate: [160, 80, 160],
      data: { url: openUrl },
    })
  );
});

self.addEventListener('notificationclick', (e) => {
  e.notification.close();
  const raw = e.notification.data;
  let url = '/hr/admin.html?hrpro_pwa=admin';
  if (typeof raw === 'string') url = raw;
  else if (raw && raw.url) url = raw.url;
  e.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      for (const c of clientList) {
        if (c.url && 'focus' in c) {
          try {
            c.postMessage({ type: 'HRPRO_PUSH_NAV', url });
          } catch (err) { /* ignore */ }
          return c.focus();
        }
      }
      if (self.clients.openWindow) return self.clients.openWindow(url);
    })
  );
});