/**
 * Main Application JavaScript
 * SSCI Office Platform
 */

// Initialize app on DOM ready
document.addEventListener('DOMContentLoaded', function() {
    initializeMenus();
    initializeNotifications();
    initializeSidebar();
    setupLanguageSwitcher();
    setupOfflineDetection();
});

/**
 * Initialize dropdown menus
 */
function initializeMenus() {
    // Helper function to close all menus
    function closeAllMenus() {
        document.getElementById('languageMenu')?.classList.add('hidden');
        document.getElementById('notificationPanel')?.classList.add('hidden');
        document.getElementById('userMenu')?.classList.add('hidden');
    }

    // Language menu toggle
    const languageBtn = document.getElementById('languageBtn');
    const languageMenu = document.getElementById('languageMenu');
    if (languageBtn && languageMenu) {
        languageBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            closeAllMenus();
            languageMenu.classList.toggle('hidden');
        });
        languageMenu.addEventListener('click', (e) => {
            e.stopPropagation();
            // Close menu when clicking on a link
            if (e.target.tagName === 'A') {
                closeAllMenus();
            }
        });
    }

    // Notification menu toggle
    const notificationBtn = document.getElementById('notificationBtn');
    const notificationPanel = document.getElementById('notificationPanel');
    if (notificationBtn && notificationPanel) {
        notificationBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            closeAllMenus();
            notificationPanel.classList.toggle('hidden');
        });
        notificationPanel.addEventListener('click', (e) => {
            e.stopPropagation();
            // Keep panel open when clicking inside
        });
    }

    // User menu toggle
    const userMenuBtn = document.getElementById('userMenuBtn');
    const userMenu = document.getElementById('userMenu');
    if (userMenuBtn && userMenu) {
        userMenuBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            closeAllMenus();
            userMenu.classList.toggle('hidden');
        });
        userMenu.addEventListener('click', (e) => {
            e.stopPropagation();
            // Close menu when clicking on a link
            if (e.target.tagName === 'A' || e.target.closest('a')) {
                closeAllMenus();
            }
        });
    }

    // Close all menus when clicking outside
    document.addEventListener('click', (e) => {
        // Don't close if clicking on header elements
        if (!e.target.closest('header')) {
            closeAllMenus();
        }
    });
}

/**
 * Initialize sidebar collapse/expand
 */
function initializeSidebar() {
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebar = document.getElementById('sidebar');
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', () => {
            sidebar.classList.toggle('collapsed');
            // Save state to localStorage
            const isCollapsed = sidebar.classList.contains('collapsed');
            localStorage.setItem('sidebarCollapsed', isCollapsed);
        });
        
        // Restore previous state
        if (localStorage.getItem('sidebarCollapsed') === 'true') {
            sidebar.classList.add('collapsed');
        }
    }
}

/**
 * Initialize notifications
 */
function initializeNotifications() {
    // Load unread notifications
    fetchNotifications();
    
    // Poll for new notifications every 30 seconds
    setInterval(fetchNotifications, 30000);
    
    // Mark all as read button
    const markAllReadBtn = document.getElementById('markAllRead');
    if (markAllReadBtn) {
        markAllReadBtn.addEventListener('click', markAllNotificationsAsRead);
    }
}

/**
 * Fetch user notifications
 */
function fetchNotifications() {
    fetch('api/notifications/get')
        .then(response => response.json())
        .then(data => {
            const notificationList = document.getElementById('notificationList');
            const notificationBadge = document.getElementById('notificationBadge');
            
            if (!notificationList) return;
            
            if (data.notifications && data.notifications.length > 0) {
                notificationBadge.textContent = data.notifications.length;
                notificationBadge.classList.remove('hidden');
                
                notificationList.innerHTML = data.notifications.map(notif => `
                    <div class="px-4 py-3 border-b border-gray-200 hover:bg-gray-50 cursor-pointer" onclick="markNotificationAsRead(${notif.id})">
                        <div class="flex justify-between items-start">
                            <div class="flex-1">
                                <p class="font-semibold text-gray-800">${notif.title}</p>
                                <p class="text-sm text-gray-600">${notif.message}</p>
                            </div>
                            <span class="text-xs text-gray-400">${timeAgo(notif.created_at)}</span>
                        </div>
                    </div>
                `).join('');
            } else {
                notificationBadge.classList.add('hidden');
                notificationList.innerHTML = '<div class="px-4 py-8 text-center text-gray-500">No notifications</div>';
            }
        })
        .catch(err => console.error('Error fetching notifications:', err));
}

