// Command-palette / keyboard bridge.
// A single window keydown listener forwards keys into .NET (CommandPalette.OnKey). The focus guard
// lives here: trade hotkeys are never forwarded while an input/textarea/select/contenteditable is
// focused. While the palette is open, navigation keys are always forwarded so the ranked list can be
// driven from the search box. Keep this minimal — all decisions beyond the guard live in .NET.
let dotnet = null;
let paletteOpen = false;
const EDIT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];
const NAV = ['Escape', 'ArrowDown', 'ArrowUp', 'Enter'];
const HOTKEYS = ['b', 'B', 's', 'S', 'f', 'F', '?', '+', '=', '-', 'Escape'];

function editable() {
    const a = document.activeElement;
    if (!a) return false;
    if (a.isContentEditable) return true;
    return EDIT_TAGS.includes(a.tagName);
}

function onKey(e) {
    if (!dotnet) return;
    const k = e.key;
    const mod = e.ctrlKey || e.metaKey;

    // Global palette toggle — works even from inside a field.
    if (mod && (k === 'k' || k === 'K')) {
        e.preventDefault();
        dotnet.invokeMethodAsync('OnKey', 'k', e.ctrlKey, e.metaKey, e.altKey, e.shiftKey, editable());
        return;
    }

    if (paletteOpen) {
        if (NAV.includes(k)) e.preventDefault();       // don't let the shell scroll / blur
        dotnet.invokeMethodAsync('OnKey', k, e.ctrlKey, e.metaKey, e.altKey, e.shiftKey, editable());
        return;
    }

    // Palette closed: only forward known hotkeys, and never a trade key while typing.
    if (mod || e.altKey) return;
    if (editable()) return;
    if (HOTKEYS.includes(k)) {
        dotnet.invokeMethodAsync('OnKey', k, e.ctrlKey, e.metaKey, e.altKey, e.shiftKey, false);
    }
}

export function init(ref) {
    dotnet = ref;
    window.addEventListener('keydown', onKey, true);
}

export function setPaletteOpen(v) { paletteOpen = !!v; }

export function dispose() {
    window.removeEventListener('keydown', onKey, true);
    dotnet = null;
}
