{% extends "base.html" %}

{% block content %}
<div class="container-fluid py-4" style="background: #020617; min-height: 100vh; color: #f8fafc; font-family: 'Segoe UI', Roboto, sans-serif;">
    <div class="row justify-content-center">
        <div class="col-lg-11">
            <div class="card border-0 shadow-lg p-4" style="background: #0f172a; border-radius: 24px; border: 1px solid #1e293b !important;">
                
                <!-- Cabeçalho de Supercomputador -->
                <div class="d-flex justify-content-between align-items-center mb-4 border-bottom border-slate-800 pb-3">
                    <div>
                        <h2 class="display-6 fw-bold mb-0 text-white text-uppercase tracking-tighter">
                            <i class="bi bi-cpu-fill text-info me-2"></i>Supercomputador <span class="text-info">IA v4.0</span>
                        </h2>
                        <p class="text-slate-400 mb-0">Análise Matemática Autônoma em Tempo Real</p>
                    </div>
                    <div class="d-flex gap-3 align-items-center">
                        <div id="elite-indicator" class="d-none badge bg-warning text-dark pulse-warning p-2 rounded-pill fw-bold">
                            <i class="bi bi-shield-check me-1"></i>PRECISÃO 99.9% ATIVA
                        </div>
                        <div id="voice-indicator" class="d-none badge bg-info pulse-info p-2 rounded-pill">
                            <i class="bi bi-volume-up-fill me-1"></i>IA NARRANDO
                        </div>
                        <a href="{% url 'full_report' %}" target="_blank" class="btn btn-info rounded-pill px-4 fw-bold shadow-sm">
                            <i class="bi bi-file-earmark-bar-graph-fill me-1"></i>ABRIR RELATÓRIO
                        </a>
                        <a href="{% url 'home' %}" class="btn btn-outline-slate rounded-pill px-4 text-white border-slate-700">Sair do Sistema</a>
                    </div>
                </div>

                <div class="row g-4">
                    <!-- Coluna Esquerda: Controles e Gerador -->
                    <div class="col-lg-8">
                        <div class="row g-3 mb-4">
                            <div class="col-md-4">
                                <label class="form-label text-slate-300 small fw-bold">LOTERIA ALVO:</label>
                                <select id="lottery-select" class="form-select bg-slate-900 text-white border-slate-700 shadow-none py-2">
                                    <option value="">--- Selecione o Jogo ---</option>
                                    {% for l in loterias %}
                                        <option value="{{ l.name }}">{{ l.get_name_display }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-8 d-flex align-items-end gap-2">
                                <button id="btn-start" class="btn btn-success btn-lg flex-grow-1 rounded-pill fw-bold shadow-glow-green" disabled>
                                    <i class="bi bi-play-fill"></i> INICIAR
                                </button>
                                <button id="btn-pause" class="btn btn-warning btn-lg flex-grow-1 rounded-pill fw-bold shadow-sm d-none">
                                    <i class="bi bi-pause-fill"></i> PAUSAR
                                </button>
                                <button id="btn-download" class="btn btn-primary btn-lg rounded-pill fw-bold shadow-sm d-none">
                                    <i class="bi bi-download"></i> BAIXAR ACERTOS
                                </button>
                                <a href="{% url 'hits_report' %}" target="_blank" id="btn-open-browser" class="btn btn-outline-info btn-lg rounded-pill fw-bold shadow-sm d-none">
                                    <i class="bi bi-window-stack"></i> ABRIR NO NAVEGADOR
                                </a>
                                <div class="btn-group shadow-sm">
                                    <button id="btn-up" class="btn btn-dark border-slate-700"><i class="bi bi-chevron-up"></i></button>
                                    <button id="btn-down" class="btn btn-dark border-slate-700"><i class="bi bi-chevron-down"></i></button>
                                </div>
                            </div>
                        </div>

                        <!-- Viewport do Motor -->
                        <div class="generator-viewport p-3 bg-black rounded-4 shadow-inner mb-3" style="min-height: 550px; max-height: 550px; overflow-y: auto; border: 2px solid #1e293b;">
                            <div id="sequence-container" class="d-flex flex-column gap-2">
                                <div class="text-center text-slate-600 py-5 mt-5">
                                    <div class="spinner-grow text-info mb-3" role="status"></div>
                                    <h4 class="fw-light">SISTEMA EM STANDBY</h4>
                                    <p class="small">Selecione uma loteria para carregar o Funil de Probabilidades</p>
                                </div>
                            </div>
                        </div>

                        <!-- Barra de Stats Rápida -->
                        <div id="stats-bar" class="row g-2 d-none mb-3">
                            <div class="col">
                                <div class="p-2 rounded bg-slate-900 border-start border-success border-2">
                                    <small class="d-block text-muted x-small">GERADOS</small>
                                    <span id="count-total" class="fw-bold text-success">0</span>
                                </div>
                            </div>
                            <div id="col-duque" class="col d-none">
                                <div class="p-2 rounded bg-slate-900 border-start border-secondary border-2">
                                    <small class="d-block text-muted x-small">DUQUES</small>
                                    <span id="count-duque" class="fw-bold text-secondary">0</span>
                                </div>
                            </div>
                            <div id="col-terno" class="col d-none">
                                <div class="p-2 rounded bg-slate-900 border-start border-primary border-2">
                                    <small class="d-block text-muted x-small">TERNOS</small>
                                    <span id="count-terno" class="fw-bold text-primary">0</span>
                                </div>
                            </div>
                            <div class="col">
                                <div class="p-2 rounded bg-slate-900 border-start border-info border-2">
                                    <small class="d-block text-muted x-small">QUADRAS</small>
                                    <span id="count-quadra" class="fw-bold text-info">0</span>
                                </div>
                            </div>
                            <div class="col">
                                <div class="p-2 rounded bg-slate-900 border-start border-warning border-2">
                                    <small class="d-block text-muted x-small">QUINAS</small>
                                    <span id="count-quina" class="fw-bold text-warning">0</span>
                                </div>
                            </div>
                            <div id="col-sena" class="col">
                                <div class="p-2 rounded bg-slate-900 border-start border-danger border-2">
                                    <small class="d-block text-muted x-small">SENAS</small>
                                    <span id="count-sena" class="fw-bold text-danger">0</span>
                                </div>
                            </div>
                        </div>

                        <!-- Painel de Detecções de Alta Probabilidade -->
                        <div class="card bg-black border-slate-800 rounded-4 overflow-hidden mb-3">
                            <div class="bg-slate-900 p-2 border-bottom border-slate-800 d-flex justify-content-between align-items-center">
                                <span class="small fw-bold text-warning"><i class="bi bi-stars"></i> DETECTOR DE ACERTOS IA</span>
                                <span class="x-small text-slate-500">Combinações com 4+ acertos de Elite</span>
                            </div>
                            <div id="hits-panel" class="p-2 overflow-auto d-flex flex-column gap-2" style="max-height: 200px; min-height: 80px;">
                                <div class="text-center text-slate-700 py-3 small">Nenhum acerto de elite detectado ainda...</div>
                            </div>
                        </div>
                    </div>

                    <!-- Coluna Direita: Funil e Super Analisador -->
                    <div class="col-lg-4">
                        <!-- Painel Configurações de Elite (99.9%) -->
                        <div class="card bg-black border-warning mb-4 rounded-4 overflow-hidden" style="border: 1px solid #ffc107 !important;">
                            <div class="bg-warning text-dark p-2 text-center fw-bold small">
                                <i class="bi bi-gear-fill"></i> CONFIGURAÇÕES DE ELITE
                            </div>
                            <div class="p-3">
                                <div class="form-check form-switch mb-3">
                                    <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>
                                <div class="row g-2" id="elite-inputs-container">
                                    <!-- Inputs para as 10 dezenas de elite -->
                                    {% for i in "1234567890"|make_list %}
                                    <div class="col-3">
                                        <input type="number" class="form-control form-control-sm bg-slate-900 text-white border-slate-700 elite-num-input" placeholder="00" min="1" max="80">
                                    </div>
                                    {% endfor %}
                                </div>
                                <div class="d-flex gap-2 mt-3">
                                    <button id="btn-recalculate-math" class="btn btn-outline-warning btn-sm flex-grow-1 fw-bold rounded-pill">
                                        <i class="bi bi-calculator-fill"></i> RECALIBRAR MATEMÁTICA
                                    </button>
                                    <button id="btn-apply-elite" class="btn btn-warning btn-sm flex-grow-1 fw-bold rounded-pill shadow-sm">
                                        <i class="bi bi-check-circle-fill"></i> ATIVAR ESTES NÚMEROS
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Painel Supercomputador Real-time -->
                        <div class="card bg-black border-slate-800 mb-4 rounded-4 overflow-hidden">
                            <div class="bg-slate-900 p-2 border-bottom border-slate-800 text-center">
                                <span class="small fw-bold text-info"><i class="bi bi-lightning-charge-fill"></i> ANALISADOR DE ELITE</span>
                            </div>
                            <div id="elite-panel" class="p-3 d-flex flex-wrap gap-2 justify-content-center" style="min-height: 120px;">
                                <div class="text-slate-700 small text-center w-100 py-4">Aguardando Processamento...</div>
                            </div>
                        </div>

                        <!-- Funil Numérico -->
                        <div class="card bg-slate-900 border-slate-800 rounded-4">
                            <div class="p-3 border-bottom border-slate-800 d-flex justify-content-between align-items-center">
                                <h6 class="mb-0 fw-bold text-white">FUNIL DE ANULAÇÃO</h6>
                                <span id="funnel-count" class="badge bg-danger rounded-pill">0 / 60</span>
                            </div>
                            <div class="p-3">
                                <p class="x-small text-slate-400 mb-3">Selecione até 60 números para o Supercomputador ignorar totalmente nas sequências.</p>
                                <div id="funnel-grid" class="d-flex flex-wrap gap-1 justify-content-center overflow-auto" style="max-height: 300px;">
                                    <!-- Grid gerado via JS -->
                                    <div class="text-muted small py-4">Selecione o jogo acima</div>
                                </div>
                            </div>
                        </div>

                        <!-- Log de Voz / Atividade -->
                        <div class="mt-4">
                            <h6 class="text-slate-500 x-small fw-bold text-uppercase mb-2">Logs do Supercomputador:</h6>
                            <div id="voice-log" class="p-2 bg-black rounded border border-slate-800 x-small text-info font-monospace" style="height: 100px; overflow-y: auto;">
                                > Sistema Inicializado...<br>
                                > Aguardando entrada de dados...
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .x-small { font-size: 0.7rem; }
    .text-emerald { color: #10b981; }
    .bg-slate-900 { background: #0f172a; }
    .border-slate-700 { border-color: #334155 !important; }
    .border-slate-800 { border-color: #1e293b !important; }
    .shadow-glow-green { box-shadow: 0 0 15px rgba(25, 135, 84, 0.4); }
    .shadow-inner { box-shadow: inset 0 2px 10px rgba(0,0,0,0.8); }

    .funnel-ball {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 6px;
        background: #1e293b;
        color: #94a3b8;
        font-size: 0.8rem;
        cursor: pointer;
        transition: all 0.2s;
        border: 1px solid transparent;
    }
    .funnel-ball:hover { background: #334155; color: white; }
    .funnel-ball.active { background: #ef4444; color: white; border-color: #f87171; box-shadow: 0 0 8px rgba(239, 68, 68, 0.4); }

    .sequence-row {
        display: flex;
        gap: 6px;
        justify-content: center;
        padding: 8px;
        background: #0f172a;
        border-radius: 10px;
        border: 1px solid #1e293b;
        transition: all 0.2s;
    }
    .sequence-row:hover { background: #1e293b; transform: scale(1.02); }

    .num-ball {
        width: 38px;
        height: 38px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        font-weight: bold;
        font-size: 1rem;
        background: #334155;
        color: white;
    }
    .num-elite { background: linear-gradient(135deg, #198754, #28a745); box-shadow: 0 0 10px rgba(40, 167, 69, 0.4); }
    .num-reclaimed { background: #10b981; animation: pulse-green 1.5s infinite; }

    @keyframes pulse-green {
        0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
        70% { transform: scale(1.1); box-shadow: 0 0 0 8px rgba(16, 185, 129, 0); }
        100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
    }
    .pulse-info { animation: pulse-blue 1s infinite; }
    @keyframes pulse-blue {
        0% { opacity: 1; } 50% { opacity: 0.5; } 100% { opacity: 1; }
    }
</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 = []; // { type, sequence, hits }
    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(); // Para a fala anterior para não encavalar
        const utter = new SpeechSynthesisUtterance(text);
        utter.lang = 'pt-BR';
        utter.rate = 1.1;
        
        // Tenta pegar voz feminina
        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 += `> IA: ${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");

    // Novo Algoritmo de Probabilidade de Elite (Busca por Quadra 4+)
    function recalculateDeepElite() {
        if (!lotteryData || !lotteryData.name.toLowerCase().includes('quina')) return;
        
        speak("Iniciando Recalibragem Neural de Alta Precisão para o próximo concurso.");
        
        const allNums = Array.from({length: 80}, (_, i) => i + 1);
        const frequency = lotteryData.elite_greens; // Histórico de frequência
        const delayed = lotteryData.reclaimed_numbers; // Números em atraso
        
        // Peso 1: Frequência Harmônica (30% de peso)
        // Peso 2: Atraso Crítico (50% de peso - Essencial para o próximo concurso)
        // Peso 3: Quadrantes (20% de peso - Equilíbrio)
        
        let candidates = allNums.map(n => {
            let score = 0;
            
            // Pontua por frequência (Inverso para evitar vício)
            const freqIdx = frequency.indexOf(n);
            if (freqIdx !== -1) score += (10 - (freqIdx / 8)); 

            // Pontua por Atraso (Ouro para o próximo sorteio)
            if (delayed.includes(n)) score += 15;
            
            // Bônus de Quadrante (Distribuição Geométrica)
            const quad = Math.ceil(n / 20);
            score += 2; 

            return { num: n, score: score };
        });

        // Ordena por maior score de probabilidade
        candidates.sort((a, b) => b.score - a.score);

        // Seleciona as 10 dezenas com Convergência Matemática
        const top10 = candidates.slice(0, 10).map(c => c.num).sort((a, b) => a - b);
        
        customEliteNumbers = top10;
        fillEliteInputs(top10);
        updateElitePanel();
        
        speak("Matemática de Elite aplicada. 10 dezenas de ouro selecionadas para busca de Quadra.");
    }

    lotterySelect.addEventListener("change", async (e) => {
        const key = e.target.value;
        if (!key) return;
        
        speak(`Iniciando análise para ${key}. Carregando base de dados histórica.`);
        const resp = await fetch(`/api/lottery-info/${key}/`);
        lotteryData = await resp.json();
        
        // Ajusta visibilidade das colunas baseado no jogo
        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");
            // Se for quina, aplica a nova matemática automaticamente
            setTimeout(recalculateDeepElite, 1000);
        } 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);
        updateElitePanel();
        if (!key.toLowerCase().includes('quina')) {
            fillEliteInputs(lotteryData.elite_greens.slice(0, 10));
        }
        btnStart.disabled = false;
        document.getElementById("stats-bar").classList.remove("d-none");
        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");
            
            // Pré-carrega os anulados do banco, se houver espaço
            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) {
                        speak("Limite do funil atingido. Máximo de 60 dezenas.");
                        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, 10);
        numbers.forEach(n => {
            const ball = document.createElement("div");
            ball.className = "num-ball num-elite mb-2";
            ball.style.width = "42px";
            ball.style.height = "42px";
            ball.innerText = n.toString().padStart(2, "0");
            elitePanel.appendChild(ball);
        });
    }

    function resetGenerator() {
        generatorRunning = false;
        btnStart.classList.remove("d-none");
        btnPause.classList.add("d-none");
        btnDownload.classList.add("d-none");
        container.innerHTML = "";
        document.getElementById("hits-panel").innerHTML = `<div class="text-center text-slate-700 py-3 small">Nenhum acerto de elite detectado ainda...</div>`;
        currentStartNum = 1;
        totalGenerated = 0;
        countDuque = 0;
        countTerno = 0;
        countQuadra = 0;
        countQuina = 0;
        countSena = 0;
        detectedHits = [];
        updateStats();
        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();
        
        if (detectedHits.length > 0) {
            document.getElementById("btn-download").classList.remove("d-none");
            document.getElementById("btn-open-browser").classList.remove("d-none");
            localStorage.setItem('detectedHits', JSON.stringify(detectedHits));
        }
    }

    // Filtra sequências longas (Permite no máx 2 números consecutivos)
    function hasForbiddenSequence(numbers) {
        const sorted = [...numbers].sort((a, b) => a - b);
        let currentSeq = 1;
        for (let i = 1; i < sorted.length; i++) {
            if (sorted[i] === sorted[i - 1] + 1) {
                currentSeq++;
                if (currentSeq > 2) return true; // Bloqueia 3 ou mais
            } else {
                currentSeq = 1;
            }
        }
        return false;
    }

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

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

        for (let i = 0; i < 4; i++) {
            let sequence = [];
            let safetyCounter = 0;
            
            // Tenta gerar uma sequência válida
            while (sequence.length < nToDraw && safetyCounter < 1000) {
                let val;
                if (eliteModeActive && eliteNums.length >= nToDraw) {
                    // Modo 99.9%: Escolhe apenas entre os números de elite
                    val = eliteNums[Math.floor(Math.random() * eliteNums.length)];
                } else {
                    // Modo Normal: Incremento dinâmico
                    let step = Math.floor(Math.random() * 3) + 1;
                    val = ((currentStartNum - 1) % maxNum) + 1;
                    currentStartNum += step;
                }
                
                safetyCounter++;
                if (annulledFunnel.has(val)) continue;
                if (!sequence.includes(val)) sequence.push(val);
            }

            if (sequence.length === nToDraw) {
                // Ordenar a sequência (Menor para o Maior) conforme solicitado
                sequence.sort((a, b) => a - b);

                // Validação de Sequência Real (Máx 2 consecutivos)
                if (hasForbiddenSequence(sequence)) {
                    continue; // Descarta e tenta a próxima no próximo loop
                }

                const hits = sequence.filter(n => lotteryData.elite_greens.includes(n)).length;
                const isQuina = lotteryData.name.toLowerCase().includes('quina');
                const minHits = isQuina ? 2 : 4;

                if (hits >= minHits) {
                    let type = "";
                    if (hits === 2) { type = "DUQUE"; countDuque++; }
                    else if (hits === 3) { type = "TERNO"; countTerno++; }
                    else if (hits === 4) { type = "QUADRA"; countQuadra++; }
                    else if (hits === 5) { type = "QUINAS"; countQuina++; }
                    else if (hits >= 6) { type = "SENA"; countSena++; }
                    
                    const hitData = { type, sequence: [...sequence], hits };
                    detectedHits.push(hitData);
                    renderHit(hitData);
                    
                    if (hits >= (isQuina ? 3 : 5)) {
                        speak(`Alerta! ${type} detectada com alto índice de probabilidade.`);
                    }
                }
                renderSequence(sequence);
                totalGenerated++;
            }
        }

        updateStats();
        viewport.scrollTop = viewport.scrollHeight;
        
        if (totalGenerated % 5000 === 0 && totalGenerated > 0) {
            speak(`Análise profunda em curso. ${totalGenerated} combinações verificadas.`);
        }

        animationId = requestAnimationFrame(generateChunk);
    }

    function renderHit(hit) {
        const panel = document.getElementById("hits-panel");
        if (detectedHits.length === 1) panel.innerHTML = "";
        
        let badgeClass = "bg-danger";
        if (hit.hits === 2) badgeClass = "bg-secondary";
        else if (hit.hits === 3) badgeClass = "bg-primary";
        else if (hit.hits === 4) badgeClass = "bg-info";
        else if (hit.hits === 5) badgeClass = "bg-warning text-dark";

        const div = document.createElement("div");
        div.className = "d-flex justify-content-between align-items-center p-2 rounded bg-slate-900 border border-slate-800 x-small";
        div.innerHTML = `
            <span class="badge ${badgeClass}">${hit.type}</span>
            <span class="text-white font-monospace">${hit.sequence.join(", ")}</span>
            <span class="text-slate-500">${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.reclaimed_numbers.includes(n)) {
                ball.classList.add("num-reclaimed");
            } else if (lotteryData.elite_greens.includes(n)) {
                ball.classList.add("num-elite");
            }
            row.appendChild(ball);
        });

        if (container.children.length > 30) container.removeChild(container.firstChild);
        container.appendChild(row);
    }

    btnStart.addEventListener("click", () => {
        if (!lotteryData) return;
        generatorRunning = true;
        btnStart.classList.add("d-none");
        btnPause.classList.remove("d-none");
        speak("Motor Sequencial Iniciado. Aplicando Funil de Sessenta Dezenas.");
        generateChunk();
    });

    btnPause.addEventListener("click", () => {
        generatorRunning = false;
        btnPause.classList.add("d-none");
        btnStart.classList.remove("d-none");
        speak("Motor pausado pelo operador.");
        if (animationId) cancelAnimationFrame(animationId);
    });

    const btnDownload = document.getElementById("btn-download");
    btnDownload.addEventListener("click", () => {
        if (detectedHits.length === 0) return;
        
        let content = `RELATÓRIO DE ELITE IA - ${lotteryData.name}\n`;
        content += `Data: ${new Date().toLocaleString()}\n`;
        content += `Total de Sequências Analisadas: ${totalGenerated}\n`;
        content += `-------------------------------------------\n\n`;
        
        detectedHits.forEach(h => {
            content += `[${h.type}] ACERTOS: ${h.hits} | JOGO: ${h.sequence.join(", ")}\n`;
        });

        const blob = new Blob([content], { type: "text/plain" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `elite_detectada_${lotteryData.name.toLowerCase()}.txt`;
        a.click();
        speak("Download do relatório de elite concluído.");
    });

    document.getElementById("btn-up").addEventListener("click", () => viewport.scrollBy({ top: -300, behavior: "smooth" }));
    document.getElementById("btn-down").addEventListener("click", () => viewport.scrollBy({ top: 300, behavior: "smooth" }));

    // Novos controles de Elite
    const eliteSwitch = document.getElementById("elite-mode-switch");
    const eliteInputs = document.querySelectorAll(".elite-num-input");
    const btnApplyElite = document.getElementById("btn-apply-elite");
    const btnRecalculateMath = document.getElementById("btn-recalculate-math");

    btnRecalculateMath.addEventListener("click", () => {
        recalculateDeepElite();
    });

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

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

    eliteSwitch.addEventListener("change", (e) => {
        eliteModeActive = e.target.checked;
        const indicator = document.getElementById("elite-indicator");
        
        if (eliteModeActive) {
            indicator.classList.remove("d-none");
            speak("Modo de Precisão 99,9% Ativado. O Supercomputador focará apenas nas dezenas de elite escolhidas.");
        } else {
            indicator.classList.add("d-none");
            speak("Modo Normal Restaurado.");
        }
        updateElitePanel();
    });

    btnApplyElite.addEventListener("click", () => {
        updateCustomElite();
        if (customEliteNumbers.length < (lotteryData ? lotteryData.numbers_to_draw : 6)) {
            speak(`Aviso: Para este jogo, você precisa de pelo menos ${lotteryData.numbers_to_draw} números de elite.`);
            return;
        }
        speak("Configurações de Elite aplicadas com sucesso. Pronto para calcular acertos.");
        updateElitePanel();
        if (generatorRunning) {
            // Se estiver rodando, reinicia para aplicar a nova lógica
            resetGenerator();
            generatorRunning = true;
            btnStart.classList.add("d-none");
            btnPause.classList.remove("d-none");
            generateChunk();
        }
    });

    // CSS para pulso amarelo
    const style = document.createElement("style");
    style.innerHTML = `
        .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); }
        }
    `;
    document.head.appendChild(style);
</script>
{% endblock %}
