(function () {
    'use strict';

    function ready(fn) {
        if (document.readyState !== 'loading') {
            fn();
        } else {
            document.addEventListener('DOMContentLoaded', fn);
        }
    }

    function toggleSidebar() {
        var collapsed = document.body.classList.toggle('sidebar-collapsed');
        try {
            localStorage.setItem('erp-sidebar-collapsed', collapsed ? '1' : '0');
        } catch (e) {}
        updateCollapseLabel();
    }

    function updateCollapseLabel() {
        var btn = document.getElementById('sidebarCollapseBtn');
        if (!btn) {
            return;
        }
        var collapsed = document.body.classList.contains('sidebar-collapsed');
        btn.innerHTML = collapsed
            ? '<i>→</i> 展开菜单'
            : '<i>←</i> 收起菜单';
    }

    function restoreSidebarState() {
        try {
            if (localStorage.getItem('erp-sidebar-collapsed') === '1') {
                document.body.classList.add('sidebar-collapsed');
            }
        } catch (e) {}
        updateCollapseLabel();
    }

    function toggleUserMenu() {
        var menu = document.getElementById('userDropdown');
        if (!menu) {
            return;
        }
        var open = menu.classList.toggle('open');
        if (open) {
            document.addEventListener('click', closeUserMenuOutside);
        } else {
            document.removeEventListener('click', closeUserMenuOutside);
        }
    }

    function closeUserMenuOutside(e) {
        var menu = document.getElementById('userDropdown');
        var profile = document.getElementById('userProfileToggle');
        if (!menu || !profile) {
            return;
        }
        if (!menu.contains(e.target) && !profile.contains(e.target)) {
            menu.classList.remove('open');
            document.removeEventListener('click', closeUserMenuOutside);
        }
    }

    function bindClick(id, handler) {
        var el = document.getElementById(id);
        if (el) {
            el.addEventListener('click', function (e) {
                e.preventDefault();
                e.stopPropagation();
                handler(e);
            });
        }
    }

    ready(function () {
        restoreSidebarState();

        bindClick('topbarMenuBtn', toggleSidebar);
        bindClick('sidebarCollapseBtn', toggleSidebar);
        bindClick('topbarNotifyBtn', function () {
            window.location.href = '/admin/workflow/todolist/';
        });
        bindClick('userProfileToggle', toggleUserMenu);
    });
})();
