{% extends 'layouts/base.html' %}
{% load static %}
{% load i18n %}

{% block title %}{% trans "Slot Machine" %}{% endblock %}

{% block extrastyle %}
<style>
    body {
        background: radial-gradient(ellipse at center, #1a1a2e 0%, #121220 100%);
        min-height: 100vh;
    }

    .slot-machine-container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    .slot-machine-box {
        background: linear-gradient(to bottom right, #1a1a2e, #121220);
        border: 2px solid #6f42c1;
        border-radius: 20px;
        padding: 40px;
        box-shadow: 0 0 15px rgba(111,66,193,.5), 0 0 25px rgba(13,202,240,.3);
        margin-bottom: 30px;
    }

    .jackpot-display {
        background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
        color: #000;
        padding: 20px;
        border-radius: 15px;
        text-align: center;
        margin-bottom: 30px;
        box-shadow: 0 0 20px rgba(251, 191, 36, 0.6);
        border: 3px solid #fbbf24;
    }

    .jackpot-amount {
        font-size: 3rem;
        font-weight: bold;
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
    }

    .slot-reels {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin: 30px 0;
    }

    .reel {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: 4px solid #6f42c1;
        border-radius: 15px;
        width: 120px;
        height: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 4rem;
        box-shadow: 0 0 15px rgba(111, 66, 193, 0.5), inset 0 3px 8px rgba(0, 0, 0, 0.3);
        transition: transform 0.3s;
        color: white;
    }

    .reel.spinning {
        animation: spin 0.5s linear infinite;
    }

    @keyframes spin {
        0% { transform: translateY(0); }
        100% { transform: translateY(-100px); }
    }

    .spin-button {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        border: none;
        color: white;
        padding: 20px 60px;
        font-size: 1.5rem;
        font-weight: bold;
        border-radius: 50px;
        cursor: pointer;
        box-shadow: 0 5px 15px rgba(245, 87, 108, 0.4);
        transition: all 0.3s;
        display: block;
        margin: 0 auto;
    }

    .spin-button:hover:not(:disabled) {
        transform: scale(1.05);
        box-shadow: 0 8px 20px rgba(245, 87, 108, 0.6);
    }

    .spin-button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }

    .fichas-display {
        background: rgba(111, 66, 193, 0.3);
        border: 2px solid rgba(111, 66, 193, 0.5);
        padding: 15px 30px;
        border-radius: 10px;
        text-align: center;
        color: white;
        font-size: 1.2rem;
        margin-bottom: 20px;
        box-shadow: 0 0 10px rgba(111, 66, 193, 0.3);
    }

    .recent-wins, .user-history {
        background: linear-gradient(to bottom right, #1a1a2e, #121220);
        border: 2px solid #6f42c1;
        border-radius: 15px;
        padding: 20px;
        margin-top: 30px;
        box-shadow: 0 0 15px rgba(111,66,193,.5);
        color: white;
    }

    .recent-wins h4,
    .user-history h4 {
        color: white;
    }

    .win-item {
        border-bottom: 1px solid rgba(111, 66, 193, 0.3);
        padding: 10px 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .win-item:last-child {
        border-bottom: none;
    }

    .jackpot-win {
        animation: jackpot-pulse 2s infinite;
    }

    @keyframes jackpot-pulse {
        0%, 100% { transform: scale(1); box-shadow: 0 0 20px rgba(251, 191, 36, 0.6); }
        50% { transform: scale(1.05); box-shadow: 0 0 30px rgba(251, 191, 36, 0.9); }
    }

    .prize-message {
        text-align: center;
        color: white;
        font-size: 1.5rem;
        margin: 20px 0;
        min-height: 50px;
        font-weight: bold;
    }

    /* Títulos e textos gerais */
    h1, h2, h3, h4, h5, h6 {
        color: white !important;
    }

    .text-muted {
        color: rgba(255, 255, 255, 0.6) !important;
    }

    /* Classes de texto colorido */
    .text-success {
        color: #22c55e !important;
    }

    .text-danger {
        color: #ef4444 !important;
    }

    .text-warning {
        color: #fbbf24 !important;
    }

    /* Badges */
    .badge {
        padding: 5px 10px;
        border-radius: 5px;
        font-weight: 600;
    }

    .bg-success {
        background: rgba(34, 197, 94, 0.8) !important;
    }

    .bg-warning {
        background: rgba(251, 191, 36, 0.9) !important;
        color: black !important;
    }

    .bg-secondary {
        background: rgba(108, 117, 125, 0.8) !important;
    }

    /* Links */
    a {
        color: #60a5fa;
        text-decoration: none;
    }

    a:hover {
        color: #93c5fd;
        text-decoration: underline;
    }

    /* Pequenos ajustes */
    .small, small {
        color: rgba(255, 255, 255, 0.7) !important;
    }

    strong {
        color: white;
    }

    /* Scrollbar */
    ::-webkit-scrollbar {
        width: 10px;
        height: 10px;
    }

    ::-webkit-scrollbar-track {
        background: rgba(0, 0, 0, 0.2);
        border-radius: 5px;
    }

    ::-webkit-scrollbar-thumb {
        background: rgba(111, 66, 193, 0.6);
        border-radius: 5px;
    }

    ::-webkit-scrollbar-thumb:hover {
        background: rgba(111, 66, 193, 0.8);
    }

    /* Modal de Compra de Fichas */
    #buyTokensModal {
        z-index: 9999 !important;
    }

    #buyTokensModal .modal-dialog {
        z-index: 10000 !important;
        position: relative;
    }

    #buyTokensModal .modal-content {
        background: linear-gradient(to bottom right, #1a1a2e, #121220) !important;
        border: 2px solid #6f42c1 !important;
        border-radius: 20px !important;
        box-shadow: 0 0 20px rgba(111, 66, 193, 0.6), 0 0 30px rgba(13, 202, 240, 0.4) !important;
        color: white !important;
        z-index: 10001 !important;
        position: relative;
    }

    #buyTokensModal .modal-title {
        color: white !important;
        font-weight: bold;
        font-size: 1.5rem;
        text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
    }

    #buyTokensModal .modal-body,
    #buyTokensModal p {
        color: rgba(255, 255, 255, 0.9) !important;
    }

    #buyTokensModal .form-control {
        background: rgba(111, 66, 193, 0.2) !important;
        border: 2px solid rgba(111, 66, 193, 0.5) !important;
        border-radius: 10px !important;
        color: white !important;
        padding: 12px 15px;
        font-size: 1.1rem;
    }

    #buyTokensModal .form-control:focus {
        background: rgba(111, 66, 193, 0.3) !important;
        border-color: #6f42c1 !important;
        box-shadow: 0 0 10px rgba(111, 66, 193, 0.5) !important;
        color: white !important;
    }

    #buyTokensModal .form-control::placeholder {
        color: rgba(255, 255, 255, 0.5) !important;
    }

    #buyTokensModal .btn-success {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%) !important;
        border: none !important;
        color: white !important;
        padding: 12px 30px;
        font-size: 1.1rem;
        font-weight: bold;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(34, 197, 94, 0.4);
        transition: all 0.3s;
    }

    #buyTokensModal .btn-success:hover {
        transform: scale(1.05);
        box-shadow: 0 8px 20px rgba(34, 197, 94, 0.6);
    }

    #buyTokensModal .btn-close {
        filter: invert(1) grayscale(100%) brightness(200%);
    }

    /* Garantir que o backdrop do modal tenha z-index apropriado */
    .modal-backdrop.show {
        z-index: 9998 !important;
    }
