document.addEventListener('DOMContentLoaded', function() {
    const langToggle = document.getElementById('langToggle');
    
    // Use the language set by PHP as initial source of truth
    const initialLang = document.documentElement.lang || 'ar';
    localStorage.setItem('lang', initialLang);

    if (langToggle) {
        langToggle.addEventListener('click', function() {
            const newLang = document.documentElement.lang === 'en' ? 'ar' : 'en';
            setLanguage(newLang);
        });
    }

    // Sidebar Toggle
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebar = document.querySelector('.sidebar');
    const overlay = document.createElement('div');
    overlay.className = 'sidebar-overlay';
    document.body.appendChild(overlay);

    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('show');
            overlay.classList.toggle('show');
        });
    }

    overlay.addEventListener('click', function() {
        sidebar.classList.remove('show');
        overlay.classList.remove('show');

    });
    // Close sidebar when a link is clicked on mobile
    const sidebarLinks = document.querySelectorAll('.sidebar .nav-link');
    sidebarLinks.forEach(link => {
        link.addEventListener('click', function() {
            if (window.innerWidth <= 1199.98) {
                sidebar.classList.remove('show');
                overlay.classList.remove('show');
            }
        });
    });

    // Sidebar Accordion logic: Close other collapses when one is opened
    const sidebarCollapses = document.querySelectorAll('.sidebar .collapse');
    sidebarCollapses.forEach(collapseEl => {
        collapseEl.addEventListener('show.bs.collapse', function () {
            sidebarCollapses.forEach(otherCollapse => {
                if (otherCollapse !== collapseEl && otherCollapse.classList.contains('show')) {
                    const bsCollapse = bootstrap.Collapse.getOrCreateInstance(otherCollapse);
                    bsCollapse.hide();
                }
            });
        });
    });

    // Theme Switcher
    const themeLinks = document.querySelectorAll('.theme-select');
    themeLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const theme = this.getAttribute('data-theme');
            
            // Remove all existing theme classes
            const themes = ['theme-default', 'theme-dark', 'theme-ocean', 'theme-forest', 'theme-sunset', 'theme-nord', 'theme-dracula', 'theme-citrus'];
            document.body.classList.remove(...themes);
            
            // Add new theme class
            document.body.classList.add(`theme-${theme}`);
            
            // Save theme to database
            const formData = new FormData();
            formData.append('action', 'save_theme');
            formData.append('theme', theme);
            
            fetch('index.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                }
            })
        });
    });
});

function setLanguage(lang) {
    document.documentElement.lang = lang;
    document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
    document.body.dir = lang === 'ar' ? 'rtl' : 'ltr';
    localStorage.setItem('lang', lang);
    
    // Update UI text
    document.querySelectorAll('[data-en]').forEach(el => {
        const text = el.getAttribute(`data-${lang}`);
        if (text) {
            // If it's a simple element with only text, update it
            // If it has children, we should only update the text node parts
            // But for simplicity in this app, we'll check if it has any children
            if (el.children.length === 0) {
                el.textContent = text;
            } else {
                // If it has children (like icons), we try to find a text node to update
                // or just update the first text node child
                let found = false;
                for (let node of el.childNodes) {
                    if (node.nodeType === 3) { // Text node
                        node.textContent = text;
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    // Fallback: append text if no text node exists
                    el.appendChild(document.createTextNode(text));
                }
            }
        }
    });

    // Update buttons/inputs
    document.querySelectorAll('input[data-en-placeholder]').forEach(el => {
        el.placeholder = el.getAttribute(`data-${lang}-placeholder`);
    });
}
