self.addEventListener('install', () => {
  self.skipWaiting();
});

self.addEventListener('activate', (event) => {
  event.waitUntil(self.clients.claim());
});

self.addEventListener('notificationclick', (event) => {
  const notification = event.notification;
  const data = notification.data || {};
  const action = event.action || 'open';
  notification.close();

  event.waitUntil((async () => {
    const targetUrl = data.url || '/';
    const allClients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });

    let client = allClients.find((c) => 'focus' in c);
    if (client) {
      try { await client.focus(); } catch (_) {}
    } else if (self.clients.openWindow) {
      try { client = await self.clients.openWindow(targetUrl); } catch (_) {}
    }

    if (client) {
      try {
        client.postMessage({
          type: 'notification-action',
          action,
          alertId: data.alertId,
          orderIds: Array.isArray(data.orderIds) ? data.orderIds : [],
          bookingIds: Array.isArray(data.bookingIds) ? data.bookingIds : [],
        });
      } catch (_) {}
    }
  })());
});
