// La Paguita - Minijuego: Drama en el Juzgado (Mari Carmen)

(function () {
    const DURATION_S = 10;
    const DRAIN_PER_S = 3; // meter drains 3% per second
    const TAP_GAIN = 5; // each tap adds 5%
    const FISCAL_PENALTY = 30; // tapping during objection costs 30%
    const FISCAL_TIMES = [3000, 7000]; // ms when fiscal interrupts
    const FISCAL_DURATION = 1500; // ms objection lasts

    function init(area, contexto, onComplete) {
        let meter = 0;
        let gameOver = false;
        let fiscalActive = false;
        let fiscalFails = 0;
        let startTime = performance.now();
        let tickTimer = null;
        let fiscalTimers = [];

        area.innerHTML = `
            <div class="drama-meter-wrap">
                <div class="drama-meter-fill" id="drama-fill" style="width: 0%"></div>
            </div>
            <div class="drama-meter-label" id="drama-label">😭 Llanto: 0%</div>
            <div class="drama-fiscal" id="drama-fiscal">⚖️ ¡OBJECIÓN! No toques</div>
            <button class="drama-tap-area" id="drama-tap">😭 LLORAR</button>
            <div class="drama-hint" id="drama-hint">¡Toca rápido para llorar!</div>
        `;

        const fillEl = document.getElementById('drama-fill');
        const labelEl = document.getElementById('drama-label');
        const fiscalEl = document.getElementById('drama-fiscal');
        const tapBtn = document.getElementById('drama-tap');
        const hintEl = document.getElementById('drama-hint');

        function updateMeter() {
            meter = Math.max(0, Math.min(100, meter));
            if (fillEl) fillEl.style.width = meter + '%';
            if (labelEl) labelEl.textContent = `😭 Llanto: ${Math.floor(meter)}%`;
            updateMinigameScore(`${Math.floor(meter)}%`);
        }

        function handleTap(e) {
            if (e) e.preventDefault();
            if (gameOver) return;

            if (fiscalActive) {
                // Tapped during objection!
                meter -= FISCAL_PENALTY;
                fiscalFails++;
                if (hintEl) {
                    hintEl.textContent = '⚠️ ¡El juez sospecha!';
                    hintEl.className = 'drama-hint warning';
                }
                updateMeter();
                return;
            }

            meter += TAP_GAIN;
            updateMeter();

            if (meter >= 100) {
                endGame();
            }
        }

        function showFiscal() {
            if (gameOver) return;
            fiscalActive = true;
            if (fiscalEl) fiscalEl.classList.add('show');
            if (tapBtn) tapBtn.classList.add('objection');
            if (hintEl) {
                hintEl.textContent = '⚖️ ¡PARA! No toques nada';
                hintEl.className = 'drama-hint warning';
            }

            setTimeout(() => {
                fiscalActive = false;
                if (fiscalEl) fiscalEl.classList.remove('show');
                if (tapBtn) tapBtn.classList.remove('objection');
                if (hintEl && !gameOver) {
                    hintEl.textContent = '¡Sigue llorando!';
                    hintEl.className = 'drama-hint';
                }
            }, FISCAL_DURATION);
        }

        function endGame() {
            if (gameOver) return;
            gameOver = true;
            clearInterval(tickTimer);
            fiscalTimers.forEach(t => clearTimeout(t));
            document.removeEventListener('keydown', onKeyDown);

            const personaje = getPersonajeActual();
            const paguitas_mult = personaje && personaje.bonus ? personaje.bonus.paguitas : 1;

            let paguitas, papeles;
            const perfecto = meter >= 100;

            if (meter >= 100) {
                paguitas = Math.floor(80 * paguitas_mult);
                papeles = 3;
            } else if (meter >= 70) {
                paguitas = Math.floor(60 * paguitas_mult);
                papeles = 2;
            } else if (meter >= 40) {
                paguitas = Math.floor(30 * paguitas_mult);
                papeles = 1;
            } else {
                paguitas = 0;
                papeles = 0;
            }

            if (tapBtn) tapBtn.disabled = true;
            const resultText = perfecto ? '🏆 ¡OSCAR AL LLANTO!' : meter >= 40 ? '😢 El juez se conmueve...' : '😐 No ha colado';
            if (hintEl) {
                hintEl.textContent = resultText;
                hintEl.className = 'drama-hint';
            }

            setTimeout(() => {
                onComplete({
                    tipo: 'drama_juzgado',
                    meterFinal: Math.floor(meter),
                    paguitas: paguitas,
                    papeles: papeles,
                    fiscalFails: fiscalFails,
                    perfecto: perfecto,
                    contexto: contexto
                });
            }, 1200);
        }

        // Tap button
        tapBtn.addEventListener('click', handleTap);
        tapBtn.addEventListener('touchstart', handleTap);

        // Keyboard
        function onKeyDown(e) {
            if (e.key === ' ' || e.key === 'Enter') {
                e.preventDefault();
                handleTap();
            }
        }
        document.addEventListener('keydown', onKeyDown);

        // Drain + timer tick
        tickTimer = setInterval(() => {
            if (gameOver) return;
            meter -= DRAIN_PER_S * 0.2; // runs at 200ms intervals
            updateMeter();

            const elapsed = (performance.now() - startTime) / 1000;
            updateMinigameTimer(Math.max(0, DURATION_S - elapsed));

            if (elapsed >= DURATION_S) endGame();
        }, 200);

        // Schedule fiscal interruptions
        FISCAL_TIMES.forEach(t => {
            fiscalTimers.push(setTimeout(showFiscal, t));
        });

        updateMeter();
    }

    registrarMinijuego('drama_juzgado', init);
})();
