/**
 * Plover CRM Service Worker
 *
 * Handles incoming Web Push notifications and click events.
 * Communicates with the app via BroadcastChannel.
 */

const CHANNEL_NAME = "plover-crm-notifications";

self.addEventListener("push", (event) => {
  if (!event.data) return;

  let payload;
  try {
    payload = event.data.json();
  } catch {
    payload = { title: "Plover CRM", body: event.data.text() };
  }

  const { title = "Plover CRM", body = "", data = {}, icon } = payload;

  // Show the system notification FIRST, then broadcast to open tabs
  const notificationPromise = self.registration
    .showNotification(title, {
      body,
      icon: icon || "/favicon.ico",
      badge: "/favicon.ico",
      data,
      tag: data.subscriber_id ? `lead-${data.subscriber_id}` : undefined,
      requireInteraction: true,
    })
    .then(() => {
      // Broadcast to open tabs AFTER showing system notification
      try {
        const bc = new BroadcastChannel(CHANNEL_NAME);
        bc.postMessage({
          type: "push-received",
          notification: {
            title,
            body,
            data,
            receivedAt: new Date().toISOString(),
          },
        });
        bc.close();
      } catch {
        // BroadcastChannel not available — no-op
      }
    });

  event.waitUntil(notificationPromise);
});

self.addEventListener("notificationclick", (event) => {
  event.notification.close();

  const data = event.notification.data || {};
  const urlPath = data.url || "/dashboard";

  // Build fallback URL with domain param (used only when opening a new tab)
  const separator = urlPath.includes("?") ? "&" : "?";
  const fallbackUrl = data.domain
    ? `${urlPath}${separator}from_domain=${encodeURIComponent(data.domain)}`
    : urlPath;

  event.waitUntil(
    clients
      .matchAll({ type: "window", includeUncontrolled: true })
      .then((windowClients) => {
        // If an existing tab is open, use postMessage directly (more reliable
        // than BroadcastChannel for SW→client communication)
        for (const client of windowClients) {
          if (new URL(client.url).origin === self.location.origin) {
            return client.focus().then((focusedClient) => {
              if (focusedClient) {
                focusedClient.postMessage({
                  type: "notification-clicked",
                  data: { url: urlPath, domain: data.domain || null },
                });
              }
            });
          }
        }
        // No existing tab — open a new one with the domain query param
        return clients.openWindow(fallbackUrl);
      }),
  );
});
