<?php 
// 1. INCLUIR ARCHIVOS DE CONEXIÓN Y SEGURIDAD
include 'files/guardiankey.php'; 
include 'db/db_connection.php'; // Conexión a la base de datos

// 2. OBTENER DATOS DE LA TABLA website_config
$user_name_from_db = ''; // Valor por defecto
$company_name_from_db = ''; // Valor por defecto
$company_logo_url = 'img/placeholder-logo.png'; // Placeholder si no hay logo
$contact_name_from_db = 'Nombre de Contacto';
$contact_email_from_db = 'correo@ejemplo.com';
$contact_phone_from_db = 'N/A';
$website_url_from_db = '';

try {
    // Se ha actualizado la consulta para obtener todos los campos necesarios para el PDF
    $stmt = $pdo->query("SELECT contact_name, company_name, phone_primary, website_url, logo_url, email FROM website_config WHERE id = 1 LIMIT 1");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($config) {
        $user_name_from_db = htmlspecialchars($config['contact_name'] ?? $user_name_from_db);
        $company_name_from_db = htmlspecialchars($config['company_name'] ?? $company_name_from_db);
        $company_logo_url = htmlspecialchars($config['logo_url'] ?? $company_logo_url);
        $contact_name_from_db = htmlspecialchars($config['contact_name'] ?? $contact_name_from_db);
        $contact_email_from_db = htmlspecialchars($config['email'] ?? $contact_email_from_db);
        $contact_phone_from_db = htmlspecialchars($config['phone_primary'] ?? $contact_phone_from_db);
        $website_url_from_db = htmlspecialchars($config['website_url'] ?? $website_url_from_db);
    }
} catch (PDOException $e) {
    // En caso de error, la página usará los valores por defecto sin romperse.
    error_log("Error fetching website_config: " . $e->getMessage());
    // No se usa showToast aquí directamente desde PHP, se manejará en JS si es necesario.
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit | Creador De Propuestas De Proyectos | OrozDesign Multimedia</title>
    <meta name="description" content="Genera propuestas de proyectos profesionales para ganar nuevos clientes con el LocalCRM ToolKit.">
    <meta name="robots" content="noindex, nofollow">
    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">
    <?php include 'files/gtm-head.php'; ?>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>

    <style>
        /* Estilos específicos para los títulos de los pasos */
        .step-header h2 {
            /* Por defecto en móvil, los hacemos una columna */
            flex-direction: column;
            align-items: flex-start; /* Alinea los ítems a la izquierda cuando están en columna */
            justify-content: flex-start; /* Asegura que el h2 se alinee a la izquierda */
            text-align: left; /* Asegura que el texto en general se alinee a la izquierda */
        }

        .step-header .step-number {
            /* Contenedor para el icono y PASO 1: */
            font-size: 1.25rem; /* Ajuste para móvil: text-xl */
            font-weight: 900;
            margin-right: 0; /* No margin a la derecha cuando está en columna */
            margin-bottom: 0.25rem; /* Espacio vertical entre "PASO 1:" y el título */
            display: flex;
            align-items: center;
            color: var(--color-secondary);
            flex-shrink: 0;
            text-align: left; /* Asegura que el texto en esta span se alinee a la izquierda */
        }
        .step-header .step-number i {
            margin-right: 0.5rem;
            font-size: 1.5rem; /* Ajuste para icono en móvil */
        }

        .step-header .step-title {
            /* Contenedor para el título principal */
            font-size: 1.4rem; /* Ajuste para móvil, un poco más grande que step-number */
            font-weight: 900;
            color: #1e293b;
            line-height: 1.2;
            text-transform: uppercase;
            text-align: left; /* Asegura que el texto en esta span se alinee a la izquierda */
            width: 100%; /* Toma todo el ancho disponible */
        }

        /* Ajustes para pantallas más grandes (md: y superiores) */
        @media (min-width: 768px) {
            .step-header h2 {
                /* Vuelve a ser fila en desktop */
                flex-direction: row;
                align-items: center; /* Alinea los ítems al centro horizontalmente */
                justify-content: flex-start; /* Alinea todo el h2 al inicio */
                text-align: left;
            }
            .step-header .step-number {
                font-size: 1.5rem; /* O md:text-2xl si usas Tailwind directamente */
                margin-right: 0.5rem; /* Vuelve a tener margen a la derecha */
                margin-bottom: 0; /* Elimina el margen vertical */
                text-align: left;
            }
            .step-header .step-number i {
                font-size: 1.8rem; /* Tamaño del icono en desktop */
            }
            .step-header .step-title {
                font-size: 1.5rem; /* Vuelve a su tamaño de desktop */
                width: auto; /* Permite que el título ocupe solo el ancho necesario */
                text-align: left;
            }
        }
    </style>

</head>
<body data-page-title="Creador De Propuestas De Proyectos"
      data-page-subtitle="Genera Propuestas Profesionales Para Ganar Nuevos Clientes"
      data-page-icon="file-signature">

    <div id="toast-container" class="toast-container"></div>
        
<?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">

    <?php include 'menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <section id="proposal-generator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <div class="lg:col-span-3">
                        <form id="proposal-form" class="space-y-8 bg-white p-8 rounded-xl shadow-md">
                            <div>
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase justify-center md:justify-start">
                                        <span class="step-number"> <i class="fas fa-clipboard-list mr-3 text-[var(--color-secondary)]"></i>
                                            PASO 1:
                                        </span>
                                        <span class="step-title"> COMPLETA LOS DATOS
                                        </span>
                                    </h2>
                                    <p class="step-subtitle text-center md:text-left uppercase">Ingresa La Información Para Generar Tu Propuesta.</p>
                                </div>
                                <div class="border-b border-[var(--color-primary)] pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                            <div><label for="your_name" class="block font-bold capitalize text-gray-700 mb-2">Tu Nombre</label><input type="text" id="your_name" name="your_name" value="<?php echo $user_name_from_db; ?>" class="w-full p-3 bg-gray-100 border border-gray-300 rounded-lg" readonly></div>
                                            <div><label for="your_company" class="block font-bold capitalize text-gray-700 mb-2">Nombre De Tu Empresa</label><input type="text" id="your_company" name="your_company" value="<?php echo $company_name_from_db; ?>" class="w-full p-3 bg-gray-100 border border-gray-300 rounded-lg" readonly></div>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                            <div><label for="client_name" class="block font-bold capitalize text-gray-700 mb-2">Nombre Del Cliente</label><input type="text" id="client_name" name="client_name" placeholder="Ej: Ana García" class="w-full p-3 bg-white border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent" required></div>
                                            <div><label for="client_company" class="block font-bold capitalize text-gray-700 mb-2">Nombre De La Empresa Del Cliente</label><input type="text" id="client_company" name="client_company" placeholder="Ej: Repostería Creativa" class="w-full p-3 bg-white border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent"></div>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="space-y-6">
                                            <div><label for="project_name" class="block font-bold capitalize text-gray-700 mb-2">Descripción Del Proyecto</label><input type="text" id="project_name" name="project_name" placeholder="Ej: Desarrollo De Nuevo Sitio Web Ecommerce" class="w-full p-3 bg-white border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent" required></div>
                                            <div><label for="project_objective" class="block font-bold capitalize text-gray-700 mb-2">Objetivo Principal Del Proyecto</label><textarea id="project_objective" name="project_objective" placeholder="Ej: Crear Una Tienda Online Para Vender Postres" class="w-full p-3 bg-white border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent" rows="3" required></textarea></div>
                                            <div><label for="key_deliverables" class="block font-bold capitalize text-gray-700 mb-2">Entregables Clave (¿Qué Incluye?)</label><textarea id="key_deliverables" name="key_deliverables" placeholder="Ej: Diseño Web, Catálogo Virtual, Pasarela De Pagos." class="w-full p-3 bg-white border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent" rows="4" required></textarea></div>
                                            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                                                <div><label for="timeline" class="block font-bold capitalize text-gray-700 mb-2">Plazo Estimado</label><input type="text" id="timeline" name="timeline" placeholder="Ej: 4 Semanas" class="w-full p-3 bg-white border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent" required></div>
                                                <div><label for="price" class="block font-bold capitalize text-gray-700 mb-2">Inversión ($)</label><input type="number" step="0.01" id="price" name="price" placeholder="Ej: 2,500" class="w-full p-3 bg-white border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent" min="1" required></div>
                                                <div><label for="validity_period" class="block font-bold capitalize text-gray-700 mb-2">Validez</label><input type="text" id="validity_period" name="validity_period" placeholder="Ej: 15 Días" class="w-full p-3 bg-white border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent" required></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        <div class="bg-white rounded-xl shadow-md">
                            <div class="native-video-wrapper" id="videoWrapper">
                                <div class="play-overlay" id="playOverlay">
                                    <img src="https://placehold.co/600x337/07162d/ffc857?text=VIDEO" alt="Imagen de previsualización del video" class="absolute inset-0 w-full h-full object-cover rounded-xl">
                                    <i class="fas fa-play play-icon"></i>
                                </div>
                                <video class="w-full h-full object-cover" id="videoPlayer" controlslist="nodownload nofullscreen">
                                    <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                                    Tu navegador no soporta la etiqueta de video.
                                </video>
                            </div>
                        </div>
                        <div class="bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-md">
                            <div class="step-header">
                                <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase justify-center md:justify-start">
                                    <span class="step-number"> <i class="fas fa-book mr-3 text-[var(--color-highlight)]"></i>
                                    </span>
                                    <span class="step-title">
                                        INSTRUCCIONES
                                    </span>
                                </h2>
                                <p class="step-subtitle text-center md:text-left uppercase">REVISA ESTOS PUNTOS DETALLADAMENTE</p>
                            </div>
                            <div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <ul class="space-y-4 text-gray-700">
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-edit"></i></span><div><strong class="text-brand-dark">COMPLETA LOS DATOS:</strong> Rellena todos los campos para dar el contexto completo a la IA.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-rocket"></i></span><div><strong class="text-brand-dark">GENERA TU PROPUESTA:</strong> Obtén un texto profesional y persuasivo en segundos.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-copy"></i></span><div><strong class="text-brand-dark">COPIA Y PEGA EN LA PLANTILLA:</strong> Usa el botón para copiar el texto y pégalo en tu Google Doc.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-check-double"></i></span><div><strong class="text-brand-dark">ENVIA A TU PROSPECTO:</strong> Una propuesta profesional aumenta tus probabilidades de ganar el proyecto.</div></li>
                            </ul>
                        </div>
                    </div>

                    <div class="lg:col-span-5 bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-md mt-6">
                        <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase justify-center md:justify-start">
                                <span class="step-number"> <i class="fas fa-magic-wand-sparkles mr-3 text-[var(--color-secondary)]"></i>
                                    PASO 2:
                                </span>
                                <span class="step-title">
                                    GENERAR MI PROPUESTA
                                </span>
                            </h2>
                            <p class="step-subtitle text-center md:text-left uppercase">Obtén un texto profesional y persuasivo listo para ser enviado.</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                        <div class="flex flex-col md:flex-row items-center md:justify-between gap-4 md:gap-8 mb-6">
                            <p class="text-lg text-center md:text-left text-gray-700 md:flex-1 md:pr-4 mb-0">Una vez que completes todos los campos, haz clic en el botón. <strong class="font-black">CLIENT3 IA</strong> creará una propuesta formal y lista para ganar a ese nuevo cliente.</p>
                            <button id="generateBtn" type="submit" form="proposal-form" class="w-full md:w-auto bg-[var(--color-highlight)] text-brand-dark font-bold py-4 px-6 rounded-lg hover:scale-105 transition-transform shadow-lg text-lg flex items-center justify-center uppercase">
                                <i class="fas fa-brain mr-3"></i>
                                <span id="btn-text">Generar Propuesta De Proyecto</span>
                                <div id="loader-container" class="hidden ml-3"></div>
                            </button>
                        </div>
                    </div>

                    <div id="result-container" class="lg:col-span-5 mt-8"></div>
                </div>
            </section>
        </div>
    </main>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Inicialización del Toast desde URL parámetros (solo aquí, no en header-manager.js)
        const urlParams = new URLSearchParams(window.location.search);
        const notificationType = urlParams.get('notification_type');
        const notificationMessage = urlParams.get('notification_message');

        if (notificationType && notificationMessage) {
            if (typeof showToast === 'function') {
                showToast(notificationMessage, notificationType);
            } else {
                console.error("showToast function is not defined. Toast notification might not display.");
            }
        }

        const form = document.getElementById('proposal-form');
        const generateBtn = document.getElementById('generateBtn');
        const btnText = document.getElementById('btn-text');
        const loaderContainer = document.getElementById('loader-container');
        const resultContainer = document.getElementById('result-container');

        // Datos de la empresa pasados desde PHP para el PDF
        const companyData = {
            logoUrl: '<?php echo $company_logo_url; ?>',
            companyName: '<?php echo $company_name_from_db; ?>',
            contactName: '<?php echo $contact_name_from_db; ?>',
            email: '<?php echo $contact_email_from_db; ?>',
            phone: '<?php echo $contact_phone_from_db; ?>',
            website: '<?php echo $website_url_from_db; ?>'
        };

        lucide.createIcons();

        const videoPlayer = document.getElementById('videoPlayer');
        const playOverlay = document.getElementById('playOverlay');
        if (videoPlayer && playOverlay) {
            videoPlayer.controls = false;
            playOverlay.addEventListener('click', () => {
                playOverlay.style.display = 'none';
                videoPlayer.controls = true;
                videoPlayer.play().catch(e => showToast("Error al reproducir video: " + e.message, 'error')); // Replaced console.error
            });
            videoPlayer.addEventListener('ended', () => {
                playOverlay.style.display = 'flex';
                videoPlayer.controls = false;
            });
        }

        form.addEventListener('submit', async function(event) {
            event.preventDefault();

            btnText.textContent = 'Generando Propuesta De Proyecto...';
            loaderContainer.innerHTML = '<div class="w-6 h-6 border-4 border-t-transparent border-brand-dark rounded-full animate-spin"></div>';
            loaderContainer.classList.remove('hidden');
            generateBtn.disabled = true;
            resultContainer.innerHTML = '';

            const formData = {
                your_name: document.getElementById('your_name').value,
                your_company: document.getElementById('your_company').value,
                client_name: document.getElementById('client_name').value,
                client_company: document.getElementById('client_company').value,
                project_name: document.getElementById('project_name').value,
                project_objective: document.getElementById('project_objective').value,
                key_deliverables: document.getElementById('key_deliverables').value,
                timeline: document.getElementById('timeline').value,
                price: document.getElementById('price').value,
                validity_period: document.getElementById('validity_period').value
            };

            try {
                const response = await fetch('api/API-Creador-De-Propuestas-De-Proyectos.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData)
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || `El servidor respondió con un error ${response.status}.`);
                }

                const data = await response.json();
                if(data.error) {
                    throw new Error(data.error);
                }
                displayResult(data, formData); // Pass formData to displayResult for potential PDF generation context

            } catch (error) {
                // console.error("Error:", error); // Replaced
                let errorMessage = "No se pudieron generar los mensajes. Por favor, revisa los datos e inténtalo de nuevo.";

                try {
                    const jsonStartIndex = error.message.indexOf('{');
                    if (jsonStartIndex !== -1) {
                        const errorJsonString = error.message.substring(jsonStartIndex);
                        const errorDetails = JSON.parse(errorJsonString);
                        if (errorDetails.error && errorDetails.error.code === 503) {
                            errorMessage = "LO SENTIMOS En Este Momento, Nuestra Inteligencia Artificial Está Saturada. Por favor, Inténtalo De Nuevo En Unos Minutos.";
                        } else {
                            errorMessage += ` Detalles: ${error.message}`;
                        }
                    } else {
                        errorMessage += ` Detalles: ${error.message}`;
                    }
                } catch (parseError) {
                    errorMessage += ` Detalles: ${error.message}`;
                }

                resultContainer.innerHTML = `<div class="bg-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300"><p><strong>Error:</strong> ${errorMessage}</p></div>`;
                resultContainer.style.opacity = '1';
                showToast(errorMessage, 'error'); // Added toast
            } finally {
                btnText.textContent = 'Generar Propuesta De Proyecto';
                loaderContainer.classList.add('hidden');
                generateBtn.disabled = false;
            }
        });


        function displayResult(data, originalFormData) {
            // Store the generated proposals globally for PDF conversion
            window.proposals = {
                spanishProposal: data.proposal_spanish || "No se pudo generar la propuesta en español.",
                englishProposal: data.proposal_english || "Could not generate the proposal in English."
            };

            const formatTextForHtml = (text) => {
                let html = (text || '').replace(/\r\n/g, '\n');
                html = html.replace(/[\n\s]*\*(.*?)\*[\n\s]*/g, '<h3 class="text-xl font-bold text-brand-dark mt-8 mb-2">$1</h3>');
                html = html.replace(/\n/g, '<br>');
                return html;
            };

            resultContainer.innerHTML = `
                <div class="bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-xl animate-slideInUp ai-response">
                    <div class="mb-6 border-b border-gray-200">
                        <nav class="flex space-x-4 -mb-px" aria-label="Tabs">
                            <button id="tab-es" class="tab-button tab-active">🇪🇸 Propuesta En Español</button>
                            <button id="tab-en" class="tab-button">🇬🇧 Propuesta En Inglés</button>
                        </nav>
                    </div>

                    <div id="content-es" class="tab-content">
                        <div class="flex flex-col sm:flex-row justify-between items-center mb-4 gap-2 sm:gap-0">
                            <h3 class="text-xl font-black text-gray-800">Propuesta Personalizada Generada</h3>
                            <div class="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
                                <button class="copy-btn bg-blue-500 text-white px-4 py-2 rounded-lg font-semibold hover:bg-blue-600 transition-opacity flex items-center justify-center w-full sm:w-auto" data-lang="es"><i class="fas fa-copy mr-2"></i><span>COPIAR PROPUESTA</span></button>
                                <button id="download-pdf-btn" class="bg-green-500 text-white px-4 py-2 rounded-lg font-semibold hover:bg-green-600 transition-opacity flex items-center justify-center w-full sm:w-auto"><i class="fas fa-file-pdf mr-2"></i><span>DESCARGAR PDF</span></button>
                            </div>
                        </div>
                        <div class="proposal-text-container bg-gray-50 p-6 rounded-lg border border-gray-200 text-gray-700 leading-relaxed">${formatTextForHtml(window.proposals.spanishProposal)}</div>
                    </div>

                    <div id="content-en" class="tab-content hidden">
                        <div class="flex flex-col sm:flex-row justify-between items-center mb-4 gap-2 sm:gap-0">
                            <h3 class="text-xl font-black text-gray-800">Generated Personalized Proposal</h3>
                            <div class="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
                                <button class="copy-btn bg-blue-500 text-white px-4 py-2 rounded-lg font-semibold hover:bg-blue-600 transition-opacity flex items-center justify-center w-full sm:w-auto" data-lang="en"><i class="fas fa-copy mr-2"></i><span>COPY PROPOSAL</span></button>
                                <button id="download-pdf-btn-en" class="bg-green-500 text-white px-4 py-2 rounded-lg font-semibold hover:bg-green-600 transition-opacity flex items-center justify-center w-full sm:w-auto"><i class="fas fa-file-pdf mr-2"></i><span>DOWNLOAD PDF</span></button>
                            </div>
                        </div>
                        <div class="proposal-text-container bg-gray-50 p-6 rounded-lg border border-gray-200 text-gray-700 leading-relaxed">${formatTextForHtml(window.proposals.englishProposal)}</div>
                    </div>
                </div>`;
            setTimeout(() => { resultContainer.style.opacity = '1'; resultContainer.style.transform = 'scale(1)'; }, 100);

            // Tab functionality
            document.getElementById('tab-es').addEventListener('click', () => {
                document.getElementById('content-es').classList.remove('hidden');
                document.getElementById('content-en').classList.add('hidden');
                document.getElementById('tab-es').classList.add('tab-active');
                document.getElementById('tab-en').classList.remove('tab-active');
            });
            document.getElementById('tab-en').addEventListener('click', () => {
                document.getElementById('content-en').classList.remove('hidden');
                document.getElementById('content-es').classList.add('hidden');
                document.getElementById('tab-en').classList.add('tab-active');
                document.getElementById('tab-es').classList.remove('tab-active');
            });

            // Add event listeners for new copy buttons
            resultContainer.querySelectorAll('.copy-btn').forEach(button => {
                button.addEventListener('click', function() {
                    const textToCopy = (this.dataset.lang === 'es' ? window.proposals.spanishProposal : window.proposals.englishProposal);
                    navigator.clipboard.writeText(textToCopy).then(() => {
                        const span = this.querySelector('span');
                        const originalText = span.textContent;
                        span.textContent = '¡Copiado!';
                        showToast('Propuesta copiada al portapapeles.', 'success');
                        setTimeout(() => { span.textContent = originalText; }, 2000);
                    }).catch(err => {
                        console.error('Error al copiar el texto: ', err);
                        showToast('Error al copiar el texto.', 'error');
                    });
                });
            });

            // PDF generation listener (for Spanish proposal)
            const downloadPdfBtn = document.getElementById('download-pdf-btn');
            if (downloadPdfBtn) {
                downloadPdfBtn.addEventListener('click', () => generatePdf('es', originalFormData));
            }
            // PDF generation listener (for English proposal)
            const downloadPdfBtnEn = document.getElementById('download-pdf-btn-en');
            if (downloadPdfBtnEn) {
                downloadPdfBtnEn.addEventListener('click', () => generatePdf('en', originalFormData));
            }

        }
        
        // PDF generation logic (moved outside displayResult to be accessible for both languages)
        function generatePdf(lang, formData) {
            showToast(`Generando PDF en ${lang === 'es' ? 'español' : 'inglés'}...`, 'info');

            const proposalText = lang === 'es' ? window.proposals.spanishProposal : window.proposals.englishProposal;
            
            // Format the proposal text for PDF (replace *headings* and newlines)
            let formattedProposalText = (proposalText || '').replace(/\r\n/g, '\n');
            formattedProposalText = formattedProposalText.replace(/[\n\s]*\*(.*?)\*[\n\s]*/g, '\n\n$1\n\n'); // Use newlines for headings in PDF
            formattedProposalText = formattedProposalText.replace(/\n/g, '\n'); // Ensure consistent newlines

            // Reconstruct elements for PDF content
            const contentForPdf = `
                <div style="font-family: 'Barlow', sans-serif; padding: 40px; color: #1e293b;">
                    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 30px;">
                        <div>
                            <img src="${companyData.logoUrl}" alt="Logo" style="height: 50px; margin-bottom: 15px;">
                            <h2 style="font-size: 24px; font-weight: 900; color: #1e293b; margin: 0;">${companyData.companyName}</h2>
                            <p style="font-size: 14px; color: #4a5568; margin: 5px 0;">${companyData.contactName}</p>
                            <p style="font-size: 14px; color: #4a5568; margin: 5px 0;">${companyData.email}</p>
                            <p style="font-size: 14px; color: #4a5568; margin: 5px 0;">${companyData.phone}</p>
                            <p style="font-size: 14px; color: #4a5568; margin: 5px 0;">${companyData.website}</p>
                        </div>
                        <div style="text-align: right;">
                            <h1 style="font-size: 48px; font-weight: 900; color: #e2e8f0; letter-spacing: 2px; margin: 0;">PROPOSAL</h1>
                            <p style="font-size: 14px; color: #4a5568; margin: 5px 0;"><strong>Date:</strong> ${new Date().toLocaleDateString('es-ES')}</p>
                            <p style="font-size: 14px; color: #4a5568; margin: 5px 0;"><strong>Project:</strong> ${formData.project_name}</p>
                        </div>
                    </div>

                    <div style="background-color: #f7fafc; padding: 20px; border-radius: 8px; margin-bottom: 30px; border: 1px solid #e2e8f0;">
                        <h3 style="font-size: 14px; font-weight: 700; color: #4a5568; letter-spacing: 1px; margin-bottom: 10px; text-transform: uppercase;">PROPOSAL FOR:</h3>
                        <p style="font-size: 16px; font-weight: 600; color: #1e293b; margin: 5px 0;">${formData.client_name} ${formData.client_company ? `(${formData.client_company})` : ''}</p>
                    </div>

                    <div style="font-size: 16px; line-height: 1.6; color: #4a5568;">
                        ${formattedProposalText}
                    </div>

                    <div style="margin-top: 50px; text-align: center; font-size: 14px; color: #4a5568;">
                        <p>${lang === 'es' ? 'Gracias por considerar nuestra propuesta. ¡Esperamos trabajar juntos!' : 'Thank you for considering our proposal. We look forward to working together!'}</p>
                    </div>
                </div>
            `;
            
            // Create a temporary div to render the content for html2canvas
            const tempDiv = document.createElement('div');
            tempDiv.style.width = '816px'; // Letter size width at 96 DPI
            tempDiv.style.margin = '0 auto';
            tempDiv.style.padding = '32px'; // Adjust padding to match p-8
            tempDiv.style.boxSizing = 'border-box';
            tempDiv.style.backgroundColor = '#FFFFFF'; // Ensure background is white for PDF
            tempDiv.innerHTML = contentForPdf;
            document.body.appendChild(tempDiv); // Append to body to render

            html2canvas(tempDiv, {
                scale: 2, // Higher scale for better quality
                useCORS: true,
                width: 816 // Explicitly set capture width
            }).then(canvas => {
                document.body.removeChild(tempDiv); // Remove temporary div

                const imgData = canvas.toDataURL('image/png');
                const pdf = new window.jspdf.jsPDF({ orientation: 'portrait', unit: 'pt', format: 'letter' }); // Use window.jspdf.jsPDF
                const pdfWidth = pdf.internal.pageSize.getWidth();
                const pdfHeight = pdf.internal.pageSize.getHeight();
                
                const imgHeight = (canvas.height * pdfWidth) / canvas.width;
                let heightLeft = imgHeight;
                let position = 0;

                pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, imgHeight);
                heightLeft -= pdfHeight;

                while (heightLeft >= 0) {
                    position = heightLeft - imgHeight;
                    pdf.addPage();
                    pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, imgHeight);
                    heightLeft -= pdfHeight;
                }

                const fileName = `${formData.client_name.replace(/\s+/g, '_')}_${formData.project_name.replace(/\s+/g, '_')}_${lang === 'es' ? 'Propuesta' : 'Proposal'}.pdf`;
                pdf.save(fileName);
                showToast(`PDF de la propuesta en ${lang === 'es' ? 'español' : 'inglés'} generado.`, 'success');

            }).catch(err => {
                document.body.removeChild(tempDiv); // Ensure removal even on error
                console.error("Error al generar PDF:", err);
                showToast('Error al generar el PDF de la propuesta.', 'error');
            });
        }
    });
</script>

</body>
</html>