<?php include 'files/guardiankey.php'; ?>
<?php
// =================================================================
//        DATA BLOCK FOR FORM PRE-FILLING (Best Practice)
// =================================================================

// 1. Include the central business information file.
//    This creates the $client_info variable with all the data.
include __DIR__ . '/client-information.php';

// 2. Assign info to easy-to-use variables for this form.
//    Using English names for consistency with the database and array keys.
$client_name       = $client_info['name'] ?? '';
$business_name     = $client_info['business_name'] ?? '';
$phone             = $client_info['phone'] ?? '';
$whatsapp          = $client_info['whatsapp'] ?? '';
$email             = $client_info['email'] ?? '';
$website           = $client_info['website'] ?? '';
$operating_cities  = $client_info['operating_cities'] ?? '';
$value_proposition = $client_info['value_proposition'] ?? '';
$logo_url          = $client_info['logo_url'] ?? '';

// Social links come as an array, hence the '?? []' fallback.
$social_links      = $client_info['social_links'] ?? [];

// =================================================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Creador De Propuestas De Proyectos Con IAMarketing™ Powered By OrozCO</title>
    <meta name="description" content="Genera Propuestas Profesionales Para Ganar Nuevos Clientes">
    <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>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>
</head>
<body data-page-title="Creador De Propuestas De Proyectos"
      data-page-subtitle="Genera Propuestas Profesionales Para Ganar Nuevos Clientes"
      data-page-icon="brain">

    <div id="toast-container" class="toast-container"></div>

    <?php include 'files/gtm-body.php'; ?>

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

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'ia-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">
                            <input type="hidden" name="value_proposition" value="<?php echo htmlspecialchars($value_proposition); ?>">
                            <div>
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                        <i data-lucide="clipboard-list" class="mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> Define Los Detalles De Tu Proyecto
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa la información detallada para generar tu propuesta de proyecto.</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>
                                <div class="space-y-6">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div><label for="your_name" class="block text-lg font-bold capitalize text-gray-700 mb-2">Tu Nombre</label><input type="text" id="your_name" name="your_name" placeholder="Ej: Juan Perez" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($client_name); ?>"></div>
                                        <div><label for="your_company" class="block text-lg font-bold capitalize text-gray-700 mb-2">Nombre De Tu Empresa</label><input type="text" id="your_company" name="your_company" placeholder="Ej: Agencia Digital Orozco" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($business_name); ?>"></div>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div><label for="client_name" class="block text-lg 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-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required></div>
                                        <div><label for="client_company" class="block text-lg 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-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]"></div>
                                    </div>
                                    <div>
                                        <label for="project_name" class="block text-lg 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-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                    </div>
                                    <div>
                                        <label for="project_objective" class="block text-lg 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-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" rows="3" required></textarea>
                                    </div>
                                    <div>
                                        <label for="key_deliverables" class="block text-lg 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-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" rows="4" required></textarea>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                                        <div><label for="timeline" class="block text-lg 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-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required></div>
                                        <div><label for="price" class="block text-lg 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-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" min="1" required></div>
                                        <div><label for="validity_period" class="block text-lg 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-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required></div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        <img src="img/VideoLeccion.png" alt="VideoLeccion - IAMarketing">
                        <div class="w-full">
                                <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                                    <div class="relative w-full" style="padding-bottom: 56.25%;">
                                        <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayer" controls controlslist="nodownload fullscreen" preload="metadata">
                                            <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                                            TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                                        </video>
                                        <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                                            <img src="img/VideoLeccion-IAMarketing.jpg" alt="VideoLeccion - IAMarketing" class="absolute inset-0 w-full h-full object-cover">
                                            <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                                            <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                                        </div>
                                    </div>
                                    <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="play-circle" class="w-4 h-4"></i> Video De Introducción A La Plataforma SiteFlowCMS
                                        </span>
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="clock" class="w-4 h-4"></i> 2–3 min
                                        </span>
                                    </div>
                                </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">
                                    <i data-lucide="book-open" class="mr-3 text-[var(--color-highlight)]"></i>
                                    <span class="step-title">INSTRUCCIONES IMPORTANTES</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 data-lucide="file-edit"></i></span><div><strong class="text-brand-dark uppercase">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 data-lucide="rocket"></i></span><div><strong class="text-brand-dark uppercase">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 data-lucide="copy"></i></span><div><strong class="text-brand-dark uppercase">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 data-lucide="send"></i></span><div><strong class="text-brand-dark uppercase">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 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">
                                <i data-lucide="zap" class="mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> Recibe Tu Propuesta Profesional
                            </h2>
                            <p class="step-subtitle uppercase">Obtén una propuesta profesional y persuasiva para presentar tu servicio</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">
                            <p class="text-lg text-center md:text-left text-gray-700 md:flex-1 md:pr-4 mb-0">Para ganar nuevos clientes, <strong>es importante</strong> que tu propuesta para nuevos proyectos se vea profesional. Nuestra Inteligencia Artificial <strong>IA Marketing</strong> generará tus <strong>Propuestas De Proyectos</strong>, para que presentes propuestas profesionales y consigas cerrar más proyectos</p>
                         <div class="flex flex-col items-center">
                            <i data-lucide="brain" class="w-12 h-12 text-[var(--color-primary)] mb-2"></i>
                             <button id="generateBtn" type="submit" form="proposal-form" class="w-full md:w-auto bg-[var(--color-highlight)] text-[var(--color-primary)] font-bold py-4 px-6 rounded-lg hover:scale-105 transition-transform shadow-lg text-lg flex items-center justify-center gap-2 uppercase">
                               <span id="btn-text">GENERAR CON IA MARKETING</span>
                               <i data-lucide="mouse-pointer-click" class="w-6 h-6 animate-bounce"></i>
                               <div id="loader-container" class="hidden ml-3"></div>
                             </button>
                        </div>
                         </div>
                    </div>

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

