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

{% block content %}
<div class="container-fluid py-5 bg-black min-vh-100 text-white" style="background: linear-gradient(135deg, #000000 0%, #0f172a 100%);">
    <div class="container">
        <!-- Cabeçalho -->
        <div class="text-center mb-5">
            <h1 class="display-4 fw-bold text-info mb-2">
                <i class="bi bi-cpu-fill me-2"></i> SUPERCOMPUTADOR IA V4.0
            </h1>
            <p class="lead text-slate-400">Análise Matemática Autônoma e Resultados em Tempo Real</p>
            <div class="badge bg-danger p-2 px-3 rounded-pill shadow-lg border border-danger">
                <i class="bi bi-broadcast me-1"></i> MONITORAMENTO AO VIVO ATIVO
            </div>
        </div>

        <div class="row g-4">
            {% for item in results %}
            <div class="col-lg-6">
                <div class="card bg-slate-900 border-slate-800 shadow-lg h-100 overflow-hidden" style="border-width: 2px;">
                    <div class="card-header bg-slate-800 border-slate-700 py-3 d-flex justify-content-between align-items-center">
                        <h4 class="mb-0 fw-bold text-uppercase tracking-wider">
                            <i class="bi bi-trophy-fill text-warning me-2"></i> {{ item.lottery.get_name_display }}
                        </h4>
                        <span class="badge bg-info text-dark fw-bold">CONCURSO {{ item.last_result.draw_number|default:"---" }}</span>
                    </div>
                    
                    <div class="card-body p-4">
                        <!-- Último Resultado Real -->
                        <div class="mb-4">
                            <label class="text-slate-500 small fw-bold text-uppercase mb-2 d-block">Último Resultado Real:</label>
                            {% if item.last_result %}
                            <div class="d-flex flex-wrap gap-2">
                                {% for n in item.last_numbers %}
                                <div class="ball-result bg-slate-700 border border-slate-600 rounded-pill px-3 d-flex align-items-center justify-content-center fw-bold" 
                                     style="min-width: 45px; height: 45px; font-size: 1.1rem;">
                                    {{ n }}
                                </div>
                                {% endfor %}
                            </div>
                            <p class="text-slate-400 small mt-2 mb-0">Sorteado em: {{ item.last_result.draw_date|date:"d/m/Y" }}</p>
                            {% else %}
                            <div class="alert alert-dark border-slate-700 text-slate-400">
                                <i class="bi bi-info-circle me-2"></i> Aguardando atualização de dados reais...
                            </div>
                            {% endif %}
                        </div>

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

                        <!-- Histórico de Resultados Reais -->
                        <div class="mb-4">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <label class="text-slate-500 small fw-bold text-uppercase mb-0">Histórico Recente:</label>
                                <button class="btn btn-sm btn-link text-info p-0 text-decoration-none small" type="button" data-bs-toggle="collapse" data-bs-target="#stats-{{ item.lottery.name }}">
                                    <i class="bi bi-bar-chart-line-fill me-1"></i> VER ANÁLISE COMPLETA
                                </button>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-dark table-hover table-sm border-slate-800 mb-0" style="font-size: 0.85rem;">
                                    <thead>
                                        <tr class="text-slate-500">
                                            <th>Concurso</th>
                                            <th>Data</th>
                                            <th>Dezenas Sorteadas</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {% for draw in item.history %}
                                        <tr>
                                            <td class="text-info fw-bold">{{ draw.draw_number }}</td>
                                            <td>{{ draw.draw_date|date:"d/m/Y" }}</td>
                                            <td class="text-success">{{ draw.numbers }}</td>
                                        </tr>
                                        {% empty %}
                                        <tr>
                                            <td colspan="3" class="text-center text-slate-600">Nenhum histórico disponível.</td>
                                        </tr>
                                        {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Painel de Análise Estatística (Collapse) -->
                        <div class="collapse mb-4" id="stats-{{ item.lottery.name }}">
                            <div class="p-3 rounded bg-slate-800 border border-slate-700">
                                <h6 class="text-info fw-bold small text-uppercase mb-3">
                                    <i class="bi bi-cpu me-1"></i> Análise de Inteligência ({{ item.stats.total_analyzed }} Concursos)
                                </h6>
                                
                                <div class="row g-3">
                                    <!-- Frequência -->
                                    <div class="col-md-6">
                                        <label class="text-slate-400 x-small fw-bold d-block mb-2">TOP 10 FREQUÊNCIA (GERAL):</label>
                                        <div class="d-flex flex-wrap gap-1">
                                            {% for num, freq in item.stats.most_common %}
                                            <span class="badge bg-slate-900 border border-info text-info p-2 px-3">
                                                {{ num }}
                                            </span>
                                            {% endfor %}
                                        </div>
                                    </div>
                                    
                                    <!-- Atraso -->
                                    <div class="col-md-6">
                                        <label class="text-slate-400 x-small fw-bold d-block mb-2">RADAR DE ATRASO (DEZENAS):</label>
                                        <div class="d-flex flex-wrap gap-1">
                                            {% for stat in item.stats.most_delayed %}
                                            <span class="badge bg-slate-900 border border-warning text-warning p-2 px-3" title="Atrasado {{ stat.delay }} concursos">
                                                {{ stat.number }} <small class="ms-1">({{ stat.delay }}c)</small>
                                            </span>
                                            {% endfor %}
                                        </div>
                                    </div>

                                    <!-- Equilíbrio -->
                                    <div class="col-12">
                                        <div class="d-flex justify-content-between align-items-center bg-slate-900 p-2 rounded border border-slate-700">
                                            <span class="x-small text-slate-400 fw-bold">EQUILÍBRIO ÚLTIMO SORTEIO:</span>
                                            <span class="badge bg-primary px-3">{{ item.stats.even_odd }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

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

                        <!-- Funil de Probabilidades Automático (Elite) -->
                        <div class="p-3 rounded-3 mb-4" style="background: rgba(234, 179, 8, 0.05); border: 1px solid rgba(234, 179, 8, 0.2);">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <div>
                                    <h5 class="text-warning fw-bold mb-1">
                                        <i class="bi bi-filter-circle-fill me-2"></i> FUNIL DE ELITE AUTOMÁTICO
                                    </h5>
                                    <p class="text-slate-400 small mb-0">Anulação automática de baixa probabilidade ativa</p>
                                </div>
                                <span class="badge bg-warning-subtle text-warning border border-warning px-2">PRECISÃO MÁXIMA</span>
                            </div>

                            {% if item.funnel_numbers %}
                            <div class="d-flex flex-wrap gap-2 mb-4">
                                {% for n in item.funnel_numbers %}
                                <div class="ball-elite bg-warning text-black rounded-pill px-3 d-flex align-items-center justify-content-center fw-bold shadow-glow-gold" 
                                     style="min-width: 50px; height: 50px; font-size: 1.2rem;"
                                     title="Número de Elite">
                                    {{ n }}
                                </div>
                                {% endfor %}
                            </div>

                            <div class="d-grid gap-2 d-md-flex">
                                <button class="btn btn-outline-warning btn-sm flex-grow-1" onclick="copyToClipboard('{{ item.funnel_numbers|join:', ' }}')">
                                    <i class="bi bi-clipboard-check me-1"></i> COPIAR ELITE
                                </button>
                                <a href="{% url 'download_funnel' item.lottery.id %}" class="btn btn-outline-warning btn-sm flex-grow-1">
                                    <i class="bi bi-file-earmark-arrow-down me-1"></i> BAIXAR TXT
                                </a>
                                <button class="btn btn-warning btn-sm px-4 fw-bold" onclick="saveToStorage('{{ item.lottery.name }}_elite', '{{ item.funnel_numbers|join:', ' }}')">
                                    <i class="bi bi-cloud-arrow-up-fill me-1"></i> SALVAR
                                </button>
                            </div>
                            {% else %}
                            <p class="text-slate-500 italic small text-center my-3">
                                <i class="bi bi-funnel me-1"></i> Filtrando números em tempo real...
                            </p>
                            {% endif %}
                        </div>

                        <!-- Predição IA V4.0 -->
                        <div class="p-3 rounded-3" style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2);">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <div>
                                    <h5 class="text-success fw-bold mb-1">
                                        <i class="bi bi-magic me-2"></i> DETERMINAÇÃO IA V4.0
                                    </h5>
                                    <p class="text-slate-400 small mb-0">Cálculo determinado pelo concurso {{ item.last_result.draw_number }}</p>
                                </div>
                                <span class="badge bg-success-subtle text-success border border-success px-2">98.4% PRESSÃO</span>
                            </div>

                            {% if item.predicted_numbers %}
                            <div class="d-flex flex-wrap gap-2 mb-4" id="pred-{{ item.lottery.name }}">
                                {% for n in item.predicted_numbers %}
                                <div class="ball-pred bg-success text-black rounded-pill px-3 d-flex align-items-center justify-content-center fw-bold shadow-glow-green" 
                                     style="min-width: 50px; height: 50px; font-size: 1.2rem; cursor: pointer;"
                                     title="Probabilidade Quente">
                                    {{ n }}
                                </div>
                                {% endfor %}
                            </div>

                            <div class="d-grid gap-2 d-md-flex">
                                <button class="btn btn-outline-success btn-sm flex-grow-1" onclick="copyToClipboard('{{ item.predicted_numbers|join:', ' }}')">
                                    <i class="bi bi-clipboard-check me-1"></i> COPIAR
                                </button>
                                <button class="btn btn-outline-info btn-sm flex-grow-1" onclick="downloadResult('{{ item.lottery.get_name_display }}', '{{ item.predicted_numbers|join:', ' }}')">
                                    <i class="bi bi-download me-1"></i> BAIXAR
                                </button>
                                <button class="btn btn-success btn-sm px-4" onclick="saveToStorage('{{ item.lottery.name }}', '{{ item.predicted_numbers|join:', ' }}')">
                                    <i class="bi bi-bookmark-fill"></i> SALVAR
                                </button>
                            </div>
                            {% else %}
                            <p class="text-slate-500 italic small text-center my-3">
                                <i class="bi bi-calculator me-1"></i> Processando algoritmos de determinação...
                            </p>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="card-footer bg-slate-900 border-slate-800 py-2">
                        <small class="text-slate-500">
                            <i class="bi bi-shield-check text-info me-1"></i> Motor de Supercomputador v4.0.2 - Autônomo
                        </small>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>

        <!-- Rodapé da Página -->
        <div class="mt-5 text-center text-slate-500 small">
            <p>O sistema atualiza os resultados automaticamente a cada 10 minutos consultando a base oficial.</p>
            <a href="{% url 'home' %}" class="btn btn-link text-info text-decoration-none">
                <i class="bi bi-arrow-left me-1"></i> Voltar ao Painel Principal
            </a>
        </div>
    </div>
</div>

<style>
    .shadow-glow-green {
        box-shadow: 0 0 15px rgba(16, 185, 129, 0.4);
        transition: transform 0.2s, box-shadow 0.2s;
    }
    .shadow-glow-gold {
        box-shadow: 0 0 15px rgba(234, 179, 8, 0.4);
        transition: transform 0.2s, box-shadow 0.2s;
    }
    .ball-pred:hover, .ball-elite:hover {
        transform: scale(1.15);
        box-shadow: 0 0 25px rgba(16, 185, 129, 0.7);
    }
    .ball-elite:hover {
        box-shadow: 0 0 25px rgba(234, 179, 8, 0.7);
    }
    .card {
        transition: transform 0.3s;
    }
    .card:hover {
        transform: translateY(-5px);
    }
    .tracking-wider {
        letter-spacing: 0.1em;
    }
</style>

<script>
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        alert("Dezenas copiadas para a área de transferência!");
    });
}

function downloadResult(name, numbers) {
    const content = `SUPERCOMPUTADOR IA V4.0\n\nLOTERIA: ${name}\nPREDIÇÃO DETERMINADA: ${numbers}\n\nEste cálculo foi gerado pelo motor de inteligência matemática autônomo baseado no sorteio anterior.`;
    const blob = new Blob([content], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `IA_V4_PREDICAO_${name.replace(' ', '_')}.txt`;
    a.click();
}

function saveToStorage(key, numbers) {
    const saved = JSON.parse(localStorage.getItem('ia_saved_predictions') || '[]');
    saved.push({
        lottery: key,
        numbers: numbers,
        date: new Date().toLocaleString()
    });
    localStorage.setItem('ia_saved_predictions', JSON.stringify(saved));
    alert("Predição salva no seu histórico do navegador!");
}
</script>
{% endblock %}