</style>
{% endblock %}

{% block content %}
<div class="slot-machine-container">
    <h1 class="text-center mb-4">🎰 {% trans "Slot Machine" %}</h1>

    <div class="slot-machine-box">
        <!-- Jackpot Display -->
        <div class="jackpot-display">
            <div>💎 {% trans "JACKPOT" %} 💎</div>
            <div class="jackpot-amount" id="jackpot-amount">{{ config.jackpot_amount }}</div>
            <div>{% trans "Fichas" %}</div>
        </div>

        <!-- Fichas Display -->
        <div class="fichas-display">
            <strong>💰 {% trans "Suas Fichas" %}:</strong> 
            <span id="user-fichas">{{ user_fichas }}</span>
        </div>

        <!-- Botão de Comprar Fichas -->
        <div class="text-center mt-3 mb-3">
            <button class="btn btn-warning btn-lg rounded-pill" data-bs-toggle="modal" data-bs-target="#buyTokensModal">
                <i class="bi bi-cart-plus me-2"></i> {% trans "Comprar Fichas" %}
            </button>
        </div>

        <!-- Slot Reels -->
        <div class="slot-reels">
            <div class="reel" id="reel1">❓</div>
            <div class="reel" id="reel2">❓</div>
            <div class="reel" id="reel3">❓</div>
        </div>

        <!-- Prize Message -->
        <div class="prize-message" id="prize-message"></div>

        <!-- Spin Button -->
        <button class="spin-button" id="spin-button" onclick="spinSlotMachine()">
            🎰 {% trans "GIRAR" %} ({{ config.cost_per_spin }} {% trans "Fichas" %})
        </button>
    </div>

    <!-- Recent Wins -->
    <div class="recent-wins">
        <h3>🏆 {% trans "Vitórias Recentes" %}</h3>
        {% if recent_wins %}
            {% for win in recent_wins %}
            <div class="win-item">
                <span>
                    <strong>{{ win.user.username }}</strong>
                    {% if win.is_jackpot %}
                        <span class="badge bg-warning">💎 JACKPOT!</span>
                    {% endif %}
                </span>
                <span class="text-success">+{{ win.fichas_won }} fichas</span>
            </div>
            {% endfor %}
        {% else %}
            <p class="text-muted">{% trans "Ainda não há vitórias registradas." %}</p>
        {% endif %}
    </div>

    <!-- User History -->
    <div class="user-history">
        <h3>📊 {% trans "Seu Histórico" %}</h3>
        <div id="history-container">
            {% if user_history %}
                {% for history in user_history %}
                <div class="win-item">
                    <span>
                        {{ history.created_at|date:"d/m/Y H:i" }}
                        {% if history.is_jackpot %}
                            <span class="badge bg-warning">💎 JACKPOT!</span>
                        {% endif %}
                    </span>
                    <span class="{% if history.fichas_won > 0 %}text-success{% else %}text-danger{% endif %}">
                        {% if history.fichas_won > 0 %}
                            +{{ history.fichas_won }} fichas
                        {% else %}
                            -{{ config.cost_per_spin }} fichas
                        {% endif %}
                    </span>
                </div>
                {% endfor %}
            {% else %}
                <p class="text-muted">{% trans "Você ainda não jogou." %}</p>
            {% endif %}
        </div>
    </div>
