/* BMS web-push service worker (staff). Shows notifications and focuses the app. */
self.addEventListener('push', function (event) {
  let data = {};
  try { data = event.data ? event.data.json() : {}; } catch (e) { data = { title: 'Banquet', body: event.data ? event.data.text() : '' }; }
  const title = data.title || 'Banquet Ops';
  const options = {
    body: data.body || '',
    icon: 'favicon.ico',
    badge: 'favicon.ico',
    data: data.data || {},
  };
  event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', function (event) {
  event.notification.close();
  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
      for (const c of list) { if ('focus' in c) return c.focus(); }
      if (clients.openWindow) return clients.openWindow('./');
    })
  );
});
