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

{% block title %}{% trans "Dice Game" %}{% endblock %}

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

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

    .dice-game-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;
    }

    .dice-display {
        width: 150px;
        height: 150px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: 3px solid #6f42c1;
        border-radius: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 5rem;
        margin: 30px auto;
        box-shadow: 0 0 20px rgba(111, 66, 193, 0.6);
        transition: transform 0.5s;
        color: white;
    }

    .dice-display.rolling {
        animation: roll 0.5s linear infinite;
    }

    @keyframes roll {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .bet-options {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
        margin: 30px 0;
    }

    .bet-option {
        background: linear-gradient(to bottom right, #1a1a2e, #121220);
        border: 2px solid rgba(111, 66, 193, 0.4);
        border-radius: 15px;
        padding: 20px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
        color: white;
    }

    .bet-option:hover {
        transform: scale(1.05);
        border-color: #6f42c1;
        box-shadow: 0 0 15px rgba(111, 66, 193, 0.5);
    }

    .bet-option.selected {
        border-color: #f5576c;
        background: linear-gradient(135deg, rgba(245, 87, 108, 0.3), rgba(240, 147, 251, 0.3));
        box-shadow: 0 0 20px rgba(245, 87, 108, 0.6);
    }

    .bet-option.disabled {
        opacity: 0.4;
        cursor: not-allowed !important;
        pointer-events: none;
        filter: grayscale(80%);
    }

    .bet-option.forced {
        border-color: #fbbf24 !important;
        background: linear-gradient(135deg, rgba(251, 191, 36, 0.3), rgba(245, 158, 11, 0.3));
        box-shadow: 0 0 20px rgba(251, 191, 36, 0.6);
        animation: pulse-forced 1.5s infinite;
    }

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

    .bet-option .multiplier {
        font-size: 1.5rem;
        font-weight: bold;
        color: #f093fb;
    }

    .bet-amount-container {
        background: rgba(111, 66, 193, 0.2);
        border: 1px solid rgba(111, 66, 193, 0.4);
        padding: 20px;
        border-radius: 15px;
        margin: 20px 0;
    }

    .bet-amount-input {
        width: 100%;
        padding: 15px;
        font-size: 1.2rem;
        border: 2px solid rgba(111, 66, 193, 0.5);
        border-radius: 10px;
        text-align: center;
        background: rgba(255, 255, 255, 0.05);
        color: white;
    }

    .bet-amount-input:focus {
        outline: none;
        border-color: #6f42c1;
        background: rgba(255, 255, 255, 0.08);
        box-shadow: 0 0 10px rgba(111, 66, 193, 0.4);
    }

    .play-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: 20px auto;
    }

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

    .play-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);
    }

    .stats-box {
        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;
    }

    .stats-box h4 {
        color: white;
    }

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

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

    .number-grid {
        display: grid;
        grid-template-columns: repeat(6, 1fr);
        gap: 10px;
        margin: 20px 0;
    }

    .number-btn {
        padding: 15px;
        font-size: 1.5rem;
        background: linear-gradient(to bottom right, #1a1a2e, #121220);
        border: 2px solid rgba(111, 66, 193, 0.4);
        border-radius: 10px;
        cursor: pointer;
        transition: all 0.3s;
        color: white;
        font-weight: bold;
    }

    .number-btn:hover {
        transform: scale(1.1);
        border-color: #6f42c1;
        box-shadow: 0 0 15px rgba(111, 66, 193, 0.5);
    }

    .number-btn.selected {
        border-color: #f5576c;
        background: linear-gradient(135deg, rgba(245, 87, 108, 0.3), rgba(240, 147, 251, 0.3));
        box-shadow: 0 0 20px rgba(245, 87, 108, 0.6);
    }

    .result-message {
        text-align: center;
        color: white;
        font-size: 1.8rem;
        margin: 20px 0;
        min-height: 60px;
        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;
    }

    .text-white {
        color: white !important;
    }

    /* Cards */
    .card {
        background: linear-gradient(to bottom right, #1a1a2e, #121220);
        border: 2px solid #6f42c1;
        box-shadow: 0 0 15px rgba(111,66,193,.5);
        color: white;
    }

    .card-header {
        background: rgba(111, 66, 193, 0.2);
        border-bottom: 1px solid rgba(111, 66, 193, 0.4);
        color: white;
    }

    .card-body {
        color: white;
    }

    /* Tabelas */
    .table {
        color: white;
    }

    .table-dark {
        background: rgba(0, 0, 0, 0.2);
    }

    .table-dark th,
    .table-dark td {
        border-color: rgba(111, 66, 193, 0.3);
    }

    /* Lista */
    .list-group-item {
        background: rgba(111, 66, 193, 0.1);
        border: 1px solid rgba(111, 66, 193, 0.3);
        color: white;
        margin-bottom: 5px;
        border-radius: 8px;
    }

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

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

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

    .text-info {
        color: #3b82f6 !important;
    }

    /* Alertas */
    .alert {
        border-radius: 10px;
        border: 1px solid;
    }

    .alert-info {
        background: rgba(59, 130, 246, 0.2);
        border-color: rgba(59, 130, 246, 0.5);
        color: white;
    }

    .alert-success {
        background: rgba(34, 197, 94, 0.2);
        border-color: rgba(34, 197, 94, 0.5);
        color: white;
    }

    .alert-warning {
        background: rgba(251, 191, 36, 0.2);
        border-color: rgba(251, 191, 36, 0.5);
        color: white;
    }

    .alert-danger {
        background: rgba(239, 68, 68, 0.2);
        border-color: rgba(239, 68, 68, 0.5);
        color: white;
    }

    .alert-secondary {
        background: rgba(108, 117, 125, 0.2);
        border-color: rgba(108, 117, 125, 0.5);
        color: white;
    }

    .alert ul {
        padding-left: 1.5rem;
        margin-bottom: 0;
    }

    .alert h6 {
        color: white !important;
        font-weight: bold;
    }

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

    strong {
        color: white;
    }

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

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

    /* 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);
    }

    /* Labels */
    label {
        color: white !important;
    }

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

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

    .bg-danger {
        background: rgba(239, 68, 68, 0.8) !important;
    }

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

    .bg-info {
        background: rgba(59, 130, 246, 0.8) !important;
    }

    /* Placeholder dos inputs */
    .bet-amount-input::placeholder {
        color: rgba(255, 255, 255, 0.5);
    }

    /* 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="dice-game-container">
    <h1 class="text-center mb-4">🎲 {% trans "Dice Game" %}</h1>

    <div class="dice-game-box">
        <!-- 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>

        <!-- Dice Display -->
        <div class="dice-display" id="dice-display">🎲</div>

        <!-- Result Message -->
        <div class="result-message" id="result-message"></div>

        <!-- Regras e Avisos -->
        <div class="alert alert-info mb-3">
            <h6 class="mb-2">📋 {% trans "Regras do Jogo:" %}</h6>
            <ul class="mb-0" style="font-size: 0.9rem;">
                <li>❌ {% trans "Não pode escolher a mesma modalidade duas vezes seguidas" %}</li>
                <li>🎯 {% trans "A cada 5 jogadas, você DEVE escolher 'Número Específico'" %}</li>
                <li>💰 {% trans "Aposta mínima para 'Número Específico': 10 fichas" %}</li>
            </ul>
        </div>

        {% if must_play_number %}
        <div class="alert alert-warning mb-3">
            <strong>⚠️ {% trans "ATENÇÃO!" %}</strong> {% trans "Esta é sua" %} {{ total_plays|add:1 }}ª {% trans "jogada. Você DEVE escolher 'Número Específico'!" %}
        </div>
        {% endif %}

        {% if last_bet_type %}
        <div class="alert alert-secondary mb-3">
            <strong>ℹ️ {% trans "Última jogada:" %}</strong> {{ last_bet_type|upper }}. {% trans "Escolha uma modalidade diferente!" %}
        </div>
        {% endif %}

        <!-- Bet Type Selection -->
        <h4 class="text-white text-center">{% trans "Escolha seu tipo de aposta:" %}</h4>
        <div class="bet-options">
            <div class="bet-option {% if must_play_number or last_bet_type == 'even' %}disabled{% endif %}" 
                 data-bet-type="even" 
                 onclick="selectBetType('even')">
                <div class="multiplier">x{{ config.even_odd_multiplier }}</div>
                <div><strong>{% trans "Par" %}</strong></div>
                <div class="text-muted">2, 4, 6</div>
                {% if last_bet_type == 'even' %}<div class="text-danger small">❌ {% trans "Última jogada" %}</div>{% endif %}
            </div>
            <div class="bet-option {% if must_play_number or last_bet_type == 'odd' %}disabled{% endif %}" 
                 data-bet-type="odd" 
                 onclick="selectBetType('odd')">
                <div class="multiplier">x{{ config.even_odd_multiplier }}</div>
                <div><strong>{% trans "Ímpar" %}</strong></div>
                <div class="text-muted">1, 3, 5</div>
                {% if last_bet_type == 'odd' %}<div class="text-danger small">❌ {% trans "Última jogada" %}</div>{% endif %}
            </div>
            <div class="bet-option {% if must_play_number or last_bet_type == 'high' %}disabled{% endif %}" 
                 data-bet-type="high" 
                 onclick="selectBetType('high')">
                <div class="multiplier">x{{ config.high_low_multiplier }}</div>
                <div><strong>{% trans "Alto" %}</strong></div>
                <div class="text-muted">4, 5, 6</div>
                {% if last_bet_type == 'high' %}<div class="text-danger small">❌ {% trans "Última jogada" %}</div>{% endif %}
            </div>
            <div class="bet-option {% if must_play_number or last_bet_type == 'low' %}disabled{% endif %}" 
                 data-bet-type="low" 
                 onclick="selectBetType('low')">
                <div class="multiplier">x{{ config.high_low_multiplier }}</div>
                <div><strong>{% trans "Baixo" %}</strong></div>
                <div class="text-muted">1, 2, 3</div>
                {% if last_bet_type == 'low' %}<div class="text-danger small">❌ {% trans "Última jogada" %}</div>{% endif %}
            </div>
            <div class="bet-option {% if last_bet_type == 'number' and not must_play_number %}disabled{% endif %} {% if must_play_number %}forced{% endif %}" 
                 data-bet-type="number" 
                 onclick="selectBetType('number')" 
                 style="grid-column: span 2;">
                <div class="multiplier">x{{ config.specific_number_multiplier }}</div>
                <div><strong>{% trans "Número Específico" %}</strong></div>
                <div class="text-muted">{% trans "Escolha 1-6" %}</div>
                {% if must_play_number %}<div class="text-warning small">⚠️ {% trans "OBRIGATÓRIO!" %}</div>{% endif %}
                {% if last_bet_type == 'number' and not must_play_number %}<div class="text-danger small">❌ {% trans "Última jogada" %}</div>{% endif %}
            </div>
        </div>

        <!-- Number Selection (hidden by default) -->
        <div id="number-selection" style="display: none;">
            <h5 class="text-white text-center">{% trans "Escolha um número:" %}</h5>
            <div class="number-grid">
                <button class="number-btn" onclick="selectNumber(1)">1</button>
                <button class="number-btn" onclick="selectNumber(2)">2</button>
                <button class="number-btn" onclick="selectNumber(3)">3</button>
                <button class="number-btn" onclick="selectNumber(4)">4</button>
                <button class="number-btn" onclick="selectNumber(5)">5</button>
                <button class="number-btn" onclick="selectNumber(6)">6</button>
            </div>
        </div>

        <!-- Bet Amount -->
        <div class="bet-amount-container">
            <label class="text-white" style="display: block; text-align: center; margin-bottom: 10px;">
                <strong>{% trans "Valor da Aposta" %} ({{ config.min_bet }}-{{ config.max_bet }} fichas):</strong>
            </label>
            <input type="number" id="bet-amount" class="bet-amount-input" 
                   min="{{ config.min_bet }}" max="{{ config.max_bet }}" value="{{ config.min_bet }}">
        </div>

        <!-- Play Button -->
        <button class="play-button" id="play-button" onclick="playDiceGame()">
            🎲 {% trans "JOGAR" %}
        </button>
    </div>

    <!-- Statistics -->
    <div class="stats-box">
        <h3>📊 {% trans "Suas Estatísticas" %}</h3>
        <div class="stat-item">
            <span>{% trans "Total de Jogos" %}:</span>
            <strong>{{ stats.total_games|default:0 }}</strong>
        </div>
        <div class="stat-item">
            <span>{% trans "Vitórias" %}:</span>
            <strong class="text-success">{{ stats.total_won|default:0 }}</strong>
        </div>
        <div class="stat-item">
            <span>{% trans "Taxa de Vitória" %}:</span>
            <strong>{{ win_rate }}%</strong>
        </div>
        <div class="stat-item">
            <span>{% trans "Lucro/Prejuízo" %}:</span>
            <strong class="{% if profit >= 0 %}text-success{% else %}text-danger{% endif %}">
                {% if profit >= 0 %}+{% endif %}{{ profit }}
            </strong>
        </div>
    </div>

    <!-- Recent History -->
    <div class="stats-box">
        <h3>📋 {% trans "Histórico Recente" %}</h3>
        {% if user_history %}
            {% for history in user_history %}
            <div class="stat-item">
                <span>
                    {{ history.created_at|date:"d/m/Y H:i" }} - 
                    {{ history.get_bet_type_display }}
                    {% if history.bet_value %}({{ history.bet_value }}){% endif %}
                    - Resultado: <strong>{{ history.dice_result }}</strong>
                </span>
                <span class="{% if history.won %}text-success{% else %}text-danger{% endif %}">
                    {% if history.won %}
                        +{{ history.prize_amount }} fichas
                    {% else %}
                        -{{ history.bet_amount }} fichas
                    {% endif %}
                </span>
            </div>
            {% endfor %}
        {% else %}
            <p class="text-muted">{% trans "Você ainda não jogou." %}</p>
        {% endif %}
    </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 selectedBetType = null;
let selectedNumber = null;
let isPlaying = false;
const minBetForNumber = {{ min_bet_for_number }};
const normalMinBet = {{ config.min_bet }};

function selectBetType(type) {
    // Verificar se a opção está desabilitada
    const clickedOption = event.target.closest('.bet-option');
    if (clickedOption.classList.contains('disabled')) {
        alert('{% trans "Esta opção está bloqueada pelas regras do jogo!" %}');
        return;
    }
    
    selectedBetType = type;
    
    // Update UI
    document.querySelectorAll('.bet-option').forEach(el => el.classList.remove('selected'));
    clickedOption.classList.add('selected');
    
    // Ajustar aposta mínima e label
    const betAmountInput = document.getElementById('bet-amount');
    const betAmountLabel = document.querySelector('.bet-amount-container label strong');
    
    if (type === 'number') {
        document.getElementById('number-selection').style.display = 'block';
        betAmountInput.min = minBetForNumber;
        if (parseInt(betAmountInput.value) < minBetForNumber) {
            betAmountInput.value = minBetForNumber;
        }
        betAmountLabel.textContent = '{% trans "Valor da Aposta" %} (' + minBetForNumber + '-{{ config.max_bet }} fichas):';
    } else {
        document.getElementById('number-selection').style.display = 'none';
        selectedNumber = null;
        betAmountInput.min = normalMinBet;
        betAmountLabel.textContent = '{% trans "Valor da Aposta" %} (' + normalMinBet + '-{{ config.max_bet }} fichas):';
    }
}

function selectNumber(num) {
    selectedNumber = num;
    
    // Update UI
    document.querySelectorAll('.number-btn').forEach(el => el.classList.remove('selected'));
    event.target.classList.add('selected');
}

function playDiceGame() {
    if (isPlaying) return;
    
    if (!selectedBetType) {
        alert('{% trans "Selecione um tipo de aposta!" %}');
        return;
    }
    
    if (selectedBetType === 'number' && !selectedNumber) {
        alert('{% trans "Selecione um número!" %}');
        return;
    }
    
    const betAmount = document.getElementById('bet-amount').value;
    
    isPlaying = true;
    const button = document.getElementById('play-button');
    const diceDisplay = document.getElementById('dice-display');
    const messageEl = document.getElementById('result-message');
    
    button.disabled = true;
    messageEl.textContent = '';
    diceDisplay.classList.add('rolling');
    diceDisplay.textContent = '🎲';
    
    // Prepare form data
    const formData = new FormData();
    formData.append('bet_type', selectedBetType);
    formData.append('bet_amount', betAmount);
    if (selectedNumber) {
        formData.append('bet_value', selectedNumber);
    }
    
    // Make AJAX request
    fetch('{% url "games:dice_game_play" %}', {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
            diceDisplay.classList.remove('rolling');
            button.disabled = false;
            isPlaying = false;
            return;
        }
        
        setTimeout(() => {
            diceDisplay.classList.remove('rolling');
            diceDisplay.textContent = '⚅'.repeat(data.dice_result).slice(-1) || data.dice_result;
            
            // Update fichas
            document.getElementById('user-fichas').textContent = data.user_fichas;
            
            // Show result
            if (data.won) {
                messageEl.innerHTML = '🎉 ' + data.message;
                messageEl.style.color = '#4ade80';
            } else {
                messageEl.innerHTML = '😢 ' + data.message;
                messageEl.style.color = '#f87171';
            }
            
            button.disabled = false;
            isPlaying = false;
            
            // Reload page after 2 seconds to update history
            setTimeout(() => location.reload(), 2000);
        }, 1500);
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{% trans "Erro ao jogar. Tente novamente." %}');
        diceDisplay.classList.remove('rolling');
        button.disabled = false;
        isPlaying = false;
    });
}
</script>
{% endblock %}

