// Request permission to receive notifications
messaging.requestPermission()
    .then(() => messaging.getToken())
    .then(token => {
        console.log('====================');
        console.log('FCM Token:', token);
        console.log('====================');
        // Send the token to the server to subscribe to notifications
        fetch('/save-fcm-token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ token: token })
        });
    })
    .catch(error => {
        console.error('Error getting permission or token', error);
    });

// Handle incoming messages
messaging.onMessage(payload => {
    console.log('Message received. ', payload);
    // Customize notification here
    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
    };

    new Notification(notificationTitle, notificationOptions);
});