const hudCtx = {
    container: null,
    pacienciaFill: null,
    progresoFill: null,
    nivelValue: null,
    vidasValue: null,
    buffsContainer: null,
    frameCount: 0
};

function initHUD() {
    hudCtx.container = document.getElementById('hud');
    hudCtx.pacienciaFill = document.getElementById('paciencia-fill');
    hudCtx.progresoFill = document.getElementById('progreso-fill');
    hudCtx.nivelValue = document.getElementById('nivel-value');
    hudCtx.vidasValue = document.getElementById('vidas-value');
    hudCtx.buffsContainer = document.getElementById('hud-buffs');
}

function showHUD() {
    if (hudCtx.container) hudCtx.container.hidden = false;
    const menuBtn = document.getElementById('menu-btn');
    if (menuBtn) menuBtn.hidden = false;
}

function hideHUD() {
    if (hudCtx.container) hudCtx.container.hidden = true;
    const menuBtn = document.getElementById('menu-btn');
    if (menuBtn) menuBtn.hidden = true;
}

function updateHUD() {
    hudCtx.frameCount++;
    if (hudCtx.frameCount % 6 !== 0) return;

    if (hudCtx.pacienciaFill) {
        const pct = (gameState.paciencia / PACIENCIA_INICIAL) * 100;
        hudCtx.pacienciaFill.style.width = pct + '%';
        hudCtx.pacienciaFill.classList.remove('warning', 'danger');
        if (pct < 25) hudCtx.pacienciaFill.classList.add('danger');
        else if (pct < 55) hudCtx.pacienciaFill.classList.add('warning');
        hudCtx.pacienciaFill.classList.toggle('sprinting', !!gameState.sprinting);
    }

    if (hudCtx.progresoFill) {
        const prog = progresoCasa(getPlayerPos().z) * 100;
        hudCtx.progresoFill.style.width = prog + '%';
    }

    if (hudCtx.nivelValue) {
        hudCtx.nivelValue.textContent = String((gameState.nivelIdx || 0) + 1);
    }

    if (hudCtx.vidasValue) {
        const v = Math.max(0, gameState.vidas);
        hudCtx.vidasValue.textContent = '❤'.repeat(v) + '·'.repeat(VIDAS_INICIALES - v);
    }

    if (hudCtx.buffsContainer && typeof getActiveBuffs === 'function') {
        const buffs = getActiveBuffs();
        if (buffs.length === 0) {
            if (hudCtx.buffsContainer.childElementCount > 0) hudCtx.buffsContainer.innerHTML = '';
        } else {
            const parts = buffs.map((b) => {
                const icon = b.id === 'auriculares' ? '🎧' : '✦';
                return `<span class="hud-buff">${icon} ${b.remaining.toFixed(1)}s</span>`;
            });
            hudCtx.buffsContainer.innerHTML = parts.join('');
        }
    }
}
