/* =============================== */
/* DemoBank Sidebar Module          */
/* =============================== */

document.addEventListener("DOMContentLoaded", function () {

    const sidebar = document.querySelector(".sidebar");
    const toggleBtn = document.querySelector(".sidebar-toggle");
    const body = document.body;

    if (!sidebar) return;

    // ===============================
    // LOAD SAVED STATE
    // ===============================
    const savedState = localStorage.getItem("demobank_sidebar");

    if (savedState === "collapsed") {
        sidebar.classList.add("collapsed");
    }

    // ===============================
    // TOGGLE SIDEBAR
    // ===============================
    if (toggleBtn) {
        toggleBtn.addEventListener("click", function () {
            sidebar.classList.toggle("collapsed");

            if (sidebar.classList.contains("collapsed")) {
                localStorage.setItem("demobank_sidebar", "collapsed");
            } else {
                localStorage.setItem("demobank_sidebar", "expanded");
            }
        });
    }

    // ===============================
    // ACTIVE MENU LINK HIGHLIGHT
    // ===============================
    const currentUrl = window.location.href;
    const links = sidebar.querySelectorAll("a");

    links.forEach(link => {
        if (currentUrl.includes(link.getAttribute("href"))) {
            link.classList.add("active");
        }
    });

    // ===============================
    // CLICK OUTSIDE TO CLOSE (MOBILE)
    // ===============================
    document.addEventListener("click", function (e) {
        const isClickInsideSidebar = sidebar.contains(e.target);
        const isClickToggle = toggleBtn && toggleBtn.contains(e.target);

        if (!isClickInsideSidebar && !isClickToggle && window.innerWidth <= 768) {
            sidebar.classList.remove("open");
        }
    });

    // ===============================
    // MOBILE OPEN STATE
    // ===============================
    if (toggleBtn) {
        toggleBtn.addEventListener("click", function () {
            if (window.innerWidth <= 768) {
                sidebar.classList.toggle("open");
            }
        });
    }

});