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

{% block title %}{{ project_name }} · Analise Loterias BR{% endblock %}

{% block content %}
<div class="hero-shell">
  <header class="site-header">
    <nav class="navbar navbar-expand-lg navbar-dark">
      <div class="container">
        <a class="navbar-brand brand" href="#top">{{ project_name }}</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarMain"
          aria-controls="navbarMain" aria-expanded="false" aria-label="Alternar navegacao">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarMain">
          <ul class="navbar-nav ms-auto align-items-lg-center gap-lg-3">
            <li class="nav-item"><a class="nav-link" href="#simulador">Simulador</a></li>
            <li class="nav-item"><a class="nav-link" href="#jogos">Jogos</a></li>
            <li class="nav-item"><a class="nav-link" href="#como-funciona">Como funciona</a></li>
            {% if is_admin %}
            <li class="nav-item"><a class="nav-link text-warning" href="{% url 'admin_dashboard' %}">Painel Admin</a></li>
            {% else %}
            <li class="nav-item"><a class="nav-link" href="{% url 'admin_login' %}">Acesso Admin</a></li>
            {% endif %}
            <li class="nav-item">
              <a class="btn btn-brand" href="#simulador">Gerar jogos</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>
  </header>

  <main id="top" class="site-main">
    <section class="hero-section">
      <div class="container">
        <div class="text-center mb-5 d-flex justify-content-center gap-3 flex-wrap">
            <a href="{% url 'sequential_generator' %}" class="btn btn-dark btn-lg rounded-pill px-4 shadow-lg border-info" style="background: #0f172a; border-width: 2px;">
                <i class="bi bi-cpu-fill text-info me-2"></i> ABRIR GERADOR SEQUENCIAL IA
            </a>
            <a href="{% url 'lottery_results' %}" class="btn btn-dark btn-lg rounded-pill px-4 shadow-lg border-warning" style="background: #0f172a; border-width: 2px;">
                <i class="bi bi-graph-up-arrow text-warning me-2"></i> CENTRAL DE RESULTADOS V4.0
            </a>
        </div>
        <div class="row align-items-center g-5">
          <div class="col-lg-6">
            <div class="eyebrow">Inteligencia matematica aplicada</div>
            <h1 class="hero-title">Geracoes inteligentes de numeros para todas as loterias do Brasil.</h1>
            <p class="hero-lead">
              Use historico recente, frequencias e probabilidades reais para montar seus jogos. Configure cada
              loteria e acompanhe os indicadores mais relevantes antes do proximo sorteio.
            </p>
            <div class="hero-actions">
              <a class="btn btn-brand btn-lg" href="#simulador">Simular agora</a>
              <a class="btn btn-ghost btn-lg" href="#jogos">Ver configuracoes</a>
            </div>
            <div class="hero-stats">
              <div class="stat-card">
                <span class="stat-value">5 loterias</span>
                <span class="stat-label">Mega-Sena, Quina, Dupla Sena, Lotomania, Lotofacil</span>
              </div>
              <div class="stat-card">
                <span class="stat-value">Analise recencia</span>
                <span class="stat-label">Ultimos sorteios para ajustar pesos e tendencias</span>
              </div>
              <div class="stat-card">
                <span class="stat-value">Probabilidade real</span>
                <span class="stat-label">Calculo matematico de combinacoes e odds</span>
              </div>
            </div>
          </div>
          <div class="col-lg-6">
            <div id="simulador" class="card-glass">
              <div class="card-glass-header">
                <h2 class="card-title">Simulador de jogos</h2>
                <p class="card-subtitle">Escolha a loteria, ajuste o recorte e gere combinacoes sugeridas.</p>
              </div>
              <form method="post" class="generator-form">
                {% csrf_token %}
                <div class="mb-3">
                  <label class="form-label" for="{{ form.lottery_type.id_for_label }}">{{ form.lottery_type.label }}</label>
                  {{ form.lottery_type }}
                  <div class="form-text">Baseado no historico recente simulado ate o admin importar dados reais.</div>
                  {{ form.lottery_type.errors }}
                </div>
                <div class="row g-3">
                  <div class="col-md-6">
                    <label class="form-label" for="{{ form.draws_to_consider.id_for_label }}">{{ form.draws_to_consider.label }}</label>
                    {{ form.draws_to_consider }}
                    {{ form.draws_to_consider.errors }}
                  </div>
                  <div class="col-md-6">
                    <label class="form-label" for="{{ form.games_to_generate.id_for_label }}">{{ form.games_to_generate.label }}</label>
                    {{ form.games_to_generate }}
                    {{ form.games_to_generate.errors }}
                  </div>
                </div>
                <div class="form-actions">
                  <button type="submit" class="btn btn-brand btn-lg w-100">Gerar sugestoes</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>
