self.addEventListener('push', (event) => {
  let payload = {};
  try {
    payload = event.data ? event.data.json() : {};
  } catch (e) {
    payload = { title: 'Nuevo pedido', body: 'Tienes un pedido pendiente.' };
  }

  const title = payload.title || 'Nuevo pedido';
  const options = {
    body: payload.body || 'Tienes un pedido pendiente por aceptar.',
    icon: '/assets/img/favicon/favicon.ico',
    badge: '/assets/img/favicon/favicon.ico',
    data: { url: payload.url || '/courier' },
    tag: payload.tag || 'courier-new-order',
    // Keep the notification visible until the rider interacts (Android Chrome supports this).
    requireInteraction: true,
    // If we re-send a push with the same tag, play sound/vibrate again.
    renotify: true,
    vibrate: [200, 100, 200, 100, 200],
    actions: [
      { action: 'open', title: 'Abrir' },
    ],
  };

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

self.addEventListener('notificationclick', (event) => {
  const action = event.action;
  event.notification.close();
  const rawUrl = event.notification?.data?.url || '/courier';
  const targetUrl = new URL(rawUrl, self.location.origin).href;
  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      for (const client of clientList) {
        if (client.url.startsWith(targetUrl) && 'focus' in client) {
          return client.focus();
        }
        // If user clicked an action, still focus any opened courier tab.
        if (action && client.url.includes('/courier') && 'focus' in client) {
          return client.focus();
        }
      }
      if (clients.openWindow) {
        return clients.openWindow(targetUrl);
      }
    })
  );
});
