// Save and restore navigation menu state from local storage.
function saveMenuState() {
    var leftNavigation = document.getElementById("left-navigation");
    if (!leftNavigation) {
        return;
    }
    var rootMenuItems = leftNavigation.getElementsByTagName("details");
    console.log(rootMenuItems);
    var rootMenuStates = {};
    for (var i = 0; i < rootMenuItems.length; i++) {
        var item = rootMenuItems[i];
        var id = item.getAttribute("id");
        var isOpen = item.hasAttribute("open");
        rootMenuStates[id] = isOpen;
    }
    var jsonMenuStates = JSON.stringify(rootMenuStates);
    localStorage.setItem("menuState", jsonMenuStates);
}

function restoreMenuState() {
    var leftNavigation = document.getElementById("left-navigation");
    if (!leftNavigation) {
        return;
    }
    var jsonMenuStates = localStorage.getItem("menuState");
    var rootMenuStates = JSON.parse(jsonMenuStates) || {};
    var rootMenuItems = leftNavigation.getElementsByTagName("details");
    for (var i = 0; i < rootMenuItems.length; i++) {
        var item = rootMenuItems[i];
        var id = item.getAttribute("id");
        var isOpen = rootMenuStates[id];
        if (isOpen === undefined) {
            isOpen = false;
        }
        if (isOpen) {
            item.setAttribute("open", "");
        } else {
            item.removeAttribute("open");
        }
    }
}

// Trap tab-targeting for ADA-compliant use
// https://scribe.bus-hit.me/how-to-trap-focus-inside-modal-to-make-it-ada-compliant-6a50f9a70700
function modal_focus(modal_name) {
    const focusableElements =
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
    const modal = document.querySelector(modal_name);

    const firstFocusableElement = modal.querySelectorAll(focusableElements)[0];
    const focusableContent = modal.querySelectorAll(focusableElements);
    const lastFocusableElement = focusableContent[focusableContent.length - 1];

    document.addEventListener('keydown', function (e) {
        let isTabPressed = e.key === 'Tab' || e.keyCode === 9;

        if (!isTabPressed) {
            return;
        }

        if (e.shiftKey) {
            if (document.activeElement === firstFocusableElement) {
                lastFocusableElement.focus();
                e.preventDefault();
            }
        } else {
            if (document.activeElement === lastFocusableElement) {
                firstFocusableElement.focus();
                e.preventDefault();
            }
        }
    });

    firstFocusableElement.focus();
}

// Hotkeys
document.addEventListener("keydown", function (event) {
    if (event.key === "Escape" || event.keyCode === 27) {
        window.location.hash = "#";
    }
    // Ctrl/Cmd+g for search modal
    else if (event.key == "g") {
        const nav_search_button = document.getElementById("nav_search_button");
        if (event.ctrlKey || event.metaKey) {
            event.preventDefault();
            nav_search_button.click();
            modal_focus("#search_modal");
        }
    }
    // Ctrl/Cmd+n for new ghost modal
    else if (event.key == "n") {
        const nav_new_button = document.getElementById("nav_new_button");
        if (event.ctrlKey || event.metaKey) {
            event.preventDefault();
            nav_new_button.click();
            modal_focus("#new-ghost-modal");
        }
    }
});

// Run various onload/unload functions since script is loaded before elements are
window.onload = function () {
    restoreMenuState();
};
window.onbeforeunload = saveMenuState;
