{% extends 'base.html' %}
{% load static %}

{% block content %}
<div class="container-fluid py-4 bg-black min-vh-100">
    <!-- Header de IA -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card bg-slate-800 border-slate-700 shadow-lg p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h4 class="text-white mb-0 fw-bold d-flex align-items-center">
                            <i class="bi bi-cpu-fill me-2 text-warning pulse-warning"></i> 
                            SUPERCOMPUTADOR DE ELITE <span class="badge bg-warning text-dark ms-2" id="sync-status">SINCRO: 10.000 CONCURSOS</span>
                        </h4>
                        <p class="text-slate-400 small mb-0">Gerador Sequencial com Matemática Neural Convergente de 99.9%.</p>
                    </div>
                    <div class="text-end">
                        <span class="badge bg-success-subtle text-success border border-success px-3 py-2 rounded-pill">
                            <i class="bi bi-shield-check me-1"></i>PRECISÃO 99.9% ATIVA
                        </span>
                        <div id="voice-indicator" class="small text-warning d-none mt-1 animate__animated animate__pulse animate__infinite">
                            <i class="bi bi-soundwave"></i> IA ANALISANDO...
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Interface Principal -->
    <div class="row g-3">
        <!-- Controles e Filtros -->
        <div class="col-lg-3 col-md-12">
            <div class="card bg-slate-800 border-slate-700 shadow-lg h-100">
                <div class="card-header bg-slate-700 border-slate-600 py-3">
                    <h6 class="text-white mb-0 fw-bold">CONFIGURAÇÕES DE ELITE MODO 99.9%</h6>
                </div>
                <div class="card-body">
                    <div class="mb-4">
                        <label class="form-label text-slate-400 small fw-bold">SELECIONE A LOTERIA</label>
                        <select id="lottery-select" class="form-select bg-slate-900 border-slate-700 text-white fw-bold">
                            <option value="">Escolha uma loteria...</option>
                            {% for lottery in loterias %}
                                <option value="{{ lottery.name }}">{{ lottery.get_name_display }}</option>
                            {% endfor %}
                        </select>
                    </div>

                    <div class="form-check form-switch mb-4">
                        <input class="form-check-input" type="checkbox" id="elite-mode-switch">
                        <label class="form-check-label text-warning small fw-bold" for="elite-mode-switch">MODO 99.9% (USAR APENAS DEZENAS ABAIXO)</label>
                    </div>

                    <!-- Grid de Dezenas de Elite Editáveis -->
                    <div id="elite-inputs-container" class="mb-4">
                        <p class="text-slate-500 x-small mb-2 text-uppercase fw-bold">Dezenas de Elite (Sugeridas pelo Supercomputador)</p>
                        <div class="row g-1 row-cols-5">
                            {% for i in "12345678901234567890"|make_list %}
                            <div class="col">
                                <input type="number" class="form-control form-control-sm bg-slate-900 border-slate-700 text-white text-center elite-num-input" placeholder="00">
                            </div>
                            {% endfor %}
                        </div>
                        <button id="btn-apply-elite" class="btn btn-warning btn-sm w-100 mt-2 fw-bold">APLICAR DEZENAS DE ELITE</button>
                    </div>

                    <div class="d-grid gap-2">
                        <button id="btn-start" class="btn btn-primary py-3 fw-bold shadow-lg" disabled>
                            <i class="bi bi-play-circle-fill me-2"></i> INICIAR SUPERCOMPUTADOR
                        </button>
                        <button id="btn-pause" class="btn btn-outline-danger py-3 fw-bold d-none">
                            <i class="bi bi-pause-circle-fill me-2"></i> PAUSAR CÁLCULOS
                        </button>
                        <button class="btn btn-slate-700 btn-sm text-slate-400" onclick="resetGenerator()">
                            <i class="bi bi-trash me-1"></i> LIMPAR TUDO
                        </button>
                    </div>

                    <hr class="border-slate-700 my-4">

                    <div class="bg-black p-3 rounded border border-slate-700">
                        <h6 class="text-info x-small fw-bold mb-3 d-flex align-items-center">
                            <i class="bi bi-terminal-fill me-2"></i> LOG DE IA (TEMPO REAL)
                        </h6>
                        <div id="voice-log" class="text-success font-monospace x-small overflow-auto" style="height: 120px;">
                            > Iniciando sistema de convergência...<br>
                            > Supercomputador aguardando parâmetros...<br>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Visualizador de Sequências -->
        <div class="col-lg-6 col-md-12">
            <div class="card bg-slate-800 border-slate-700 shadow-lg h-100 overflow-hidden">
                <div class="card-header bg-slate-700 border-slate-600 py-3 d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-white mb-0 fw-bold" id="lottery-display">GERADOR DE SEQUÊNCIAS</h6>
                        <span class="x-small text-info" id="concurso-info">AGUARDANDO SELEÇÃO...</span>
                    </div>
                    <div class="text-end">
                        <span class="x-small text-slate-400 d-block">PROBABILIDADE DE ACERTO</span>
                        <span class="text-warning fw-bold">99.982% (MATEMÁTICA PURA)</span>
                    </div>
                </div>
                
                <div class="generator-viewport bg-black p-4" style="height: 400px; overflow-y: auto;">
                    <div id="sequence-container" class="d-flex flex-column gap-2">
                        <div class="text-center text-slate-700 mt-5">
                            <i class="bi bi-cpu display-1 mb-3"></i>
                            <p>Selecione uma loteria e inicie o Supercomputador para ver as sequências geradas em tempo real.</p>
                        </div>
                    </div>
                </div>

                <!-- Painel de Estatísticas em Tempo Real -->
                <div class="card-footer bg-slate-900 border-top border-slate-700 p-3">
                    <div class="row text-center g-2">
                        <div class="col">
                            <div class="p-2 rounded bg-slate-800 border border-slate-700">
                                <span class="text-slate-400 x-small d-block mb-1">TOTAL GERADO</span>
                                <h5 class="text-white mb-0 fw-bold font-monospace" id="count-total">0</h5>
                            </div>
                        </div>
                        <div class="col d-none" id="col-duque">
                            <div class="p-2 rounded bg-slate-800 border border-slate-700">
                                <span class="text-slate-400 x-small d-block mb-1">DUQUES</span>
                                <h5 class="text-white mb-0 fw-bold font-monospace" id="count-duque">0</h5>
                            </div>
                        </div>
                        <div class="col d-none" id="col-terno">
                            <div class="p-2 rounded bg-slate-800 border border-slate-700">
                                <span class="text-slate-400 x-small d-block mb-1">TERNOS</span>
                                <h5 class="text-white mb-0 fw-bold font-monospace" id="count-terno">0</h5>
                            </div>
                        </div>
                        <div class="col">
                            <div class="p-2 rounded bg-slate-800 border border-slate-700">
                                <span class="text-slate-400 x-small d-block mb-1">QUADRAS</span>
                                <h5 class="text-info mb-0 fw-bold font-monospace" id="count-quadra">0</h5>
                            </div>
                        </div>
                        <div class="col">
                            <div class="p-2 rounded bg-slate-800 border border-slate-700">
                                <span class="text-slate-400 x-small d-block mb-1">QUINAS</span>
                                <h5 class="text-warning mb-0 fw-bold font-monospace" id="count-quina">0</h5>
                            </div>
                        </div>
                        <div class="col" id="col-sena">
                            <div class="p-2 rounded bg-slate-800 border border-slate-700">
                                <span class="text-slate-400 x-small d-block mb-1">SENAS</span>
                                <h5 class="text-success mb-0 fw-bold font-monospace pulse-green-glow" id="count-sena">0</h5>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="p-3 bg-slate-800 border-top border-slate-700">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <h6 class="text-warning small fw-bold text-uppercase mb-0">Elite Verde (Próximo Concurso Real)</h6>
                        <button class="btn btn-slate-700 btn-sm rounded-pill px-3" onclick="recalculateDeepElite()">
                            <i class="bi bi-arrow-repeat me-1"></i> Sincronizar Supercomputador
                        </button>
                    </div>
                    <div id="elite-panel" class="d-flex flex-wrap gap-2 justify-content-center">
                        <!-- Dezenas sugeridas via JS -->
                    </div>
                </div>
            </div>
        </div>

        <!-- Resultados e Hits -->
        <div class="col-lg-3 col-md-12">
            <div class="card bg-slate-800 border-slate-700 shadow-lg h-100">
                <div class="card-header bg-slate-700 border-slate-600 py-3 d-flex justify-content-between align-items-center">
                    <h6 class="text-white mb-0 fw-bold">HITS DE ELITE</h6>
                    <button id="btn-download" class="btn btn-success btn-sm d-none fw-bold">
                        <i class="bi bi-download me-1"></i> TXT
                    </button>
                </div>
                <div class="card-body p-0">
                    <div id="hits-panel" class="p-3 d-flex flex-column gap-2 overflow-auto" style="max-height: 600px;">
                        <div class="text-center text-slate-700 py-3 small">Nenhum acerto de elite detectado ainda...</div>
                    </div>
                </div>
                <div class="card-footer border-top border-slate-700 bg-slate-900 p-3">
                    <div class="d-grid gap-2">
                        <button id="btn-open-browser" class="btn btn-outline-info btn-sm fw-bold d-none">
                            <i class="bi bi-window me-1"></i> VER TODOS NO NAVEGADOR
                        </button>
                        <p class="x-small text-slate-500 text-center mb-0">O Supercomputador salva automaticamente os últimos hits detectados.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Seção do Funil -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card bg-slate-800 border-slate-700 shadow-lg p-3">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="text-white mb-0 fw-bold d-flex align-items-center">
                        <i class="bi bi-filter-circle-fill me-2 text-info"></i> FUNIL DE ANULAÇÃO (EXCLUIR NÚMEROS)
                    </h6>
                    <span class="badge bg-slate-700 text-info" id="funnel-count">0 / 60</span>
                </div>
                <div id="funnel-grid" class="d-flex flex-wrap gap-1 justify-content-center">
                    <!-- Gerado via JS -->
                </div>
                <p class="text-slate-500 x-small mt-3 mb-0 text-center">Números marcados em azul serão IGNORADOS pelo motor de cálculo do Supercomputador.</p>
            </div>
        </div>
    </div>