</div>

<!-- Modal de Compra de Fichas -->
<div class="modal fade" id="buyTokensModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-0 pb-2">
        <h5 class="modal-title">💰 {% trans "Comprar Fichas" %}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body text-center">
        <p class="mb-4">{% trans "Escolha a quantidade de fichas que deseja comprar." %}</p>
        <p class="mb-4 text-warning">
          <strong>💵 {% trans "Valor" %}: R$0,10 {% trans "por ficha" %}</strong>
        </p>
        <input type="number" id="buyQuantity" class="form-control mb-4" min="1" value="1" placeholder="{% trans 'Quantidade' %}">
        <button class="btn btn-success w-100" onclick="buyFichas()">
          <i class="bi bi-cart-check me-2"></i>{% trans "Confirmar Compra" %}
        </button>
      </div>
    </div>
  </div>
</div>

<script>
  const FICHAS_URL = "{% url 'games:comprar_fichas' %}";

  // Helper function to get CSRF token from cookie
  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== "") {
      const cookies = document.cookie.split(";");
      for (let cookie of cookies) {
        cookie = cookie.trim();
        if (cookie.startsWith(name + "=")) {
          cookieValue = decodeURIComponent(cookie.slice(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

  // Function to buy fichas
  function buyFichas() {
    const quantity = parseInt(document.getElementById("buyQuantity").value);
    const csrfToken = getCookie('csrftoken');

    fetch(FICHAS_URL, {
      method: "POST",
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-CSRFToken': csrfToken
      },
      body: `quantidade=${quantity}`
    })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        alert(`Compra realizada! Você agora tem ${data.fichas} ficha(s).`);
        location.reload(); // Atualiza para refletir no contador de fichas
      } else {
        alert(data.error || "Erro ao processar a compra.");
      }
    })
    .catch(error => {
      alert("Erro de conexão com o servidor.");
      console.error(error);
    });
  }
</script>

<script>
let isSpinning = false;

function spinSlotMachine() {
    if (isSpinning) return;
    
    const button = document.getElementById('spin-button');
    const reels = [
        document.getElementById('reel1'),
        document.getElementById('reel2'),
        document.getElementById('reel3')
    ];
    const messageEl = document.getElementById('prize-message');
    
    isSpinning = true;
    button.disabled = true;
    messageEl.textContent = '';
    
    // Animate reels
    reels.forEach(reel => {
        reel.classList.add('spinning');
        reel.textContent = '🎰';
    });
    
    // Make AJAX request
    fetch('{% url "games:slot_machine_spin" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRFToken': '{{ csrf_token }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
            reels.forEach(reel => reel.classList.remove('spinning'));
            button.disabled = false;
            isSpinning = false;
            return;
        }
        
        // Stop reels with result
        setTimeout(() => {
            reels.forEach((reel, index) => {
                reel.classList.remove('spinning');
                reel.textContent = data.symbols[index].icon;
            });
            
            // Update fichas
            document.getElementById('user-fichas').textContent = data.user_fichas;
            document.getElementById('jackpot-amount').textContent = data.current_jackpot;
            
            // Show message
            if (data.is_jackpot) {
                messageEl.innerHTML = '<span class="jackpot-win">💎 JACKPOT! 💎<br>Você ganhou ' + data.fichas_won + ' fichas!</span>';
            } else if (data.fichas_won > 0) {
                messageEl.innerHTML = '🎉 Você ganhou ' + data.fichas_won + ' fichas!';
                if (data.item_won) {
                    messageEl.innerHTML += '<br>📦 ' + data.item_won.name + ' +' + data.item_won.enchant;
                }
            } else {
                messageEl.innerHTML = '😢 Não foi dessa vez!';
            }
            
            button.disabled = false;
            isSpinning = false;
            
            // Add to history dynamically
            const historyContainer = document.getElementById('history-container');
            if (historyContainer) {
                const newHistoryItem = document.createElement('div');
                newHistoryItem.className = 'win-item';
                
                const now = new Date();
                const dateStr = now.toLocaleString('pt-BR', { 
                    day: '2-digit', 
                    month: '2-digit', 
                    year: 'numeric',
                    hour: '2-digit', 
                    minute: '2-digit' 
                });
                
                let resultClass = data.fichas_won > 0 ? 'text-success' : 'text-danger';
                let resultText = data.fichas_won > 0 ? '+' + data.fichas_won + ' fichas' : '-{{ config.cost_per_spin }} fichas';
                
                newHistoryItem.innerHTML = `
                    <span>
                        ${dateStr}
                        ${data.is_jackpot ? '<span class="badge bg-warning">💎 JACKPOT!</span>' : ''}
                    </span>
                    <span class="${resultClass}">
                        ${resultText}
                    </span>
                `;
                
                // Add at the beginning and keep only 10
                historyContainer.insertBefore(newHistoryItem, historyContainer.firstChild);
                const items = historyContainer.querySelectorAll('.win-item');
                if (items.length > 10) {
                    items[items.length - 1].remove();
                }
            }
        }, 2000);
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Erro ao girar. Tente novamente.');
        reels.forEach(reel => reel.classList.remove('spinning'));
        button.disabled = false;
        isSpinning = false;
    });
}
</script>
{% endblock %}

