const controlsCtx = {
    keys: {},
    actionPressed: false,
    actionEdge: false
};

function initControls() {
    window.addEventListener('keydown', (e) => {
        const k = e.key.toLowerCase();
        controlsCtx.keys[k] = true;
        if (k === ' ' || k === 'enter') {
            if (!controlsCtx.actionPressed) controlsCtx.actionEdge = true;
            controlsCtx.actionPressed = true;
        }
        if (k === 'arrowup' || k === 'arrowdown' || k === 'arrowleft' || k === 'arrowright' || k === ' ') {
            e.preventDefault();
        }
    });
    window.addEventListener('keyup', (e) => {
        const k = e.key.toLowerCase();
        controlsCtx.keys[k] = false;
        if (k === ' ' || k === 'enter') {
            controlsCtx.actionPressed = false;
        }
    });
    window.addEventListener('blur', () => {
        controlsCtx.keys = {};
        controlsCtx.actionPressed = false;
    });
}

function readInput() {
    let mx = 0, my = 0;
    if (controlsCtx.keys['w'] || controlsCtx.keys['arrowup']) my -= 1;
    if (controlsCtx.keys['s'] || controlsCtx.keys['arrowdown']) my += 1;
    if (controlsCtx.keys['a'] || controlsCtx.keys['arrowleft']) mx -= 1;
    if (controlsCtx.keys['d'] || controlsCtx.keys['arrowright']) mx += 1;

    if (mx !== 0 && my !== 0) {
        const inv = 1 / Math.SQRT2;
        mx *= inv;
        my *= inv;
    }

    if (joystickEnabled()) {
        const jv = readJoystick();
        if (jv.x !== 0 || jv.y !== 0) {
            mx = jv.x;
            my = jv.y;
        }
    }

    const action = controlsCtx.actionPressed || readJoystickAction();
    return { move: { x: mx, y: my }, action: action };
}

function consumeActionEdge() {
    const v = controlsCtx.actionEdge;
    controlsCtx.actionEdge = false;
    return v;
}
