/* Seven Digital — Web Push service worker */
self.addEventListener('install', e => self.skipWaiting());
self.addEventListener('activate', e => e.waitUntil(self.clients.claim()));

self.addEventListener('push', event => {
    let data = { title: 'Seven Digital', body: 'You have a new request', url: './' };
    try { if (event.data) data = Object.assign(data, event.data.json()); }
    catch (_) { if (event.data) data.body = event.data.text(); }

    const opts = {
        body: data.body || '',
        icon: data.icon || 'assets/7.png',
        badge: data.badge || 'assets/7.png',
        data: { url: data.url || './' },
        vibrate: [200, 100, 200],
        tag: data.tag || ('sd-' + Date.now()),
        renotify: true,
        requireInteraction: false
    };
    const jobs = [ self.registration.showNotification(data.title || 'Seven Digital', opts) ];
    if (typeof data.badge === 'number' && self.navigator && 'setAppBadge' in self.navigator) {
        jobs.push(self.navigator.setAppBadge(data.badge).catch(function(){}));
    }
    event.waitUntil(Promise.all(jobs));
});

self.addEventListener('notificationclick', event => {
    event.notification.close();
    const target = (event.notification.data && event.notification.data.url) || './';
    event.waitUntil(
        self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(list => {
            for (const c of list) {
                if ('focus' in c) { try { c.navigate(target); } catch (_) {} return c.focus(); }
            }
            if (self.clients.openWindow) return self.clients.openWindow(target);
        })
    );
});