document.addEventListener('DOMContentLoaded', () => {
    const sidebar = document.getElementById('appSidebar');
    const wrapper = document.getElementById('appWrapper');
    const sidebarToggleBtn = document.getElementById('sidebarToggleBtn');
    const topbarToggleBtn = document.getElementById('topbarToggleBtn');
    const toggleIcon = document.getElementById('sidebarToggleIcon');

    if (!sidebar) return;

    // Criar elemento backdrop se não existir
    let backdrop = document.querySelector('.sidebar-backdrop');
    if (!backdrop) {
        backdrop = document.createElement('div');
        backdrop.className = 'sidebar-backdrop';
        document.body.appendChild(backdrop);
    }

    function toggleSidebar() {
        const isMobile = window.innerWidth <= 768;
        if (isMobile) {
            const isOpen = sidebar.classList.contains('mobile-open');
            if (isOpen) {
                sidebar.classList.remove('mobile-open');
                backdrop.classList.remove('active');
            } else {
                sidebar.classList.add('mobile-open');
                backdrop.classList.add('active');
            }
        } else {
            const currentlyCollapsed = sidebar.classList.contains('collapsed');
            if (currentlyCollapsed) {
                sidebar.classList.remove('collapsed');
                if (wrapper) wrapper.classList.remove('sidebar-collapsed');
                if (toggleIcon) toggleIcon.textContent = '◀';
                localStorage.setItem('sidebarCollapsed', 'false');
            } else {
                sidebar.classList.add('collapsed');
                if (wrapper) wrapper.classList.add('sidebar-collapsed');
                if (toggleIcon) toggleIcon.textContent = '▶';
                localStorage.setItem('sidebarCollapsed', 'true');
            }
        }
    }

    if (sidebarToggleBtn) {
        sidebarToggleBtn.addEventListener('click', toggleSidebar);
    }
    if (topbarToggleBtn) {
        topbarToggleBtn.addEventListener('click', toggleSidebar);
    }
    if (backdrop) {
        backdrop.addEventListener('click', () => {
            sidebar.classList.remove('mobile-open');
            backdrop.classList.remove('active');
        });
    }

    // 1. Restaurar estado inicial do localStorage no desktop
    if (window.innerWidth > 768) {
        const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
        if (isCollapsed) {
            sidebar.classList.add('collapsed');
            if (wrapper) wrapper.classList.add('sidebar-collapsed');
            if (toggleIcon) toggleIcon.textContent = '▶';
        } else {
            if (toggleIcon) toggleIcon.textContent = '◀';
        }
    }

    // 2. Preservar a posição do scroll do menu sem pular para o topo
    const activeMenuItem = sidebar.querySelector('.sidebar-link.active');
    if (activeMenuItem) {
        activeMenuItem.scrollIntoView({ block: 'nearest' });
    }

    const savedScrollTop = sessionStorage.getItem('sidebarScrollTop');
    if (savedScrollTop !== null) {
        sidebar.scrollTop = parseInt(savedScrollTop, 10);
    }

    sidebar.addEventListener('scroll', () => {
        sessionStorage.setItem('sidebarScrollTop', sidebar.scrollTop);
    });
});