</div>

<section class="insights-section">
  <div class="container">
    <div class="section-header">
      <h2>Resumo matematico</h2>
      <p>Resultados calculados com base no recorte selecionado.</p>
    </div>
    {% if result %}
    <div class="row g-4 align-items-stretch">
      <div class="col-lg-6">
        <div class="card-soft">
          <div class="card-soft-header">
            <h3>{{ result.lottery }}</h3>
            <span class="pill">{{ result.draws_used }} sorteios analisados</span>
          </div>
          <div class="metrics">
            <div class="metric">
              <span class="metric-label">Combinacoes possiveis</span>
              <span class="metric-value">{{ result.total_combinations }}</span>
            </div>
            <div class="metric">
              <span class="metric-label">Odds de acerto total</span>
              <span class="metric-value">{{ result.odds }}</span>
            </div>
            <div class="metric">
              <span class="metric-label">Probabilidade</span>
              <span class="metric-value">{{ result.percent }}</span>
            </div>
          </div>
          <div class="number-groups">
            <div>
              <div class="group-title text-success">Probabilidades Quentes (Elite Verde)</div>
              <div class="badge-grid">
                {% for number in result.hot_numbers %}
                <span class="badge shadow-sm" style="background: linear-gradient(135deg, #198754, #28a745); font-size: 1.1rem; border: none;">{{ number|stringformat:"02d" }}</span>
                {% endfor %}
              </div>
              <small class="text-muted mt-2 d-block" style="font-size: 0.75rem;">* Atualizado ao vivo conforme anulações no editor.</small>
            </div>
            <div class="mt-3">
              <div class="group-title text-danger">Números Anulados (IA Radar Radar)</div>
              <div class="badge-grid">
                {% for number in result.annulled_numbers %}
                  {% if number in result.reclaimed_numbers %}
                  <span class="badge shadow-sm pulse-green" style="background: linear-gradient(135deg, #198754, #20c997); font-size: 1.1rem; border: 2px solid #fff;">{{ number|stringformat:"02d" }}</span>
                  {% else %}
                  <span class="badge" style="background-color: #dc3545; font-size: 1.1rem;">{{ number|stringformat:"02d" }}</span>
                  {% endif %}
                {% endfor %}
                {% if not result.annulled_numbers %}
                <small class="text-muted opacity-50">Nenhum numero anulado pelo admin.</small>
                {% endif %}
              </div>
              {% if result.reclaimed_numbers %}
              <small class="text-success mt-2 d-block fw-bold" style="font-size: 0.8rem;">
                <i class="bi bi-radar"></i> IA DETECTOU: {{ result.reclaimed_numbers|length }} número(s) anulado(s) com alta chance de sorteio imediato (Verde)!
              </small>
              {% endif %}
            </div>
          </div>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="card-soft">
          <div class="card-soft-header">
            <h3>Jogos sugeridos</h3>
            <span class="pill">{{ result.suggestions|length }} combinacoes</span>
          </div>
          <div class="suggestions-grid">
            {% if result.is_trillion %}
            <div class="alert alert-success mb-3 shadow-sm border-0" style="background: linear-gradient(135deg, #198754, #20c997); color: white;">
              <strong>Simulação de {{ result.trillion_label }} Concluída!</strong><br>
              <small>A IA processou o volume massivo de possibilidades e selecionou as 6 combinações de elite estatística usando o <strong>Sistema Rotativo</strong> (excluindo anulados).</small>
            </div>
            {% endif %}
            {% for suggestion in result.suggestions %}
            <div class="suggestion">
              {% for number in suggestion %}
              <span class="ball {% if number in result.hot_numbers %}ball-hot{% elif number in result.cold_numbers %}ball-cold{% endif %}">
                {{ number|stringformat:"02d" }}
              </span>
              {% endfor %}
            </div>
            {% endfor %}
          </div>
        </div>
      </div>
    </div>
    {% else %}
    <div class="card-soft placeholder-card">
      <div class="placeholder-icon">&middot;&middot;&middot;</div>
      <div>
        <h3>Simule para ver as probabilidades</h3>
        <p>Escolha a loteria e o recorte no simulador acima para gerar os primeiros jogos sugeridos.</p>
      </div>
    </div>
    {% endif %}
  </div>
