self.addEventListener('push', event => {
  const data = event.data ? event.data.json() : {};
  const title = data.title || 'Notification';
  console.log('notification dat i recive', data);
  const rawUrl = data.url || (data.requestNumber ? `/request/${data.requestNumber}` : '/');
  const absoluteUrl = /^https?:\/\//i.test(rawUrl) ? rawUrl : (self.location.origin + rawUrl);
  const options = {
    body: data.body || 'New message',
    icon: '/royal_enfield_logo.png',
    badge: '/royal_enfield_logo.png',
    data: { url: absoluteUrl }
  };
  console.log('options', options);
  event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', function (event) {
  event.notification.close();
  const targetUrl = (event.notification && event.notification.data && event.notification.data.url) || (self.location.origin + '/');
  event.waitUntil((async () => {
    // Always open a new window/tab to ensure SPA router picks up the correct path
    if (clients.openWindow) return clients.openWindow(targetUrl);
  })());
});


