/**
 * Módulo de Sorteos — Animaciones y lógica frontend
 * Sprint 12 — Brújula Virtual / FONDOENERGIA
 *
 * Dependencias: canvas-confetti (cargada vía CDN en sorteos.php)
 */
const SorteoUI = (() => {

    function sonidoCelebracion() {
        try {
            const ctx = new (window.AudioContext || window.webkitAudioContext)();
            const notas = [523, 659, 784, 1047, 1319];
            notas.forEach((freq, i) => {
                const osc = ctx.createOscillator();
                const gain = ctx.createGain();
                osc.connect(gain);
                gain.connect(ctx.destination);
                osc.type = 'triangle';
                osc.frequency.value = freq;
                gain.gain.setValueAtTime(0.3, ctx.currentTime + i * 0.12);
                gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + i * 0.12 + 0.5);
                osc.start(ctx.currentTime + i * 0.12);
                osc.stop(ctx.currentTime + i * 0.12 + 0.6);
            });
        } catch (e) {}
    }

    function lanzarConfeti() {
        if (typeof confetti === 'undefined') return;
        const colores = ['#1F4E79','#2E75B6','#FFD700','#FF6347','#32CD32','#FF69B4'];
        const duracion = 3500;
        const fin = Date.now() + duracion;
        (function frame() {
            confetti({ particleCount: 6, angle: 60,  spread: 55, origin: { x: 0 }, colors: colores });
            confetti({ particleCount: 6, angle: 120, spread: 55, origin: { x: 1 }, colors: colores });
            if (Date.now() < fin) requestAnimationFrame(frame);
        })();
    }

    function mostrarGanadores(ganadores, regalo) {
        const container = document.getElementById('sorteo-resultado');
        if (!container) return;

        let html = `<div class="text-center mb-3">
            <span class="fs-2">🎉</span>
            <h4 class="mt-2 text-success fw-bold">¡Felicidades!</h4>
            <p class="text-muted">Premio: <strong>${regalo}</strong></p>
        </div><div class="row justify-content-center g-2">`;

        ganadores.forEach(g => {
            html += `<div class="col-md-6">
                <div class="card border-success shadow-sm">
                    <div class="card-body text-center py-2">
                        <div class="fs-4">🏆</div>
                        <div class="fw-bold">${g.nombre}</div>
                        <small class="text-muted">Cédula: ${g.cedula} | Zona: ${g.zona}</small>
                    </div>
                </div>
            </div>`;
        });
        html += '</div>';
        container.innerHTML = html;
        container.classList.remove('d-none');
    }

    return {
        async contarRegresiva(callback) {
            const display = document.getElementById('sorteo-countdown');
            if (!display) { callback(); return; }

            const nums = ['5','4','3','2','1','🎰'];
            display.classList.remove('d-none');

            for (const n of nums) {
                display.textContent = n;
                display.style.transform = 'scale(1.3)';
                display.style.transition = 'transform 0.15s ease';
                await new Promise(r => setTimeout(r, 150));
                display.style.transform = 'scale(1)';
                await new Promise(r => setTimeout(r, 750));
            }
            display.classList.add('d-none');
            callback();
        },

        celebrar(ganadores, regalo) {
            sonidoCelebracion();
            lanzarConfeti();
            mostrarGanadores(ganadores, regalo);
        }
    };
})();
