// Custom Service Worker for Push Notifications
self.addEventListener('push', function (event) {
    console.log('[SW] Push event received:', event);

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

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

    const promiseChain = self.registration.showNotification(
        notificationData.title,
        {
            body: notificationData.body,
            icon: notificationData.icon,
            badge: notificationData.badge,
            vibrate: notificationData.vibrate,
            requireInteraction: notificationData.requireInteraction,
            tag: notificationData.tag
        }
    );

    event.waitUntil(promiseChain);
});

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

    event.waitUntil(
        clients.openWindow('/')
    );
});
