// Notifications Manager
class NotificationsManager {
    constructor() {
        this.permission = 'default';
        this.subscription = null;
        this.init();
    }

    async init() {
        if (!('Notification' in window) || !('serviceWorker' in navigator)) {
            console.log('Push notifications not supported');
            return;
        }

        this.permission = Notification.permission;

        // Request permission if not already granted
        if (this.permission === 'default') {
            await this.requestPermission();
        }

        // Subscribe to push notifications if permission granted
        if (this.permission === 'granted') {
            await this.subscribeToPush();
        }

        // Load notifications
        this.loadNotifications();
    }

    async requestPermission() {
        try {
            this.permission = await Notification.requestPermission();

            if (this.permission === 'granted') {
                console.log('Notification permission granted');
                await this.subscribeToPush();
            } else {
                console.log('Notification permission denied');
            }
        } catch (error) {
            console.error('Error requesting notification permission:', error);
        }
    }

    async subscribeToPush() {
        try {
            const registration = await navigator.serviceWorker.ready;

            // Get VAPID public key from server
            const response = await fetch('/api/notifications/vapid-public-key');
            const data = await response.json();

            if (!data.publicKey) {
                console.log('VAPID public key not configured');
                return;
            }

            // Subscribe to push notifications
            const subscription = await registration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: this.urlBase64ToUint8Array(data.publicKey)
            });

            // Send subscription to server
            await fetch('/api/notifications/subscribe', {
                method: 'POST',
                headers: window.auth.getAuthHeaders(),
                body: JSON.stringify({ subscription })
            });

            this.subscription = subscription;
            console.log('Subscribed to push notifications');
        } catch (error) {
            console.error('Error subscribing to push notifications:', error);
        }
    }

    async unsubscribe() {
        try {
            if (this.subscription) {
                await this.subscription.unsubscribe();

                // Remove subscription from server
                await fetch('/api/notifications/unsubscribe', {
                    method: 'POST',
                    headers: window.auth.getAuthHeaders(),
                    body: JSON.stringify({ endpoint: this.subscription.endpoint })
                });

                this.subscription = null;
                console.log('Unsubscribed from push notifications');
            }
        } catch (error) {
            console.error('Error unsubscribing from push notifications:', error);
        }
    }

    async loadNotifications() {
        try {
            const response = await fetch('/api/notifications', {
                headers: window.auth.getAuthHeaders()
            });

            if (!response.ok) return;

            const data = await response.json();
            if (data.success && data.notifications) {
                this.displayNotifications(data.notifications);
            }
        } catch (error) {
            console.error('Error loading notifications:', error);
        }
    }

    displayNotifications(notifications) {
        // This can be used to show notifications in the UI
        console.log('Notifications:', notifications);

        // Count unread notifications
        const unreadCount = notifications.filter(n => !n.read_status).length;

        // Update UI badge if exists
        const badge = document.getElementById('notificationBadge');
        if (badge) {
            if (unreadCount > 0) {
                badge.textContent = unreadCount;
                badge.classList.remove('hidden');
            } else {
                badge.classList.add('hidden');
            }
        }
    }

    async markAsRead(notificationId) {
        try {
            await fetch(`/api/notifications/${notificationId}/read`, {
                method: 'PATCH',
                headers: window.auth.getAuthHeaders()
            });
        } catch (error) {
            console.error('Error marking notification as read:', error);
        }
    }

    async markAllAsRead() {
        try {
            await fetch('/api/notifications/mark-all-read', {
                method: 'POST',
                headers: window.auth.getAuthHeaders()
            });

            await this.loadNotifications();
        } catch (error) {
            console.error('Error marking all notifications as read:', error);
        }
    }

    // Show local notification (for testing)
    showLocalNotification(title, body, data = {}) {
        if (this.permission !== 'granted') {
            console.log('Notification permission not granted');
            return;
        }

        navigator.serviceWorker.ready.then(registration => {
            registration.showNotification(title, {
                body,
                icon: '/images/icons/icon-192x192.png',
                badge: '/images/icons/icon-192x192.png',
                vibrate: [200, 100, 200],
                data,
                actions: [
                    { action: 'view', title: 'View' },
                    { action: 'close', title: 'Close' }
                ]
            });
        });
    }

    // Helper function to convert VAPID key
    urlBase64ToUint8Array(base64String) {
        const padding = '='.repeat((4 - base64String.length % 4) % 4);
        const base64 = (base64String + padding)
            .replace(/\-/g, '+')
            .replace(/_/g, '/');

        const rawData = window.atob(base64);
        const outputArray = new Uint8Array(rawData.length);

        for (let i = 0; i < rawData.length; ++i) {
            outputArray[i] = rawData.charCodeAt(i);
        }
        return outputArray;
    }
}

// Initialize notifications manager
const notifications = new NotificationsManager();

// Export for global use
window.notifications = notifications;
