// Service Worker for push notifications and PWA support
self.addEventListener('push', event => {
  if (!event.data) return;
  const data = event.data.json();
  const notifUrl = data.url || '/';

  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then(clientList => {
      // Suppress notification if the user already has the relevant page focused
      for (const client of clientList) {
        if (client.visibilityState === 'visible' && client.url.includes(notifUrl)) {
          return;
        }
      }
      return self.registration.showNotification(data.title || 'Scribe', {
        body: data.body || '',
        icon: '/favicon.ico',
        badge: '/favicon.ico',
        data: { url: notifUrl },
      });
    })
  );
});

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

// PWA: serve cached assets for offline support (minimal)
self.addEventListener('fetch', event => {
  // Pass-through — no offline caching in v1
});