</section>

<section class="manual-selection-section py-5" style="background: #f8f9fa;">
  <div class="container">
    <div class="section-header text-center mb-5">
      <h2 class="display-6 fw-bold">Seleção Manual & Matemática Ao Vivo</h2>
      <p class="text-muted">Escolha 6 ou mais números e peça à IA para calcular a elite estatística agora.</p>
    </div>
    
    <div class="row g-4">
      <div class="col-lg-8">
        <div class="card shadow-sm border-0 p-4">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="mb-0">Quadro de Dezenas</h4>
            <span class="badge bg-success" id="selected-count">0 selecionados</span>
          </div>
          <div id="number-grid" class="d-flex flex-wrap gap-2 justify-content-center p-3" style="background: #fff; border-radius: 12px; min-height: 200px;">
            <p class="text-muted mt-4">Selecione uma loteria no simulador acima para carregar o quadro.</p>
          </div>
        </div>
      </div>
      <div class="col-lg-4">
        <div class="card shadow-sm border-0 p-4 h-100 text-center" style="background: linear-gradient(135deg, #1e293b, #0f172a); color: white;">
          <h4>Análise Ao Vivo</h4>
          <hr class="border-secondary">
          <div id="live-result-area" class="py-4">
            <div class="display-1 fw-bold mb-0" id="live-score">--</div>
            <div class="text-uppercase tracking-wider small opacity-75">Score de Elite IA</div>
          </div>
          <div class="mt-auto">
            <button id="btn-live-math" class="btn btn-success btn-lg w-100 py-3 fw-bold shadow">
              <i class="bi bi-cpu"></i> CÁLCULO MATEMÁTICO AO VIVO
            </button>
            <p class="small mt-3 opacity-50">Mínimo de 6 dezenas para processar.</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const grid = document.getElementById('number-grid');
    const selectCount = document.getElementById('selected-count');
    const lotterySelect = document.querySelector('select[name="lottery_type"]');
    const btnLive = document.getElementById('btn-live-math');
    const liveScore = document.getElementById('live-score');
    const liveResultArea = document.getElementById('live-result-area');
    
    let selectedNumbers = new Set();
    let currentMax = 60;

    const lotteryConfigs = {
        'mega_sena': 60,
        'quina': 80,
        'dupla_sena': 50,
        'lotomania': 100,
        'lotofacil': 25
    };

    function renderGrid() {
        const type = lotterySelect.value;
        currentMax = lotteryConfigs[type] || 60;
        grid.innerHTML = '';
        selectedNumbers.clear();
        updateUI();

        for (let i = 1; i <= currentMax; i++) {
            const ball = document.createElement('div');
            ball.className = 'live-ball';
            ball.textContent = i.toString().padStart(2, '0');
            ball.onclick = () => toggleNumber(i, ball);
            grid.appendChild(ball);
        }
    }

    function toggleNumber(num, element) {
        if (selectedNumbers.has(num)) {
            selectedNumbers.delete(num);
            element.classList.remove('active');
        } else {
            selectedNumbers.add(num);
            element.classList.add('active');
        }
        updateUI();
    }

    function updateUI() {
        selectCount.textContent = `${selectedNumbers.size} selecionados`;
    }

    lotterySelect.addEventListener('change', renderGrid);
    renderGrid(); // Initial load

    btnLive.onclick = async () => {
        if (selectedNumbers.size < 6) {
            alert('Por favor, selecione pelo menos 6 números.');
            return;
        }

        btnLive.disabled = true;
        btnLive.textContent = 'PROCESSANDO MATEMÁTICA...';
        
        try {
            const response = await fetch('{% url "live_math" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: JSON.stringify({
                    lottery: lotterySelect.value,
                    numbers: Array.from(selectedNumbers)
                })
            });

            const data = await response.json();
            if (data.error) throw new Error(data.error);

            liveScore.textContent = data.score + '%';
            liveScore.style.color = data.status === 'success' ? '#22c55e' : '#eab308';
            
            // Efeito visual de sucesso
            liveResultArea.style.transform = 'scale(1.1)';
            setTimeout(() => liveResultArea.style.transform = 'scale(1)', 200);

        } catch (err) {
            alert('Erro no cálculo: ' + err.message);
        } finally {
            btnLive.disabled = false;
            btnLive.textContent = 'CÁLCULO MATEMÁTICO AO VIVO';
        }
    };
});
</script>

