// network.js : websocket client (ouverture, send, listeners par type)

const WS_URL = `ws://${location.hostname}:8000/ws`;

let _ws = null;
const _handlers = {};


export function connect() {
    _ws = new WebSocket(WS_URL);
    _ws.onopen  = () => _emit({ type: '_open' });
    _ws.onclose = () => _emit({ type: '_close' });
    _ws.onmessage = ({ data }) => {
        try {
            _emit(JSON.parse(data));
        } catch {
            console.warn('SOULGATE — message non-JSON reçu');
        }
    };
}


export function send(type, data = {}) {
    if (_ws?.readyState === WebSocket.OPEN) {
        _ws.send(JSON.stringify({ type, ...data }));
    }
}


export function on(type, fn) {
    _handlers[type] = fn;
}


function _emit(msg) {
    _handlers[msg.type]?.(msg);
}
