(() => {
    const root = document.documentElement;
    const toggle = document.querySelector('[data-sidebar-toggle]');
    const mobileDrawer = document.querySelector('[data-mobile-drawer]');
    const mobileOverlay = document.querySelector('[data-mobile-overlay]');
    const closeButtons = document.querySelectorAll('[data-close-sidebar]');
    const desktop = window.matchMedia('(min-width: 1024px)');
    const storageKey = 'microfinance-sidebar-collapsed';

    if (!toggle) return;

    const storedDesktopState = () => {
        try {
            return localStorage.getItem(storageKey) === '1';
        } catch (_) {
            return false;
        }
    };

    const storeDesktopState = (collapsed) => {
        try {
            localStorage.setItem(storageKey, collapsed ? '1' : '0');
        } catch (_) {
            // Sidebar still works when browser storage is unavailable.
        }
    };

    const setMobileDrawer = (open) => {
        mobileDrawer?.classList.toggle('is-open', open);
        mobileOverlay?.classList.toggle('is-open', open);
        document.body.style.overflow = open ? 'hidden' : '';
        toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
        toggle.setAttribute('aria-label', open ? 'Close navigation' : 'Open navigation');
    };

    const setDesktopSidebar = (collapsed, persist = true) => {
        root.classList.toggle('mf-sidebar-collapsed', collapsed);
        toggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
        toggle.setAttribute('aria-label', collapsed ? 'Expand sidebar' : 'Collapse sidebar');
        if (persist) storeDesktopState(collapsed);
    };

    const applyViewportState = () => {
        if (desktop.matches) {
            setMobileDrawer(false);
            setDesktopSidebar(storedDesktopState(), false);
            return;
        }

        root.classList.remove('mf-sidebar-collapsed');
        setMobileDrawer(false);
    };

    toggle.addEventListener('click', () => {
        if (desktop.matches) {
            setDesktopSidebar(!root.classList.contains('mf-sidebar-collapsed'));
            return;
        }

        setMobileDrawer(!mobileDrawer?.classList.contains('is-open'));
    });

    closeButtons.forEach((button) => button.addEventListener('click', () => {
        if (!desktop.matches) setMobileDrawer(false);
    }));

    mobileOverlay?.addEventListener('click', () => {
        if (!desktop.matches) setMobileDrawer(false);
    });

    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape' && !desktop.matches) setMobileDrawer(false);
    });

    if (typeof desktop.addEventListener === 'function') {
        desktop.addEventListener('change', applyViewportState);
    } else {
        desktop.addListener(applyViewportState);
    }

    applyViewportState();
})();