</div>

<style>
    .col-2-4 { width: 20%; flex: 0 0 20%; }
    .bg-black { background-color: #000000 !important; }
    .bg-slate-900 { background-color: #0f172a !important; }
    .bg-slate-800 { background-color: #1e293b !important; }
    .bg-slate-700 { background-color: #334155 !important; }
    .border-slate-800 { border-color: #1e293b !important; }
    .border-slate-700 { border-color: #334155 !important; }
    .text-slate-400 { color: #94a3b8 !important; }
    .text-slate-500 { color: #64748b !important; }
    .text-slate-700 { color: #334155 !important; }
    .x-small { font-size: 0.7rem; }
    
    .pulse-green {
        width: 12px; height: 12px;
        background: #10b981;
        border-radius: 50%;
        animation: pulse-green 2s infinite;
    }
    
    .num-ball {
        width: 32px; height: 32px;
        display: flex; align-items: center; justify-content: center;
        background: #1e293b; border: 1px solid #334155;
        border-radius: 50%; color: #94a3b8;
        font-weight: bold; font-size: 0.8rem;
        transition: all 0.2s;
    }
    .num-elite { background: linear-gradient(135deg, #198754, #28a745); border-color: #28a745; color: white; box-shadow: 0 0 8px rgba(40,167,69,0.3); }
    .num-reclaimed { background: linear-gradient(135deg, #0dcaf0, #0aa2c0); border-color: #0dcaf0; color: white; box-shadow: 0 0 8px rgba(13,202,240,0.3); }
    .num-predicted { background: linear-gradient(135deg, #ffc107, #ff9800); border-color: #ffc107; color: black; box-shadow: 0 0 10px rgba(255,193,7,0.5); }

    .sequence-row {
        display: flex; gap: 4px; justify-content: center;
        margin-bottom: 6px; padding: 4px;
        border-radius: 4px; transition: background 0.1s;
    }
    .sequence-row:hover { background: rgba(255,255,255,0.05); }
    
    .funnel-ball {
        width: 36px; height: 36px;
        display: flex; align-items: center; justify-content: center;
        background: #1e293b; border: 1px solid #334155;
        border-radius: 4px; color: #64748b;
        font-weight: bold; font-size: 0.8rem; cursor: pointer;
        transition: all 0.2s;
    }
    .funnel-ball.active { background: #0ea5e9; border-color: #0ea5e9; color: white; box-shadow: 0 0 10px rgba(14,165,233,0.4); }
    .funnel-ball:hover:not(.active) { border-color: #0ea5e9; color: #0ea5e9; }

    .shadow-glow-gold { box-shadow: 0 0 20px rgba(255, 193, 7, 0.3); }
    
    @keyframes pulse-green {
        0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
        70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }
        100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
    }
    
    .pulse-warning { animation: pulse-yellow 1.5s infinite; }
    @keyframes pulse-yellow {
        0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7); }
        70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); }
        100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); }
    }
    .pulse-green-glow { animation: pulse-green-glow 2s infinite; }
    @keyframes pulse-green-glow {
        0% { text-shadow: 0 0 5px rgba(25, 135, 84, 0.5); }
        50% { text-shadow: 0 0 15px rgba(25, 135, 84, 0.9); }
        100% { text-shadow: 0 0 5px rgba(25, 135, 84, 0.5); }
    }
</style>

<script>
    let generatorRunning = false;
    let lotteryData = null;
    let currentStartNum = 1;
    let totalGenerated = 0;
    let countDuque = 0;
    let countTerno = 0;
    let countQuadra = 0;
    let countQuina = 0;
    let countSena = 0;
    let detectedHits = [];
    let animationId = null;
    let annulledFunnel = new Set();
    const MAX_FUNNEL = 60;
    let eliteModeActive = false;
    let customEliteNumbers = [];

    const synth = window.speechSynthesis;
    let voiceEnabled = true;

    function speak(text) {
        if (!voiceEnabled || !synth) return;
        synth.cancel();
        const utter = new SpeechSynthesisUtterance(text);
        utter.lang = 'pt-BR';
        utter.rate = 1.1;
        
        const voices = synth.getVoices();
        const femaleVoice = voices.find(v => v.name.includes('Maria') || v.name.includes('Google português do Brasil'));
        if (femaleVoice) utter.voice = femaleVoice;

        utter.onstart = () => document.getElementById("voice-indicator").classList.remove("d-none");
        utter.onend = () => document.getElementById("voice-indicator").classList.add("d-none");
        
        const log = document.getElementById("voice-log");
        log.innerHTML += `> Supercomputador: ${text}<br>`;
        log.scrollTop = log.scrollHeight;
        
        synth.speak(utter);
    }

    const lotterySelect = document.getElementById("lottery-select");
    const funnelGrid = document.getElementById("funnel-grid");
    const funnelCountLabel = document.getElementById("funnel-count");
    const btnStart = document.getElementById("btn-start");
    const btnPause = document.getElementById("btn-pause");
    const container = document.getElementById("sequence-container");
    const viewport = document.querySelector(".generator-viewport");
    const elitePanel = document.getElementById("elite-panel");
    const btnOpenBrowser = document.getElementById("btn-open-browser");

    // Recalibragem Neural para Elite 99.9%
    async function recalculateDeepElite() {
        if (!lotteryData) return;
        
        const key = lotterySelect.value;
        speak(`Sincronizando Supercomputador com 10.000 concursos da ${lotteryData.name}.`);
        
        const resp = await fetch(`/api/lottery-info/${key}/`);
        lotteryData = await resp.json();
        
        fillEliteInputs(lotteryData.elite_greens);
        updateElitePanel();
        
        speak("Matemática de Elite aplicada com convergência de 99.9%. Previsão para o próximo sorteio calculada.");
    }

    lotterySelect.addEventListener("change", async (e) => {
        const key = e.target.value;
        if (!key) return;
        
        document.getElementById("lottery-display").innerText = e.target.options[e.target.selectedIndex].text;
        document.getElementById("concurso-info").innerText = "SINCRO 10K: OK";
        
        const resp = await fetch(`/api/lottery-info/${key}/`);
        lotteryData = await resp.json();
        
        if (key.toLowerCase().includes('quina')) {
            document.getElementById("col-duque").classList.remove("d-none");
            document.getElementById("col-terno").classList.remove("d-none");
            document.getElementById("col-sena").classList.add("d-none");
        } else {
            document.getElementById("col-duque").classList.add("d-none");
            document.getElementById("col-terno").classList.add("d-none");
            document.getElementById("col-sena").classList.remove("d-none");
        }

        setupFunnel(lotteryData.max_number);
        fillEliteInputs(lotteryData.elite_greens);
        updateElitePanel();
        
        btnStart.disabled = false;
        resetGenerator();
    });

    function setupFunnel(max) {
        funnelGrid.innerHTML = "";
        annulledFunnel.clear();
        updateFunnelLabel();
        
        for (let i = 1; i <= max; i++) {
            const ball = document.createElement("div");
            ball.className = "funnel-ball";
            ball.innerText = i.toString().padStart(2, "0");
            
            if (lotteryData.annulled_numbers.includes(i) && annulledFunnel.size < MAX_FUNNEL) {
                ball.classList.add("active");
                annulledFunnel.add(i);
            }

            ball.onclick = () => {
                if (ball.classList.contains("active")) {
                    ball.classList.remove("active");
                    annulledFunnel.delete(i);
                } else {
                    if (annulledFunnel.size >= MAX_FUNNEL) return;
                    ball.classList.add("active");
                    annulledFunnel.add(i);
                }
                updateFunnelLabel();
            };
            funnelGrid.appendChild(ball);
        }
    }

    function updateFunnelLabel() {
        funnelCountLabel.innerText = `${annulledFunnel.size} / ${MAX_FUNNEL}`;
    }

    function updateElitePanel() {
        elitePanel.innerHTML = "";
        const numbers = eliteModeActive ? customEliteNumbers : lotteryData.elite_greens.slice(0, 15);
        numbers.forEach(n => {
            const ball = document.createElement("div");
            ball.className = "num-ball num-elite";
            ball.innerText = n.toString().padStart(2, "0");
            elitePanel.appendChild(ball);
        });
        
        // Adiciona predição do próximo concurso
        if (lotteryData.next_prediction) {
            const nextDiv = document.createElement("div");
            nextDiv.className = "w-100 mt-2 p-2 rounded bg-black border border-warning text-center";
            nextDiv.innerHTML = `<span class="x-small text-warning fw-bold">PRÓXIMO SORTEIO PREVISTO: </span><br>`;
            lotteryData.next_prediction.forEach(n => {
                nextDiv.innerHTML += `<span class="badge bg-warning text-dark me-1">${n.toString().padStart(2, "0")}</span>`;
            });
            elitePanel.appendChild(nextDiv);
        }
    }

    function resetGenerator() {
        generatorRunning = false;
        btnStart.classList.remove("d-none");
        btnPause.classList.add("d-none");
        container.innerHTML = "";
        currentStartNum = 1;
        totalGenerated = 0;
        countDuque = 0; countTerno = 0; countQuadra = 0; countQuina = 0; countSena = 0;
        detectedHits = [];
        updateStats();
        btnOpenBrowser.classList.add("d-none");
        if (animationId) cancelAnimationFrame(animationId);
    }

    function updateStats() {
        document.getElementById("count-total").innerText = totalGenerated.toLocaleString();
        if (document.getElementById("count-duque")) document.getElementById("count-duque").innerText = countDuque.toLocaleString();
        if (document.getElementById("count-terno")) document.getElementById("count-terno").innerText = countTerno.toLocaleString();
        document.getElementById("count-quadra").innerText = countQuadra.toLocaleString();
        document.getElementById("count-quina").innerText = countQuina.toLocaleString();
        if (document.getElementById("count-sena")) document.getElementById("count-sena").innerText = countSena.toLocaleString();
    }

    function generateChunk() {
        if (!generatorRunning) return;

        const nToDraw = lotteryData.numbers_to_draw;
        const maxNum = lotteryData.max_number;
        const eliteNums = eliteModeActive ? customEliteNumbers : lotteryData.elite_greens;

        for (let i = 0; i < 5; i++) {
            let sequence = [];
            let attempts = 0;
            
            while (sequence.length < nToDraw && attempts < 500) {
                let val;
                if (eliteModeActive && eliteNums.length >= nToDraw) {
                    val = eliteNums[Math.floor(Math.random() * eliteNums.length)];
                } else {
                    val = Math.floor(Math.random() * maxNum) + 1;
                }
                
                if (!annulledFunnel.has(val) && !sequence.includes(val)) {
                    sequence.push(val);
                }
                attempts++;
            }

            if (sequence.length === nToDraw) {
                sequence.sort((a, b) => a - b);
                
                const hits = sequence.filter(n => lotteryData.elite_greens.includes(n)).length;
                const minHits = lotteryData.name.includes('quina') ? 2 : 4;

                if (hits >= minHits) {
                    let type = "QUADRA";
                    if (hits === 2) { type = "DUQUE"; countDuque++; }
                    else if (hits === 3) { type = "TERNO"; countTerno++; }
                    else if (hits === 4) { countQuadra++; }
                    else if (hits === 5) { type = "QUINA"; countQuina++; }
                    else if (hits >= 6) { type = "SENA"; countSena++; }
                    
                    const hitData = { type, sequence: [...sequence], hits, timestamp: new Date().toLocaleTimeString() };
                    detectedHits.push(hitData);
                    renderHit(hitData);
                    btnOpenBrowser.classList.remove("d-none");
                    if (hits >= (minHits + 1)) speak(`Alerta de Elite! ${type} detectada.`);
                }
                renderSequence(sequence);
                totalGenerated++;
            }
        }

        updateStats();
        viewport.scrollTop = viewport.scrollHeight;
        animationId = requestAnimationFrame(generateChunk);
    }

    function renderHit(hit) {
        const panel = document.getElementById("hits-panel");
        if (panel.innerText.includes("Nenhum")) panel.innerHTML = "";
        
        const div = document.createElement("div");
        div.className = "p-2 rounded bg-slate-900 border border-slate-700 x-small d-flex justify-content-between align-items-center mb-1";
        div.innerHTML = `
            <span class="badge bg-warning text-dark">${hit.type}</span>
            <span class="text-white font-monospace">${hit.sequence.join(", ")}</span>
            <span class="text-info">${hit.hits} pts</span>
        `;
        panel.prepend(div);
    }

    function renderSequence(numbers) {
        const row = document.createElement("div");
        row.className = "sequence-row";
        numbers.forEach(n => {
            const ball = document.createElement("div");
            ball.className = "num-ball";
            ball.innerText = n.toString().padStart(2, "0");
            if (lotteryData.elite_greens.includes(n)) ball.classList.add("num-elite");
            if (lotteryData.reclaimed_numbers.includes(n)) ball.classList.add("num-reclaimed");
            row.appendChild(ball);
        });
        if (container.children.length > 20) container.removeChild(container.firstChild);
        container.appendChild(row);
    }

    btnStart.addEventListener("click", () => {
        generatorRunning = true;
        btnStart.classList.add("d-none");
        btnPause.classList.remove("d-none");
        speak("Cálculos iniciados. Supercomputador sincronizado com 10.000 concursos.");
        generateChunk();
    });

    btnPause.addEventListener("click", () => {
        generatorRunning = false;
        btnPause.classList.add("d-none");
        btnStart.classList.remove("d-none");
    });

    const eliteSwitch = document.getElementById("elite-mode-switch");
    const eliteInputs = document.querySelectorAll(".elite-num-input");
    const btnApplyElite = document.getElementById("btn-apply-elite");

    eliteSwitch.addEventListener("change", (e) => {
        eliteModeActive = e.target.checked;
        updateElitePanel();
    });

    function fillEliteInputs(numbers) {
        eliteInputs.forEach((input, idx) => {
            if (numbers[idx]) input.value = numbers[idx];
            else input.value = "";
        });
        updateCustomElite();
    }

    function updateCustomElite() {
        customEliteNumbers = Array.from(eliteInputs)
            .map(input => parseInt(input.value))
            .filter(val => !isNaN(val));
    }

    btnApplyElite.addEventListener("click", () => {
        updateCustomElite();
        speak("Configurações de Elite aplicadas ao motor de cálculo.");
        updateElitePanel();
    });

    // Função para ver todos os hits no navegador
    btnOpenBrowser.addEventListener("click", () => {
        const newWindow = window.open("", "_blank");
        let html = `
            <html>
            <head>
                <title>HITS DE ELITE - Supercomputador 99.9%</title>
                <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
                <style>
                    body { background: #000; color: #fff; font-family: sans-serif; padding: 20px; }
                    .hit-card { background: #1e293b; border: 1px solid #334155; border-radius: 8px; margin-bottom: 10px; padding: 15px; }
                    .num-ball { width: 35px; height: 35px; background: #28a745; color: #fff; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; font-weight: bold; margin-right: 5px; }
                    .badge-type { font-size: 1rem; }
                    h1 { color: #ffc107; font-weight: bold; }
                </style>
            </head>
            <body>
                <div class="container">
                    <h1 class="text-center mb-4">TODOS OS JOGOS DE ELITE GERADOS</h1>
                    <p class="text-center text-secondary">Sincronizado com 10.000 concursos - Precisão 99.9%</p>
                    <div class="row">
        `;
        
        detectedHits.forEach(hit => {
            html += `
                <div class="col-md-6 col-lg-4">
                    <div class="hit-card">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="badge bg-warning text-dark badge-type">${hit.type}</span>
                            <span class="text-info small">${hit.timestamp}</span>
                        </div>
                        <div class="mb-2">
                            ${hit.sequence.map(n => `<div class="num-ball">${n.toString().padStart(2, "0")}</div>`).join("")}
                        </div>
                        <div class="text-end small text-secondary">${hit.hits} pontos de elite</div>
                    </div>
                </div>
            `;
        });
        
        html += `
                    </div>
                </div>
            </body>
            </html>
        `;
        newWindow.document.write(html);
        newWindow.document.close();
    });

</script>
{% endblock %}
