// Dabil service worker — handles Web Push display + click.
self.addEventListener('install', function () { self.skipWaiting(); });
self.addEventListener('activate', function (e) { e.waitUntil(self.clients.claim()); });

self.addEventListener('push', function (event) {
  let data = {};
  try { data = event.data ? event.data.json() : {}; }
  catch (e) { data = { title: 'Dabil', body: event.data ? event.data.text() : '' }; }

  const title = data.title || 'Dabil';
  const options = {
    body: data.body || '',
    icon: data.icon || 'assets/img/noticon.png',
    badge: 'assets/img/noticon.png',
    tag: data.tag || undefined,
    data: { url: data.url || 'dashboard.php' }
  };
  event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', function (event) {
  event.notification.close();
  const target = (event.notification.data && event.notification.data.url) || 'dashboard.php';
  event.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
      for (const c of list) {
        if ('focus' in c) { try { c.navigate(target); } catch (e) {} return c.focus(); }
      }
      if (self.clients.openWindow) return self.clients.openWindow(target);
    })
  );
});
