// La Paguita - Minijuego: Cola de Extranjería

(function () {
    const NUMBERS_BEFORE = 25;
    const SPEED_FAST_MS = 250;
    const SPEED_SLOW_MS = 700;
    const SLOWDOWN_START = 10; // Slow down when this many away
    const OVERSHOOT = 8; // How far past your number it goes

    const PAUSA_CHANCE = 0.15;
    const PAUSA_DURATION_MS = 2000;
    const PAUSA_MESSAGES = [
        '☕ El funcionario se ha ido a desayunar...',
        '🚬 Pausa para fumar del funcionario...',
        '📱 El funcionario está hablando por teléfono...',
        '🖨️ Se ha atascado la impresora...',
        '💻 "El sistema está caído"...'
    ];

    function init(area, contexto, onComplete) {
        const targetNum = 30 + Math.floor(Math.random() * 70); // 30-99
        const prefix = ['A', 'B', 'C', 'G', 'H'][Math.floor(Math.random() * 5)];
        let currentNum = targetNum - NUMBERS_BEFORE;
        let pressed = false;
        let gameOver = false;
        let counterTimer = null;
        let pausaActive = false;

        area.innerHTML = `
            <div class="cola-tu-numero">Tu turno: ${prefix}-${targetNum}</div>
            <div class="cola-display" id="cola-display">${prefix}-${currentNum}</div>
            <div class="cola-hint" id="cola-hint">Esperando tu turno...</div>
            <button class="cola-btn" id="cola-btn" disabled>¡ESTOY AQUÍ!</button>
            <div class="cola-result" id="cola-result"></div>
        `;

        const displayEl = document.getElementById('cola-display');
        const hintEl = document.getElementById('cola-hint');
        const btn = document.getElementById('cola-btn');
        const resultEl = document.getElementById('cola-result');

        function getSpeed() {
            const distance = targetNum - currentNum;
            if (distance > SLOWDOWN_START) return SPEED_FAST_MS;
            if (distance > 5) return SPEED_FAST_MS + (SLOWDOWN_START - distance) * ((SPEED_SLOW_MS - SPEED_FAST_MS) / SLOWDOWN_START);
            return SPEED_SLOW_MS + (5 - distance) * 80;
        }

        function advance() {
            if (gameOver) return;

            // Random pause
            if (!pausaActive && currentNum > targetNum - SLOWDOWN_START && currentNum < targetNum - 3 && Math.random() < PAUSA_CHANCE) {
                pausaActive = true;
                const msg = PAUSA_MESSAGES[Math.floor(Math.random() * PAUSA_MESSAGES.length)];
                hintEl.textContent = msg;
                hintEl.className = 'cola-hint funcionario';
                setTimeout(() => {
                    pausaActive = false;
                    hintEl.textContent = 'Esperando tu turno...';
                    hintEl.className = 'cola-hint';
                    scheduleNext();
                }, PAUSA_DURATION_MS);
                return;
            }

            currentNum++;
            displayEl.textContent = prefix + '-' + currentNum;

            // Enable button when close
            const distance = Math.abs(currentNum - targetNum);
            if (distance <= 5 && !pressed) {
                btn.disabled = false;
                if (currentNum === targetNum) {
                    hintEl.textContent = '¡¡TU NÚMERO!! ¡AHORA!';
                    hintEl.className = 'cola-hint funcionario';
                } else if (currentNum > targetNum) {
                    hintEl.textContent = '¡Se ha pasado tu turno!';
                    hintEl.className = 'cola-hint funcionario';
                } else {
                    hintEl.textContent = '¡Ya casi!';
                    hintEl.className = 'cola-hint';
                }
            }

            // Game ends when we overshoot enough
            if (currentNum >= targetNum + OVERSHOOT) {
                if (!pressed) handlePress(true);
                return;
            }

            scheduleNext();
        }

        function scheduleNext() {
            if (gameOver) return;
            counterTimer = setTimeout(advance, getSpeed());
        }

        function handlePress(autoMiss) {
            if (pressed || gameOver) return;
            pressed = true;
            gameOver = true;
            btn.disabled = true;
            clearTimeout(counterTimer);

            const diff = Math.abs(currentNum - targetNum);

            let papeles, clase, texto;
            if (autoMiss) {
                papeles = 0;
                clase = 'mal';
                texto = '😴 Te has dormido en la cola. 0 papeles.';
            } else if (diff === 0) {
                papeles = 4;
                clase = 'perfecto';
                texto = '🎯 ¡PERFECTO! Tu número exacto. +4 papeles';
            } else if (diff === 1) {
                papeles = 2;
                clase = 'bien';
                texto = '👍 Casi perfecto. +2 papeles';
            } else if (diff <= 3) {
                papeles = 1;
                clase = 'bien';
                texto = '😐 Por los pelos. +1 papel';
            } else {
                papeles = 0;
                clase = 'mal';
                texto = '❌ Demasiado lejos. 0 papeles.';
            }

            // Apply character bonus
            const personaje = getPersonajeActual();
            if (personaje && personaje.bonus && personaje.bonus.papeles && papeles > 0) {
                papeles = Math.floor(papeles * personaje.bonus.papeles);
            }

            resultEl.textContent = texto;
            resultEl.className = 'cola-result ' + clase;
            hintEl.textContent = '';
            updateMinigameScore(`Diferencia: ${autoMiss ? 'perdido' : diff}`);

            setTimeout(() => {
                onComplete({
                    tipo: 'cola_extranjeria',
                    papeles: papeles,
                    diff: diff,
                    perfecto: diff === 0 && !autoMiss,
                    contexto: contexto
                });
            }, 1500);
        }

        // Button click
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            handlePress(false);
        });

        // Keyboard (space/enter)
        function onKeyDown(e) {
            if ((e.key === ' ' || e.key === 'Enter') && !btn.disabled) {
                e.preventDefault();
                handlePress(false);
            }
        }
        document.addEventListener('keydown', onKeyDown);

        // Clean up keyboard on finish
        const originalOnComplete = onComplete;
        onComplete = function (result) {
            document.removeEventListener('keydown', onKeyDown);
            originalOnComplete(result);
        };

        // Start counter
        scheduleNext();
    }

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