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

{% block content %}
<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-8 text-center">
            <h1 class="mb-4 text-primary">{{ game.title }}</h1>
            <p class="lead mb-5">Selecione o tempo de jogo desejado para liberar o acesso.</p>

            <!-- Opções de Aluguel -->
            <div class="row g-4 mb-5" id="options-grid">
                {% for option in options %}
                <div class="col-md-6">
                    <div class="card h-100 border-0 shadow-sm rental-card" onclick="selectOption({{ option.id }}, '{{ option.title }}', '{{ option.price }}')">
                        <div class="card-body p-4 text-center">
                            <div class="mb-3 text-primary">
                                <i class="bi bi-clock-history h2"></i>
                            </div>
                            <h3 class="h5 mb-2">{{ option.title }}</h3>
                            <p class="text-muted small mb-3">{{ option.description }}</p>
                            <div class="h3 text-dark fw-bold mb-0">R$ {{ option.price }}</div>
                            <div class="badge bg-light text-primary border mt-2">{{ option.duration_days }} dia(s) de jogo</div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>

            <!-- Seção de Pagamento -->
            <div id="payment-section" style="display: none;">
                <div class="card border-0 shadow-lg p-4 mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h4 class="mb-0 text-primary" id="selected-option-name"></h4>
                        <button class="btn btn-sm btn-outline-secondary" onclick="resetSelection()">Trocar Plano</button>
                    </div>
                    
                    <!-- Passo 1: Instruções e Botão de Início -->
                    <div id="qr-instructions" class="py-4">
                        <div class="mb-4 text-center">
                            <i class="bi bi-qr-code-scan display-1 text-muted opacity-25"></i>
                        </div>
                        <p class="h5 mb-4">Para ver os QR Codes e iniciar o pagamento:</p>
                        <button class="btn btn-primary btn-lg px-5 shadow" id="start-timer-btn" onclick="startPaymentProcess()">
                            <i class="bi bi-eye-fill me-2"></i> CLICK NO QR
                        </button>
                    </div>

                    <!-- Passo 2: QR Codes e Timer -->
                    <div id="qr-display" style="display: none;">
                        <div class="alert alert-warning border-0 shadow-sm mb-4">
                            <i class="bi bi-shield-lock-fill me-2"></i>
                            <strong>SISTEMA ANTI-FRAUDE ATIVO:</strong> O sistema está monitorando a transação. O código de acesso só será liberado se o pagamento for concluído dentro dos 3 minutos.
                        </div>

                        <div class="row justify-content-center mb-4 g-3">
                            <div class="col-6 col-md-5">
                                <div class="p-3 border rounded bg-light">
                                    <p class="small fw-bold text-muted mb-2">PAGAMENTO PIX 1</p>
                                    <img id="qr-img-1" src="" class="img-fluid rounded shadow-sm bg-white p-2" alt="QR Code 1">
                                </div>
                            </div>
                            <div class="col-6 col-md-5">
                                <div class="p-3 border rounded bg-light">
                                    <p class="small fw-bold text-muted mb-2">PAGAMENTO PIX 2</p>
                                    <img id="qr-img-2" src="" class="img-fluid rounded shadow-sm bg-white p-2" alt="QR Code 2">
                                </div>
                            </div>
                        </div>

                        <div class="timer-container py-3">
                            <div class="d-flex justify-content-between mb-2">
                                <span class="fw-bold">Tempo Restante:</span>
                                <span class="h4 fw-bold text-primary mb-0" id="timer-text">03:00</span>
                            </div>
                            <div class="progress" style="height: 12px;">
                                <div id="timer-bar" class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" style="width: 100%;"></div>
                            </div>
                            <p class="small text-muted mt-3 italic">
                                <span class="spinner-border spinner-border-sm me-1" role="status"></span>
                                Aguardando identificação do pagamento...
                            </p>
                        </div>

                        <!-- Botão de Simulação (Representando o Sistema Inteligente) -->
                        <div class="mt-4 pt-3 border-top">
                            <button class="btn btn-outline-info btn-sm opacity-50" onclick="simulatePaymentDetection()">
                                <i class="bi bi-robot me-1"></i> [Simular Identificação de Pagamento Real]
                            </button>
                        </div>
                    </div>

                    <!-- Passo 3: Código Revelado (Sucesso) -->
                    <div id="code-reveal" style="display: none;" class="animate__animated animate__fadeIn">
                        <div class="alert alert-success border-0 shadow py-5">
                            <i class="bi bi-check-circle-fill display-3 mb-3 d-block"></i>
                            <h2 class="alert-heading fw-bold">PAGAMENTO CONFIRMADO!</h2>
                            <p class="lead mb-4">Seu código de acesso foi gerado com sucesso pelo sistema inteligente.</p>
                            
                            <div class="bg-white rounded p-4 mb-4 border-dashed">
                                <p class="text-muted small mb-2 text-uppercase fw-bold">Código de Liberação do Jogo</p>
                                <div class="display-3 fw-bold text-dark letter-spacing-5" id="reveal-conf-code">000000</div>
                            </div>

                            <form method="POST">
                                {% csrf_token %}
                                <input type="hidden" name="purchase_id" id="hidden-purchase-id">
                                <input type="hidden" name="confirm_code" id="hidden-confirm-code">
                                <button type="submit" class="btn btn-success btn-lg px-5 shadow-lg w-100 py-3 fw-bold">
                                    <i class="bi bi-play-fill me-2 h4 align-middle"></i> LIBERAR JOGO AGORA
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- Passo 4: Código Inválido (Fraude ou Timeout) -->
                    <div id="code-invalid" style="display: none;" class="animate__animated animate__shakeX">
                        <div class="alert alert-danger border-0 shadow py-5">
                            <i class="bi bi-exclamation-triangle-fill display-3 mb-3 d-block"></i>
                            <h3 class="fw-bold">PAGAMENTO NÃO IDENTIFICADO</h3>
                            <p class="mb-4">O tempo de 3 minutos expirou e o sistema não detectou uma transação real. O código gerado é inválido e não dará acesso ao jogo.</p>
                            
                            <div class="bg-light rounded p-4 mb-4 border text-muted opacity-50">
                                <p class="small mb-1 text-uppercase">Código Inválido Gerado</p>
                                <div class="h2 fw-bold" id="invalid-code-display">000000</div>
                            </div>

                            <div class="alert alert-info py-2">
                                <small>O temporizador reiniciará automaticamente em instantes para uma nova tentativa.</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .rental-card { transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); cursor: pointer; border: 1px solid #eee !important; }
    .rental-card:hover { transform: scale(1.05); box-shadow: 0 15px 30px rgba(0,0,0,0.1) !important; border-color: var(--bs-primary) !important; }
    .border-dashed { border: 2px dashed #28a745; }
    .letter-spacing-5 { letter-spacing: 5px; }
    .animate__animated { animation-duration: 0.8s; }
</style>

<script>
let currentPurchaseId = null;
let timerInterval = null;
const totalTime = 180; // 3 minutes
let remainingTime = 180;

function selectOption(optionId, title, price) {
    document.querySelectorAll('.rental-card').forEach(c => c.classList.remove('border-primary', 'shadow'));
    
    fetch(`/generate-purchase/{{ game.id }}/${optionId}/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentPurchaseId = data.purchase_id;
                document.getElementById('hidden-purchase-id').value = data.purchase_id;
                document.getElementById('selected-option-name').innerText = `${title} - R$ ${price}`;
                
                document.getElementById('options-grid').style.display = 'none';
                document.getElementById('payment-section').style.display = 'block';
                document.getElementById('qr-instructions').style.display = 'block';
                document.getElementById('qr-display').style.display = 'none';
                document.getElementById('code-reveal').style.display = 'none';
                document.getElementById('code-invalid').style.display = 'none';
                
                // Set Placeholder QR (In real app, these come from RentalOption model)
                document.getElementById('qr-img-1').src = "{% if options.0.qr_code_1 %}{{ options.0.qr_code_1.url }}{% else %}{% static 'images/placeholder-qr.png' %}{% endif %}";
                document.getElementById('qr-img-2').src = "{% if options.0.qr_code_2 %}{{ options.0.qr_code_2.url }}{% else %}{% static 'images/placeholder-qr.png' %}{% endif %}";
                
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        });
}

function resetSelection() {
    if (timerInterval) clearInterval(timerInterval);
    document.getElementById('options-grid').style.display = 'flex';
    document.getElementById('payment-section').style.display = 'none';
}

function startPaymentProcess() {
    document.getElementById('qr-instructions').style.display = 'none';
    document.getElementById('qr-display').style.display = 'block';
    startTimer();
}

function startTimer() {
    remainingTime = totalTime;
    updateTimerDisplay();
    
    if (timerInterval) clearInterval(timerInterval);
    
    timerInterval = setInterval(() => {
        remainingTime--;
        updateTimerDisplay();
        
        if (remainingTime <= 0) {
            clearInterval(timerInterval);
            finalizePayment();
        }
    }, 1000);
}

function updateTimerDisplay() {
    const minutes = Math.floor(remainingTime / 60);
    const seconds = remainingTime % 60;
    document.getElementById('timer-text').innerText = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    
    const percentage = (remainingTime / totalTime) * 100;
    document.getElementById('timer-bar').style.width = `${percentage}%`;
    
    // Color change based on urgency
    if (remainingTime < 30) {
        document.getElementById('timer-bar').classList.replace('bg-success', 'bg-danger');
    } else if (remainingTime < 90) {
        document.getElementById('timer-bar').classList.replace('bg-success', 'bg-warning');
    }
}

function simulatePaymentDetection() {
    fetch(`/simulate-payment/${currentPurchaseId}/`, {
        method: 'POST',
        headers: { 'X-CSRFToken': '{{ csrf_token }}' }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert("SISTEMA INTELIGENTE: Pagamento real identificado! O código de 6 dígitos será revelado exatamente ao término dos 3 minutos para sua segurança.");
        }
    });
}

function finalizePayment() {
    fetch(`/verify-payment-status/${currentPurchaseId}/`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('qr-display').style.display = 'none';
            if (data.success && data.paid) {
                document.getElementById('code-reveal').style.display = 'block';
                document.getElementById('reveal-conf-code').innerText = data.confirmation_code;
                document.getElementById('hidden-confirm-code').value = data.confirmation_code;
            } else {
                document.getElementById('code-invalid').style.display = 'block';
                document.getElementById('invalid-code-display').innerText = data.invalid_code;
                
                // Anti-fraud: Auto-restart after 10 seconds
                setTimeout(() => {
                    restartPayment();
                }, 10000);
            }
        });
}

function restartPayment() {
    document.getElementById('code-invalid').style.display = 'none';
    document.getElementById('qr-instructions').style.display = 'block';
    window.scrollTo({ top: 0, behavior: 'smooth' });
}
</script>
{% endblock %}