// Browser Notifications with Sound Support
class NotificationManager {
    constructor() {
        this.permission = null;
        this.checkPermission();
        this.setupPolling();
    }

    async checkPermission() {
        if (!('Notification' in window)) {
            console.log('This browser does not support notifications');
            return;
        }

        this.permission = Notification.permission;
        
        if (this.permission === 'default') {
            // Request permission when user interacts with the page
            document.addEventListener('click', () => {
                this.requestPermission();
            }, { once: true });
        }
    }

    async requestPermission() {
        if (!('Notification' in window)) return;

        try {
            const permission = await Notification.requestPermission();
            this.permission = permission;
            
            if (permission === 'granted') {
                this.showNotification('Notifications Enabled', 'You will now receive browser notifications with sound.');
            }
        } catch (error) {
            console.error('Error requesting notification permission:', error);
        }
    }

    showNotification(title, message, options = {}) {
        if (!('Notification' in window) || this.permission !== 'granted') {
            return;
        }

        const notification = new Notification(title, {
            body: message,
            icon: '/favicon.ico',
            badge: '/favicon.ico',
            tag: options.tag || 'assignment-notification',
            requireInteraction: options.requireInteraction || false,
            ...options
        });

        // Play sound
        this.playNotificationSound();

        // Auto-close after 5 seconds
        setTimeout(() => {
            notification.close();
        }, 5000);

        // Handle click
        notification.onclick = () => {
            window.focus();
            if (options.url) {
                window.location.href = options.url;
            }
            notification.close();
        };
    }

    playNotificationSound() {
        // Create audio context for notification sound
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();

        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);

        // Create a pleasant notification sound (two-tone beep)
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
        oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.1);
        
        gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);

        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.2);
    }

    setupPolling() {
        // Poll for new notifications every 30 seconds
        setInterval(() => {
            this.checkForNewNotifications();
        }, 30000);

        // Also check immediately on page load
        this.checkForNewNotifications();
    }

    async checkForNewNotifications() {
        try {
            const response = await fetch('/api/notifications/unread-count', {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                credentials: 'same-origin'
            });

            if (!response.ok) return;

            const data = await response.json();
            const unreadCount = data.count || 0;

            // Update badge
            this.updateBadge(unreadCount);

            // Check for new notifications (if count increased)
            if (unreadCount > (window.lastNotificationCount || 0)) {
                this.fetchLatestNotification();
            }

            window.lastNotificationCount = unreadCount;
        } catch (error) {
            console.error('Error checking notifications:', error);
        }
    }

    async fetchLatestNotification() {
        try {
            const response = await fetch('/api/notifications/latest', {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                credentials: 'same-origin'
            });

            if (!response.ok) return;

            const data = await response.json();
            if (data.notification) {
                this.showNotification(
                    data.notification.title,
                    data.notification.message,
                    {
                        url: data.notification.url || '/notifications',
                        tag: `notification-${data.notification.id}`
                    }
                );
            }
        } catch (error) {
            console.error('Error fetching latest notification:', error);
        }
    }

    updateBadge(count) {
        // Update document title
        if (count > 0) {
            document.title = `(${count}) ${document.title.replace(/^\(\d+\)\s*/, '')}`;
        } else {
            document.title = document.title.replace(/^\(\d+\)\s*/, '');
        }

        // Update notification badge in UI if exists
        const badge = document.getElementById('notification-badge');
        if (badge) {
            if (count > 0) {
                badge.textContent = count > 99 ? '99+' : count;
                badge.classList.remove('hidden');
            } else {
                badge.classList.add('hidden');
            }
        }
    }
}

// Initialize notification manager when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        window.notificationManager = new NotificationManager();
    });
} else {
    window.notificationManager = new NotificationManager();
}
