/**
 * Rainmaker Service Worker
 * - Cache management on new deployments
 * - Push notification display
 */

const CACHE_VERSION = 'v20260305-1';

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

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(
        keys.filter((key) => key !== CACHE_VERSION).map((key) => caches.delete(key))
      )
    ).then(() => self.clients.claim())
  );
});

// Push notification received
self.addEventListener('push', (event) => {
  if (!event.data) return;
  try {
    const data = event.data.json();
    const options = {
      body: data.body || '',
      icon: data.icon || '/cloud-bolt-logo.webp',
      badge: data.badge || '/cloud-bolt-logo.webp',
      tag: data.tag || 'rainmaker-default',
      data: { url: data.url || '/' },
      vibrate: [100, 50, 100],
    };
    event.waitUntil(
      self.registration.showNotification(data.title || 'Rainmaker Sports', options)
    );
  } catch (err) {
    console.error('Push parse error:', err);
  }
});

// Notification click — open the target URL
self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const url = event.notification.data?.url || '/';
  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
      for (const client of windowClients) {
        if (client.url.includes(self.location.origin) && 'focus' in client) {
          client.navigate(url);
          return client.focus();
        }
      }
      return clients.openWindow(url);
    })
  );
});
