<?php
$dbFile = __DIR__ . '/api/.db.db';
$trialDays = 0;
$trialHours = 4;
$downloadUrl = '#';
$downloaderCode = '';
$publicBrandName = 'MyTube';
$publicBrandBadge = 'PREMIUM';
$publicHeroTitle = 'Prueba Premium Gratis';
$publicHeroSubtitle = '<?=htmlspecialchars($publicHeroSubtitle)?>';
$publicFormTitle = '<?=htmlspecialchars($publicFormTitle)?>';
$publicFormSubtitle = '<?=htmlspecialchars($publicFormSubtitle)?>';
$resellerTitle = 'Planes Reseller';
$resellerLines = "10 créditos|$10 USD\n50 créditos|$30 USD\n100 créditos|$50 USD\n500 créditos|$200 USD\n1000 créditos|$300 USD";
$resellerFooter = '<?=htmlspecialchars($resellerFooter)?>';
$downloadTitle = '<?=htmlspecialchars($downloadTitle)?>';
$downloadText = '<?=htmlspecialchars($downloadText)?>';
$downloadButtonText = '<?=htmlspecialchars($downloadButtonText)?>';
try {
    if (file_exists($dbFile)) {
        $sqlite = new SQLite3($dbFile);
        $result = $sqlite->query("SELECT key, value FROM settings");
        $settings = [];
        while ($result && ($row = $result->fetchArray(SQLITE3_ASSOC))) {
            $settings[$row['key']] = $row['value'];
        }
        if (isset($settings['trial_days'])) $trialDays = (int)$settings['trial_days'];
        if (isset($settings['trial_hours'])) $trialHours = (int)$settings['trial_hours'];
        if (!empty($settings['app_download_url'])) $downloadUrl = $settings['app_download_url'];
        if (!empty($settings['app_downloader_code'])) $downloaderCode = $settings['app_downloader_code'];
        if (!empty($settings['public_brand_name'])) $publicBrandName = $settings['public_brand_name'];
        if (!empty($settings['public_brand_badge'])) $publicBrandBadge = $settings['public_brand_badge'];
        if (!empty($settings['public_hero_title'])) $publicHeroTitle = $settings['public_hero_title'];
        if (!empty($settings['public_hero_subtitle'])) $publicHeroSubtitle = $settings['public_hero_subtitle'];
        if (!empty($settings['public_form_title'])) $publicFormTitle = $settings['public_form_title'];
        if (!empty($settings['public_form_subtitle'])) $publicFormSubtitle = $settings['public_form_subtitle'];
        if (!empty($settings['reseller_title'])) $resellerTitle = $settings['reseller_title'];
        if (!empty($settings['reseller_lines'])) $resellerLines = $settings['reseller_lines'];
        if (!empty($settings['reseller_footer'])) $resellerFooter = $settings['reseller_footer'];
        if (!empty($settings['download_title'])) $downloadTitle = $settings['download_title'];
        if (!empty($settings['download_text'])) $downloadText = $settings['download_text'];
        if (!empty($settings['download_button_text'])) $downloadButtonText = $settings['download_button_text'];
    }
} catch (Throwable $e) {}
$parts = [];
if ($trialDays > 0) $parts[] = $trialDays . ' día' . ($trialDays !== 1 ? 's' : '');
if ($trialHours > 0) $parts[] = $trialHours . ' hora' . ($trialHours !== 1 ? 's' : '');
$trialLabel = $parts ? 'Tiempo de prueba: ' . implode(' y ', $parts) : 'Tiempo de prueba: 4 horas';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <base target="_self">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?=htmlspecialchars($publicBrandName)?> - Genera tu Código de Prueba Gratis</title>
    <meta name="description" content="Obtén acceso premium con un código de prueba gratuito.">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        "youtube-red": "#FF0000",
                        "youtube-dark": "#0F0F0F",
                        "youtube-darker": "#0A0A0A",
                        "youtube-gray": "#282828",
                        "youtube-light": "#AAAAAA"
                    }
                }
            }
        }
    </script>
    <style>
        @import url("https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700;900&display=swap");
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: "Roboto", sans-serif;
            background: linear-gradient(135deg, #0A0A0A 0%, #1a1a1a 100%);
            color: #ffffff;
            min-height: 100vh;
        }
        
        .gradient-text {
            background: linear-gradient(135deg, #FF0000 0%, #CC0000 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .premium-badge {
            background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
            color: #000;
            padding: 6px 16px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            box-shadow: 0 4px 15px rgba(255, 215, 0, 0.3);
        }
        
        .hero-icon {
            font-size: 5rem;
            color: #FF0000;
            animation: float 3s ease-in-out infinite;
            filter: drop-shadow(0 0 20px rgba(255, 0, 0, 0.5));
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-20px); }
        }
        
        .card-premium {
            background: linear-gradient(135deg, #1a1a1a 0%, #282828 100%);
            border: 1px solid rgba(255, 0, 0, 0.2);
            border-radius: 20px;
            padding: 3rem;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
            transition: all 0.3s ease;
        }
        
        .card-premium:hover {
            transform: translateY(-5px);
            box-shadow: 0 25px 70px rgba(255, 0, 0, 0.2);
        }
        
        .btn-generate {
            background: linear-gradient(135deg, #FF0000 0%, #CC0000 100%);
            color: white;
            border: none;
            padding: 18px 50px;
            font-size: 1.2rem;
            font-weight: 700;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 10px 30px rgba(255, 0, 0, 0.3);
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .btn-generate:hover:not(:disabled) {
            transform: translateY(-3px);
            box-shadow: 0 15px 40px rgba(255, 0, 0, 0.5);
        }
        
        .btn-generate:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .code-display {
            background: linear-gradient(135deg, rgba(255, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0.5) 100%);
            border: 2px solid #FF0000;
            border-radius: 20px;
            padding: 2.5rem;
            margin-top: 2rem;
            animation: slideIn 0.5s ease;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .code-value {
            font-size: 3.5rem;
            font-weight: 900;
            letter-spacing: 12px;
            color: #FF0000;
            text-align: center;
            font-family: "Courier New", monospace;
            text-shadow: 0 0 20px rgba(255, 0, 0, 0.5);
            padding: 1rem;
        }
        
        .btn-copy {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50px;
            padding: 12px 30px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-copy:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }
        
        .btn-copy.copied {
            background: rgba(0, 255, 0, 0.2);
            border-color: #00ff00;
            color: #00ff00;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 24px;
            height: 24px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .alert-error {
            background: rgba(220, 53, 69, 0.15);
            border: 1px solid rgba(220, 53, 69, 0.4);
            border-radius: 12px;
            padding: 1rem;
            margin-top: 1.5rem;
            color: #ff6b6b;
        }
        
        .info-card {
            background: linear-gradient(135deg, #1a1a1a 0%, #282828 100%);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 16px;
            padding: 2rem;
            transition: all 0.3s ease;
        }
        
        .info-card:hover {
            transform: translateY(-5px);
            border-color: rgba(255, 0, 0, 0.3);
        }
        
        .form-control {
            background: rgba(255, 255, 255, 0.05);
            border: 2px solid rgba(255, 255, 255, 0.1);
            color: white;
            border-radius: 12px;
            padding: 14px 18px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            background: rgba(255, 255, 255, 0.08);
            border-color: #FF0000;
            outline: none;
            box-shadow: 0 0 0 4px rgba(255, 0, 0, 0.1);
        }
        
        .form-control::placeholder {
            color: rgba(255, 255, 255, 0.4);
        }
        
        @media (max-width: 768px) {
            .hero-icon { font-size: 3.5rem; }
            .code-value { font-size: 2.5rem; letter-spacing: 6px; }
            .card-premium { padding: 2rem; }
        }
    </style>
</head>
<body>
    <header class="sticky top-0 z-50 bg-youtube-darker border-b border-gray-800 shadow-lg">
        <div class="container mx-auto px-4 py-4">
            <div class="flex justify-between items-center">
                <div class="flex items-center gap-3">
                    <i class="fab fa-youtube text-youtube-red text-4xl"></i>
                    <div>
                        <h1 class="text-2xl font-bold"><?=htmlspecialchars($publicBrandName)?></h1>
                        <span class="premium-badge"><?=htmlspecialchars($publicBrandBadge)?></span>
                    </div>
                </div>
                <a href="#download" class="hidden md:flex items-center gap-2 bg-youtube-red hover:bg-red-700 text-white px-6 py-3 rounded-full font-semibold transition-all">
                    <i class="fas fa-download"></i>
                    <?=htmlspecialchars($downloadButtonText)?>
                </a>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-12 max-w-6xl">
        <section class="text-center mb-12">
            <div class="hero-icon mb-6">
                <i class="fas fa-play-circle"></i>
            </div>
            <h2 class="text-5xl md:text-6xl font-black mb-4">
                <?=htmlspecialchars($publicHeroTitle)?>
            </h2>
            <p class="text-xl text-youtube-light max-w-2xl mx-auto mb-6">
                <?=htmlspecialchars($publicHeroSubtitle)?>
            </p>
            <div class="inline-flex items-center gap-3 bg-youtube-gray px-6 py-3 rounded-full border border-youtube-red">
                <i class="fas fa-clock text-youtube-red"></i>
                <span class="font-semibold" id="trial-duration"><?=htmlspecialchars($trialLabel)?></span>
            </div>
        </section>

        <section class="card-premium max-w-3xl mx-auto mb-12">
            <h3 class="text-3xl font-bold text-center mb-2"><?=htmlspecialchars($publicFormTitle)?></h3>
            <p class="text-center text-youtube-light mb-8"><?=htmlspecialchars($publicFormSubtitle)?></p>

            <form id="trialForm" class="space-y-6">
                <div class="grid md:grid-cols-2 gap-6">
                    <div>
                        <label for="inpName" class="block text-sm font-semibold mb-2 text-youtube-light">
                            <i class="fas fa-user mr-2"></i>Nombre Completo
                        </label>
                        <input 
                            id="inpName" 
                            type="text" 
                            class="form-control w-full" 
                            placeholder="Ej: Juan Pérez"
                            minlength="2"
                            maxlength="60"
                            required
                        >
                    </div>
                    <div>
                        <label for="inpPhone" class="block text-sm font-semibold mb-2 text-youtube-light">
                            <i class="fas fa-phone mr-2"></i>Teléfono
                        </label>
                        <input 
                            id="inpPhone" 
                            type="tel" 
                            class="form-control w-full" 
                            placeholder="(11) 99999-9999"
                            minlength="10"
                            maxlength="20"
                            required
                        >
                        <p class="text-xs text-youtube-light mt-2">
                            <i class="fas fa-info-circle mr-1"></i>
                            Usado junto con IP y dispositivo para evitar demos repetidas
                        </p>
                    </div>
                </div>

                <div class="text-center">
                    <button id="btnGen" type="submit" class="btn-generate">
                        <i class="fas fa-magic mr-2"></i>
                        Generar Código Demo
                    </button>
                    <div id="loading" class="mt-4 hidden">
                        <div class="loading-spinner mx-auto"></div>
                        <p class="text-youtube-light mt-3">Generando tu código...</p>
                    </div>
                </div>
            </form>

            <div id="result" class="code-display hidden">
                <div class="text-center">
                    <p class="text-youtube-light mb-3 text-lg">
                        <i class="fas fa-check-circle text-green-500 mr-2"></i>
                        Tu código premium:
                    </p>
                    <div id="code" class="code-value">------</div>
                    <div class="text-youtube-light mb-6">
                        <i class="fas fa-calendar-check mr-2"></i>
                        Válido hasta: <strong id="exp" class="text-white">-</strong>
                    </div>
                    <button id="btnCopy" type="button" class="btn-copy">
                        <i class="fas fa-copy mr-2"></i>
                        Copiar Código
                    </button>
                    <div id="downloaderWrap" class="hidden mt-4 rounded-2xl border border-gray-700 bg-black/30 px-4 py-3 text-left text-sm">
                        <div class="text-youtube-light">Código downloader: <strong id="downloaderCode" class="text-white">-</strong></div>
                    </div>
                    <p class="text-sm text-youtube-light mt-4">
                        <i class="fas fa-lightbulb mr-1"></i>
                        Guarda este código. También puedes consultar luego su vencimiento en el enlace público de verificación.
                    </p>
                    <a href="./consulta_codigo.php" class="inline-flex mt-4 items-center gap-2 text-sm text-red-400 hover:text-red-300">
                        <i class="fas fa-search"></i> Consultar fecha de expiración de un código
                    </a>
                </div>
            </div>

            <div id="err" class="alert-error hidden">
                <i class="fas fa-exclamation-triangle mr-2"></i>
                <span id="errMsg">Error desconocido</span>
            </div>

            <div class="mt-8 text-center">
                <a href="./consulta_codigo.php" class="inline-flex items-center gap-3 border border-red-600 text-white px-6 py-3 rounded-full font-semibold hover:bg-red-600/10">
                    <i class="fas fa-search"></i>
                    Consultar fecha de expiración
                </a>
            </div>
        </section>

        <section class="grid md:grid-cols-3 gap-6 mb-12">
            <div class="info-card">
                <div class="text-youtube-red text-3xl mb-4">
                    <i class="fas fa-list-check"></i>
                </div>
                <h4 class="text-xl font-bold mb-3">Cómo Usar</h4>
                <ul class="space-y-2 text-youtube-light">
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-youtube-red mt-1"></i>
                        <span>Descarga e instala MyTube Premium</span>
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-youtube-red mt-1"></i>
                        <span>Abre la app y ve a Activación</span>
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-youtube-red mt-1"></i>
                        <span>Pega tu código generado</span>
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-youtube-red mt-1"></i>
                        <span>Disfruta de Premium gratis</span>
                    </li>
                </ul>
            </div>

            <div class="info-card">
                <div class="text-youtube-red text-3xl mb-4">
                    <i class="fas fa-crown"></i>
                </div>
                <h4 class="text-xl font-bold mb-3">Beneficios Premium</h4>
                <ul class="space-y-2 text-youtube-light">
                    <li class="flex items-start gap-2">
                        <i class="fas fa-star text-yellow-500 mt-1"></i>
                        <span>Sin anuncios molestos</span>
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-star text-yellow-500 mt-1"></i>
                        <span>Reproducción en segundo plano</span>
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-star text-yellow-500 mt-1"></i>
                        <span>Descargas offline ilimitadas</span>
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-star text-yellow-500 mt-1"></i>
                        <span>Calidad de video 4K</span>
                    </li>
                </ul>
            </div>

            <div class="info-card">
                <div class="text-youtube-red text-3xl mb-4">
                    <i class="fas fa-users"></i>
                </div>
                <h4 class="text-xl font-bold mb-3"><?=htmlspecialchars($resellerTitle)?></h4>
                <ul class="space-y-2 text-youtube-light text-sm">
                    <?php foreach (preg_split('/
|
|
/', (string)$resellerLines) as $line): ?>
                        <?php $line = trim($line); if ($line === '') continue; $partsLine = array_map('trim', explode('|', $line, 2)); ?>
                        <li class="flex justify-between">
                            <span><?=htmlspecialchars($partsLine[0] ?? '')?></span>
                            <strong class="text-white"><?=htmlspecialchars($partsLine[1] ?? '')?></strong>
                        </li>
                    <?php endforeach; ?>
                </ul>
                <p class="text-xs text-youtube-light mt-4">
                    <i class="fas fa-envelope mr-1"></i>
                    <?=htmlspecialchars($resellerFooter)?>
                </p>
            </div>
        </section>

        <section id="download" class="card-premium text-center">
            <div class="text-youtube-red text-5xl mb-6">
                <i class="fas fa-mobile-screen-button"></i>
            </div>
            <h3 class="text-3xl font-bold mb-4"><?=htmlspecialchars($downloadTitle)?></h3>
            <p class="text-youtube-light mb-6 max-w-xl mx-auto">
                <?=htmlspecialchars($downloadText)?>
            </p>
            <a href="<?=htmlspecialchars($downloadUrl)?>" id="btnDownload" class="inline-flex items-center gap-3 bg-gradient-to-r from-youtube-red to-red-700 hover:from-red-700 hover:to-red-800 text-white px-8 py-4 rounded-full font-bold text-lg transition-all shadow-lg hover:shadow-xl">
                <i class="fas fa-download text-2xl"></i>
                <?=htmlspecialchars($downloadButtonText)?>
            </a>
        </section>
    </main>

    <footer class="border-t border-gray-800 mt-16 py-8">
        <div class="container mx-auto px-4 text-center">
            <div class="flex items-center justify-center gap-2 mb-4">
                <i class="fab fa-youtube text-youtube-red text-2xl"></i>
                <span class="text-xl font-bold"><?=htmlspecialchars($publicBrandName)?> <?=htmlspecialchars($publicBrandBadge)?></span>
            </div>
            <p class="text-youtube-light mb-2">
                &copy; <span id="currentYear"></span> MyTube Premium. Todos los derechos reservados.
            </p>
            <p class="text-sm text-youtube-light">
                Esta página genera códigos de prueba temporales para evaluar el servicio premium.
            </p>
        </div>
    </footer>

    <script>
        // Configuración
        const API_URL = "./api/generate_trial_code.php";
        function generateDeviceId() {
            const raw = [navigator.userAgent || "", navigator.language || "", navigator.platform || "", screen.width + "x" + screen.height, Intl.DateTimeFormat().resolvedOptions().timeZone || "", navigator.hardwareConcurrency || ""].join("|");
            let hash = 0;
            for (let i = 0; i < raw.length; i++) { hash = ((hash << 5) - hash) + raw.charCodeAt(i); hash |= 0; }
            return "dev-" + Math.abs(hash);
        }
        
        // Elementos del DOM
        const elements = {
            form: document.getElementById("trialForm"),
            nameInput: document.getElementById("inpName"),
            phoneInput: document.getElementById("inpPhone"),
            generateBtn: document.getElementById("btnGen"),
            loading: document.getElementById("loading"),
            result: document.getElementById("result"),
            codeDisplay: document.getElementById("code"),
            expiryDisplay: document.getElementById("exp"),
            errorBox: document.getElementById("err"),
            errorMsg: document.getElementById("errMsg"),
            copyBtn: document.getElementById("btnCopy"),
            trialDuration: document.getElementById("trial-duration"),
            downloadBtn: document.getElementById("btnDownload"),
            downloaderWrap: document.getElementById("downloaderWrap"),
            downloaderCode: document.getElementById("downloaderCode"),
            deviceId: generateDeviceId(),
            currentYear: document.getElementById("currentYear")
        };
        
        // Establecer año actual
        elements.currentYear.textContent = new Date().getFullYear();
        
        // Función para mostrar error
        function showError(message) {
            elements.errorMsg.textContent = message;
            elements.errorBox.classList.remove("hidden");
            elements.result.classList.add("hidden");
        }
        
        // Función para ocultar error
        function hideError() {
            elements.errorBox.classList.add("hidden");
        }
        
        // Función para formatear fecha
        function formatDate(dateString) {
            const date = new Date(dateString);
            const day = String(date.getDate()).padStart(2, "0");
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const year = date.getFullYear();
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            
            return day + "/" + month + "/" + year + " " + hours + ":" + minutes;
        }
        
        // Manejador del formulario
        elements.form.addEventListener("submit", async function(e) {
            e.preventDefault();
            
            hideError();
            
            const name = elements.nameInput.value.trim();
            const phone = elements.phoneInput.value.trim();
            
            // Validaciones básicas
            if (name.length < 2 || name.length > 60) {
                showError("El nombre debe tener entre 2 y 60 caracteres.");
                return;
            }
            
            if (phone.length < 10) {
                showError("El teléfono debe tener al menos 10 dígitos.");
                return;
            }
            
            // Deshabilitar botón y mostrar loading
            elements.generateBtn.disabled = true;
            elements.loading.classList.remove("hidden");
            
            try {
                // Crear FormData
                const formData = new FormData();
                formData.append("name", name);
                formData.append("phone", phone);
                formData.append("device_id", elements.deviceId);
                
                // Hacer petición
                const response = await fetch(API_URL, {
                    method: "POST",
                    body: formData
                });
                
                // Verificar si la respuesta es JSON
                const contentType = response.headers.get("content-type");
                if (!contentType || !contentType.includes("application/json")) {
                    throw new Error("La respuesta del servidor no es JSON válido");
                }
                
                const data = await response.json();
                
                if (data.success || data.ok) {
                    // Éxito - mostrar código
                    elements.codeDisplay.textContent = data.code;
                    elements.expiryDisplay.textContent = formatDate(data.expires_at || data.expiry);
                    elements.result.classList.remove("hidden");
                    
                    // Actualizar duración si está disponible
                    if (data.duration) {
                        const durationParts = [];
                        if (data.duration.days > 0) {
                            durationParts.push(data.duration.days + " día" + (data.duration.days > 1 ? "s" : ""));
                        }
                        if (data.duration.hours > 0) {
                            durationParts.push(data.duration.hours + " hora" + (data.duration.hours > 1 ? "s" : ""));
                        }
                        if (durationParts.length > 0) {
                            elements.trialDuration.textContent = "Tiempo de prueba: " + durationParts.join(" y ");
                        }
                    }
                    
                    // Actualizar URL de descarga si está disponible
                    if (data.download_url) {
                        elements.downloadBtn.href = data.download_url;
                    }
                    if (data.downloader_code) {
                        elements.downloaderCode.textContent = data.downloader_code;
                        elements.downloaderWrap.classList.remove('hidden');
                    } else {
                        elements.downloaderCode.textContent = '-';
                        elements.downloaderWrap.classList.add('hidden');
                    }
                    
                    // Limpiar formulario
                    elements.form.reset();
                } else {
                    // Error del servidor
                    showError(data.message || "Error al generar el código. Intenta nuevamente.");
                }
            } catch (error) {
                console.error("Error:", error);
                showError("Error de conexión. Por favor, verifica tu conexión a internet e intenta nuevamente.");
            } finally {
                // Rehabilitar botón y ocultar loading
                elements.generateBtn.disabled = false;
                elements.loading.classList.add("hidden");
            }
        });
        
        // Manejador del botón copiar
        elements.copyBtn.addEventListener("click", function() {
            const code = elements.codeDisplay.textContent;
            
            navigator.clipboard.writeText(code).then(function() {
                // Cambiar apariencia del botón
                elements.copyBtn.classList.add("copied");
                elements.copyBtn.innerHTML = "<i class=\"fas fa-check mr-2\"></i>¡Copiado!";
                
                // Restaurar después de 2 segundos
                setTimeout(function() {
                    elements.copyBtn.classList.remove("copied");
                    elements.copyBtn.innerHTML = "<i class=\"fas fa-copy mr-2\"></i>Copiar Código";
                }, 2000);
            }).catch(function(err) {
                console.error("Error al copiar:", err);
                showError("No se pudo copiar el código. Cópialo manualmente.");
            });
        });
        
        // Prevenir navegación en enlaces con #
        document.addEventListener("click", function(e) {
            const link = e.target.closest("a[href^=\"#\"]");
            if (link && link.getAttribute("href") !== "#download") {
                e.preventDefault();
            }
        });
    </script>
</body>
</html>