<script type="module">
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    // MENU MOBILE
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');

    mobileMenuButton.addEventListener('click', () => {
        sidebar.classList.toggle('-translate-x-full');
        sidebarOverlay.classList.toggle('hidden');
    });

    sidebarOverlay.addEventListener('click', () => {
        sidebar.classList.add('-translate-x-full');
        sidebarOverlay.classList.add('hidden');
    });

    // NOTIFICACIONES TOAST
    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.");
        }
    }
    
    // VIDEO PLAYER
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');
    
    if (playOverlay && videoPlayer) {
        videoPlayer.controls = false;
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.controls = true;
            videoPlayer.play().catch(e => {
                if (typeof showToast === 'function') {
                    showToast("Error al reproducir video: " + e.message, 'error');
                }
            });
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }
    
    // MASCARA DEL TELEFONO
    const phoneInput = document.getElementById('contact_phone');
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }
    
    const form = document.getElementById('proposal-form');
    const generateBtn = document.getElementById('generateBtn');
    const resultContainer = document.getElementById('result-container');

    function validateForm() {
        const requiredInputs = form.querySelectorAll('[required]');
        let allValid = true;
        requiredInputs.forEach(input => {
            if (!input.value.trim() || (input.tagName === 'SELECT' && input.value === '')) {
                input.classList.add('border-red-500');
                allValid = false;
            } else {
                input.classList.remove('border-red-500');
            }
        });

        const formErrorMessage = document.getElementById('form-error-message');
        if (!allValid) {
            if (formErrorMessage) formErrorMessage.classList.remove('hidden');
            if (typeof showToast === 'function') {
                showToast('Por favor, completa todos los campos requeridos.', 'warning');
            }
        } else {
            if (formErrorMessage) formErrorMessage.classList.add('hidden');
        }
        return allValid;
    }

    function setProcessingState(isProcessing) {
        const btnText = document.getElementById('btn-text');
        const loaderContainer = document.getElementById('loader-container');
        
        if (isProcessing) {
            loaderContainer.innerHTML = '<div class="w-6 h-6 border-4 border-t-transparent border-[var(--color-primary)] rounded-full animate-spin"></div>';
            loaderContainer.classList.remove('hidden');
            generateBtn.disabled = true;
            generateBtn.classList.add('opacity-50', 'cursor-not-allowed');
            resultContainer.innerHTML = '';
            
            const messages = ["Contactando Con OrozCO IA...", "Analizando Tu Proyecto...", "Redactando La Propuesta...", "Casi Está Lista..."];
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];
            
            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);

        } else {
            if (window.loadingInterval) {
                clearInterval(window.loadingInterval);
            }
            btnText.textContent = 'Generar Propuesta De Proyecto';
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
            generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        }
    }

    form.addEventListener('submit', async function(event) {
        event.preventDefault();
        
        if (!validateForm()) {
            return;
        }
        
        setProcessingState(true);

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

            const data = await response.json();
            if (!response.ok) {
                throw new Error(data.error || `Error del servidor: ${response.status}`);
            }
            
            displayResult(data);

        } catch (error) {
            let errorMessage = error.message || "No se pudo generar la propuesta. Inténtalo de nuevo.";
            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';
            if (typeof showToast === 'function') {
                showToast(errorMessage, 'error');
            }
        } finally {
            setProcessingState(false);
        }
    });

    function displayResult(data) {
        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').trim();
            html = html.replace(/\n/g, '<br>');
            return html;
        };

        resultContainer.innerHTML = `
            <div class="ai-response p-6 md:p-8 rounded-xl shadow-xl">
                <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-start mb-4 gap-2">
                        <h3 class="text-2xl font-black text-gray-800 flex items-center"><i data-lucide="file-text" class="mr-2 text-[var(--color-secondary)]"></i>Propuesta Personalizada</h3>
                        <button class="btn-copy mt-3" data-lang="es">
                            <i data-lucide="copy"></i><span class="copy-text">Copiar Propuesta</span>
                        </button>
                    </div>
                    <div class="proposal-text-container message-box">${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-start mb-4 gap-2">
                        <h3 class="text-2xl font-black text-gray-800 flex items-center"><i data-lucide="file-text" class="mr-2 text-[var(--color-secondary)]"></i>Generated Personalized Proposal</h3>
                        <button class="btn-copy mt-3" data-lang="en">
                            <i data-lucide="copy"></i><span class="copy-text">Copy Proposal</span>
                        </button>
                    </div>
                    <div class="proposal-text-container message-box">${formatTextForHtml(window.proposals.englishProposal)}</div>
                </div>
            </div>`;
            
        lucide.createIcons();

        const tabEs = document.getElementById('tab-es');
        const tabEn = document.getElementById('tab-en');
        const contentEs = document.getElementById('content-es');
        const contentEn = document.getElementById('content-en');

        if (tabEs && tabEn && contentEs && contentEn) {
            tabEs.addEventListener('click', () => {
                contentEs.classList.remove('hidden');
                contentEn.classList.add('hidden');
                tabEs.classList.add('tab-active');
                tabEn.classList.remove('tab-active');
                lucide.createIcons();
            });
            tabEn.addEventListener('click', () => {
                contentEn.classList.remove('hidden');
                contentEs.classList.add('hidden');
                tabEn.classList.add('tab-active');
                tabEs.classList.remove('tab-active');
                lucide.createIcons();
            });
        }
        
        resultContainer.querySelectorAll('.btn-copy').forEach(button => {
            button.addEventListener('click', function() {
                const textToCopy = (this.dataset.lang === 'es' ? window.proposals.spanishProposal : window.proposals.englishProposal)
                    .replace(/<br\s*\/?>/gi, '\n')
                    .replace(/<h3.*?>/gi, '\n\n')
                    .replace(/<\/h3>/gi, '\n\n')
                    .trim();

                navigator.clipboard.writeText(textToCopy).then(() => {
                    const originalHTML = button.innerHTML;
                    button.innerHTML = '<i data-lucide="check" class="mr-2"></i><span>¡Copiado!</span>';
                    lucide.createIcons({ nodes: [button] });
                    if (typeof showToast === 'function') {
                        showToast('Propuesta copiada al portapapeles.', 'success');
                    }
                    setTimeout(() => { 
                        button.innerHTML = originalHTML; 
                        lucide.createIcons({ nodes: [button] });
                    }, 2000);
                }).catch(err => {
                    console.error('Error al copiar el texto: ', err);
                    if (typeof showToast === 'function') {
                        showToast('Error al copiar el texto.', 'error');
                    }
                });
            });
        });

        resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
});
</script>
</body>
</html>