// This line is required by vite-plugin-pwa's injectManifest strategy —
// it's the token the build looks for to inject the precache list.
// We don't use it for anything (no offline caching), so it's discarded.
self.__WB_MANIFEST;

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

    const data = event.data.json();

    event.waitUntil(
        self.registration.showNotification(data.title, {
            body: data.body,
            icon: data.icon || '/img/app_icons/icon-192.png',
            badge: '/img/app_icons/icon-192.png',
            data: data.data,
        })
    );
});

self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    const url = event.notification.data?.url || '/';

    event.waitUntil(
        self.clients.matchAll({ type: 'window' }).then((clientList) => {
            for (const client of clientList) {
                if (client.url.includes(url) && 'focus' in client) {
                    return client.focus();
                }
            }
            if (self.clients.openWindow) {
                return self.clients.openWindow(url);
            }
        })
    );
});
