/* Service Worker for My Truck — Web Push notifications */
/* eslint-disable no-restricted-globals */

const APP_ICON = '/logo-192.png';

self.addEventListener('install', (event) => {
    // Activate immediately on first install
    self.skipWaiting();
});

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

self.addEventListener('push', (event) => {
    let data = {};
    try {
        data = event.data ? event.data.json() : {};
    } catch (_) {
        try { data = { title: event.data && event.data.text() ? event.data.text() : 'Notification' }; } catch (_) {}
    }
    const title = data.title || 'My Truck';
    const body = data.body || '';
    const tag = data.tag || 'mytruck';
    const url = data.url || '/';
    const folderId = data.folder_id;
    event.waitUntil(
        self.registration.showNotification(title, {
            body,
            tag,
            icon: APP_ICON,
            badge: APP_ICON,
            requireInteraction: false,
            data: { url, folderId },
        })
    );
});

self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    const url = (event.notification.data && event.notification.data.url) || '/';
    event.waitUntil((async () => {
        const allClients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
        // If app is already open, focus + navigate it
        for (const client of allClients) {
            try {
                if ('focus' in client) {
                    await client.focus();
                    if ('navigate' in client) {
                        try { await client.navigate(url); } catch (_) {}
                    } else {
                        client.postMessage({ type: 'navigate', url });
                    }
                    return;
                }
            } catch (_) { /* try next */ }
        }
        // Else open a new tab
        if (self.clients.openWindow) {
            await self.clients.openWindow(url);
        }
    })());
});
