// Global JavaScript utilities for Prolex application

/**
 * Toggle sidebar for mobile navigation
 */
window.toggleSidebar = function() {
    const sidebar = document.getElementById('sidebar');
    if (sidebar) {
        sidebar.classList.toggle('show');

        // Update aria-expanded for accessibility
        const toggleBtn = document.querySelector('.mobile-toggle');
        if (toggleBtn) {
            const isExpanded = sidebar.classList.contains('show');
            toggleBtn.setAttribute('aria-expanded', isExpanded);
        }
    }
};

/**
 * Toggle theme (light/dark mode)
 */
window.toggleTheme = function() {
    const html = document.documentElement;
    const toggleBtn = document.getElementById('theme-toggle');
    const icon = toggleBtn ? toggleBtn.querySelector('i') : null;

    // Get current theme
    const currentTheme = html.getAttribute('data-bs-theme') || 'light';
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';

    // Set new theme
    html.setAttribute('data-bs-theme', newTheme);

    // Update icon
    if (icon) {
        icon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
    }

    // Save to localStorage
    localStorage.setItem('theme', newTheme);
};

// Initialize theme on page load
document.addEventListener('DOMContentLoaded', function() {
    const html = document.documentElement;
    const toggleBtn = document.getElementById('theme-toggle');
    const icon = toggleBtn ? toggleBtn.querySelector('i') : null;

    // Check for saved theme or use system preference
    const savedTheme = localStorage.getItem('theme');
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

    let currentTheme = savedTheme || (prefersDark ? 'dark' : 'light');

    // Set initial theme
    html.setAttribute('data-bs-theme', currentTheme);
    if (icon) {
        icon.className = currentTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
    }

    // Listen for system theme changes if no saved preference
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
        if (!localStorage.getItem('theme')) {
            currentTheme = e.matches ? 'dark' : 'light';
            html.setAttribute('data-bs-theme', currentTheme);
            if (icon) {
                icon.className = currentTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
            }
        }
    });
});
