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

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

self.addEventListener('sync', (event) => {
  if (event.tag === 'upload-queue') {
    event.waitUntil(
      (async () => {
        const clients = await self.clients.matchAll({ includeUncontrolled: true, type: 'window' });
        clients.forEach((client) => client.postMessage({ type: 'sync-queue' }));
      })()
    );
  }
});

self.addEventListener('push', (event) => {
  const payload = event.data?.json?.() ?? {};

  event.waitUntil(
    (async () => {
      const title = payload.title ?? 'Neue Nachricht';
      const options = {
        body: payload.body ?? '',
        icon: '/icons/icon-192.png',
        badge: '/icons/badge.png',
        data: payload.data ?? {},
      };

      await self.registration.showNotification(title, options);

      const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
      clients.forEach((client) => client.postMessage({ type: 'guest-notification-refresh' }));
    })()
  );
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const targetUrl = event.notification.data?.url || '/';

  event.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      for (const client of clientList) {
        if ('focus' in client) {
          client.navigate(targetUrl);
          return client.focus();
        }
      }
      if (self.clients.openWindow) {
        return self.clients.openWindow(targetUrl);
      }
    })
  );
});

self.addEventListener('pushsubscriptionchange', (event) => {
  event.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      clientList.forEach((client) => client.postMessage({ type: 'push-subscription-change' }));
    })
  );
});
