<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sorteador de Combinaciones de Cartones - LA DOLORENSE RIFA</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Google Fonts: Inter para UI y JetBrains Mono para códigos/números -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                        mono: ['JetBrains Mono', 'monospace'],
                    }
                }
            }
        }
    </script>
    <style>
        /* Animaciones personalizadas */
        @keyframes pulse-glow {
            0%, 100% { opacity: 0.5; filter: drop-shadow(0 0 15px rgba(16, 185, 129, 0.4)); }
            50% { opacity: 1; filter: drop-shadow(0 0 30px rgba(16, 185, 129, 0.8)); }
        }
        .glow-active {
            animation: pulse-glow 2s infinite;
        }
        /* Custom scrollbar para el historial */
        ::-webkit-scrollbar {
            width: 6px;
        }
        ::-webkit-scrollbar-track {
            background: #0f172a;
        }
        ::-webkit-scrollbar-thumb {
            background: #334155;
            border-radius: 3px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #475569;
        }
    </style>
</head>
<body class="bg-slate-950 text-slate-100 font-sans min-h-screen flex flex-col justify-between selection:bg-emerald-500 selection:text-slate-950">

    <!-- HEADER DE LA COMPAÑÍA -->
    <header class="border-b border-slate-800 bg-slate-900/80 backdrop-blur sticky top-0 z-50 px-6 py-4">
        <div class="max-w-7xl mx-auto flex flex-col sm:flex-row justify-between items-center gap-4">
            <div class="flex items-center gap-3">
                <!-- Logotipo Isotipo de Argentum -->
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-emerald-500 via-teal-600 to-indigo-600 flex items-center justify-center shadow-lg shadow-emerald-500/10">
                    <span class="font-black text-white text-lg tracking-wider">A</span>
                </div>
                <div>
                    <h1 class="font-bold text-lg tracking-wide text-white flex items-center gap-2">
                        LA DOLORENSE RIFA <span class="text-emerald-400 font-medium text-xs bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20">ASIGNACIÓN NÚMEROS</span>
                    </h1>
                    <p class="text-xs text-slate-400 font-medium">División de Desarrollo de Software & Auditoría Forense</p>
                </div>
            </div>
            <div class="flex items-center gap-4 text-xs">
                <div class="text-right">
                    <span class="text-slate-500 block">SISTEMA INTEGRADO DE CONTROL</span>
                    <span class="text-emerald-400 font-mono font-bold" id="header-stats">DISPONIBLES: 10,000 NÚMEROS</span>
                </div>
            </div>
        </div>
    </header>

    <!-- CUERPO PRINCIPAL -->
    <main class="max-w-7xl mx-auto w-full p-4 lg:p-8 flex-grow grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        <!-- COLUMNA IZQUIERDA: CONTROL DE SORTEO -->
        <section class="lg:col-span-7 flex flex-col gap-6">
            
            <!-- PANEL DEL CARTÓN ACTUAL -->
            <div class="bg-slate-900 border border-slate-800 rounded-3xl p-6 lg:p-8 relative overflow-hidden shadow-2xl flex flex-col justify-between min-h-[420px]">
                <!-- Fondo decorativo abstracto -->
                <div class="absolute -top-24 -left-24 w-60 h-60 bg-indigo-600/10 rounded-full blur-3xl pointer-events-none"></div>
                <div class="absolute -bottom-24 -right-24 w-60 h-60 bg-emerald-600/10 rounded-full blur-3xl pointer-events-none"></div>
                
                <!-- Encabezado del cartón -->
                <div class="flex justify-between items-start z-10">
                    <div>
                        <span class="text-xs font-bold text-emerald-400 tracking-widest uppercase">CARTÓN EN PROCESO</span>
                        <h2 class="text-4xl font-extrabold text-white font-mono tracking-tight mt-1" id="display-carton-id">AA0001</h2>
                    </div>
                    <div class="text-right">
                        <span class="text-xs text-slate-400 block uppercase font-medium">Progreso General</span>
                        <span class="text-xl font-bold text-slate-200 font-mono" id="progress-text">0 / 2500</span>
                    </div>
                </div>

                <!-- DISPLAY GRANDE DE LAS DOS COMBINACIONES -->
                <div class="my-8 flex justify-around items-center gap-4 z-10">
                    <!-- Número 1 -->
                    <div class="flex flex-col items-center flex-1">
                        <span class="text-[10px] text-slate-500 font-bold uppercase tracking-wider mb-2">COMBINACIÓN Alfa</span>
                        <div class="w-full py-6 bg-slate-950 border border-slate-800 rounded-2xl flex items-center justify-center shadow-inner">
                            <span class="text-4xl md:text-6xl font-black font-mono tracking-widest text-white glow-target" id="num-1">----</span>
                        </div>
                    </div>

                    <!-- Separador -->
                    <div class="text-slate-600 font-mono text-2xl font-bold flex items-center justify-center pt-6 px-1">
                        &bull;
                    </div>

                    <!-- Número 2 -->
                    <div class="flex flex-col items-center flex-1">
                        <span class="text-[10px] text-slate-500 font-bold uppercase tracking-wider mb-2">COMBINACIÓN Beta</span>
                        <div class="w-full py-6 bg-slate-950 border border-slate-800 rounded-2xl flex items-center justify-center shadow-inner">
                            <span class="text-4xl md:text-6xl font-black font-mono tracking-widest text-emerald-400 glow-target" id="num-2">----</span>
                        </div>
                    </div>
                </div>

                <!-- BARRA DE PROGRESO INFERIOR -->
                <div class="z-10">
                    <div class="w-full bg-slate-950 h-2 rounded-full overflow-hidden border border-slate-800/85">
                        <div class="bg-gradient-to-r from-emerald-500 to-indigo-600 h-full w-0 transition-all duration-300" id="progress-bar"></div>
                    </div>
                    <div class="flex justify-between items-center mt-3 text-xs text-slate-500">
                        <span>Emisión Mínima (AA0001)</span>
                        <span>Emisión Límite (AA2500)</span>
                    </div>
                </div>
            </div>

            <!-- BOTONERAS DE ACCIÓN -->
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <!-- Botón de Sorteo Manual -->
                <button onclick="triggerDraw()" id="btn-draw" class="group relative bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-400 hover:to-teal-500 text-slate-950 font-bold py-5 px-6 rounded-2xl transition-all duration-200 shadow-lg shadow-emerald-500/10 hover:shadow-emerald-500/20 active:scale-95 flex items-center justify-center gap-3">
                    <span class="text-base tracking-wide">GENERAR SIGUIENTE PAR</span>
                    <!-- Icono SVG Siguiente -->
                    <svg class="w-5 h-5 group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M13 5l7 7-7 7M5 5l7 7-7 7"></path>
                    </svg>
                </button>

                <!-- Panel de Simulación por Lotes -->
                <div class="bg-slate-900 border border-slate-800 rounded-2xl p-4 flex items-center justify-between gap-3">
                    <div class="flex-grow">
                        <label class="text-[10px] text-slate-400 font-bold uppercase tracking-wider block mb-1">Simular Lote Rápido</label>
                        <select id="batch-size" class="bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono py-2 px-3 text-slate-300 focus:outline-none focus:border-emerald-500 w-full">
                            <option value="10">Generar próximos 10</option>
                            <option value="50">Generar próximos 50</option>
                            <option value="100">Generar próximos 100</option>
                            <option value="500">Generar próximos 500</option>
                            <option value="full">Generar hasta completar (2500)</option>
                        </select>
                    </div>
                    <button onclick="triggerBatchDraw()" id="btn-batch" class="bg-slate-800 hover:bg-slate-700 active:bg-slate-600 text-white p-3 rounded-xl transition-all duration-150 flex items-center justify-center h-10 w-12 mt-4" title="Ejecutar lote">
                        <!-- Play Icon -->
                        <svg class="w-5 h-5 text-emerald-400" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M8 5v14l11-7z"></path>
                        </svg>
                    </button>
                </div>
            </div>

            <!-- ANALÍTICAS DEL SORTEO (ESTADÍSTICAS EN TIEMPO REAL) -->
            <div class="bg-slate-900 border border-slate-800 rounded-3xl p-6">
                <h3 class="text-xs font-bold text-slate-400 tracking-wider uppercase mb-4">Métricas de Probabilidad & Consumo</h3>
                <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center">
                    <div class="bg-slate-950 p-4 border border-slate-800/60 rounded-2xl">
                        <span class="text-slate-500 text-[10px] block uppercase font-medium">Números Usados</span>
                        <span class="text-xl font-black text-white font-mono block mt-1" id="stats-used-numbers">0</span>
                        <span class="text-[9px] text-slate-400 block mt-0.5" id="stats-used-pct">0.0% del total</span>
                    </div>
                    <div class="bg-slate-950 p-4 border border-slate-800/60 rounded-2xl">
                        <span class="text-slate-500 text-[10px] block uppercase font-medium">Números Disponibles</span>
                        <span class="text-xl font-black text-emerald-400 font-mono block mt-1" id="stats-free-numbers">10,000</span>
                        <span class="text-[9px] text-slate-400 block mt-0.5" id="stats-free-pct">100.0% restante</span>
                    </div>
                    <div class="bg-slate-950 p-4 border border-slate-800/60 rounded-2xl">
                        <span class="text-slate-500 text-[10px] block uppercase font-medium">Desviación Par/Impar</span>
                        <span class="text-xl font-black text-slate-300 font-mono block mt-1" id="stats-parity">0 / 0</span>
                        <span class="text-[9px] text-slate-400 block mt-0.5">Distribución %</span>
                    </div>
                    <div class="bg-slate-950 p-4 border border-slate-800/60 rounded-2xl">
                        <span class="text-slate-500 text-[10px] block uppercase font-medium">Rango Máximo Sorteado</span>
                        <span class="text-xl font-black text-indigo-400 font-mono block mt-1" id="stats-max-val">-</span>
                        <span class="text-[9px] text-slate-400 block mt-0.5">Límite de valor</span>
                    </div>
                </div>
            </div>

        </section>

        <!-- COLUMNA DERECHA: HISTORIAL Y AUDITORÍA -->
        <section class="lg:col-span-5 flex flex-col gap-4">
            
            <!-- CONTENEDOR BUSCADOR Y ACCIONES DE LISTA -->
            <div class="bg-slate-900 border border-slate-800 rounded-3xl p-6 flex flex-col gap-4 flex-grow max-h-[640px] lg:max-h-none overflow-hidden">
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="font-bold text-white tracking-wide text-sm">Historial & Control Auditores</h3>
                        <p class="text-xs text-slate-500">Búsqueda rápida en tiempo real</p>
                    </div>
                    <!-- Acciones del historial -->
                    <div class="flex items-center gap-2">
                        <!-- Exportar base de datos -->
                        <button onclick="exportCSV()" class="p-2 bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white rounded-xl transition" title="Exportar a CSV">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                            </svg>
                        </button>
                        <!-- Reiniciar Sorteador -->
                        <button onclick="confirmReset()" class="p-2 bg-rose-950/20 hover:bg-rose-950/60 border border-rose-900/30 text-rose-400 hover:text-rose-300 rounded-xl transition" title="Reiniciar base de datos">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                            </svg>
                        </button>
                    </div>
                </div>

                <!-- Input de búsqueda -->
                <div class="relative">
                    <span class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                        <svg class="w-4 h-4 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                        </svg>
                    </span>
                    <input type="text" id="search-input" onkeyup="filterHistory()" placeholder="Buscar por Cartón o Número..." class="bg-slate-950 border border-slate-800 rounded-xl py-3 pl-10 pr-4 text-xs font-mono text-slate-300 w-full focus:outline-none focus:border-emerald-500 placeholder-slate-600 transition">
                </div>

                <!-- CONTENEDOR DE SCROLL PARA LA LISTA -->
                <div class="flex-grow overflow-y-auto pr-1 flex flex-col gap-2 min-h-[300px]" id="history-scroll-container">
                    <!-- Placeholder si no hay registros -->
                    <div id="history-placeholder" class="flex flex-col items-center justify-center py-20 text-center text-slate-600 border border-dashed border-slate-800 rounded-2xl flex-grow">
                        <svg class="w-10 h-10 mb-3 text-slate-700" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"></path>
                        </svg>
                        <p class="text-xs font-medium">No se han emitido sorteos en esta sesión.</p>
                        <p class="text-[10px] text-slate-700 mt-1">Presione el botón para iniciar.</p>
                    </div>
                    
                    <!-- CONTENEDOR DINÁMICO DE CARTONES SORTEADOS -->
                    <div id="history-container" class="flex flex-col gap-2"></div>
                </div>

                <!-- Totales de búsqueda en el footer del panel -->
                <div class="text-right text-[10px] text-slate-500 font-mono" id="search-results-info">
                    Historial vacío.
                </div>
            </div>

        </section>

    </main>

    <!-- FOOTER GENERAL -->
    <footer class="border-t border-slate-900 bg-slate-950 py-4 px-6 text-center text-xs text-slate-500">
        <div class="max-w-7xl mx-auto flex flex-col sm:flex-row justify-between items-center gap-2">
            <span>© 2026 ARGENTUM INDUSTRIES. Todos los derechos reservados.</span>
            <span class="font-mono text-[10px] text-slate-600">ID de Auditoría: SF-9999-AA2500-ENG</span>
        </div>
    </footer>

    <!-- MODALES / NOTIFICACIONES INLINE (EVITANDO ALERT() DE NAVEGADOR) -->
    <div id="modal" class="fixed inset-0 bg-slate-950/80 backdrop-blur-sm z-50 flex items-center justify-center opacity-0 pointer-events-none transition-all duration-300 px-4">
        <div class="bg-slate-900 border border-slate-800 p-6 rounded-3xl max-w-sm w-full shadow-2xl flex flex-col gap-4 text-center">
            <div class="w-12 h-12 rounded-full mx-auto flex items-center justify-center" id="modal-icon-bg">
                <!-- Icono dinámico -->
                <svg id="modal-icon" class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"></svg>
            </div>
            <div>
                <h4 class="font-bold text-lg text-white" id="modal-title">Título del Modal</h4>
                <p class="text-slate-400 text-xs mt-1" id="modal-message">Mensaje del modal explicativo.</p>
            </div>
            <div class="flex gap-2 justify-center mt-2">
                <button onclick="closeModal()" id="modal-btn-cancel" class="hidden px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl text-xs font-bold transition">Cancelar</button>
                <button onclick="confirmAction()" id="modal-btn-action" class="px-5 py-2 bg-emerald-500 hover:bg-emerald-400 text-slate-950 rounded-xl text-xs font-bold transition">Aceptar</button>
            </div>
        </div>
    </div>

    <!-- LOGIC SCRIPT (JAVASCRIPT) -->
    <script>
        // CONFIGURACIONES Y CONSTANTES
        const TOTAL_CARTONS = 2500;
        const NUMBER_MIN = 0;
        const NUMBER_MAX = 9999;

        // ESTADO GLOBAL DE LA APLICACIÓN
        const state = {
            pool: [],               // Bolsa con números de 0000 a 9999
            drawn: [],              // Almacena objetos de cartones { id, num1, num2, timestamp }
            isDrawing: false,       // Bloquea ejecuciones simultáneas de animación
            pendingAction: null     // Callback de confirmación para el modal personalizado
        };

        // INICIALIZADOR AL CARGAR LA PÁGINA
        window.onload = function() {
            initPool();
            updateUI();
        };

        // Genera el pool de números aleatorios sin repetición
        function initPool() {
            state.pool = [];
            for (let i = NUMBER_MIN; i <= NUMBER_MAX; i++) {
                state.pool.push(i);
            }
            state.drawn = [];
            state.isDrawing = false;
        }

        // Recupera un número aleatorio del pool y lo remueve físicamente
        function pullFromPool() {
            if (state.pool.length === 0) return null;
            const randomIndex = Math.floor(Math.random() * state.pool.length);
            const valueSelected = state.pool[randomIndex];
            state.pool.splice(randomIndex, 1); // Remoción sin reemplazo
            
            // Retorna formateado con 4 dígitos siempre
            return String(valueSelected).padStart(4, '0');
        }

        // TRIGGER PRINCIPAL - SORTEO MANUAL (CON ANIMACIÓN)
        function triggerDraw() {
            if (state.isDrawing) return;
            if (state.drawn.length >= TOTAL_CARTONS) {
                showModal(
                    "Sorteo Completado", 
                    "Se ha alcanzado la asignación máxima permitida de 2500 cartones (AA2500).", 
                    "info"
                );
                return;
            }

            state.isDrawing = true;
            document.getElementById("btn-draw").disabled = true;

            const cartonNumber = state.drawn.length + 1;
            const cartonId = "AA" + String(cartonNumber).padStart(4, '0');

            // Variables para la simulación visual
            const num1El = document.getElementById("num-1");
            const num2El = document.getElementById("num-2");
            const displayIdEl = document.getElementById("display-carton-id");

            displayIdEl.innerText = cartonId;
            displayIdEl.classList.add("text-emerald-400");

            // Extraemos los números reales de nuestro pool seguro
            const finalNum1 = pullFromPool();
            const finalNum2 = pullFromPool();

            let tickCount = 0;
            const maxTicks = 20; // 1 segundo de simulación (50ms por tick)
            
            const interval = setInterval(() => {
                num1El.innerText = String(Math.floor(Math.random() * 10000)).padStart(4, '0');
                num2El.innerText = String(Math.floor(Math.random() * 10000)).padStart(4, '0');
                
                tickCount++;
                if (tickCount >= maxTicks) {
                    clearInterval(interval);
                    
                    // Asignación de los valores verdaderos y seguros extraídos del pool
                    num1El.innerText = finalNum1;
                    num2El.innerText = finalNum2;

                    // Marcamos los campos con animación de resplandor
                    num1El.classList.add("text-emerald-300");
                    num2El.classList.add("text-emerald-300");

                    // Registramos en base de datos local temporal
                    const now = new Date();
                    const timestamp = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
                    
                    state.drawn.push({
                        id: cartonId,
                        num1: finalNum1,
                        num2: finalNum2,
                        timestamp: timestamp
                    });

                    setTimeout(() => {
                        num1El.classList.remove("text-emerald-300");
                        num2El.classList.remove("text-emerald-300");
                        displayIdEl.classList.remove("text-emerald-400");
                        
                        state.isDrawing = false;
                        document.getElementById("btn-draw").disabled = false;
                        
                        updateUI();
                        // Hacemos scroll suave al último elemento agregado en el historial
                        scrollToTopHistory();
                    }, 200);
                }
            }, 50);
        }

        // SIMULACIÓN EN LOTE RÁPIDA (SIN INTERFAZ DE TIEMPO REAL PARA VELOCIDAD EXTREMA)
        function triggerBatchDraw() {
            if (state.isDrawing) return;
            
            const batchSelect = document.getElementById("batch-size");
            let size = batchSelect.value;
            
            const remaining = TOTAL_CARTONS - state.drawn.length;
            if (remaining <= 0) {
                showModal("Límite Alcanzado", "Todos los cartones ya han sido generados.", "info");
                return;
            }

            if (size === "full") {
                size = remaining;
            } else {
                size = Math.min(parseInt(size, 10), remaining);
            }

            // Realizamos la extracción directa
            for (let i = 0; i < size; i++) {
                const cartonNumber = state.drawn.length + 1;
                const cartonId = "AA" + String(cartonNumber).padStart(4, '0');
                const finalNum1 = pullFromPool();
                const finalNum2 = pullFromPool();
                const now = new Date();
                const timestamp = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });

                state.drawn.push({
                    id: cartonId,
                    num1: finalNum1,
                    num2: finalNum2,
                    timestamp: timestamp
                });
            }

            // Mostrar el último sorteado en el display principal
            if (state.drawn.length > 0) {
                const last = state.drawn[state.drawn.length - 1];
                document.getElementById("display-carton-id").innerText = last.id;
                document.getElementById("num-1").innerText = last.num1;
                document.getElementById("num-2").innerText = last.num2;
            }

            updateUI();
            showModal("Lote Generado", `Se han procesado correctamente ${size} cartones de manera inmediata.`, "success");
        }

        // ACTUALIZACIÓN DE ELEMENTOS DE LA INTERFAZ DE USUARIO
        function updateUI() {
            const count = state.drawn.length;
            
            // Textos de Progreso
            document.getElementById("progress-text").innerText = `${count} / ${TOTAL_CARTONS}`;
            document.getElementById("header-stats").innerText = `DISPONIBLES: ${state.pool.length.toLocaleString('es-AR')} NÚMEROS`;
            
            // Barra de Progreso
            const percentage = (count / TOTAL_CARTONS) * 100;
            document.getElementById("progress-bar").style.width = `${percentage}%`;

            // Configuración del siguiente ID a mostrar en el panel principal cuando no se está sorteando
            if (!state.isDrawing) {
                if (count < TOTAL_CARTONS) {
                    const nextNumber = count + 1;
                    document.getElementById("display-carton-id").innerText = "AA" + String(nextNumber).padStart(4, '0');
                    document.getElementById("num-1").innerText = "----";
                    document.getElementById("num-2").innerText = "----";
                } else {
                    document.getElementById("display-carton-id").innerText = "COMPLETO";
                    document.getElementById("num-1").innerText = "FIN";
                    document.getElementById("num-2").innerText = "FIN";
                }
            }

            // Renderizar Historial
            renderHistory(state.drawn);
            
            // Actualizar Métricas de Probabilidad
            calculateStats();
        }

        // RENDERIZADOR DENTRO DE HISTORIAL CON FORMATO AUDITABLE
        function renderHistory(itemsToRender) {
            const container = document.getElementById("history-container");
            const placeholder = document.getElementById("history-placeholder");
            const searchResultsInfo = document.getElementById("search-results-info");

            // Si está vacío
            if (itemsToRender.length === 0) {
                container.innerHTML = '';
                placeholder.classList.remove("hidden");
                searchResultsInfo.innerText = "Historial vacío.";
                return;
            }

            placeholder.classList.add("hidden");
            
            // Limpiar e inyectar elementos ordenados de forma descendente (el más nuevo primero)
            let htmlBuffer = "";
            const itemsReversed = [...itemsToRender].reverse();

            itemsReversed.forEach(item => {
                htmlBuffer += `
                    <div class="bg-slate-950 border border-slate-900/60 hover:border-slate-800 p-3 rounded-2xl flex items-center justify-between transition-all hover:translate-x-1 duration-150">
                        <div class="flex items-center gap-3">
                            <span class="font-mono font-bold text-xs bg-slate-900 px-3 py-1.5 rounded-lg border border-slate-800 text-slate-300">${item.id}</span>
                            <div class="flex items-center gap-2">
                                <span class="font-mono text-xs font-semibold text-slate-200 tracking-wider">${item.num1}</span>
                                <span class="text-slate-700 text-[10px]">•</span>
                                <span class="font-mono text-xs font-semibold text-emerald-400 tracking-wider">${item.num2}</span>
                            </div>
                        </div>
                        <span class="font-mono text-[10px] text-slate-600">${item.timestamp}</span>
                    </div>
                `;
            });

            container.innerHTML = htmlBuffer;
            searchResultsInfo.innerText = `Mostrando ${itemsToRender.length} de ${state.drawn.length} registros.`;
        }

        // BÚSQUEDA Y FILTRADO INSTANTÁNEO EN EL HISTORIAL
        function filterHistory() {
            const query = document.getElementById("search-input").value.trim().toUpperCase();
            if (!query) {
                renderHistory(state.drawn);
                return;
            }

            const filtered = state.drawn.filter(item => {
                return item.id.includes(query) || item.num1.includes(query) || item.num2.includes(query);
            });

            renderHistory(filtered);
        }

        // CÁLCULO DE MÉTRICAS EN TIEMPO REAL
        function calculateStats() {
            const used = state.drawn.length * 2;
            const free = 10000 - used;
            const usedPct = ((used / 10000) * 100).toFixed(1);
            const freePct = ((free / 10000) * 100).toFixed(1);

            document.getElementById("stats-used-numbers").innerText = used.toLocaleString('es-AR');
            document.getElementById("stats-used-pct").innerText = `${usedPct}% del total`;

            document.getElementById("stats-free-numbers").innerText = free.toLocaleString('es-AR');
            document.getElementById("stats-free-pct").innerText = `${freePct}% restante`;

            // Paridad
            let even = 0;
            let odd = 0;
            let maxVal = 0;

            state.drawn.forEach(item => {
                const n1 = parseInt(item.num1, 10);
                const n2 = parseInt(item.num2, 10);
                
                if (n1 % 2 === 0) even++; else odd++;
                if (n2 % 2 === 0) even++; else odd++;

                if (n1 > maxVal) maxVal = n1;
                if (n2 > maxVal) maxVal = n2;
            });

            const totalCalculated = even + odd;
            if (totalCalculated > 0) {
                const evenPct = Math.round((even / totalCalculated) * 100);
                const oddPct = Math.round((odd / totalCalculated) * 100);
                document.getElementById("stats-parity").innerText = `${evenPct}% / ${oddPct}%`;
            } else {
                document.getElementById("stats-parity").innerText = "0 / 0";
            }

            document.getElementById("stats-max-val").innerText = state.drawn.length > 0 ? String(maxVal).padStart(4, '0') : "-";
        }

        // SCROLL AUTOMÁTICO AL COMIENZO DEL HISTORIAL AL AGREGAR UN COMPONENTE
        function scrollToTopHistory() {
            const container = document.getElementById("history-scroll-container");
            if (container) {
                container.scrollTop = 0;
            }
        }

        // EXPORTADOR AUDITABLE DIRECTO A ARCHIVO CSV
        function exportCSV() {
            if (state.drawn.length === 0) {
                showModal("Sin Datos", "No hay combinaciones sorteadas para exportar.", "warning");
                return;
            }

            let csvContent = "data:text/csv;charset=utf-8,";
            csvContent += "ID CARTON,COMBINACION ALFA,COMBINACION BETA,HORA SORTEO\n";

            state.drawn.forEach(item => {
                csvContent += `${item.id},${item.num1},${item.num2},${item.timestamp}\n`;
            });

            const encodedUri = encodeURI(csvContent);
            const downloadAnchor = document.createElement("a");
            
            const timestampFile = new Date().toISOString().slice(0,10);
            downloadAnchor.setAttribute("href", encodedUri);
            downloadAnchor.setAttribute("download", `sorteo_cartones_argentum_${timestampFile}.csv`);
            document.body.appendChild(downloadAnchor);
            
            downloadAnchor.click();
            document.body.removeChild(downloadAnchor);
        }

        // DIÁLOGOS Y MODALES PERSONALIZADOS (EVITANDO BUGS EN IFRAMES POR ALERT())
        function showModal(title, message, type = "info", onConfirm = null, showCancel = false) {
            const modal = document.getElementById("modal");
            const modalTitle = document.getElementById("modal-title");
            const modalMsg = document.getElementById("modal-message");
            const modalIconBg = document.getElementById("modal-icon-bg");
            const modalIcon = document.getElementById("modal-icon");
            const btnCancel = document.getElementById("modal-btn-cancel");
            const btnAction = document.getElementById("modal-btn-action");

            modalTitle.innerText = title;
            modalMsg.innerText = message;
            state.pendingAction = onConfirm;

            // Configurar tipo visual
            if (type === "success") {
                modalIconBg.className = "w-12 h-12 rounded-full mx-auto flex items-center justify-center bg-emerald-950 border border-emerald-500/30 text-emerald-400";
                modalIcon.innerHTML = `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>`;
                btnAction.className = "px-5 py-2 bg-emerald-500 hover:bg-emerald-400 text-slate-950 rounded-xl text-xs font-bold transition";
            } else if (type === "warning") {
                modalIconBg.className = "w-12 h-12 rounded-full mx-auto flex items-center justify-center bg-amber-950 border border-amber-500/30 text-amber-400";
                modalIcon.innerHTML = `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>`;
                btnAction.className = "px-5 py-2 bg-amber-500 hover:bg-amber-400 text-slate-950 rounded-xl text-xs font-bold transition";
            } else if (type === "danger") {
                modalIconBg.className = "w-12 h-12 rounded-full mx-auto flex items-center justify-center bg-rose-950 border border-rose-500/30 text-rose-400";
                modalIcon.innerHTML = `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>`;
                btnAction.className = "px-5 py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-xl text-xs font-bold transition";
            } else {
                modalIconBg.className = "w-12 h-12 rounded-full mx-auto flex items-center justify-center bg-indigo-950 border border-indigo-500/30 text-indigo-400";
                modalIcon.innerHTML = `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>`;
                btnAction.className = "px-5 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl text-xs font-bold transition";
            }

            if (showCancel) {
                btnCancel.classList.remove("hidden");
            } else {
                btnCancel.classList.add("hidden");
            }

            // Transición de apertura
            modal.classList.remove("opacity-0", "pointer-events-none");
        }

        function closeModal() {
            const modal = document.getElementById("modal");
            modal.classList.add("opacity-0", "pointer-events-none");
            state.pendingAction = null;
        }

        function confirmAction() {
            if (state.pendingAction) {
                state.pendingAction();
            }
            closeModal();
        }

        // CONFIRMACIÓN DE REINICIO DE BASE DE DATOS
        function confirmReset() {
            showModal(
                "¿Reiniciar Sorteo?",
                "Esta acción borrará todo el historial y reestablecerá el pool de 10.000 números sin usar. No se puede deshacer.",
                "danger",
                () => {
                    initPool();
                    updateUI();
                },
                true
            );
        }
    </script>
</body>
</html>