// Service Worker for Push Notifications
self.addEventListener('push', function(event) {
    const data = event.data ? event.data.json() : {};

    const options = {
        body: data.body || 'You have a new notification',
        icon: '/Capstone_Project/assets/images/logo.png',
        badge: '/Capstone_Project/assets/images/badge.png',
        vibrate: [200, 100, 200],
        data: {
            url: data.url || '/Capstone_Project/student/dashboard.php',
            activity_id: data.activity_id
        },
        actions: data.activity_id ? [
            { action: 'view', title: 'View Activity' },
            { action: 'close', title: 'Close' }
        ] : []
    };

    event.waitUntil(
        self.registration.showNotification(data.title || 'CODELAB Notification', options)
    );
});

self.addEventListener('notificationclick', function(event) {
    event.notification.close();

    if (event.action === 'view' || !event.action) {
        const urlToOpen = event.notification.data.url;

        event.waitUntil(
            clients.matchAll({ type: 'window', includeUncontrolled: true })
                .then(function(clientList) {
                    // Check if there's already a window open
                    for (let i = 0; i < clientList.length; i++) {
                        const client = clientList[i];
                        if (client.url === urlToOpen && 'focus' in client) {
                            return client.focus();
                        }
                    }
                    // Open new window if none exists
                    if (clients.openWindow) {
                        return clients.openWindow(urlToOpen);
                    }
                })
        );
    }
});
