// La Paguita - Minijuego: Carterista Express (Bogdan, Mohamed, MENA)

(function () {
    const DURATION_S = 12;
    const TOURIST_INTERVAL_MS = 1500;
    const TOURIST_LIFETIME_MS = 2500;
    const CAMERA_SWEEP_DURATION_MS = 3000;
    const CAMERA_WIDTH_PCT = 30;
    const MAX_SPOTS = 3;
    const STEAL_VALUES = [8, 10, 12, 15];

    const TOURISTS = ['🧳', '📸', '👒', '🕶️', '🎒', '👜', '🧓', '👴'];

    function init(area, contexto, onComplete) {
        let earnings = 0;
        let steals = 0;
        let spots = 0;
        let caught = false;
        let gameOver = false;
        let startTime = performance.now();
        let touristTimer = null;
        let tickTimer = null;
        let cameraPos = -CAMERA_WIDTH_PCT; // starts off-screen left
        let cameraDirection = 1;
        let cameraAnimFrame = null;
        let lastCameraTime = 0;

        area.innerHTML = `
            <div class="carterista-earnings" id="carterista-earnings">💶 0</div>
            <div class="carterista-field" id="carterista-field">
                <div class="carterista-camera" id="carterista-camera"></div>
            </div>
            <div class="carterista-hint" id="carterista-hint">Roba cuando no mire la cámara (${MAX_SPOTS - spots} fallos restantes)</div>
        `;

        const field = document.getElementById('carterista-field');
        const earningsEl = document.getElementById('carterista-earnings');
        const cameraEl = document.getElementById('carterista-camera');
        const hintEl = document.getElementById('carterista-hint');

        // Camera sweep animation
        function animateCamera() {
            if (gameOver) return;
            const now = performance.now();
            const delta = (now - lastCameraTime) / CAMERA_SWEEP_DURATION_MS;
            lastCameraTime = now;

            cameraPos += delta * 100 * cameraDirection;
            if (cameraPos >= 100) { cameraPos = 100; cameraDirection = -1; }
            if (cameraPos <= -CAMERA_WIDTH_PCT) { cameraPos = -CAMERA_WIDTH_PCT; cameraDirection = 1; }

            cameraEl.style.left = cameraPos + '%';
            cameraEl.style.width = CAMERA_WIDTH_PCT + '%';

            cameraAnimFrame = requestAnimationFrame(animateCamera);
        }

        function isInCameraZone(xPct) {
            return xPct >= cameraPos && xPct <= cameraPos + CAMERA_WIDTH_PCT;
        }

        function spawnTourist() {
            if (gameOver) return;

            const entity = document.createElement('span');
            entity.className = 'carterista-entity tourist';
            entity.textContent = TOURISTS[Math.floor(Math.random() * TOURISTS.length)];
            const value = STEAL_VALUES[Math.floor(Math.random() * STEAL_VALUES.length)];
            entity.dataset.value = value;

            const x = 5 + Math.random() * 80;
            const y = 10 + Math.random() * 60;
            entity.style.left = x + '%';
            entity.style.top = y + '%';
            entity.dataset.x = x;

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

                const entityX = parseFloat(entity.dataset.x);

                if (isInCameraZone(entityX)) {
                    // Spotted!
                    spots++;
                    earnings = Math.max(0, earnings - 5);
                    entity.classList.add('spotted');
                    hintEl.textContent = `📷 ¡Detectado! (${MAX_SPOTS - spots} fallos restantes)`;
                    hintEl.className = 'carterista-hint warning';
                    earningsEl.textContent = '💶 ' + Math.floor(earnings);

                    if (spots >= MAX_SPOTS) {
                        caught = true;
                        endGame();
                        return;
                    }
                    setTimeout(() => {
                        if (!gameOver) {
                            hintEl.textContent = `Roba fuera de la cámara (${MAX_SPOTS - spots} fallos)`;
                            hintEl.className = 'carterista-hint';
                        }
                    }, 1000);
                } else {
                    // Successful steal
                    const val = parseInt(entity.dataset.value);
                    earnings += val;
                    steals++;
                    entity.classList.add('stolen');
                    earningsEl.textContent = '💶 ' + Math.floor(earnings);

                    // Float feedback
                    const floater = document.createElement('span');
                    floater.className = 'manta-floater'; // reuse existing CSS
                    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
            setTimeout(() => {
                if (!entity.classList.contains('stolen') && !entity.classList.contains('spotted')) {
                    entity.style.opacity = '0';
                    setTimeout(() => entity.remove(), 300);
                }
            }, TOURIST_LIFETIME_MS);
        }

        function endGame() {
            if (gameOver) return;
            gameOver = true;
            clearInterval(touristTimer);
            clearInterval(tickTimer);
            cancelAnimationFrame(cameraAnimFrame);

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

            const perfecto = spots === 0 && steals >= 6;
            if (perfecto) earnings += 10;

            const label = caught ? '📷 ¡PILLADO POR LA CÁMARA!' : perfecto ? '⭐ ¡Carterista de élite!' : '🚇 Fin del turno';
            field.innerHTML = `<div style="padding:2rem;font-size:1.2rem;text-align:center">${label}</div>`;
            earningsEl.textContent = '💶 ' + Math.floor(earnings) + (perfecto ? ' ⭐' : '');
            updateMinigameScore(`${steals} robos · ${spots} detectado(s)`);

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

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

        // Spawn tourists
        touristTimer = setInterval(() => {
            if (!gameOver) spawnTourist();
        }, TOURIST_INTERVAL_MS);

        // Start camera animation
        lastCameraTime = performance.now();
        animateCamera();

        // First tourist immediately
        spawnTourist();
    }

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