'use strict';

const ARKHON_ICON = '/arkhon-icon.png';

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

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

function normalizePayload(event) {
  try {
    const raw = event.data ? event.data.json() : {};
    return raw && typeof raw === 'object' ? raw : {};
  } catch (_) {
    return {};
  }
}

function notificationOptions(data) {
  const id = data.eventId || data.id || data.type || 'arkhon-live';
  return {
    body: data.body || 'Abre ARKHON Monitor para revisar el detalle.',
    tag: id,
    renotify: true,
    silent: false,
    timestamp: data.timestamp || Date.now(),
    requireInteraction: data.priority === 'alta' || data.priority === 'critica',
    badge: ARKHON_ICON,
    icon: ARKHON_ICON,
    data: {
      url: data.url || '/',
      notification: data,
    },
  };
}

async function notifyOpenClients(data) {
  const allClients = await clients.matchAll({ type: 'window', includeUncontrolled: true });
  allClients.forEach(client => {
    try { client.postMessage({ type: 'arkhon-push', notification: data }); } catch (_) {}
  });
}

self.addEventListener('push', event => {
  const data = normalizePayload(event);
  const title = data.title || 'ARKHON Monitor';
  const options = notificationOptions(data);

  event.waitUntil(Promise.all([
    self.registration.showNotification(title, options),
    notifyOpenClients(data),
  ]));
});

self.addEventListener('notificationclick', event => {
  event.notification.close();
  const rawUrl = (event.notification.data && event.notification.data.url) || '/';
  const targetUrl = new URL(rawUrl, self.location.origin).href;

  event.waitUntil((async () => {
    const allClients = await clients.matchAll({ type: 'window', includeUncontrolled: true });
    for (const client of allClients) {
      const clientUrl = new URL(client.url);
      if (clientUrl.origin !== self.location.origin) continue;
      if ('navigate' in client) await client.navigate(targetUrl);
      if ('focus' in client) return client.focus();
    }
    if (clients.openWindow) return clients.openWindow(targetUrl);
  })());
});

self.addEventListener('notificationclose', event => {
  const notification = event.notification && event.notification.data
    ? event.notification.data.notification
    : null;
  if (notification) event.waitUntil(notifyOpenClients({ ...notification, dismissed: true }));
});
