// DST Collection — Service Worker
// Push Notification + Install/Activate Handler

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

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

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

    let data = {};
    try {
        data = event.data.json();
    } catch {
        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,
    };

    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 ('focus' in client) {
                        return client.navigate(targetUrl).then((c) => c && c.focus());
                    }
                }
                return self.clients.openWindow(targetUrl);
            }),
    );
});
