self.addEventListener('push', function (event) {
    console.log('[SW] Push Received', event);
    if (!event.data) {
        console.log('[SW] No data provided in push event');
        return;
    }

    try {
        const data = event.data.json();
        console.log('[SW] Push Data:', data);
        const title = data.title || 'Cat Sitting Planner';
        const options = {
            body: data.body || '',
            icon: '/icon.png',
            badge: '/icon.png',
            data: {
                url: data.url || '/'
            }
        };

        event.waitUntil(
            self.registration.showNotification(title, options)
                .then(() => console.log('[SW] Notification shown'))
                .catch(e => console.error('[SW] Error showing notification:', e))
        );
    } catch (err) {
        console.error('Error processing push event:', err);
    }
});

self.addEventListener('notificationclick', function (event) {
    event.notification.close();
    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then(windowClients => {
            const urlToOpen = event.notification.data.url;

            // Check if there is already a window/tab open with the target URL
            for (let i = 0; i < windowClients.length; i++) {
                const client = windowClients[i];
                if (client.url === urlToOpen && 'focus' in client) {
                    return client.focus();
                }
            }
            // If not, open a new window
            if (clients.openWindow) {
                return clients.openWindow(urlToOpen);
            }
        })
    );
});
