// La Paguita - Minijuego: Trapicheo del Mercadillo (Heredia)

(function () {
    const TOTAL_CUSTOMERS = 3;
    const BAR_SPEEDS = [2000, 1500, 1100]; // ms per full oscillation cycle
    const MIN_PRICE = 5;
    const MAX_PRICE = 80;
    const GUARDIA_PER_SALE = 25; // % per sale
    const CUSTOMER_EMOJIS = ['🧔', '👩', '👴', '🧑‍🦱', '👨‍🦳', '🧕'];
    const CUSTOMER_ITEMS = ['"¿Cuánto por el reloj?"', '"¿Tienes móviles?"', '"¿Qué llevas ahí?"', '"¿Esto es original?"', '"Dame dos camisetas"', '"¿Tienes bolsos?"'];

    function init(area, contexto, onComplete) {
        let currentCustomer = 0;
        let earnings = 0;
        let salesCount = 0;
        let guardia = 0;
        let caught = false;
        let gameOver = false;
        let barAnimFrame = null;
        let barPosition = 0; // 0-1
        let barDirection = 1;
        let lastBarTime = 0;

        area.innerHTML = `
            <div class="mercadillo-cliente" id="mercadillo-cliente"></div>
            <div class="mercadillo-bar-wrap" id="mercadillo-bar-wrap">
                <div class="mercadillo-bar-zones">
                    <span class="zone zone-low">💩</span>
                    <span class="zone zone-mid">👍</span>
                    <span class="zone zone-high">💰</span>
                    <span class="zone zone-mid">👍</span>
                    <span class="zone zone-low">💩</span>
                </div>
                <div class="mercadillo-bar-indicator" id="mercadillo-indicator"></div>
            </div>
            <div class="mercadillo-guardia">
                <span>🚔 Sospecha:</span>
                <div class="mercadillo-guardia-bar"><div class="mercadillo-guardia-fill" id="mercadillo-guardia-fill" style="width: 0%"></div></div>
                <span id="mercadillo-guardia-pct">0%</span>
            </div>
            <div class="mercadillo-controls">
                <button class="mercadillo-btn-vender" id="mercadillo-vender">💰 VENDER</button>
                <button class="mercadillo-btn-pasar" id="mercadillo-pasar">🏃 PASAR</button>
            </div>
        `;

        const clienteEl = document.getElementById('mercadillo-cliente');
        const indicatorEl = document.getElementById('mercadillo-indicator');
        const guardiaFill = document.getElementById('mercadillo-guardia-fill');
        const guardiaPct = document.getElementById('mercadillo-guardia-pct');
        const venderBtn = document.getElementById('mercadillo-vender');
        const pasarBtn = document.getElementById('mercadillo-pasar');

        function showCustomer() {
            if (currentCustomer >= TOTAL_CUSTOMERS || gameOver) {
                endGame();
                return;
            }

            const emoji = CUSTOMER_EMOJIS[Math.floor(Math.random() * CUSTOMER_EMOJIS.length)];
            const item = CUSTOMER_ITEMS[Math.floor(Math.random() * CUSTOMER_ITEMS.length)];
            clienteEl.textContent = `Cliente ${currentCustomer + 1}/${TOTAL_CUSTOMERS}: ${emoji} ${item}`;

            venderBtn.disabled = false;
            pasarBtn.disabled = false;

            // Start bar oscillation
            barPosition = 0;
            barDirection = 1;
            lastBarTime = performance.now();
            animateBar();

            updateMinigameScore(`💶 ${Math.floor(earnings)} | 🚔 ${Math.floor(guardia)}%`);
        }

        function animateBar() {
            if (gameOver) return;
            const now = performance.now();
            const speed = BAR_SPEEDS[Math.min(currentCustomer, BAR_SPEEDS.length - 1)];
            const delta = (now - lastBarTime) / speed;
            lastBarTime = now;

            barPosition += delta * barDirection * 2; // full cycle = 2x speed
            if (barPosition >= 1) { barPosition = 1; barDirection = -1; }
            if (barPosition <= 0) { barPosition = 0; barDirection = 1; }

            indicatorEl.style.left = (barPosition * 100) + '%';
            barAnimFrame = requestAnimationFrame(animateBar);
        }

        function getPriceFromPosition(pos) {
            // Position 0-1 maps to a bell curve: center = highest
            // 0-0.2 = low, 0.2-0.4 = mid, 0.4-0.6 = high, 0.6-0.8 = mid, 0.8-1 = low
            const center = Math.abs(pos - 0.5) * 2; // 0 at center, 1 at edges
            if (center < 0.2) return MIN_PRICE + Math.floor((MAX_PRICE - MIN_PRICE) * (1 - center / 0.2));
            if (center < 0.6) return MIN_PRICE + Math.floor((MAX_PRICE - MIN_PRICE) * 0.5 * (1 - (center - 0.2) / 0.4));
            return MIN_PRICE + Math.floor((MAX_PRICE - MIN_PRICE) * 0.1);
        }

        function handleVender() {
            if (gameOver) return;
            cancelAnimationFrame(barAnimFrame);
            venderBtn.disabled = true;
            pasarBtn.disabled = true;

            const price = getPriceFromPosition(barPosition);
            earnings += price;
            salesCount++;
            guardia += GUARDIA_PER_SALE;

            // Update guardia display
            guardiaFill.style.width = Math.min(100, guardia) + '%';
            guardiaPct.textContent = Math.floor(guardia) + '%';
            if (guardia >= 75) guardiaFill.classList.add('danger');

            clienteEl.textContent = `💰 ¡Vendido por ${price}💶!`;

            if (guardia >= 100) {
                caught = true;
                earnings = Math.floor(earnings * 0.5);
                setTimeout(endGame, 800);
                return;
            }

            currentCustomer++;
            setTimeout(showCustomer, 1000);
        }

        function handlePasar() {
            if (gameOver) return;
            cancelAnimationFrame(barAnimFrame);
            venderBtn.disabled = true;
            pasarBtn.disabled = true;

            clienteEl.textContent = '🏃 Pasas del cliente...';
            currentCustomer++;
            setTimeout(showCustomer, 800);
        }

        function endGame() {
            if (gameOver) return;
            gameOver = true;
            cancelAnimationFrame(barAnimFrame);
            document.removeEventListener('keydown', onKeyDown);
            venderBtn.disabled = true;
            pasarBtn.disabled = true;

            // Apply character bonus
            const personaje = getPersonajeActual();
            if (personaje && personaje.bonus && personaje.bonus.trabajoB) {
                earnings = Math.floor(earnings * personaje.bonus.trabajoB);
            }

            const perfecto = salesCount === TOTAL_CUSTOMERS && earnings >= 150 && !caught;
            if (perfecto) earnings += 20;

            const label = caught ? '🚔 ¡Guardia Civil!' : perfecto ? '⭐ ¡Príncipe del Mercadillo!' : '🏪 Fin del mercadillo';
            clienteEl.textContent = label;
            updateMinigameScore(`${salesCount} ventas · ${Math.floor(earnings)}💶`);

            setTimeout(() => {
                onComplete({
                    tipo: 'trapicheo_mercadillo',
                    earnings: Math.floor(earnings),
                    caught: caught,
                    salesCount: salesCount,
                    perfecto: perfecto,
                    contexto: contexto
                });
            }, 1200);
        }

        // Buttons
        venderBtn.addEventListener('click', (e) => { e.preventDefault(); handleVender(); });
        pasarBtn.addEventListener('click', (e) => { e.preventDefault(); handlePasar(); });

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

        showCustomer();
    }

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