/**
 * Mark notification as read
 */
function markNotificationAsRead(notificationId) {
    fetch(`api/notifications/mark-read/${notificationId}`, { method: 'POST' })
        .then(() => fetchNotifications());
}

/**
 * Mark all notifications as read
 */
function markAllNotificationsAsRead() {
    fetch('api/notifications/mark-all-read', { method: 'POST' })
        .then(() => fetchNotifications())
        .catch(err => console.error('Error marking all notifications as read:', err));
}

/**
 * Setup language switcher
 */
function setupLanguageSwitcher() {
    const languageLinks = document.querySelectorAll('[href*="?lang="]');
    languageLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const lang = new URLSearchParams(link.search).get('lang');
            fetch(`api/language/set`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ language: lang })
            }).then(() => location.reload());
        });
    });
}

/**
 * Setup offline detection
 */
function setupOfflineDetection() {
    window.addEventListener('offline', () => {
        document.getElementById('offlineBanner').classList.remove('hidden');
    });

    window.addEventListener('online', () => {
        document.getElementById('offlineBanner').classList.add('hidden');
        showToast('success', 'You are back online!');
    });
}

/**
 * Show toast notification using SweetAlert2
 */
function showToast(type = 'info', message = '', title = '') {
    const Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        didOpen: (toast) => {
            toast.addEventListener('mouseenter', Swal.stopTimer)
            toast.addEventListener('mouseleave', Swal.resumeTimer)
        }
    });

    Toast.fire({
        icon: type,
        title: title,
        text: message
    });
}

/**
 * Show confirmation dialog
 */
function showConfirm(title = 'Are you sure?', message = '', onConfirm = null) {
    Swal.fire({
        title: title,
        text: message,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#2563eb',
        cancelButtonColor: '#ef4444',
        confirmButtonText: 'Yes, continue',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed && onConfirm) {
            onConfirm();
        }
    });
}

/**
 * Format time ago
 */
function timeAgo(date) {
    const seconds = Math.floor((new Date() - new Date(date)) / 1000);
    const intervals = {
        year: 31536000,
        month: 2592000,
        week: 604800,
        day: 86400,
        hour: 3600,
        minute: 60
    };

    for (const [name, secondsInInterval] of Object.entries(intervals)) {
        const interval = Math.floor(seconds / secondsInInterval);
        if (interval >= 1) {
            return interval + ' ' + name + (interval > 1 ? 's' : '') + ' ago';
        }
    }
    return 'just now';
}

/**
 * Make AJAX request
 */
function ajaxRequest(url, method = 'GET', data = null, callback = null) {
    const options = {
        method: method,
        headers: {
            'Content-Type': 'application/json',
        }
    };

    if (data) {
        options.body = JSON.stringify(data);
    }

    fetch(url, options)
        .then(response => response.json())
        .then(result => {
            if (callback) {
                callback(result);
            }
        })
        .catch(error => {
            console.error('AJAX Error:', error);
            showToast('error', 'An error occurred. Please try again.');
        });
}

/**
 * Format currency
 */
function formatCurrency(amount, currency = 'USD') {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: currency,
    }).format(amount);
}

/**
 * Format date
 */
function formatDate(date, format = 'YYYY-MM-DD') {
    const d = new Date(date);
    const day = String(d.getDate()).padStart(2, '0');
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const year = d.getFullYear();

    return format
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day);
}

/**
 * Validate email
 */
function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

/**
 * Validate phone
 */
function validatePhone(phone) {
    const re = /^[\d\s\-\+\(\)]{10,}$/;
    return re.test(phone);
}
