document.addEventListener('DOMContentLoaded', function () {
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const sidebarOverlay = document.querySelector('.sidebar-overlay');
    const sidebarClose = document.querySelector('.sidebar-close');
    const modeToggle = document.querySelector('.mode-toggle');
    const body = document.body;

    const collapseKey = 'hk_nav_collapsed';
    const themeKey = 'hk_theme';

    const setCollapsed = function (collapsed) {
        body.classList.toggle('nav-collapsed', collapsed);
        localStorage.setItem(collapseKey, collapsed ? '1' : '0');
    };

    const setTheme = function (theme) {
        const dark = theme === 'dark';
        body.classList.toggle('theme-dark', dark);
        if (modeToggle) {
            modeToggle.textContent = dark ? 'Light' : 'Dark';
            modeToggle.setAttribute('aria-label', dark ? 'Switch to light mode' : 'Switch to dark mode');
        }
        localStorage.setItem(themeKey, dark ? 'dark' : 'light');
    };

    const savedTheme = localStorage.getItem(themeKey) || 'light';
    setTheme(savedTheme);

    if (window.innerWidth > 1024) {
        setCollapsed(localStorage.getItem(collapseKey) === '1');
    }

    if (modeToggle) {
        modeToggle.addEventListener('click', function () {
            setTheme(body.classList.contains('theme-dark') ? 'light' : 'dark');
        });
    }

    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', function () {
            if (window.innerWidth <= 1024) {
                body.classList.toggle('sidebar-open');
                return;
            }
            setCollapsed(!body.classList.contains('nav-collapsed'));
        });
    }

    if (sidebarOverlay) {
        sidebarOverlay.addEventListener('click', function () {
            body.classList.remove('sidebar-open');
        });
    }

    if (sidebarClose) {
        sidebarClose.addEventListener('click', function () {
            body.classList.remove('sidebar-open');
        });
    }

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape') {
            body.classList.remove('sidebar-open');
        }
    });
});
