const bocadillosCtx = {
    layer: null,
    activos: []
};

const _bocVec = (typeof THREE !== 'undefined') ? new THREE.Vector3() : null;

function initBocadillos() {
    let layer = document.getElementById('bocadillos-layer');
    if (!layer) {
        layer = document.createElement('div');
        layer.id = 'bocadillos-layer';
        document.body.appendChild(layer);
    }
    bocadillosCtx.layer = layer;
}

function mostrarBocadillo(npc, frase, duracionMs) {
    if (!bocadillosCtx.layer || !npc || !npc.mesh) return;
    const dur = duracionMs || 2500;

    if (npc._bocadilloActivo) {
        npc._bocadilloActivo.expira = performance.now() + 600;
    }

    const div = document.createElement('div');
    div.className = 'bocadillo';
    div.textContent = frase;
    bocadillosCtx.layer.appendChild(div);

    const entry = {
        div: div,
        npc: npc,
        expira: performance.now() + dur,
        offsetY: 2.7
    };
    bocadillosCtx.activos.push(entry);
    npc._bocadilloActivo = entry;
}

function updateBocadillos() {
    if (!bocadillosCtx.layer || !sceneCtx.camera || !_bocVec) return;
    const now = performance.now();
    const cam = sceneCtx.camera;
    const w = window.innerWidth;
    const h = window.innerHeight;

    for (let i = bocadillosCtx.activos.length - 1; i >= 0; i--) {
        const b = bocadillosCtx.activos[i];
        const npc = b.npc;
        if (now >= b.expira || !npc.mesh || !npc.mesh.visible || npc.estado === 'done') {
            b.div.remove();
            if (npc._bocadilloActivo === b) npc._bocadilloActivo = null;
            bocadillosCtx.activos.splice(i, 1);
            continue;
        }
        _bocVec.set(npc.pos.x, npc.pos.y + b.offsetY, npc.pos.z);
        _bocVec.project(cam);
        if (_bocVec.z > 1 || _bocVec.x < -1.4 || _bocVec.x > 1.4) {
            b.div.style.display = 'none';
            continue;
        }
        const sx = (_bocVec.x * 0.5 + 0.5) * w;
        const sy = (-_bocVec.y * 0.5 + 0.5) * h;
        b.div.style.display = '';
        b.div.style.left = sx + 'px';
        b.div.style.top = sy + 'px';
        const remaining = b.expira - now;
        if (remaining < 400) {
            b.div.style.opacity = String(Math.max(0, remaining / 400));
        } else {
            b.div.style.opacity = '1';
        }
    }
}

function clearBocadillos() {
    for (const b of bocadillosCtx.activos) {
        if (b.npc) b.npc._bocadilloActivo = null;
        b.div.remove();
    }
    bocadillosCtx.activos = [];
}
