// Service Worker — Sargasse-Sentry push notifications
self.addEventListener('push', (event) => {
  if (!event.data) return;

  let payload;
  try {
    payload = event.data.json();
  } catch {
    payload = { title: 'Alerte sargasses', body: event.data.text() };
  }

  const title   = payload.title ?? 'Alerte sargasses';
  const options = {
    body:  payload.body ?? '',
    icon:  '/icons.svg',
    badge: '/icons.svg',
    tag:   payload.spotId ? `sargasse-${payload.spotId}` : 'sargasse-alert',
    renotify: true,
    data: { url: payload.url ?? '/' },
  };

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

self.addEventListener('notificationclick', (event) => {
  event.notification.close();

  const targetUrl = event.notification.data?.url ?? '/';

  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
      for (const client of windowClients) {
        if (client.url === targetUrl && 'focus' in client) {
          return client.focus();
        }
      }
      if (clients.openWindow) {
        return clients.openWindow(targetUrl);
      }
    })
  );
});
