/* Smart Doctor - Service Worker - PWA + Offline + Push */
const CACHE_NAME = 'smart-doctor-v3';
const STATIC_ASSETS = [
  'doctor.php',
  'styles.css',
  'doctor.css',
  'js/doctor.js',
  'favicon.svg',
  'https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js',
  'https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;600;700;800&display=swap'
];

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

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

self.addEventListener('fetch', (e) => {
  const url = new URL(e.request.url);
  
  // API - pass through, return offline response on fail
  if (url.pathname.includes('doctor_api') || url.pathname.includes('api/doctor')) {
    e.respondWith(
      fetch(e.request).catch(() => {
        return new Response(JSON.stringify({ success: false, offline: true, error: 'لا يوجد اتصال' }), {
          headers: { 'Content-Type': 'application/json' }
        });
      })
    );
    return;
  }
  
  if (e.request.method !== 'GET') return;
  
  // Doctor pages and static
  if (url.pathname.includes('doctor') || url.pathname.endsWith('.css') || 
      url.pathname.endsWith('.js') || url.pathname.includes('favicon') || url.pathname.includes('icons/')) {
    e.respondWith(
      fetch(e.request)
        .then((r) => {
          const clone = r.clone();
          caches.open(CACHE_NAME).then((c) => c.put(e.request, clone));
          return r;
        })
        .catch(() => caches.match(e.request).then((r) => r || caches.match('doctor.php')))
    );
  }
});

// Push notifications for critical results
self.addEventListener('push', (e) => {
  let data = { title: 'Smart Doctor', body: 'لديك تنبيه جديد', badge: '/favicon.svg', icon: '/favicon.svg' };
  try {
    if (e.data) data = { ...data, ...e.data.json() };
  } catch (_) {}
  const opts = {
    body: data.body,
    icon: data.icon || '/favicon.svg',
    badge: data.badge || '/favicon.svg',
    data: { url: data.url || '/ss/doctor.php?page=results&critical=1', ...data },
    tag: data.tag || 'smart-doctor',
    requireInteraction: !!data.critical,
    dir: 'rtl',
    lang: 'ar'
  };
  e.waitUntil(self.registration.showNotification(data.title || 'Smart Doctor', opts));
});

self.addEventListener('notificationclick', (e) => {
  e.notification.close();
  const url = e.notification.data?.url || 'doctor.php?page=dashboard';
  e.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => {
      if (list.length) {
        list[0].navigate(url);
        list[0].focus();
      } else if (clients.openWindow) {
        clients.openWindow(url);
      }
    })
  );
});
