// Imported by Workbox's generated SW (vite.config.ts → workbox.importScripts).
// Adds push handling to the staff PWA.
//
// Payload (sent by StaffPushSender):
//   { title, body, url, icon, badge, tag, persistent }
self.addEventListener('push', (event) => {
  let data = {};
  try { data = event.data ? event.data.json() : {}; } catch { data = {}; }

  const title = data.title || 'Shifa Staff';
  const options = {
    body:    data.body  || '',
    icon:    data.icon  || 'icon-192.png',
    badge:   data.badge || 'icon-192.png',
    tag:     data.tag,
    data:    { url: data.url || '/' },
    requireInteraction: data.persistent === true,
  };

  event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const targetUrl = event.notification.data?.url || '/';
  event.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      for (const client of clientList) {
        if (client.url.includes('/staff-app/') && 'focus' in client) {
          client.navigate(targetUrl);
          return client.focus();
        }
      }
      return self.clients.openWindow(targetUrl);
    })
  );
});
