// Global JavaScript utilities for Prolex application

/**
 * Toggle sidebar for desktop and mobile navigation.
 * Desktop: retracts half width by toggling the body class.
 * Mobile: slides sidebar in/out.
 */
window.toggleSidebar = function() {
    const sidebar = document.getElementById('sidebar');
    const body = document.body;
    const desktopToggle = document.getElementById('sidebar-toggle');
    const mobileToggle = document.querySelector('.mobile-toggle');

    if (!sidebar) return;

    if (window.innerWidth <= 991) {
        sidebar.classList.toggle('show');
        if (mobileToggle) {
            const isExpanded = sidebar.classList.contains('show');
            mobileToggle.setAttribute('aria-expanded', isExpanded);
        }
        return;
    }

    body.classList.toggle('sidebar-collapsed');
    if (desktopToggle) {
        desktopToggle.classList.toggle('active');
    }
    if (sidebar.classList.contains('show')) {
        sidebar.classList.remove('show');
    }
};

/**
 * 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';
            }
        }
    });
});
