// La Paguita - Minijuego: Top Manta Sprint

(function () {
    const DURATION_S = 15;
    const CUSTOMER_INTERVAL_MS = 1200;
    const CUSTOMER_LIFETIME_MS = 2200;
    const POLICE_INTERVAL_MIN_MS = 3500;
    const POLICE_INTERVAL_MAX_MS = 5500;
    const POLICE_DURATION_MS = 2500;
    const POLICE_WARNING_MS = 500;

    const CUSTOMERS = ['🧳', '📸', '👒', '🕶️', '👜', '🎒', '💅', '🧓'];
    const SALE_VALUES = [5, 6, 7, 8, 9, 10];

    function init(area, contexto, onComplete) {
        let earnings = 0;
        let totalCustomers = 0;
        let soldCount = 0;
        let caught = false;
        let hiding = false;
        let policePresent = false;
        let gameOver = false;
        let startTime = performance.now();
        let customerTimer = null;
        let policeTimer = null;
        let endTimer = null;
        let tickTimer = null;

        area.innerHTML = `
            <div class="manta-earnings" id="manta-earnings">💶 0</div>
            <div class="manta-field" id="manta-field"></div>
            <div class="manta-controls">
                <button class="manta-btn-recoger" id="manta-recoger">🧹 RECOGER MANTA</button>
            </div>
        `;

        const field = document.getElementById('manta-field');
        const earningsEl = document.getElementById('manta-earnings');
        const recogerBtn = document.getElementById('manta-recoger');

        function spawnCustomer() {
            if (gameOver) return;
            totalCustomers++;

            const entity = document.createElement('span');
            entity.className = 'manta-entity customer';
            entity.textContent = CUSTOMERS[Math.floor(Math.random() * CUSTOMERS.length)];
            entity.dataset.value = SALE_VALUES[Math.floor(Math.random() * SALE_VALUES.length)];

            // Random position
            const x = 10 + Math.random() * 70; // 10-80% from left
            const y = 10 + Math.random() * 60; // 10-70% from top
            entity.style.left = x + '%';
            entity.style.top = y + '%';

            entity.addEventListener('click', (e) => {
                e.preventDefault();
                if (gameOver || entity.classList.contains('sold')) return;

                if (policePresent && !hiding) {
                    // Caught selling during police
                    caught = true;
                    endGame();
                    return;
                }

                if (hiding) return; // Can't sell while hiding

                const val = parseInt(entity.dataset.value);
                earnings += val;
                soldCount++;
                earningsEl.textContent = '💶 ' + Math.floor(earnings);
                entity.classList.add('sold');

                // Floating feedback
                const floater = document.createElement('span');
                floater.className = 'manta-floater';
                floater.textContent = '+' + val + '💶';
                floater.style.left = entity.style.left;
                floater.style.top = entity.style.top;
                field.appendChild(floater);
                setTimeout(() => floater.remove(), 800);
            });

            field.appendChild(entity);

            // Auto-remove after lifetime
            setTimeout(() => {
                if (!entity.classList.contains('sold')) {
                    entity.style.opacity = '0';
                    setTimeout(() => entity.remove(), 300);
                }
            }, CUSTOMER_LIFETIME_MS);
        }

        function spawnPolice() {
            if (gameOver) return;
            policePresent = false;

            // Warning first
            const warning = document.createElement('div');
            warning.className = 'manta-warning';
            warning.textContent = '🚨 ¡POLICÍA!';
            field.appendChild(warning);

            setTimeout(() => {
                if (gameOver) { warning.remove(); return; }
                warning.remove();
                policePresent = true;

                const cop = document.createElement('span');
                cop.className = 'manta-entity policia';
                cop.textContent = '👮';
                cop.style.left = (20 + Math.random() * 60) + '%';
                cop.style.top = (20 + Math.random() * 50) + '%';
                field.appendChild(cop);

                setTimeout(() => {
                    policePresent = false;
                    cop.style.opacity = '0';
                    setTimeout(() => cop.remove(), 300);

                    if (hiding) {
                        hiding = false;
                        recogerBtn.classList.remove('hiding');
                        recogerBtn.textContent = '🧹 RECOGER MANTA';
                    }

                    // Schedule next police
                    if (!gameOver) {
                        const nextIn = POLICE_INTERVAL_MIN_MS + Math.random() * (POLICE_INTERVAL_MAX_MS - POLICE_INTERVAL_MIN_MS);
                        policeTimer = setTimeout(spawnPolice, nextIn);
                    }
                }, POLICE_DURATION_MS);
            }, POLICE_WARNING_MS);
        }

        // Recoger button
        recogerBtn.addEventListener('click', (e) => {
            e.preventDefault();
            if (gameOver || hiding) return;
            hiding = true;
            recogerBtn.classList.add('hiding');
            recogerBtn.textContent = '🙈 ESCONDIDO...';
        });

        function endGame() {
            gameOver = true;
            clearInterval(customerTimer);
            clearTimeout(policeTimer);
            clearTimeout(endTimer);
            clearInterval(tickTimer);

            if (caught) {
                earnings = Math.floor(earnings * 0.5);
            }

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

            const perfecto = !caught && soldCount > 0 && soldCount >= totalCustomers * 0.8;
            if (perfecto) earnings += 15;

            // Show result
            field.innerHTML = caught
                ? '<div style="padding:2rem;font-size:1.5rem">🚔 ¡TE HAN PILLADO!</div>'
                : '<div style="padding:2rem;font-size:1.5rem">🏁 ¡Tiempo!</div>';

            earningsEl.textContent = '💶 ' + Math.floor(earnings) + (perfecto ? ' ⭐' : '');
            updateMinigameScore(caught ? 'Pillado - mitad de ganancias' : `${soldCount} ventas`);

            setTimeout(() => {
                onComplete({
                    tipo: 'top_manta',
                    earnings: Math.floor(earnings),
                    caught: caught,
                    perfecto: perfecto,
                    soldCount: soldCount,
                    contexto: contexto
                });
            }, 1500);
        }

        // Timer tick
        tickTimer = setInterval(() => {
            if (gameOver) return;
            const elapsed = (performance.now() - startTime) / 1000;
            const remaining = Math.max(0, DURATION_S - elapsed);
            updateMinigameTimer(remaining);
            if (remaining <= 0) endGame();
        }, 200);

        // Start spawning
        customerTimer = setInterval(() => {
            if (!gameOver && !policePresent) spawnCustomer();
        }, CUSTOMER_INTERVAL_MS);

        // First police after 4-6s
        policeTimer = setTimeout(spawnPolice, 4000 + Math.random() * 2000);

        // Hard end
        endTimer = setTimeout(endGame, DURATION_S * 1000 + 100);

        // Spawn first customer immediately
        spawnCustomer();
    }

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