self.addEventListener('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 (_) {
        data = {};
    }
    const title = data.notification?.title || data.title || 'New offer';
    const body = data.notification?.body || data.body || '';
    const icon = data.notification?.icon || data.icon || '/favicon.ico';
    const badge = data.notification?.badge || data.badge || '/favicon.ico';
    const clickUrl = data.data?.clickUrl || data.clickUrl || '/';
    event.waitUntil(
        self.registration.showNotification(title, {
            body,
            icon,
            badge,
            data: { clickUrl }
        })
    );
});

self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    const clickUrl = event.notification?.data?.clickUrl || '/';
    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
            for (let i = 0; i < windowClients.length; i++) {
                const c = windowClients[i];
                if ('focus' in c) {
                    c.navigate(clickUrl);
                    return c.focus();
                }
            }
            if (clients.openWindow) return clients.openWindow(clickUrl);
            return Promise.resolve();
        })
    );
});
