// ============================================
// BAITARI - Service Worker v1.0
// ============================================
const CACHE_NAME = 'baitari-v1.0.0';
const STATIC_ASSETS = [
  '/',
  '/index.html',
  '/login.php',
  '/manifest.json',
  '/lang/ar.js',
  '/lang/fr.js',
  '/lang/en.js',
  '/pages/vet-profile.html',
  'https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap',
];

// ── INSTALL: cache static assets ──
self.addEventListener('install', event => {
  console.log('[SW] Installing...');
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      return cache.addAll(STATIC_ASSETS.map(url => new Request(url, { cache: 'reload' })))
        .catch(err => console.warn('[SW] Cache failed for some assets:', err));
    }).then(() => self.skipWaiting())
  );
});

// ── ACTIVATE: cleanup old caches ──
self.addEventListener('activate', event => {
  console.log('[SW] Activating...');
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(
        keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k))
      )
    ).then(() => self.clients.claim())
  );
});

// ── FETCH: network-first for API, cache-first for static ──
self.addEventListener('fetch', event => {
  const { request } = event;
  const url = new URL(request.url);

  // Skip non-GET and external requests
  if (request.method !== 'GET') return;
  if (!url.origin.includes(self.location.origin) && !url.hostname.includes('fonts.googleapis.com')) return;

  // API calls: network-only with offline fallback
  if (url.pathname.startsWith('/api/')) {
    event.respondWith(
      fetch(request).catch(() =>
        new Response(
          JSON.stringify({ error: 'offline', message: 'أنت غير متصل بالإنترنت' }),
          { headers: { 'Content-Type': 'application/json' } }
        )
      )
    );
    return;
  }

  // Static assets: cache-first, fallback to network
  event.respondWith(
    caches.match(request).then(cached => {
      if (cached) return cached;
      return fetch(request).then(response => {
        if (response.ok) {
          const clone = response.clone();
          caches.open(CACHE_NAME).then(cache => cache.put(request, clone));
        }
        return response;
      }).catch(() => {
        // Offline fallback for HTML pages
        if (request.destination === 'document') {
          return caches.match('/index.html');
        }
      });
    })
  );
});

// ── PUSH NOTIFICATIONS ──
self.addEventListener('push', event => {
  const data = event.data ? event.data.json() : {};
  const options = {
    body: data.body || 'لديك إشعار جديد من بيطري',
    icon: '/assets/img/icon-192.png',
    badge: '/assets/img/badge-72.png',
    tag: data.tag || 'baitari-notif',
    dir: 'rtl',
    lang: 'ar',
    vibrate: [200, 100, 200],
    data: { url: data.url || '/' },
    actions: data.actions || [
      { action: 'view', title: 'عرض' },
      { action: 'dismiss', title: 'إغلاق' },
    ],
  };
  event.waitUntil(
    self.registration.showNotification(
      data.title || 'بيطري 🐾',
      options
    )
  );
});

// ── NOTIFICATION CLICK ──
self.addEventListener('notificationclick', event => {
  event.notification.close();
  if (event.action === 'dismiss') return;
  const url = event.notification.data?.url || '/';
  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then(windowClients => {
      for (const client of windowClients) {
        if (client.url === url && 'focus' in client) return client.focus();
      }
      if (clients.openWindow) return clients.openWindow(url);
    })
  );
});

// ── BACKGROUND SYNC (for offline bookings) ──
self.addEventListener('sync', event => {
  if (event.tag === 'sync-bookings') {
    event.waitUntil(syncPendingBookings());
  }
  if (event.tag === 'sync-emergencies') {
    event.waitUntil(syncPendingEmergencies());
  }
});

async function syncPendingBookings() {
  try {
    // In production: read from IndexedDB and send to API
    const pending = await getPendingFromIDB('pending-bookings');
    for (const booking of pending) {
      await fetch('/api/?action=book_appointment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(booking),
      });
    }
  } catch (err) {
    console.error('[SW] Sync failed:', err);
  }
}

async function syncPendingEmergencies() {
  try {
    const pending = await getPendingFromIDB('pending-emergencies');
    for (const emg of pending) {
      await fetch('/api/?action=emergency_request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(emg),
      });
    }
  } catch (err) {
    console.error('[SW] Emergency sync failed:', err);
  }
}

function getPendingFromIDB(storeName) {
  return new Promise((resolve) => resolve([])); // Placeholder
}
