{% extends 'base.html' %}

{% block content %}
<div class="row">
    <div class="col-lg-6">
        <div class="glass-card mb-4">
            <h2 class="mb-4">{{ game.title }}</h2>
            <p class="text-secondary mb-4">{{ game.prompt }}</p>
            <div class="d-flex align-items-center p-3 bg-dark rounded-3 border border-info mb-4">
                <div class="me-3 fs-3">💳</div>
                <div>
                    <div class="small text-secondary">Instruções de Aluguel</div>
                    <div>Selecione um plano, clique em <strong>"CLICK NO QR"</strong>, escaneie o código e aguarde 3 minutos para receber seu código de validação.</div>
                </div>
            </div>
            
            <h4 class="mb-3">Escolha o tempo de acesso:</h4>
            <div class="row g-3 mb-4">
                {% for option in options %}
                <div class="col-6">
                    <div class="p-3 border border-secondary rounded-4 text-center option-card" 
                         id="option-{{ option.pk }}"
                         style="cursor: pointer;"
                         onclick="selectOption('{{ option.pk }}', '{{ option.title }}', '{{ option.price }}', '{{ option.qr_code_1.url|default:'' }}', '{{ option.qr_code_2.url|default:'' }}')">
                        <div class="fw-bold">{{ option.title }}</div>
                        <div class="text-info fs-5">R$ {{ option.price }}</div>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div id="payment-area" class="glass-card h-100 d-flex flex-column justify-content-center text-center" style="min-height: 450px;">
            <div id="payment-empty">
                <div class="display-1 opacity-25 mb-4">🛒</div>
                <h3>Selecione uma opção</h3>
                <p class="text-secondary">Escolha um plano ao lado para começar.</p>
            </div>
            
            <div id="payment-details" class="d-none">
                <h3 id="selected-title" class="mb-4 text-info"></h3>
                
                <div id="qr-unlock-section" class="mb-4">
                    <button type="button" class="btn btn-lg btn-warning fw-bold px-5 py-3 rounded-pill" onclick="unlockQR()">CLICK NO QR</button>
                    <p class="mt-3 text-secondary small">Clique para visualizar os códigos de pagamento</p>
                </div>

                <div id="qr-display-section" class="d-none">
                    <div class="row mb-4">
                        <div class="col-6">
                            <div class="bg-white p-2 rounded-3 mb-2 mx-auto" style="width: 140px; height: 140px;">
                                <img id="qr1-img" src="" class="w-100 h-100 object-fit-contain" alt="QR 1">
                            </div>
                            <div class="small text-secondary">QR CODE 1</div>
                        </div>
                        <div class="col-6">
                            <div class="bg-white p-2 rounded-3 mb-2 mx-auto" style="width: 140px; height: 140px;">
                                <img id="qr2-img" src="" class="w-100 h-100 object-fit-contain" alt="QR 2">
                            </div>
                            <div class="small text-secondary">QR CODE 2</div>
                        </div>
                    </div>

                    <div id="timer-section" class="alert alert-info py-3 mb-4">
                        <div class="small mb-1">Aguardando confirmação do pagamento...</div>
                        <div id="countdown" class="fs-2 fw-bold font-monospace">03:00</div>
                        <div class="progress mt-2" style="height: 5px;">
                            <div id="timer-progress" class="progress-bar progress-bar-striped progress-bar-animated bg-info" style="width: 0%"></div>
                        </div>
                    </div>

                    <div id="conf-code-display" class="alert alert-success d-none mb-4 animate__animated animate__pulse animate__infinite">
                        <div class="small">Pagamento Concluído! Seu código de 6 dígitos:</div>
                        <div id="generated-code" class="display-4 fw-bold font-monospace mt-1"></div>
                        <div class="small text-dark mt-1">Copie e cole no campo abaixo para liberar o jogo.</div>
                    </div>
                </div>

                <hr class="border-secondary my-4">
                
                <form method="POST" id="purchase-form">
                    {% csrf_token %}
                    <input type="hidden" name="purchase_id" id="purchase_id_input">
                    <div class="mb-4">
                        <label class="form-label">Insira o Código de Confirmação</label>
                        <input type="text" name="confirm_code" class="form-control bg-dark text-white border-info text-center fs-3 font-monospace" placeholder="000000" maxlength="6" required>
                    </div>
                    <button type="submit" id="submit-btn" class="btn btn-primary w-100 py-3 rounded-pill fw-bold" disabled>VALIDAR ALUGUEL E JOGAR</button>
                </form>
            </div>
        </div>
    </div>
</div>

{% block extra_js %}
<script>
let currentOptionId = null;
let timerInterval = null;
const WAIT_TIME = 180; // 3 minutes in seconds

function selectOption(id, title, price, qr1, qr2) {
    currentOptionId = id;
    document.getElementById('payment-empty').classList.add('d-none');
    document.getElementById('payment-details').classList.remove('d-none');
    
    // Reset sections
    document.getElementById('qr-unlock-section').classList.remove('d-none');
    document.getElementById('qr-display-section').classList.add('d-none');
    document.getElementById('conf-code-display').classList.add('d-none');
    document.getElementById('timer-section').classList.remove('d-none');
    document.getElementById('submit-btn').disabled = true;
    
    if (timerInterval) clearInterval(timerInterval);
    
    document.getElementById('selected-title').innerText = title + ' - R$ ' + price;
    
    const placeholder = 'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=Pagamento_AI_Forge';
    document.getElementById('qr1-img').src = qr1 || placeholder;
    document.getElementById('qr2-img').src = qr2 || placeholder;
    
    // Highlight selected
    document.querySelectorAll('.option-card').forEach(el => el.classList.remove('border-info', 'bg-info', 'bg-opacity-10'));
    document.getElementById('option-' + id).classList.add('border-info', 'bg-info', 'bg-opacity-10');
}

function unlockQR() {
    if (!currentOptionId) return;
    
    document.getElementById('qr-unlock-section').classList.add('d-none');
    document.getElementById('qr-display-section').classList.remove('d-none');
    
    startTimer();
}

function startTimer() {
    let timeLeft = WAIT_TIME;
    const countdownEl = document.getElementById('countdown');
    const progressEl = document.getElementById('timer-progress');
    
    if (timerInterval) clearInterval(timerInterval);
    
    timerInterval = setInterval(() => {
        timeLeft--;
        
        const minutes = Math.floor(timeLeft / 60);
        const seconds = timeLeft % 60;
        countdownEl.innerText = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        const progress = ((WAIT_TIME - timeLeft) / WAIT_TIME) * 100;
        progressEl.style.width = progress + '%';
        
        if (timeLeft <= 0) {
            clearInterval(timerInterval);
            generateCode();
        }
    }, 1000);
}

function generateCode() {
    fetch(`/generate-purchase/{{ game.pk }}/${currentOptionId}/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('purchase_id_input').value = data.purchase_id;
                document.getElementById('generated-code').innerText = data.confirmation_code;
                
                document.getElementById('timer-section').classList.add('d-none');
                document.getElementById('conf-code-display').classList.remove('d-none');
                document.getElementById('submit-btn').disabled = false;
                
                // Add success animation
                document.getElementById('conf-code-display').classList.add('animate__animated', 'animate__bounceIn');
            } else {
                alert('Erro ao processar: ' + data.error);
            }
        });
}
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
{% endblock %}
{% endblock %}