// site.js

function activateCurrentPageNavLink() {
    // Activate nav-link that matches current path
    const currentPath = window.location.pathname.replace(/\/+$/, "") || "/";

    $(".navbar-nav .nav-link").each(function () {
        const href = $(this).attr("href");
        if (!href) return;

        const linkPath = new URL(href, window.location.origin).pathname.replace(/\/+$/, "") || "/";
        const isActive = linkPath === currentPath;

        $(this).toggleClass("active", isActive);
        if (isActive) {
            $(this).attr("aria-current", "page");
        } else {
            $(this).removeAttr("aria-current");
        }
    });
}

/**************************************** Accordion State ****************************************/

function saveAccordionState(collapseId) {
    const pageId = window.location.pathname.replace('/', '');
    if (!pageId) { return; }
    localStorage.setItem(`lastAccordionState-${pageId}`, collapseId);
}

function removeAccordionState(collapseId) {
    const pageId = window.location.pathname.replace('/', '');
    if (!pageId) { return; }
    const lastStateId = localStorage.getItem(`lastAccordionState-${pageId}`);
    if (lastStateId === collapseId) {
        localStorage.removeItem(`lastAccordionState-${pageId}`);
    }
}

function loadAccordionState() {
    const pageId = window.location.pathname.replace('/', '');
    if (!pageId) { return; }

    const lastStateId = localStorage.getItem(`lastAccordionState-${pageId}`);
    if (lastStateId) {
        const accordion = $('.accordion')[0];
        const collapseElement = $(`#${lastStateId}`)[0];
        if (accordion && collapseElement) {
            const bsCollapse = new bootstrap.Collapse(collapseElement, { toggle: true});
        }
    }
}

/***************************************** Debugging Page ****************************************/


/******************************************* Page Load *******************************************/

$(async () => {
    $("#copyright-year").text(new Date().getFullYear());
    activateCurrentPageNavLink();

    // listen to accordion events
    loadAccordionState();
    const accordion = $('.accordion');
    accordion.on('show.bs.collapse', (e) => saveAccordionState(e.target.id));
    accordion.on('hide.bs.collapse', (e) => removeAccordionState(e.target.id));
});
