document.addEventListener('DOMContentLoaded', function() {
    const sidebarLinks = document.querySelectorAll('.sidebar-nav a');
    const currentPath = window.location.pathname;
    
    sidebarLinks.forEach(link => {
        if (link.getAttribute('href') === currentPath) {
            link.classList.add('active');
        }
    });
    
    // 侧边栏折叠功能
    const sidebar = document.getElementById('sidebar');
    const sidebarToggle = document.getElementById('sidebarToggle');
    const adminMain = document.querySelector('.admin-main');
    
    // 从 localStorage 恢复折叠状态
    const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
    if (isCollapsed) {
        sidebar.classList.add('collapsed');
        adminMain.style.marginLeft = '60px';
    }
    
    sidebarToggle.addEventListener('click', function() {
        sidebar.classList.toggle('collapsed');
        
        if (sidebar.classList.contains('collapsed')) {
            adminMain.style.marginLeft = '60px';
            localStorage.setItem('sidebarCollapsed', 'true');
        } else {
            adminMain.style.marginLeft = '220px';
            localStorage.setItem('sidebarCollapsed', 'false');
        }
    });
    
    // 折叠状态下的悬停提示
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        const navText = item.querySelector('.nav-text');
        if (navText) {
            item.setAttribute('title', navText.textContent);
        }
    });
    
    // 菜单分组折叠功能
    const navSections = document.querySelectorAll('.nav-section');
    
    // 从 localStorage 恢复分组折叠状态
    navSections.forEach(section => {
        const sectionName = section.dataset.section;
        const isSectionCollapsed = localStorage.getItem('navSection_' + sectionName) === 'true';
        
        if (isSectionCollapsed) {
            section.classList.add('collapsed');
        } else {
            section.classList.remove('collapsed');
        }
    });
    
    // 点击分组标题展开/折叠
    const sectionTitles = document.querySelectorAll('.nav-section-title');
    sectionTitles.forEach(title => {
        title.addEventListener('click', function() {
            const section = this.parentElement;
            const sectionName = section.dataset.section;
            
            section.classList.toggle('collapsed');
            
            // 保存状态到 localStorage
            const isCollapsed = section.classList.contains('collapsed');
            localStorage.setItem('navSection_' + sectionName, isCollapsed.toString());
        });
    });
});
