// input.js : capture clavier + souris, envoi au serveur

import { send } from './network.js';

const moveKeys = { up: false, down: false, left: false, right: false };

let lastDx = 0, lastDy = 0;
let inputBlocked = false;

export function setInputBlocked(blocked) {
    if (blocked && !inputBlocked) {
        // on coupe le mouvement cote serveur si on bougeait, sinon le perso continue d avancer
        if (lastDx !== 0 || lastDy !== 0) {
            lastDx = 0; lastDy = 0;
            send('input', { dx: 0, dy: 0 });
        }
        moveKeys.up = moveKeys.down = moveKeys.left = moveKeys.right = false;
    }
    inputBlocked = blocked;
}

export function isInputBlocked() { return inputBlocked; }


const MOVE_KEY_MAP = {
    'z': 'up',    'ArrowUp':    'up',
    's': 'down',  'ArrowDown':  'down',
    'q': 'left',  'ArrowLeft':  'left',
    'd': 'right', 'ArrowRight': 'right',
};

// AZERTY : on utilise e.code (Digit1) plutot que e.key (qui donne '&', 'é')
const ABILITY_CODE_MAP = { 'Digit1': 1, 'Digit2': 2 };


function computeDirection() {
    let dx = 0, dy = 0;
    if (moveKeys.left)  dx -= 1;
    if (moveKeys.right) dx += 1;
    if (moveKeys.up)    dy -= 1;
    if (moveKeys.down)  dy += 1;

    // normaliser sinon la diagonale est plus rapide que les axes
    if (dx !== 0 && dy !== 0) {
        const inv = 1 / Math.SQRT2;
        dx *= inv;
        dy *= inv;
    }

    return { dx, dy };
}


function onKeyDown(e, getTarget) {
    if (inputBlocked) return;

    const moveAction = MOVE_KEY_MAP[e.key];
    if (moveAction) {
        e.preventDefault();
        if (moveKeys[moveAction]) return;
        moveKeys[moveAction] = true;

        const { dx, dy } = computeDirection();
        if (dx !== lastDx || dy !== lastDy) {
            lastDx = dx; lastDy = dy;
            send('input', { dx, dy });
        }
        return;
    }

    const abilityId = ABILITY_CODE_MAP[e.code];
    if (abilityId) {
        e.preventDefault();
        const { wx, wy } = getTarget();
        send('ability', { id: abilityId, tx: wx, ty: wy });
        return;
    }

    if (e.key === 'e') {
        e.preventDefault();
        const { wx, wy } = getTarget();
        send('displacement', { tx: wx, ty: wy });
        return;
    }
}


function onKeyUp(e) {
    if (inputBlocked) return;

    const moveAction = MOVE_KEY_MAP[e.key];
    if (!moveAction) return;

    e.preventDefault();
    if (!moveKeys[moveAction]) return;

    moveKeys[moveAction] = false;
    const { dx, dy } = computeDirection();

    if (dx !== lastDx || dy !== lastDy) {
        lastDx = dx; lastDy = dy;
        send('input', { dx, dy });
    }
}


export function startInputTracking(getTarget) {
    document.addEventListener('keydown', e => onKeyDown(e, getTarget));
    document.addEventListener('keyup',   e => onKeyUp(e));
}
