(function () {
    document.addEventListener('keydown', function (e) {
        if (!e.altKey || !e.shiftKey) return;
        switch (e.key) {
            case 'E':
                e.preventDefault();
                // replace, not assign — same reasoning as history-nav.js.
                window.location.replace(window.location.pathname + '?edit');
                break;
            case 'N':
                e.preventDefault();
                if (typeof newPage === 'function') newPage();
                break;
            case 'M':
                e.preventDefault();
                if (window.location.pathname !== '/' && typeof movePage === 'function') movePage();
                break;
            case 'F':
                var input = document.querySelector('.search-input');
                if (!input) return;
                e.preventDefault();
                input.focus();
                input.select();
                break;
        }
    });
})();

// Wire a dropdown: clicking the trigger toggles its sibling .dropdown-menu;
// clicking outside or pressing Escape closes all wired menus. Safe to call
// multiple times on the same trigger (no-op on re-registration).
function wireDropdown(trigger) {
    if (!trigger || trigger.dataset.wired) return;
    var menu = trigger.parentElement && trigger.parentElement.querySelector('.dropdown-menu');
    if (!menu) return;
    trigger.dataset.wired = '1';
    trigger.addEventListener('click', function (e) {
        e.stopPropagation();
        document.querySelectorAll('.dropdown-menu.is-open').forEach(function (m) {
            if (m !== menu) m.classList.remove('is-open');
        });
        menu.classList.toggle('is-open');
    });
    menu.addEventListener('click', function () { menu.classList.remove('is-open'); });
}

document.addEventListener('click', function (e) {
    document.querySelectorAll('.dropdown-menu.is-open').forEach(function (menu) {
        if (!menu.parentElement.contains(e.target)) menu.classList.remove('is-open');
    });
});
document.addEventListener('keydown', function (e) {
    if (e.key !== 'Escape') return;
    document.querySelectorAll('.dropdown-menu.is-open').forEach(function (menu) {
        menu.classList.remove('is-open');
    });
});
