// push-notification.js
// Save this file as: js/push-notification.js

// Firebase configuration - Already configured for your project
const firebaseConfig = {
    apiKey: "AIzaSyC8u-Ihu0DF5FfRomcQ9ogy41V9N83qxdo",
    authDomain: "skkd-smkms.firebaseapp.com",
    projectId: "skkd-smkms",
    storageBucket: "skkd-smkms.firebasestorage.app",
    messagingSenderId: "955863651296",
    appId: "1:955863651296:web:d1b7a1890975247783d185"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

// Request notification permission and get token
async function requestNotificationPermission() {
    try {
        const permission = await Notification.requestPermission();
        
        if (permission === 'granted') {
            console.log('✅ Notification permission granted');
            
            // Get FCM token
            const token = await messaging.getToken({
                vapidKey: 'BI4RjxUgkKwRhNjVd8SQ1ov_AQYiYh05DW5i1LLDRQSplY2UVeMyFK9STV57olG02PXXFIi8HvdponInpXjnR8I'
            });
            
            if (token) {
                console.log('✅ FCM Token received:', token);
                // Save token to server
                await saveTokenToServer(token);
                localStorage.setItem('fcm_token', token);
                
                // Update button UI
                const btn = document.getElementById('enableNotifBtn');
                if (btn) {
                    btn.innerHTML = '<i class="bi bi-check-circle-fill me-1"></i> Notifications Enabled';
                    btn.classList.remove('btn-primary');
                    btn.classList.add('btn-success');
                    btn.disabled = true;
                }
                
                return token;
            } else {
                console.error('❌ No token received');
                return null;
            }
        } else if (permission === 'denied') {
            console.log('❌ Notification permission denied');
            alert('Please enable notifications in your browser settings to receive alerts.');
            return null;
        } else {
            console.log('⚠️ Notification permission dismissed');
            return null;
        }
    } catch (error) {
        console.error('❌ Error getting permission:', error);
        alert('Error enabling notifications: ' + error.message);
        return null;
    }
}

// Save token to your server
async function saveTokenToServer(token) {
    try {
        const response = await fetch('save_fcm_token.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ token: token })
        });
        
        const data = await response.json();
        console.log('Token save response:', data);
        
        if (data.success) {
            console.log('✅ Push notifications successfully enabled!');
        } else {
            console.error('❌ Failed to save token:', data.message);
        }
    } catch (error) {
        console.error('❌ Error saving token:', error);
    }
}

// Handle foreground messages (when app is open)
messaging.onMessage((payload) => {
    console.log('📨 Foreground message received:', payload);
    
    // Show custom notification or update UI
    showCustomNotification(payload);
    
    // Play sound if enabled
    if (typeof triggerAlertSound === 'function') {
        triggerAlertSound();
    }
    
    // Update notification badge
    updateNotificationBadge();
});

// Show custom in-app notification
function showCustomNotification(payload) {
    const title = payload.notification?.title || 'New Notification';
    const body = payload.notification?.body || '';
    const type = payload.data?.type || 'general';
    
    // Choose icon based on type
    let icon = 'bi-bell-fill';
    let bgColor = 'primary';
    
    if (type === 'announcement') {
        icon = 'bi-megaphone-fill';
        bgColor = 'info';
    } else if (type === 'missed_class') {
        icon = 'bi-exclamation-triangle-fill';
        bgColor = 'danger';
    } else if (type === 'birthday') {
        icon = 'bi-cake2-fill';
        bgColor = 'warning';
    }
    
    // Create toast notification
    const toast = document.createElement('div');
    toast.className = 'position-fixed top-0 start-50 translate-middle-x mt-3 animate__animated animate__fadeInDown';
    toast.style.zIndex = '9999';
    toast.innerHTML = `
        <div class="alert alert-${bgColor} shadow-lg border-0 rounded-4 d-flex align-items-start" style="max-width: 350px;">
            <i class="${icon} me-3 fs-4 mt-1"></i>
            <div style="flex-grow: 1;">
                <div class="fw-bold mb-1">${title}</div>
                <div class="small">${body}</div>
            </div>
            <button class="btn-close ms-2" onclick="this.closest('.position-fixed').remove()"></button>
        </div>
    `;
    
    document.body.appendChild(toast);
    
    // Auto remove after 6 seconds
    setTimeout(() => {
        toast.classList.remove('animate__fadeInDown');
        toast.classList.add('animate__fadeOutUp');
        setTimeout(() => toast.remove(), 500);
    }, 6000);
}

