"""Service Worker – Web Push für Jami."""

PUSH_SW_JS = """/* Jami Web Push */
self.addEventListener('push', (event) => {
  let data = { title: 'Jami', body: 'Neue Nachricht', data: { url: '/' } };
  try {
    if (event.data) data = { ...data, ...event.data.json() };
  } catch (e) {}
  const opts = {
    body: data.body || '',
    icon: data.icon || '/images/lena.jpg',
    badge: data.badge || data.icon || '/images/lena.jpg',
    tag: data.tag || 'jami-chat',
    data: data.data || { url: '/' },
    requireInteraction: false,
  };
  event.waitUntil(self.registration.showNotification(data.title || 'Jami', opts));
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const url = (event.notification.data && event.notification.data.url) || '/';
  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => {
      for (const c of list) {
        if (c.url && 'focus' in c) {
          c.postMessage({ type: 'jami-open-chat', url });
          return c.focus();
        }
      }
      if (clients.openWindow) return clients.openWindow(url);
    })
  );
});

self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (event) => event.waitUntil(clients.claim()));
"""
