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

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

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

    .fishing-container {
        max-width: 1400px;
        margin: 0 auto;
        padding: 20px;
    }

    .fishing-main {
        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;
        position: relative;
        overflow: hidden;
    }

    .fishing-main::before {
        content: '🌊';
        position: absolute;
        font-size: 10rem;
        opacity: 0.05;
        right: -50px;
        bottom: -50px;
    }

    .rod-info {
        background: rgba(111, 66, 193, 0.2);
        border: 1px solid rgba(111, 66, 193, 0.4);
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 30px;
        color: white;
    }

    .xp-bar-container {
        background: rgba(0, 0, 0, 0.3);
        border-radius: 10px;
        height: 30px;
        margin-top: 10px;
        overflow: hidden;
    }

    .xp-bar {
        background: linear-gradient(90deg, #4ade80, #22c55e);
        height: 100%;
        transition: width 0.5s;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
    }

    .fishing-pond {
        background: linear-gradient(180deg, #3b82f6 0%, #1e40af 100%);
        border: 5px solid #1e3a8a;
        border-radius: 20px;
        height: 300px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 30px 0;
        position: relative;
        overflow: hidden;
    }

    .fishing-pond::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 50%;
        background: linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.3));
    }

    .fish-caught {
        font-size: 6rem;
        animation: fish-jump 1s ease-out;
    }

    @keyframes fish-jump {
        0% { transform: translateY(200px) scale(0); opacity: 0; }
        50% { transform: translateY(-50px) scale(1.2); opacity: 1; }
        100% { transform: translateY(0) scale(1); opacity: 1; }
    }

    .cast-button {
        background: linear-gradient(135deg, #10b981 0%, #059669 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(16, 185, 129, 0.4);
        transition: all 0.3s;
        display: block;
        margin: 0 auto;
    }

    .cast-button:hover:not(:disabled) {
        transform: scale(1.05);
        box-shadow: 0 8px 20px rgba(16, 185, 129, 0.6);
    }

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

    .cast-button.casting {
        animation: pulse 1s infinite;
    }

    @keyframes pulse {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.05); }
    }

    .fish-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }
    
    @media (min-width: 768px) {
        .fish-grid {
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        }
    }
    
    @media (min-width: 1200px) {
        .fish-grid {
            grid-template-columns: repeat(6, 1fr);
        }
    }

    .fish-card {
        background: linear-gradient(to bottom right, #1a1a2e, #121220);
        border: 2px solid rgba(111, 66, 193, 0.3);
        border-radius: 12px;
        padding: 20px 15px;
        text-align: center;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.5);
        transition: transform 0.3s, box-shadow 0.3s, border-color 0.3s;
        color: white;
        min-height: 200px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 10px;
    }

    .fish-card:hover {
        transform: translateY(-8px);
        box-shadow: 0 8px 25px rgba(111, 66, 193, 0.5);
        border-color: rgba(111, 66, 193, 0.6);
    }

    .fish-icon {
        font-size: 4rem;
        margin-bottom: 5px;
        line-height: 1;
    }
    
    .fish-card strong {
        font-size: 1.1rem;
    }

    .rarity-common { border-left: 5px solid #9ca3af; }
    .rarity-rare { border-left: 5px solid #3b82f6; }
    .rarity-epic { border-left: 5px solid #a855f7; }
    .rarity-legendary { border-left: 5px solid #fbbf24; }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 15px;
        margin-top: 20px;
        margin-bottom: 30px;
    }

    @media (min-width: 768px) {
        .stats-grid {
            grid-template-columns: repeat(5, 1fr);
        }
    }

    .stat-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.5);
        color: white;
    }

    .stat-value {
        font-size: 2rem;
        font-weight: bold;
        color: white;
    }
    
    .stat-card small {
        color: rgba(255, 255, 255, 0.8);
    }

    .bait-shop {
        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;
    }

    .bait-shop h4 {
        color: white;
        margin-bottom: 20px;
        font-size: 1.5rem;
        font-weight: bold;
    }

    .bait-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px;
        border-bottom: 1px solid rgba(111, 66, 193, 0.3);
        background: rgba(111, 66, 193, 0.05);
        border-radius: 8px;
        margin-bottom: 10px;
    }

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

    .buy-bait-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 3px 10px rgba(102, 126, 234, 0.4);
    }

    .buy-bait-btn:hover {
        background: linear-gradient(135deg, #5568d3 0%, #5a32a3 100%);
        transform: scale(1.05);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.6);
    }

    .active-bait {
        background: rgba(34, 197, 94, 0.2);
        border: 2px solid #22c55e;
    }

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

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

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

    /* Cards de seção */
    .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;
    }

    /* Badges de raridade */
    .badge {
        padding: 5px 10px;
        border-radius: 5px;
        font-weight: 600;
        font-size: 0.875rem;
    }

    .badge-common {
        background: #9ca3af;
        color: white;
    }

    .badge-rare {
        background: #3b82f6;
        color: white;
    }

    .badge-epic {
        background: #a855f7;
        color: white;
    }

    .badge-legendary {
        background: #fbbf24;
        color: black;
    }

    /* 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 de histórico */
    .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;
    }

    /* Abas/Tabs */
    .nav-tabs {
        border-bottom: 2px solid rgba(111, 66, 193, 0.4);
    }

    .nav-tabs .nav-link {
        color: rgba(255, 255, 255, 0.7);
        border: none;
        background: transparent;
    }

    .nav-tabs .nav-link:hover {
        color: white;
        background: rgba(111, 66, 193, 0.2);
    }

    .nav-tabs .nav-link.active {
        color: white;
        background: rgba(111, 66, 193, 0.3);
        border: 1px solid rgba(111, 66, 193, 0.4);
        border-bottom: none;
    }

    /* Botões secundários */
    .btn-secondary {
        background: rgba(111, 66, 193, 0.6);
        border: 1px solid rgba(111, 66, 193, 0.8);
        color: white;
    }

    .btn-secondary:hover {
        background: rgba(111, 66, 193, 0.8);
        border: 1px solid rgba(111, 66, 193, 1);
    }

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

    /* Pond - Lagoa de pesca */
    .fishing-pond {
        background: linear-gradient(180deg, rgba(59, 130, 246, 0.6) 0%, rgba(30, 64, 175, 0.8) 100%);
        border: 3px solid rgba(30, 58, 138, 0.8);
    }

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

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

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

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

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

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

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

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

    strong {
        color: white;
    }

    /* Background do badge padrão */
    .bg-secondary {
        background: rgba(108, 117, 125, 0.8) !important;
    }

    /* Peixes bloqueados */
    .locked-fish {
        opacity: 0.7;
        position: relative;
    }

    .locked-fish::after {
        content: '🔒';
        position: absolute;
        top: 10px;
        right: 10px;
        font-size: 1.5rem;
        opacity: 0.8;
    }

    .locked-fish:hover {
        opacity: 0.9;
        transform: translateY(-2px);
    }

    /* Separadores de seções */
    h6.text-success,
    h6.text-warning {
        font-size: 1.1rem;
        font-weight: bold;
        padding: 12px 15px;
        border-radius: 8px;
        margin-bottom: 20px;
    }
    
    h6.text-success {
        background: rgba(34, 197, 94, 0.15);
        border-left: 4px solid #22c55e;
    }
    
    h6.text-warning {
        background: rgba(251, 191, 36, 0.15);
        border-left: 4px solid #fbbf24;
    }

    /* Badge de level */
    .badge.bg-success {
        background: rgba(34, 197, 94, 0.8) !important;
    }

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

    /* 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="fishing-container">
    <h1 class="text-center mb-4">🎣 {% trans "Fishing Game" %}</h1>

    <div class="row">
        <div class="col-lg-8">
            <div class="fishing-main">
                <!-- Rod Info -->
                <div class="rod-info">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h4>🎣 {% trans "Sua Vara" %} - Level {{ rod.level }}</h4>
                            <p class="mb-0">💰 {% trans "Fichas" %}: <strong id="user-fichas">{{ user_fichas }}</strong></p>
                        </div>
                        <div class="text-end">
                            <div>⭐ XP: {{ rod.experience }} / {{ xp_for_next_level }}</div>
                        </div>
                    </div>
                    <div class="xp-bar-container">
                        <div class="xp-bar" style="width: {{ xp_percentage }}%">
                            {{ xp_percentage }}%
                        </div>
                    </div>
                </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>

                <!-- Fishing Pond -->
                <div class="fishing-pond" id="fishing-pond">
                    <div id="pond-content" style="z-index: 10;">
                        <div style="font-size: 4rem; text-align: center; color: white;">
                            🎣<br>
                            <small style="font-size: 1.5rem;">{% trans "Clique para pescar!" %}</small>
                        </div>
                    </div>
                </div>

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

                <!-- Cast Button -->
                <button class="cast-button" id="cast-button" onclick="castLine()">
                    🎣 {% trans "LANÇAR LINHA" %} ({{ config.cost_per_cast }} {% if config.cost_per_cast == 1 %}{% trans "Ficha" %}{% else %}{% trans "Fichas" %}{% endif %})
                </button>

                <!-- Active Baits -->
                {% if active_baits %}
                <div class="rod-info mt-3">
                    <h5>✨ {% trans "Iscas Ativas" %}</h5>
                    {% for user_bait in active_baits %}
                    <div class="active-bait p-2 rounded mb-2">
                        <strong>{{ user_bait.bait.name }}</strong> - 
                        {% trans "Expira em" %}: {{ user_bait.expires_at|date:"d/m/Y H:i" }}
                    </div>
                    {% endfor %}
                </div>
                {% endif %}
            </div>

            <!-- Statistics -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-value">{{ stats.total_catches|default:0 }}</div>
                    <div>{% trans "Total de Pescarias" %}</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value text-success">{{ stats.successful_catches|default:0 }}</div>
                    <div>{% trans "Peixes Capturados" %}</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value" style="color: #3b82f6;">{{ stats.rare_fish|default:0 }}</div>
                    <div>{% trans "Peixes Raros" %}</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value" style="color: #a855f7;">{{ stats.epic_fish|default:0 }}</div>
                    <div>{% trans "Peixes Épicos" %}</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value" style="color: #fbbf24;">{{ stats.legendary_fish|default:0 }}</div>
                    <div>{% trans "Peixes Lendários" %}</div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- Bait Shop -->
            <div class="bait-shop">
                <h4>🏪 {% trans "Loja de Iscas" %}</h4>
                {% if available_baits %}
                    {% for bait in available_baits %}
                    <div class="bait-item">
                        <div>
                            <strong>{{ bait.name }}</strong>
                            <div class="text-muted small">{{ bait.description }}</div>
                            <div class="text-muted small">
                                +{{ bait.boost_percentage }}% para {{ bait.get_rarity_boost_display }}
                            </div>
                            <div class="text-muted small">⏱️ {{ bait.duration_minutes }} min</div>
                        </div>
                        <button class="buy-bait-btn" onclick="buyBait({{ bait.id }}, {{ bait.price }})">
                            {{ bait.price }} 💰
                        </button>
                    </div>
                    {% endfor %}
                {% else %}
                    <p class="text-muted">{% trans "Nenhuma isca disponível." %}</p>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Available Fish - Movido para baixo -->
    <div class="bait-shop mt-4" style="max-width: 100%; padding: 30px;">
        <h4 class="mb-4">🐟 {% trans "Todos os Peixes" %}</h4>
        
        <!-- Peixes Disponíveis -->
        {% if available_fish %}
        <div class="mb-4">
            <h6 class="text-success mb-3">✅ {% trans "Disponíveis para Pescar" %} ({% trans "Seu nível" %}: {{ rod.level }})</h6>
            <div class="fish-grid">
                {% for fish in available_fish %}
                <div class="fish-card rarity-{{ fish.rarity }}">
                    <div class="fish-icon">
                        {% if fish.image %}
                            <img src="{{ fish.image.url }}" alt="{{ fish.name }}" 
                                 style="width: 60px; height: 60px; object-fit: cover; border-radius: 8px;">
                        {% else %}
                            {{ fish.icon }}
                        {% endif %}
                    </div>
                    <div><strong>{{ fish.name }}</strong></div>
                    <div class="text-muted small">{{ fish.get_rarity_display }}</div>
                    <div class="badge bg-success mt-1">Level {{ fish.min_rod_level }}+</div>
                </div>
                {% endfor %}
            </div>
        </div>
        {% endif %}
        
        <!-- Peixes Bloqueados -->
        {% if locked_fish %}
        <div class="mt-5">
            <hr style="border-color: rgba(111, 66, 193, 0.3); margin: 30px 0;">
            <h6 class="text-warning mb-3">🔒 {% trans "Bloqueados" %} ({% trans "Aumente o nível da sua vara" %})</h6>
            <div class="fish-grid">
                {% for fish in locked_fish %}
                <div class="fish-card rarity-{{ fish.rarity }} locked-fish">
                    <div class="fish-icon" style="opacity: 0.5; filter: grayscale(70%);">
                        {% if fish.image %}
                            <img src="{{ fish.image.url }}" alt="{{ fish.name }}" 
                                 style="width: 60px; height: 60px; object-fit: cover; border-radius: 8px;">
                        {% else %}
                            {{ fish.icon }}
                        {% endif %}
                    </div>
                    <div><strong>{{ fish.name }}</strong></div>
                    <div class="text-muted small">{{ fish.get_rarity_display }}</div>
                    <div class="badge bg-warning text-dark mt-1">🔒 Level {{ fish.min_rod_level }}+</div>
                </div>
                {% endfor %}
            </div>
        </div>
        {% endif %}
    </div>

    <!-- Fishing History -->
    <div class="bait-shop mt-3">
        <h4>📋 {% trans "Histórico de Pescarias" %}</h4>
        {% if fishing_history %}
            {% for history in fishing_history %}
            <div class="bait-item">
                <span>
                    {% if history.fish.image %}
                        <img src="{{ history.fish.image.url }}" alt="{{ history.fish.name }}" 
                             style="width: 40px; height: 40px; object-fit: cover; border-radius: 5px; margin-right: 8px; vertical-align: middle;">
                    {% else %}
                        <span style="font-size: 1.5rem; margin-right: 8px;">{{ history.fish.icon }}</span>
                    {% endif %}
                    <strong>{{ history.fish.name }}</strong>
                    <span class="badge bg-secondary">{{ history.fish.get_rarity_display }}</span>
                    <small class="text-muted">- {{ history.created_at|date:"d/m/Y H:i" }}</small>
                </span>
                <span class="{% if history.success %}text-success{% else %}text-danger{% endif %}">
                    {% if history.success %}✅ {% trans "Sucesso" %}{% else %}❌ {% trans "Escapou" %}{% endif %}
                </span>
            </div>
            {% endfor %}
        {% else %}
            <p class="text-muted">{% trans "Você ainda não pescou nada." %}</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 isFishing = false;

function castLine() {
    if (isFishing) return;
    
    isFishing = true;
    const button = document.getElementById('cast-button');
    const pondContent = document.getElementById('pond-content');
    const messageEl = document.getElementById('result-message');
    
    button.disabled = true;
    button.classList.add('casting');
    messageEl.textContent = '🎣 {% trans "Pescando..." %}';
    pondContent.innerHTML = '<div style="font-size: 4rem; color: white;">🌊🌊🌊</div>';
    
    // Make AJAX request
    fetch('{% url "games:fishing_game_cast" %}', {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
            pondContent.innerHTML = '<div style="font-size: 4rem; text-align: center; color: white;">🎣<br><small style="font-size: 1.5rem;">{% trans "Clique para pescar!" %}</small></div>';
            button.classList.remove('casting');
            button.disabled = false;
            isFishing = false;
            return;
        }
        
        setTimeout(() => {
            // Show caught fish
            if (data.success) {
                let fishDisplay = '';
                if (data.fish.image_url) {
                    fishDisplay = `<img src="${data.fish.image_url}" alt="${data.fish.name}" 
                                        style="width: 150px; height: 150px; object-fit: cover; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.5);">`;
                } else {
                    fishDisplay = `<span style="font-size: 6rem;">${data.fish.icon}</span>`;
                }
                
                pondContent.innerHTML = `<div class="fish-caught">${fishDisplay}</div>`;
                messageEl.innerHTML = `<span style="color: #4ade80;">🎉 ${data.message}<br>+${data.xp_gained} XP</span>`;
                
                if (data.fichas_won > 0) {
                    messageEl.innerHTML += `<br>💰 +${data.fichas_won} fichas`;
                }
                
                if (data.item_won) {
                    messageEl.innerHTML += `<br>📦 ${data.item_won.name} +${data.item_won.enchant}`;
                }
            } else {
                pondContent.innerHTML = '<div style="font-size: 4rem; color: white;">💨</div>';
                messageEl.innerHTML = `<span style="color: #f87171;">😢 ${data.message}<br>+${data.xp_gained} XP</span>`;
            }
            
            // Update fichas and XP
            document.getElementById('user-fichas').textContent = data.user_fichas;
            
            button.classList.remove('casting');
            button.disabled = false;
            isFishing = false;
            
            // Reset pond after 3 seconds
            setTimeout(() => {
                pondContent.innerHTML = '<div style="font-size: 4rem; text-align: center; color: white;">🎣<br><small style="font-size: 1.5rem;">{% trans "Clique para pescar!" %}</small></div>';
                messageEl.textContent = '';
            }, 3000);
            
            // Reload after 4 seconds to update stats
            setTimeout(() => location.reload(), 4000);
        }, 2000);
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{% trans "Erro ao pescar. Tente novamente." %}');
        pondContent.innerHTML = '<div style="font-size: 4rem; text-align: center; color: white;">🎣<br><small style="font-size: 1.5rem;">{% trans "Clique para pescar!" %}</small></div>';
        button.classList.remove('casting');
        button.disabled = false;
        isFishing = false;
    });
}

function buyBait(baitId, price) {
    if (!confirm(`{% trans "Comprar isca por" %} ${price} {% trans "fichas" %}?`)) {
        return;
    }
    
    const formData = new FormData();
    formData.append('bait_id', baitId);
    
    fetch('{% url "games:fishing_buy_bait" %}', {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
            return;
        }
        
        alert(data.message);
        location.reload();
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{% trans "Erro ao comprar isca." %}');
    });
}
</script>
{% endblock %}