// Update notification badge
function updateNotificationBadge() {
    const badge = document.getElementById('notifBadge');
    if (badge) {
        badge.classList.add('active');
    }
}

// Check if notifications are already enabled
function checkNotificationStatus() {
    const btn = document.getElementById('enableNotifBtn');
    const token = localStorage.getItem('fcm_token');
    
    if (btn && token && Notification.permission === 'granted') {
        btn.innerHTML = '<i class="bi bi-check-circle-fill me-1"></i> Notifications Enabled';
        btn.classList.remove('btn-primary');
        btn.classList.add('btn-success');
        btn.disabled = true;
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', async () => {
    console.log('🚀 Push notification script loaded');
    
    // Check if service worker and notifications are supported
    if (!('serviceWorker' in navigator)) {
        console.warn('⚠️ Service Workers not supported in this browser');
        return;
    }
    
    if (!('Notification' in window)) {
        console.warn('⚠️ Notifications not supported in this browser');
        return;
    }
    
    try {
        // Check if service worker is already registered
        const existingRegistration = await navigator.serviceWorker.getRegistration('/firebase-messaging-sw.js');
        
        if (existingRegistration) {
            console.log('✅ Service Worker already registered:', existingRegistration);
        } else {
            // Register service worker
            console.log('📝 Registering Service Worker...');
            const registration = await navigator.serviceWorker.register('/firebase-messaging-sw.js', {
                scope: '/'
            });
            console.log('✅ Service Worker registered successfully:', registration);
        }
        
        // Check notification status
        checkNotificationStatus();
        
        // If already granted permission, ensure token is saved
        if (Notification.permission === 'granted') {
            const existingToken = localStorage.getItem('fcm_token');
            if (!existingToken) {
                console.log('⚠️ Permission granted but no token found. Getting new token...');
                // Token might have been cleared, get new one
                await requestNotificationPermission();
            } else {
                console.log('✅ Existing token found:', existingToken.substring(0, 20) + '...');
            }
        } else {
            console.log('ℹ️ Notification permission status:', Notification.permission);
        }
    } catch (error) {
        console.error('❌ Service Worker registration failed:', error);
        console.error('Error details:', error.message);
        
        // Check if the service worker file exists
        try {
            const response = await fetch('/firebase-messaging-sw.js');
            if (!response.ok) {
                console.error('❌ Service worker file not found at /firebase-messaging-sw.js');
                console.error('Please ensure the file is in your root directory');
            }
        } catch (fetchError) {
            console.error('❌ Cannot access service worker file:', fetchError.message);
        }
    }
});

// Export function to manually request permission
window.enablePushNotifications = async function() {
    if (Notification.permission === 'granted') {
        const existingToken = localStorage.getItem('fcm_token');
        if (existingToken) {
            alert('Notifications are already enabled!');
            return existingToken;
        }
    }
    
    console.log('🔔 Requesting notification permission...');
    return await requestNotificationPermission();
};

// Note: onTokenRefresh is deprecated in Firebase v9
// Token refresh is now handled automatically by the SDK
// If you need to manually check for token updates, use this pattern:
setInterval(async () => {
    try {
        if (Notification.permission === 'granted') {
            const currentToken = await messaging.getToken({
                vapidKey: 'BI4RjxUgkKwRhNjVd8SQ1ov_AQYiYh05DW5i1LLDRQSplY2UVeMyFK9STV57olG02PXXFIi8HvdponInpXjnR8I'
            });
            
            const savedToken = localStorage.getItem('fcm_token');
            
            if (currentToken && currentToken !== savedToken) {
                console.log('🔄 Token refreshed:', currentToken);
                await saveTokenToServer(currentToken);
                localStorage.setItem('fcm_token', currentToken);
            }
        }
    } catch (error) {
        console.error('❌ Error checking token:', error);
    }
}, 3600000); // Check every hour

console.log('✅ Push notification module loaded successfully');