self.addEventListener('install', event => {
  event.waitUntil(caches.open('portal-v2').then(cache => cache.addAll(['/portal/login', '/track', '/portal-offline.html'])));
});

self.addEventListener('fetch', event => {
  if (event.request.method !== 'GET') {
    return;
  }

  event.respondWith(
    fetch(event.request)
      .then(response => {
        const copy = response.clone();
        caches.open('portal-v2').then(cache => cache.put(event.request, copy));
        return response;
      })
      .catch(() => caches.match(event.request).then(cached => cached || caches.match('/portal-offline.html')))
  );
});

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

  event.waitUntil(
    self.registration.showNotification(data.title || 'Update Laundry', {
      body: data.body || 'Ada update baru di portal pelanggan.',
      icon: data.icon || '/favicon.ico',
      badge: '/favicon.ico',
      data: { url: data.url || '/portal/notifications' }
    })
  );
});

self.addEventListener('notificationclick', event => {
  event.notification.close();
  const url = event.notification.data?.url || '/portal/notifications';
  event.waitUntil(clients.openWindow(url));
});
