/**
 * 彩虹外链网盘 - 管理员后台侧边栏交互功能
 */
(function() {
    var sidebar = document.getElementById('adminSidebar');
    var overlay = document.getElementById('sidebarOverlay');

    function toggleSubmenu(element) {
        var parent = element.closest('.has-submenu');
        if (!parent) return;

        // 关闭其他已展开的子菜单
        document.querySelectorAll('.has-submenu.open').forEach(function(item) {
            if (item !== parent) {
                item.classList.remove('open');
            }
        });

        // 切换当前子菜单状态
        parent.classList.toggle('open');
    }

    function toggleSidebar() {
        if (window.innerWidth <= 991) {
            sidebar.classList.toggle('show');
            overlay.classList.toggle('show');
        } else {
            document.body.classList.toggle('sidebar-collapsed');
            localStorage.setItem('sidebar_collapsed', document.body.classList.contains('sidebar-collapsed'));
        }
    }

    function closeMobileSidebar() {
        sidebar.classList.remove('show');
        overlay.classList.remove('show');
    }

    document.addEventListener('DOMContentLoaded', function() {
        var sidebarToggle = document.getElementById('sidebarToggle');

        if (sidebarToggle) {
            sidebarToggle.addEventListener('click', toggleSidebar);
        }

        if (overlay) {
            overlay.addEventListener('click', closeMobileSidebar);
        }

        // 恢复侧边栏折叠状态
        if (window.innerWidth > 991) {
            var isCollapsed = localStorage.getItem('sidebar_collapsed') === 'true';
            if (isCollapsed) {
                document.body.classList.add('sidebar-collapsed');
            }
        }

        // 为所有有子菜单的项绑定点击事件
        var hasSubmenuItems = document.querySelectorAll('.has-submenu');
        hasSubmenuItems.forEach(function(item) {
            var link = item.querySelector('.sidebar-link');
            if (link) {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    toggleSubmenu(link);
                });
            }
        });

        // 窗口大小改变时处理
        var resizeTimer;
        window.addEventListener('resize', function() {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function() {
                if (window.innerWidth > 991) {
                    sidebar.classList.remove('show');
                    overlay.classList.remove('show');
                } else {
                    document.body.classList.remove('sidebar-collapsed');
                }
            }, 250);
        });
    });
})();
