importScripts('https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.7.1/firebase-messaging-compat.js');

// Fetch configuration from the API
// Note: In Service Worker, we use the absolute path or relative to the SW location
fetch('api/get_firebase_config.php')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            firebase.initializeApp(data.config);
            const messaging = firebase.messaging();

            messaging.onBackgroundMessage((payload) => {
                console.log('[firebase-messaging-sw.js] Received background message ', payload);
                const notificationTitle = payload.notification.title;
                const notificationOptions = {
                    body: payload.notification.body,
                    data: payload.data,
                    icon: 'admin/assets/img/icon.png' // Optional: add an icon
                };

                self.registration.showNotification(notificationTitle, notificationOptions);
            });
        } else {
            console.error('Failed to load Firebase config in Service Worker');
        }
    })
    .catch(err => {
        console.error('Error fetching Firebase config in Service Worker:', err);
    });