<style>
.live-ball {
    width: 45px;
    height: 45px;
    border: 2px solid #e2e8f0;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-weight: bold;
    transition: all 0.2s;
    user-select: none;
    background: white;
    color: #475569;
}
.live-ball:hover {
    border-color: #198754;
    transform: translateY(-2px);
}
.live-ball.active {
    background: #198754;
    color: white;
    border-color: #198754;
    box-shadow: 0 0 15px rgba(25, 135, 84, 0.4);
}
.pulse-green {
    animation: pulse-animation 2s infinite;
    box-shadow: 0 0 0 0 rgba(32, 201, 151, 0.7);
}
@keyframes pulse-animation {
    0% {
        box-shadow: 0 0 0 0 rgba(32, 201, 151, 0.7);
    }
    70% {
        box-shadow: 0 0 0 10px rgba(32, 201, 151, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(32, 201, 151, 0);
    }
}
#live-result-area {
    transition: all 0.3s;
}
</style>

<section id="jogos" class="games-section">
  <div class="container">
    <div class="section-header">
      <h2>Configuracoes por loteria</h2>
      <p>Regras atuais e odds de acerto total para cada jogo.</p>
    </div>
    <div class="row g-4">
      {% for lottery in lottery_cards %}
      <div class="col-md-6 col-xl-4">
        <div class="game-card">
          <div class="game-card-header">
            <h3>{{ lottery.label }}</h3>
            <span class="pill">{{ lottery.tagline }}</span>
          </div>
          <div class="game-meta">
            <span>Dezenas: {{ lottery.picks }}</span>
            <span>Universo: {{ lottery.range_max }}</span>
          </div>
          <div class="game-odds">Odds de acerto total: <strong>{{ lottery.odds }}</strong></div>
          <a class="btn btn-ghost w-100" href="#simulador">Simular {{ lottery.label }}</a>
        </div>
      </div>
      {% endfor %}
    </div>
  </div>
</section>

<section id="como-funciona" class="process-section">
  <div class="container">
    <div class="section-header">
      <h2>Como a inteligencia funciona</h2>
      <p>Fluxo simples para gerar jogos com base matematica.</p>
    </div>
    <div class="row g-4">
      <div class="col-md-4">
        <div class="process-card">
          <div class="step">01</div>
          <h3>Importar sorteios</h3>
          <p>O admin registra os ultimos concursos e atualiza o motor de analise.</p>
        </div>
      </div>
      <div class="col-md-4">
        <div class="process-card">
          <div class="step">02</div>
          <h3>Calcular pesos</h3>
          <p>Frequencias e recencia criam o mapa de probabilidades por dezena.</p>
        </div>
      </div>
      <div class="col-md-4">
        <div class="process-card">
          <div class="step">03</div>
          <h3>Gerar combinacoes</h3>
          <p>Jogos sugeridos sao montados com equilibrio matematico e transparencia.</p>
        </div>
      </div>
    </div>
  </div>
</section>

<section class="cta-section">
  <div class="container">
    <div class="cta-card">
      <div>
        <h2>Pronto para configurar seus sorteios?</h2>
        <p>Acesse o painel de admin para registrar concursos reais e refinar a analise.</p>
      </div>
      <a class="btn btn-brand btn-lg" href="/admin/">Ir para admin</a>
    </div>
  </div>
</section>

<footer class="site-footer">
  <div class="container">
    <div>
      <strong>{{ project_name }}</strong>
      <span>Analise estatistica para loterias BR.</span>
    </div>
    <div class="footer-meta">Atualizado em {{ current_time|date:"d/m/Y H:i" }} (UTC)</div>
  </div>
</footer>
{% endblock %}
