// Push notification event handler
// This will be injected into the Service Worker

self.addEventListener('push', function (event) {
    console.log('[SW Push] Push event received');

    let notificationData = {
        title: 'snStatus Alert',
        body: 'System alert',
        icon: '/pwa-192x192.png',
        badge: '/pwa-192x192.png',
        vibrate: [200, 100, 200],
        requireInteraction: true,
        tag: 'snstatus-alert',
        data: {
            url: '/'
        }
    };

    if (event.data) {
        try {
            const data = event.data.json();
            console.log('[SW Push] Data:', data);
            if (data.title) notificationData.title = data.title;
            if (data.body) notificationData.body = data.body;
            if (data.icon) notificationData.icon = data.icon;
        } catch (e) {
            console.error('[SW Push] Parse error:', e);
            notificationData.body = event.data.text();
        }
    }

    event.waitUntil(
        self.registration.showNotification(notificationData.title, {
            body: notificationData.body,
            icon: notificationData.icon,
            badge: notificationData.badge,
            vibrate: notificationData.vibrate,
            requireInteraction: notificationData.requireInteraction,
            tag: notificationData.tag,
            data: notificationData.data
        })
    );
});

self.addEventListener('notificationclick', function (event) {
    console.log('[SW] Notification clicked');
    event.notification.close();

    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true })
            .then(function (clientList) {
                // Focus existing window if available
                for (let i = 0; i < clientList.length; i++) {
                    const client = clientList[i];
                    if (client.url === '/' && 'focus' in client) {
                        return client.focus();
                    }
                }
                // Open new window
                if (clients.openWindow) {
                    return clients.openWindow('/');
                }
            })
    );
});
