(function () {
    const storageKey = 'akkurtcast-sidebar-scroll-left';

    function sidebar() {
        return document.querySelector('.sidebar');
    }

    function savePosition() {
        const nav = sidebar();
        if (!nav) return;
        try {
            sessionStorage.setItem(storageKey, String(nav.scrollLeft || 0));
        } catch (error) {}
    }

    function restorePosition() {
        const nav = sidebar();
        if (!nav || window.innerWidth > 767) return;
        let saved = 0;
        try {
            saved = Number(sessionStorage.getItem(storageKey) || 0);
        } catch (error) {}
        window.requestAnimationFrame(() => {
            if (saved > 0) {
                nav.scrollLeft = saved;
                setTimeout(() => { nav.scrollLeft = saved; }, 80);
                return;
            }
            const active = nav.querySelector('a.active');
            if (active) {
                active.scrollIntoView({ block: 'nearest', inline: 'center' });
            }
        });
    }

    document.addEventListener('click', (event) => {
        if (event.target.closest('.sidebar a[href]')) {
            savePosition();
        }
    });
    window.addEventListener('beforeunload', savePosition);
    window.addEventListener('pagehide', savePosition);
    document.addEventListener('DOMContentLoaded', () => {
        const nav = sidebar();
        if (nav) {
            let pending = false;
            nav.addEventListener('scroll', () => {
                if (pending) return;
                pending = true;
                window.requestAnimationFrame(() => {
                    savePosition();
                    pending = false;
                });
            }, { passive: true });
        }
        restorePosition();
    });
})();
