<?php
    session_start();

    // Incluir archivo de configuración
    require_once 'configs.php';

    // Valor del coin
    $precio_coin_peso = 100; // En pesos
    $valor_dolar = 1000; // Valor del dolar a convertir **Variable Importante - Incluido en script**
    $precio_coin_dolar = $precio_coin_peso/$valor_dolar;  // Conversión de peso a dolar 
    
    // Array de sesión para almacenar el valor r
    $_SESSION['valor_coin'] = array('peso'=>$precio_coin_peso, 'dolar'=>$precio_coin_dolar);
    
    // Generar token CSRF si no existe
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    
    // Definir los niveles de bonificación
    $JC_TIERS = [
        ["value" => 10, "label" => "10", "bonus" => 1],
        ["value" => 100, "label" => "100", "bonus" => 15],
        ["value" => 500, "label" => "500", "bonus" => 100],
        ["value" => 1000, "label" => "1000", "bonus" => 250],
        ["value" => 3000, "label" => "3000", "bonus" => 900],
        ["value" => 7500, "label" => "7500", "bonus" => 2625],
        ["value" => 10000, "label" => "10000", "bonus" => 3500]
    ];
    
    // Convertir a JSON para usar en JavaScript
    $JC_TIERS_JSON = json_encode($JC_TIERS);
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>L2Jade - Donaciones</title>
    <!-- Favicon -->
    <link rel="icon" type="image/png" href="assets/media/favicons/favicon-32x32.png">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome para iconos -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Modern Antiqua Font -->
    <link href="https://fonts.googleapis.com/css2?family=Modern+Antiqua&display=swap" rel="stylesheet">
    <!-- Ion Range Slider CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ion-rangeslider/2.3.1/css/ion.rangeSlider.min.css"/>
    <!-- Estilos personalizados -->
    <style>
        :root {
            --jade: #00c896;
            --jade-light: #33d9ac;
            --jade-dark: #00967c;
            --dark-bg: #0a0a12;
        }
        
        /* Estilos de cursor personalizado */
        body {
            cursor: url("assets/media/cursors/image.png"), auto !important;
        }
        
        a, 
        button,
        .btn,
        .language-button,
        .back-button,
        input,
        .radio-custom-label {
            cursor: url("assets/media/cursors/image.png"), auto !important;
        }
        
        a:hover, 
        button:hover,
        .btn:hover,
        .language-button:hover,
        .back-button:hover,
        input:hover,
        .radio-custom-label:hover {
            cursor: url("assets/media/cursors/image2.png"), auto !important;
        }
        
        body {
            font-family: 'Modern Antiqua', serif;
            background-color: #000000;
            color: #f1f1f1;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .background-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            overflow: hidden;
        }
        
        .background-image {
            position: absolute;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
        }
        
        header {
            padding: 1rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            z-index: 10;
        }
        
        .back-button {
            display: inline-flex;
            align-items: center;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            background-color: rgba(10, 10, 18, 0.8);
            backdrop-filter: blur(4px);
            border: 1px solid rgba(0, 200, 150, 0.2);
            color: var(--jade);
            text-decoration: none;
            transition: all 0.3s;
            font-weight: 500;
            letter-spacing: 0.05em;
        }
        
        .back-button:hover {
            color: var(--jade-light);
            background-color: rgba(10, 10, 18, 0.95);
            border-color: rgba(0, 200, 150, 0.4);
        }
        
        .language-selector {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            display: flex;
            gap: 10px;
            background: rgba(0, 0, 0, 0.5);
            padding: 10px;
            border-radius: 8px;
            backdrop-filter: blur(5px);
        }

        .language-button {
            background: transparent;
            border: 1px solid #4a9e83;
            color: #fff;
            padding: 5px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .language-button:hover {
            background: rgba(74, 158, 131, 0.2);
        }

        .language-button.active {
            background: #4a9e83;
        }
        
        main {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            z-index: 10;
            padding: 2rem 1rem;
        }
        
        .content-container {
            width: 100%;
            max-width: 768px;
            margin: 0 auto;
            animation: fadeInUp 0.5s ease-out;
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .header-section {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        h1 {
            color: var(--jade);
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
            letter-spacing: 0.05em;
        }
        
        .subtitle {
            color: #daa520;
            font-size: 1.25rem;
            margin-bottom: 2rem;
        }
        
        .form-container {
            background-color: rgba(10, 10, 18, 0.8);
            backdrop-filter: blur(4px);
            border: 1px solid rgba(0, 200, 150, 0.2);
            border-radius: 0.5rem;
            padding: 1.5rem;
        }
        
        .error-message {
            padding: 0.75rem;
            background-color: rgba(220, 38, 38, 0.2);
            border: 1px solid rgba(220, 38, 38, 0.4);
            color: white;
            border-radius: 0.375rem;
            margin-bottom: 1.5rem;
            font-weight: 500;
            animation: slideIn 0.3s ease-out;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            color: #d1d5db;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 0.75rem 1rem;
            background-color: rgba(17, 24, 39, 0.5);
            border: 1px solid #4b5563;
            color: white;
            border-radius: 0.375rem;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        
        .form-control:focus {
            border-color: var(--jade);
            box-shadow: 0 0 0 0.2rem rgba(0, 200, 150, 0.25);
            background-color: rgba(17, 24, 39, 0.7);
            color: white;
        }
        
        .form-control::placeholder {
            color: rgba(255, 255, 255, 0.5);
        }
        
        /* Asegurar que el texto sea blanco en todos los estados */
        input, select, textarea {
            color: white !important;
        }
        
        .input-group {
            position: relative;
            display: flex;
            align-items: stretch;
            width: 100%;
        }
        
        .input-group-text {
            display: flex;
            align-items: center;
            padding: 0.75rem 1rem;
            font-size: 1rem;
            font-weight: 400;
            line-height: 1.5;
            color: #d1d5db;
            text-align: center;
            white-space: nowrap;
            background-color: rgba(17, 24, 39, 0.7);
            border: 1px solid #4b5563;
            border-radius: 0.375rem;
        }
        
        .input-group > .form-control {
            position: relative;
            flex: 1 1 auto;
            width: 1%;
            min-width: 0;
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
        }
        
        .input-group-text:first-child {
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
        }
        
        .input-group > .input-group-text:last-child {
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
        }
        
        .bonus-badge {
            background-color: rgba(0, 200, 150, 0.2);
            color: var(--jade);
            padding: 0.375rem 0.75rem;
            border-radius: 0.375rem;
            font-weight: 500;
            margin-left: 1rem;
        }
        
        .price-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            padding: 1rem 0;
        }
        
        .price-item {
            display: flex;
            justify-content: space-between;
            color: #9ca3af;
        }
        
        .price-value {
            color: white;
            font-weight: 500;
        }
        
        .radio-group {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin-top: 0.5rem;
        }
        
        @media (min-width: 768px) {
            .radio-group {
                grid-template-columns: repeat(4, 1fr);
            }
        }
        
        .radio-button {
            position: absolute;
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .radio-custom-label {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 1rem;
            background-color: rgba(17, 24, 39, 0.5);
            border: 2px solid #4b5563;
            border-radius: 0.5rem;
            transition: all 0.3s ease;
            cursor: pointer;
            height: 100%;
        }
        
        .radio-button:checked + .radio-custom-label {
            border-color: var(--jade);
            background-color: rgba(0, 200, 150, 0.1);
            box-shadow: 0 0 20px rgba(0, 168, 107, 0.3);
        }
        
        .payment-logo {
            height: 3rem;
            max-width: 100%;
            object-fit: contain;
        }
        
        .notes {
            margin-top: 1.5rem;
            color: #9ca3af;
            font-size: 0.875rem;
        }
        
        .notes a {
            color: var(--jade);
            text-decoration: none;
            transition: text-decoration 0.3s ease;
        }
        
        .notes a:hover {
            text-decoration: underline;
        }
        
        .submit-button {
            width: 100%;
            background-color: var(--jade);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 0.375rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-top: 1.5rem;
            transition: background-color 0.3s ease;
        }
        
        .submit-button:hover:not(:disabled) {
            background-color: var(--jade-dark);
        }
        
        .submit-button:disabled {
            background-color: #6b7280;
            cursor: not-allowed;
        }
        
        footer {
            padding: 1rem;
            text-align: center;
            font-size: 0.875rem;
            color: #6b7280;
            position: relative;
            z-index: 10;
        }
        
        /* Estilos para el slider personalizado */
        .irs--round .irs-bar {
            background-color: var(--jade) !important;
        }
        
        .irs--round .irs-handle {
            border: 4px solid var(--jade) !important;
            background-color: white !important;
        }
        
        .irs--round .irs-from, 
        .irs--round .irs-to, 
        .irs--round .irs-single {
            background-color: var(--jade) !important;
        }
        
        .irs--round .irs-grid-text {
            color: #9ca3af !important;
        }
        
        .irs--round .irs-grid-pol {
            background-color: #4b5563 !important;
        }
        
        .btn {
            position: relative;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            z-index: 10;
            background-color: transparent;
            transform: scale(1);
            transition: transform 0.2s;
        }
        
        .btn:hover {
            transform: scale(1.05);
        }

        .btn::before,
        .btn::after {
            content: "";
            position: absolute;
            top: 0;
        }

        .btn::after {
            width: calc(100% + 6px);
            height: 100%;
            z-index: 2;
            left: -3px;
            background: url("https://hebbkx1anhila5yf.public.blob.vercel-storage.com/bg_btn_red_left-oS4gSgIbHzacJPhxkdy439dSIvhsRB.png")
                left center / auto 100% no-repeat,
                url("https://hebbkx1anhila5yf.public.blob.vercel-storage.com/bg_btn_red_right-D2erGMEqvd01Kk4K2rynDUoxQvdvMO.png")
                right center / auto 100% no-repeat;
        }

        .btn::before {
            height: 100%;
            z-index: 1;
            left: 50%;
            transform: translateX(-50%);
            background: url("https://hebbkx1anhila5yf.public.blob.vercel-storage.com/bg_btn_red_middle-O4426m3uVxk9u8eeyh7MOzfx37Ri1j.png")
                center center / auto 100% repeat-x;
        }
        
        .btn-register {
            padding: 0 30px !important;
            min-width: 150px;
            height: 54px;
            font-size: 0.875rem;
        }

        .btn-register::before {
            width: calc(100% - 60px);
        }
        
        .btn-text {
            position: relative;
            z-index: 20;
            color: white;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .vote-section {
            position: fixed;
            z-index: 50;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
        }

        .vote-container {
            padding: 1rem;
        }

        .vote-title {
            font-size: 1.25rem;
            font-weight: bold;
            color: white;
            margin-bottom: 1rem;
            text-align: center;
            text-transform: uppercase;
            letter-spacing: 0.1em;
        }

        .vote-buttons {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
            align-items: center;
        }

        .vote-button {
            position: relative;
            display: block;
            text-decoration: none;
        }

        .vote-button-glow {
            position: absolute;
            inset: 0;
            border-radius: 9999px;
            background-color: rgba(0, 200, 150, 0.2);
            opacity: 0;
            transition: opacity 0.3s, filter 0.3s;
            filter: blur(1rem);
        }

        .vote-button:hover .vote-button-glow {
            opacity: 1;
        }

        .vote-button-content {
            position: relative;
            width: 4rem;
            height: 4rem;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgba(10, 10, 18, 0.8);
            border-radius: 9999px;
            border: 2px solid rgba(0, 200, 150, 0.2);
            backdrop-filter: blur(4px);
            transition: border-color 0.3s, transform 0.3s;
        }

        .vote-button:hover .vote-button-content {
            border-color: rgba(0, 200, 150, 0.5);
            transform: scale(1.1);
        }

        .vote-icon {
            width: 2rem;
            height: 2rem;
            transition: transform 0.3s;
        }

        .vote-button:hover .vote-icon {
            transform: scale(1.1);
        }
    </style>
</head>
<body>
    <!-- Contenedor de fondo -->
    <div class="background-container">
        <img src="assets/media/background 3.jpg.jpeg" alt="Fondo místico" class="background-image">
        <div class="overlay"></div>
    </div>
    
    <!-- Sección de votación -->
    <div class="vote-section">
        <div class="vote-container">
            <h3 class="vote-title lang-vote-title">Votar</h3>
            <div class="vote-buttons">
                <a href="https://l2.hopzone.net/site/vote/106242/1" target="_blank" rel="noopener noreferrer" class="vote-button">
                    <div class="vote-button-glow"></div>
                    <div class="vote-button-content">
                        <img src="assets/media/hopzone.png" alt="Vote on Hopzone" class="vote-icon">
                    </div>
                </a>
                <a href="https://svtop.net/vote/618" target="_blank" rel="noopener noreferrer" class="vote-button">
                    <div class="vote-button-glow"></div>
                    <div class="vote-button-content">
                        <img src="assets/media/server-top.png" alt="Vote on Server Top" class="vote-icon">
                    </div>
                </a>
            </div>
        </div>
    </div>
    
    <!-- Cabecera con botón de regreso y selector de idioma -->
    <header>
        <div class="language-selector">
            <button type="button" class="language-button active" data-lang="es" onclick="cambiarIdioma('es')">ES</button>
            <button type="button" class="language-button" data-lang="en" onclick="cambiarIdioma('en')">EN</button>
            <button type="button" class="language-button" data-lang="br" onclick="cambiarIdioma('br')">PT</button>
        </div>
        <a href="index.php" class="back-button">
            <i class="fas fa-arrow-left"></i>
            <span class="lang-back-to-panel">Volver al Panel</span>
        </a>
    </header>

    <!-- Contenido principal -->
    <main>
        <div class="content-container">
            <div class="header-section">
                <h1 class="lang-donate-title">Donar a L2Jade</h1>
                <p class="subtitle lang-donate-subtitle">Apoya al servidor y recibe recompensas exclusivas</p>
            </div>

            <div class="form-container">
                <form action="don_save.php" method="post">
                    <!-- Campos ocultos -->
                    <input type="hidden" name="module_form" value="Modules\Globals\Donations\Donations">
                    <input type="hidden" name="module" value="checkout_no_auth">
                    <input type="hidden" name="type_id" value="68" data-type="char" data-message="" data-long-name="Donate Coin" data-short-name="JC" data-price="<?=$precio_coin_peso?>">
                    <input type="hidden" name="csrf_token" value="<?=$_SESSION['csrf_token']?>">

                    <!-- Mensaje de error si existe -->
                    <?php if (isset($_GET['error']) && strlen($_GET['error'])>2): ?>
                        <div class="error-message">
                            <strong><i class="fas fa-exclamation-triangle"></i> Error de Validación:</strong><br>
                            <?php echo htmlentities(urldecode($_GET['error'])); ?>
                            <script>
                                // Auto-ocultar el error después de 8 segundos
                                setTimeout(function() {
                                    const errorAlert = document.querySelector('.error-message');
                                    if (errorAlert) {
                                        errorAlert.style.transition = 'opacity 0.5s';
                                        errorAlert.style.opacity = '0';
                                        setTimeout(() => errorAlert.remove(), 500);
                                    }
                                }, 8000);
                                
                                // Limpiar URL
                                window.history.replaceState({}, document.title, "./donaciones_jade.php");
                            </script>
                        </div>
                    <?php endif; ?>

                    <!-- Nombre del personaje -->
                    <div class="form-group">
                        <label for="recipient" class="form-label lang-character-name">Nombre del personaje</label>
                        <input type="text" id="recipient" name="recipient" class="form-control" required 
                               placeholder="Nombre" maxlength="50" minlength="2" 
                               pattern="[a-zA-Z0-9_-]+" 
                               title="Solo se permiten letras, números, guiones y guiones bajos">
                    </div>

                    <!-- Cantidad de JC -->
                    <div class="form-group">
                        <label for="coin" class="form-label lang-amount">Cantidad</label>
                        <div class="d-flex align-items-center">
                            <div class="input-group">
                                <span class="input-group-text">JC</span>
                                <input type="number" id="coin" name="sum" class="form-control" 
                                       min="1" max="10000" value="10" step="1" required
                                       onchange="changeSum(this.value, false);" 
                                       onkeyup="changeSum(this.value, false);"
                                       title="Cantidad entre 1 y 10,000 JC">
                                <span class="bonus-badge" id="bonus_sum">+0 Bonus</span>
                            </div>
                        </div>
                    </div>

                    <!-- Slider personalizado -->
                    <div class="form-group">
                        <input type="text" id="sum_slider" class="js-range-slider" data-grid="true">
                    </div>

                    <!-- Precios -->
                    <div class="price-grid">
                        <div class="price-item">
                            USD <span class="price-value" id="sum_USD">$0</span>
                            <input type="hidden" name="sum_USD" id="sum_USD_i" value="0">
                        </div>
                        <div class="price-item">
                            ARG <span class="price-value" id="sum_ARG">$0</span>
                            <input type="hidden" name="sum_ARG" id="sum_ARG_i" value="0">
                        </div>
                    </div>

                    <!-- Método de pago -->
                    <div class="form-group">
                        <label class="form-label">Selecciona método de pago <span style="color: #dc2626;">*</span></label>
                        <div class="radio-group">
                            <div>
                                <input type="radio" id="mercadopago" name="payment_method" value="mercadopago" class="radio-button" checked required>
                                <label for="mercadopago" class="radio-custom-label">
                                    <img src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-QmhWmyPTNEubSCv2RNqBjlvuNgNyNu.png" alt="Mercado Pago" class="payment-logo">
                                </label>
                            </div>
                            <div>
                                <input type="radio" id="paypal" name="payment_method" value="paypal" class="radio-button" required>
                                <label for="paypal" class="radio-custom-label">
                                    <img src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-8toSSnoxzp24Ny4acIS4uMMmEvtwu4.png" alt="PayPal" class="payment-logo">
                                </label>
                            </div>
                            <div>
                                <input type="radio" id="kamipay" name="payment_method" value="kamipay" class="radio-button" required>
                                <label for="kamipay" class="radio-custom-label">
                                    <div style="display: flex; flex-direction: column; align-items: center; gap: 0.5rem;">
                                        <div style="background: #00C896; color: white; padding: 0.5rem 1rem; border-radius: 0.375rem; font-weight: bold; font-size: 1.2rem;">PIX</div>
                                        <div style="color: #00C896; font-size: 0.875rem; text-align: center;">🇧🇷 Brasil</div>
                                        <div style="color: #22c55e; font-size: 0.75rem; font-weight: bold;">Instantâneo</div>
                                    </div>
                                </label>
                            </div>
                            <div>
                                <input type="radio" id="crypto" name="payment_method" value="crypto" class="radio-button" required>
                                <label for="crypto" class="radio-custom-label">
                                    <img src="criptomonedasPago.png" alt="crypto" class="payment-logo">
                                    <p>+10% Bonus</p>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Notas -->
                    <div class="notes">
                        <p class="lang-donate-note">Las donaciones se acreditan automáticamente al reiniciar tu personaje.</p>
                        <p class="lang-donate-pix">PIX é a forma mais rápida de doar! Pagamentos são processados instantaneamente e o JC é creditado automaticamente. Disponível 24/7 para jogadores brasileiros.</p>
                        <p class="lang-donate-contact">Para suporte ou dúvidas, entre em contato através da nossa página no <a href="https://www.facebook.com/messages/t/375479225640935" target="_blank">Facebook</a>.</p>
                    </div>

                    <!-- Botón de envío -->
                    <button type="submit" id="submit-button" class="submit-button lang-make-payment">
                        <span id="btnText">Realizar Pago</span>
                    </button>
                </form>
            </div>
        </div>
    </main>

    <!-- Pie de página -->
    <footer>
        <p>&copy; <?php echo date('Y'); ?> L2JADE. <span class="lang-all-rights">Todos los derechos reservados</span>.</p>
    </footer>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Ion Range Slider JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ion-rangeslider/2.3.1/js/ion.rangeSlider.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Script de traducciones -->
    <script>
        // Traducciones
        const translations = {
            en: {
                "lang-back-to-panel": "Back to Panel",
                "lang-donate-title": "Donate to L2Jade",
                "lang-donate-subtitle": "Support the server and receive exclusive rewards",
                "lang-donate-note": "Donations are credited automatically when you restart your character.",
                "lang-donate-pix": "PIX is the fastest way to donate! Payments are processed instantly and JC is credited automatically. Available 24/7 for Brazilian players.",
                "lang-donate-contact": "For support or questions, contact us through our Facebook page.",
                "lang-vote-title": "Vote",
                "lang-character-name": "Character Name",
                "lang-amount": "Amount",
                "lang-make-payment": "Make Payment",
                "lang-all-rights": "All rights reserved"
            },
            es: {
                "lang-back-to-panel": "Volver al Panel",
                "lang-donate-title": "Donar a L2Jade",
                "lang-donate-subtitle": "Apoya al servidor y recibe recompensas exclusivas",
                "lang-donate-note": "Las donaciones se acreditan automáticamente al reiniciar tu personaje.",
                "lang-donate-pix": "¡PIX es la forma más rápida de donar! Los pagos se procesan instantáneamente y el JC se acredita automáticamente. Disponible 24/7 para jugadores brasileños.",
                "lang-donate-contact": "Para soporte o consultas, contáctanos a través de nuestra página de Facebook.",
                "lang-vote-title": "Votar",
                "lang-character-name": "Nombre del personaje",
                "lang-amount": "Cantidad",
                "lang-make-payment": "Realizar Pago",
                "lang-all-rights": "Todos los derechos reservados"
            },
            br: {
                "lang-back-to-panel": "Voltar ao Painel",
                "lang-donate-title": "Doar para L2Jade",
                "lang-donate-subtitle": "Apoie o servidor e receba recompensas exclusivas",
                "lang-donate-note": "As doações são creditadas automaticamente ao reiniciar seu personagem.",
                "lang-donate-pix": "PIX é a forma mais rápida de doar! Pagamentos são processados instantaneamente e o JC é creditado automaticamente. Disponível 24/7 para jogadores brasileiros.",
                "lang-donate-contact": "Para suporte ou dúvidas, entre em contato através da nossa página no Facebook.",
                "lang-vote-title": "Votar",
                "lang-character-name": "Nome do personagem",
                "lang-amount": "Quantidade",
                "lang-make-payment": "Realizar Pagamento",
                "lang-all-rights": "Todos os direitos reservados"
            }
        };

        // Función global para cambiar idioma desde el HTML
        function cambiarIdioma(lang) {
            console.log("Cambiando idioma a: " + lang);
            
            // Verificar que el idioma sea válido
            if (!translations[lang]) {
                lang = 'es'; // Idioma por defecto si el guardado no es válido
            }

            // Guardar el idioma
            localStorage.setItem('language', lang);
            document.documentElement.lang = lang;
            
            // Actualizar textos
            Object.entries(translations[lang]).forEach(([key, value]) => {
                $(`.${key}`).text(value);
            });
            
            // Actualizar botones
            $('.language-button').removeClass('active');
            $(`.language-button[data-lang="${lang}"]`).addClass('active');
        }

        $(document).ready(function() {
            // Obtener idioma guardado o usar español por defecto
            let savedLang = localStorage.getItem('language');
            let currentLang = translations[savedLang] ? savedLang : 'es';
            
            // Configurar idioma inicial
            cambiarIdioma(currentLang);
            
            // También mantenemos el evento jQuery por si acaso
            $('.language-button').click(function() {
                cambiarIdioma($(this).attr('data-lang'));
            });
        });
        
        // Configurar el slider
        $("#sum_slider").ionRangeSlider({
            min: 1,
            max: 10000,
            from: 10,
            grid: true,
            postfix: ' JC',
            skin: 'round',
            prettify: function(num) {
                let bonus = 0;
                let payment_method = $("input[name='payment_method']:checked").val() || "all";
                let price = parseFloat($("input[name='type_id']:checked").data('price')) || 1;
                
                // Asegurarnos que num es un número
                num = parseFloat(num) || 0;
                
                // Cálculo de bonus según cantidad
                let temp_agrigator_40 = ["all"];
                if (temp_agrigator_40.includes(payment_method) || temp_agrigator_40.includes('all')) {
                    if (num >= 0 && num <= 99) {
                        // 10% de bonus
                        bonus += (num * price * 100) / 1000;
                    } else if (num >= 100 && num <= 499) {
                        // 15% de bonus
                        bonus += (num * price * 150) / 1000;
                    } else if (num >= 500 && num <= 999) {
                        // 20% de bonus
                        bonus += (num * price * 200) / 1000;
                    } else if (num >= 1000 && num <= 2999) {
                        // 25% de bonus
                        bonus += (num * price * 250) / 1000;
                    } else if (num >= 3000 && num <= 7499) {
                        // 30% de bonus
                        bonus += (num * price * 300) / 1000;
                    } else if (num >= 7500 && num <= 9999999) {
                        // 35% de bonus
                        bonus += (num * price * 350) / 1000;
                    }
                    
                    // Redondear el bonus y prevenir NaN
                    bonus = Math.floor(bonus);
                    if (isNaN(bonus)) bonus = 0;
                    
                    // Actualizar el valor de bonus para que se refleje
                    $('#bonus_sum').html(`+${bonus} Bonus`);
                }
                
                return num;
            },
            onChange: function(data) {
                $('#coin').val(data.from);
                changeSum(data.from, true);
            }
        });
        
        // Función para cambiar la suma y calcular precios
        window.changeSum = function(sum, slider) {
            let price = parseFloat($("input[name='type_id']:checked").data('price')) || 1;
            let bonus = 0;
            
            // Asegurarnos que sum es un número
            sum = parseFloat(sum) || 0;
            
            // Calcular bonus basado en la cantidad usando la fórmula correcta
            if (sum >= 0 && sum <= 99) {
                // 10% de bonus
                bonus = (sum * price * 100) / 1000;
            } else if (sum >= 100 && sum <= 499) {
                // 15% de bonus
                bonus = (sum * price * 150) / 1000;
            } else if (sum >= 500 && sum <= 999) {
                // 20% de bonus
                bonus = (sum * price * 200) / 1000;
            } else if (sum >= 1000 && sum <= 2999) {
                // 25% de bonus
                bonus = (sum * price * 250) / 1000;
            } else if (sum >= 3000 && sum <= 7499) {
                // 30% de bonus
                bonus = (sum * price * 300) / 1000;
            } else if (sum >= 7500) {
                // 35% de bonus
                bonus = (sum * price * 350) / 1000;
            }
            
            // Redondear el bonus y prevenir NaN
            bonus = Math.floor(bonus);
            if (isNaN(bonus)) bonus = 0;
            
            // Actualizar UI con bonus
            $('#bonus_sum').html(`+${bonus} Bonus`);
            
            // Calcular y mostrar precios
            let usdPrice = (sum * <?= $precio_coin_dolar ?>).toFixed(2);
            let argPrice = (sum * <?= $precio_coin_peso ?>).toFixed(0);
            
            $('#sum_USD').html(`$${usdPrice}`);
            $('#sum_USD_i').val(usdPrice);
            $('#sum_ARG').html(`$${argPrice}`);
            $('#sum_ARG_i').val(argPrice);
            
            // Actualizar slider si el cambio viene del input
            if (!slider) {
                let slider_instance = $("#sum_slider").data("ionRangeSlider");
                if (slider_instance) {
                    slider_instance.update({
                        from: sum
                    });
                }
            }
        };
        
        // Inicializar
        changeSum(10, false);

        // 🛡️ SISTEMA DE VALIDACIÓN FRONTEND COMPLETO - ADAPTADO PARA JADE
        document.addEventListener("DOMContentLoaded", function() {
            const form = document.querySelector('form[action="don_save.php"]');
            const btnSubmit = document.getElementById('submit-button');
            const btnText = document.getElementById('btnText');
            
            // 📝 Función para mostrar errores
            function mostrarError(mensaje) {
                // Remover alertas anteriores
                const alertaAnterior = document.querySelector('.alerta-validacion');
                if (alertaAnterior) {
                    alertaAnterior.remove();
                }
                
                // Crear nueva alerta
                const alerta = document.createElement('div');
                alerta.className = 'alerta-validacion alert-jade';
                alerta.innerHTML = '<strong>❌ Error:</strong> ' + mensaje;
                alerta.style.marginTop = '15px';
                
                // Insertar antes del botón
                btnSubmit.parentNode.insertBefore(alerta, btnSubmit);
                
                // Auto-ocultar después de 5 segundos
                setTimeout(() => {
                    if (alerta.parentNode) {
                        alerta.remove();
                    }
                }, 5000);
            }
            
            // 🔍 Función de validación completa
            function validarFormulario() {
                const personaje = document.querySelector('input[name="recipient"]').value.trim();
                const cantidad = parseInt(document.querySelector('input[name="sum"]').value);
                const metodoPago = document.querySelector('input[name="payment_method"]:checked');
                
                // 1️⃣ Validar personaje
                if (!personaje || personaje.length < 2) {
                    mostrarError('El nombre del personaje debe tener al menos 2 caracteres');
                    return false;
                }
                
                if (personaje.length > 50) {
                    mostrarError('El nombre del personaje no puede tener más de 50 caracteres');
                    return false;
                }
                
                // Validar caracteres permitidos (solo letras, números, guiones)
                const caracteresPermitidos = /^[a-zA-Z0-9_-]+$/;
                if (!caracteresPermitidos.test(personaje)) {
                    mostrarError('El nombre del personaje solo puede contener letras, números, guiones y guiones bajos');
                    return false;
                }
                
                // 2️⃣ Validar cantidad
                if (!cantidad || isNaN(cantidad)) {
                    mostrarError('Debe especificar una cantidad válida');
                    return false;
                }
                
                if (cantidad < 1) {
                    mostrarError('La cantidad mínima es 1 JC');
                    return false;
                }
                
                if (cantidad > 10000) {
                    mostrarError('La cantidad máxima es 10,000 JC');
                    return false;
                }
                
                // 3️⃣ Validar método de pago
                if (!metodoPago) {
                    mostrarError('Debe seleccionar un método de pago');
                    return false;
                }
                
                // 4️⃣ 💰 VALIDACIÓN CRÍTICA: Mínimo $1 USD para PayPal
                if (metodoPago.value === 'paypal') {
                    const sumUSDText = document.getElementById('sum_USD').textContent.replace('$', '');
                    const sumUSD = parseFloat(sumUSDText);
                    
                    if (sumUSD < 1.00) {
                        mostrarError('El monto mínimo para PayPal es $1.00 USD. Cantidad actual: $' + sumUSD.toFixed(2) + ' USD');
                        return false;
                    }
                }
                
                // 5️⃣ Validación adicional: precio lógico
                const sumARGText = document.getElementById('sum_ARG').textContent.replace('$', '');
                const sumARG = parseFloat(sumARGText);
                if (sumARG <= 0) {
                    mostrarError('Error en el cálculo del precio. Intente nuevamente');
                    return false;
                }
                
                return true;
            }
            
            // 🎯 Interceptar envío del formulario
            form.addEventListener('submit', function(event) {
                event.preventDefault(); // Detener envío automático
                
                // Cambiar estado del botón
                btnSubmit.disabled = true;
                btnText.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Validando...';
                
                // Ejecutar validaciones
                setTimeout(() => {
                    if (validarFormulario()) {
                        // ✅ Validación exitosa
                        btnText.innerHTML = '<i class="fas fa-check"></i> Procesando...';
                        
                        // Enviar formulario
                        setTimeout(() => {
                            form.submit();
                        }, 500);
                    } else {
                        // ❌ Validación fallida
                        btnSubmit.disabled = false;
                        btnText.innerHTML = 'Realizar Pago';
                    }
                }, 300);
            });
            
            // 🔄 Validación en tiempo real del personaje
            const inputPersonaje = document.querySelector('input[name="recipient"]');
            inputPersonaje.addEventListener('input', function() {
                const valor = this.value;
                
                // Remover caracteres no permitidos
                this.value = valor.replace(/[^a-zA-Z0-9_-]/g, '');
                
                // Límite visual de caracteres
                if (this.value.length > 50) {
                    this.value = this.value.substring(0, 50);
                }
            });
            
            // 🔄 Validación en tiempo real de cantidad
            const inputCantidad = document.querySelector('input[name="sum"]');
            inputCantidad.addEventListener('input', function() {
                let valor = parseInt(this.value);
                
                // Aplicar límites automáticamente
                if (valor < 1) {
                    this.value = 1;
                } else if (valor > 10000) {
                    this.value = 10000;
                }
                
                // Actualizar cálculos
                changeSum(this.value, false);
            });
            
            // 🔄 Detectar cambios en método de pago para validaciones específicas
            const paymentMethods = document.querySelectorAll('input[name="payment_method"]');
            paymentMethods.forEach(method => {
                method.addEventListener('change', function() {
                    // Recalcular para aplicar validaciones específicas del método
                    changeSum(document.querySelector('input[name="sum"]').value, false);
                    
                    // Remover alertas previas si cambia el método
                    const alertaAnterior = document.querySelector('.alerta-validacion');
                    if (alertaAnterior) {
                        alertaAnterior.remove();
                    }
                });
            });
            
            // 🎨 Agregar estilos CSS para las alertas
            const style = document.createElement('style');
            style.textContent = `
                .alerta-validacion {
                    padding: 12px 15px;
                    border: 1px solid rgba(220, 38, 38, 0.4);
                    border-radius: 0.375rem;
                    background-color: rgba(220, 38, 38, 0.2);
                    color: white;
                    margin: 10px 0;
                    animation: slideIn 0.3s ease-out;
                    font-weight: 500;
                }
                
                @keyframes slideIn {
                    from { opacity: 0; transform: translateY(-10px); }
                    to { opacity: 1; transform: translateY(0); }
                }
                
                .submit-button:disabled {
                    opacity: 0.6;
                    cursor: not-allowed;
                    background-color: #6b7280 !important;
                }
            `;
            document.head.appendChild(style);
        });
    </script>
</body>
</html>