/**
 * OTIS Browser Push Notifications
 * Polling for system notifications and triggering Browser Notification API.
 */

document.addEventListener('DOMContentLoaded', () => {
    
    // Check if browser supports notifications
    if (!('Notification' in window)) {
        console.warn('This browser does not support desktop notification');
        return;
    }

    // Request permission if not already granted/denied
    if (Notification.permission !== 'granted' && Notification.permission !== 'denied') {
        Notification.requestPermission().then(permission => {
            if (permission === 'granted') {
                console.log('Browser notifications enabled.');
            }
        });
    }

    // Start polling if permission is granted
    if (Notification.permission === 'granted' || Notification.permission === 'default') {
        // Poll every 60 seconds
        setInterval(pollNotifications, 60000);
        
        // Initial poll after 5 seconds to not delay page load
        setTimeout(pollNotifications, 5000);
    }
});

async function pollNotifications() {
    // Only poll if window is visible and permission is granted
    if (Notification.permission !== 'granted') return;

    try {
        const response = await fetch(BASE_URL + '/system/pollNotifications');
        if(!response.ok) return;
        
        const data = await response.json();
        
        if (data.success && data.notifications && data.notifications.length > 0) {
            data.notifications.forEach(notif => {
                showBrowserNotification(notif.title, notif.message, notif.type);
            });
        }
    } catch (e) {
        console.warn('Failed to poll notifications', e);
    }
}

function showBrowserNotification(title, message, type) {
    let iconPath = BASE_URL + '/assets/images/logo.png'; // Assuming we have a logo
    
    // Customize icon or behavior based on type if needed
    // 'info', 'warning', 'success', 'error'
    
    const notification = new Notification(title, {
        body: message,
        icon: iconPath,
        requireInteraction: (type === 'warning' || type === 'error') // Keep on screen if important
    });

    notification.onclick = function(event) {
        event.preventDefault(); // prevent the browser from focusing the Notification's tab
        window.open(BASE_URL + '/system/notifications', '_blank');
        notification.close();
    };
}
