// DST Collection — Service Worker
// Push Notification Handler

const CACHE_NAME = 'dst-v1';

// ── Install ──────────────────────────────────────────────────────────────────
self.addEventListener('install', () => {
    self.skipWaiting();
});

// ── Activate ─────────────────────────────────────────────────────────────────
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches
            .keys()
            .then((keys) =>
                Promise.all(
                    keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)),
                ),
            )
            .then(() => self.clients.claim()),
    );
});

// ── Push Notification ─────────────────────────────────────────────────────────
self.addEventListener('push', (event) => {
    if (!event.data) return;

    let data = {};
    try {
        data = event.data.json();
    } catch (e) {
        data = { title: 'DST Collection', body: event.data.text() };
    }

    const title = data.title || 'DST Collection';
    const options = {
        body: data.body || '',
        icon: data.icon || '/assets/pwa-192x192.png',
        badge: '/assets/pwa-64x64.png',
        data: { url: data.url || '/admin/master/categories' },
        tag: 'dst-notification',
        renotify: true,
        requireInteraction: false,
    };

    event.waitUntil(self.registration.showNotification(title, options));
});

// ── Notification Click ────────────────────────────────────────────────────────
self.addEventListener('notificationclick', (event) => {
    event.notification.close();

    const targetUrl = (event.notification.data && event.notification.data.url)
        ? event.notification.data.url
        : '/admin/dashboard';

    event.waitUntil(
        self.clients
            .matchAll({ type: 'window', includeUncontrolled: true })
            .then((clientList) => {
                for (const client of clientList) {
                    if ('navigate' in client) {
                        return client.navigate(targetUrl).then((c) => c && c.focus());
                    }
                }
                return self.clients.openWindow(targetUrl);
            }),
    );
});
