<?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 Propuesta De Valor Comercial Con IAMarketing™ Powered By OrozCO</title>
    <meta name="description" content="Crea Una Propuesta De Valor Impresionante Para Tu Negocio">
    <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 Propuesta De Valor Comercial"
      data-page-subtitle="Crea Una Propuesta De Valor Impresionante Para Tu Negocio"
      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-tool" 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">
                                            <span class="step-number"> <i data-lucide="lightbulb" class="mr-3 text-[var(--color-secondary)]"></i> PASO 1:
                                            </span>
                                            <span class="step-title"> Describe Tu Negocio y Cliente Ideal
                                            </span>
                                        </h2>
                                        <p class="step-subtitle uppercase">Ingresa los datos para que la IA entienda tu negocio</p>
                                    </div>
                                    <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                    <div class="space-y-6">
                                        <div class="form-group">
                                            <label for="business-name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre del Negocio:</label>
                                            <input type="text" id="business-name" name="businessName" placeholder="Ej: Rod Cleaning Services" 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 class="form-group">
                                            <label for="client-types" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tipo de Clientes (separados por comas):</label>
                                            <input type="text" id="client-types" name="clientTypes" placeholder="Ej: Profesionales Ocupados, Familias Con Hijos, Jubilados" 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 class="form-group">
                                            <label for="cities" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Ciudades donde Trabaja (separadas por comas):</label>
                                            <input type="text" id="cities" name="cities" placeholder="Ej: Miami, Orlando, Tampa" 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($operating_cities); ?>">
                                        </div>
                                        <div class="form-group">
                                            <label for="business-description" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Descripción del Negocio (Mínimo 250 caracteres):</label>
                                            <textarea id="business-description" name="businessDescription" rows="6" placeholder="Qué Hace Tu Negocio, Qué Problemas Resuelve, Etc." minlength="250" maxlength="1500" 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></textarea>
                                            <div class="char-count text-right text-sm text-gray-500 mt-1" id="description-char-count">0 / 1500 Caracteres</div>
                                            <div class="error-message text-red-500 text-sm mt-1" id="description-error"></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="lightbulb"></i></span><div><strong class="text-brand-dark uppercase">DESCRIPCIÓN CLARA:</strong> Cuanto más detalles des sobre tu negocio, sus problemas y soluciones, mejor serán las propuestas.</div></li>
                                    <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="bot"></i></span><div><strong class="text-brand-dark uppercase">GENERA Y PERFECCIONA:</strong> La IA te proporcionará dos opciones de propuestas. Revísalas y ajústalas para tu toque personal.</div></li>
                                    <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="handshake"></i></span><div><strong class="text-brand-dark uppercase">IMPRESIONA A TUS CLIENTES:</strong> Una propuesta de valor clara y concisa te ayudará a captar la atención y cerrar más ventas.</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">
                                    <span class="step-number"> <i data-lucide="target" class="mr-3 text-[var(--color-secondary)]"></i>
                                        PASO 2:
                                    </span>
                                    <span class="step-title">
                                        Genera tu Propuesta de Valor
                                    </span>
                                </h2>
                                <p class="step-subtitle uppercase">Crea tu propuesta estratégica y persuasiva para tu negocio</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 crear una propuesta que conecte con tu cliente, <b>es importante</b> tener información clara de tu negocio. Con esa base, nuestra Inteligencia Artificial <b>IA Marketing</b> Generará tu <b>Propuesta De Valor</b> persuasiva, para que tengas un texto que realmente te ayude a vender y a destacar</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();
    
    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');
    });

    const urlParams = new URLSearchParams(window.location.search);
    const notificationType = urlParams.get('notification_type');
    const notificationMessage = urlParams.get('notification_message');

    if (notificationType && notificationMessage && typeof showToast === 'function') {
        showToast(notificationMessage, notificationType);
    }
    
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');
    
    if(playOverlay && videoPlayer) {
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.play();
        });
    }
    
    const phoneInput = document.getElementById('contact_phone');
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }

    const proposalForm = document.getElementById('proposal-form');
    const resultContainer = document.getElementById('result-container');
    const generateProposalBtn = document.getElementById('generate-proposal-btn');
    const btnText = generateProposalBtn.querySelector('span');
    const loaderContainer = document.getElementById('loader-container');
    const businessDescriptionInput = document.getElementById('business-description');
    const descriptionCharCount = document.getElementById('description-char-count');
    const descriptionError = document.getElementById('description-error');

    businessDescriptionInput.addEventListener('input', function() {
        const currentLength = this.value.length;
        descriptionCharCount.textContent = `${currentLength} / ${this.maxLength} Caracteres`;
        descriptionError.textContent = currentLength < this.minLength ? `Mínimo ${this.minLength} caracteres.` : '';
    });

function setProcessingState(isProcessing) {
    const btnText = document.getElementById('btn-text');
    const loaderContainer = document.getElementById('loader-container');
    const generateProposalBtn = document.getElementById('generate-proposal-btn');
    
    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');
        generateProposalBtn.disabled = true;
        generateProposalBtn.classList.add('opacity-50', 'cursor-not-allowed');
        resultContainer.innerHTML = '';
        
        const messages = ["Contactando Con OrozCO IA...", "Analizando Tu Negocio...", "Redactando Propuestas...", "Casi Esta Listo..."];
        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 Otras Propuestas';
        loaderContainer.classList.add('hidden');
        generateProposalBtn.disabled = false;
        generateProposalBtn.classList.remove('opacity-50', 'cursor-not-allowed');
    }
}

    proposalForm.addEventListener('submit', async function(event) {
        event.preventDefault();
        if (!proposalForm.checkValidity() || businessDescriptionInput.value.length < businessDescriptionInput.minLength) {
            proposalForm.reportValidity();
            showToast('Por favor, completa todos los campos requeridos correctamente.', 'error');
            return;
        }

        setProcessingState(true);

        const formData = {
            purpose: 'generate_proposal',
            businessName: document.getElementById('business-name').value,
            clientTypes: document.getElementById('client-types').value,
            cities: document.getElementById('cities').value,
            businessDescription: document.getElementById('business-description').value
        };

        try {
            const response = await fetch('api/api-propuesta-de-valor.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                body: JSON.stringify(formData)
            });
            const data = await response.json();
            if (response.ok) {
                if (data.option1_es && data.option2_es) {
                    displayResult(data);
                    showToast('¡Propuesta de valor generada con éxito!', 'success');
                } else {
                    showToast(`Error: ${data.error || 'La IA no devolvió un formato válido.'}`, 'error');
                }
            } else {
                showToast(`Error del servidor: ${data.error || 'Error desconocido'}`, 'error');
            }
        } catch (error) {
            console.error('Error en la llamada a la API:', error);
            showToast('Error en la conexión con el servidor de IA.', 'error');
        } finally {
            setProcessingState(false);
        }
    });

   function displayResult(data) {
        resultContainer.innerHTML = `
            <div class="ai-response p-6 md:p-8 rounded-xl shadow-md space-y-8">
                <h3 class="text-2xl font-bold text-gray-800 mb-6 flex items-center"><i data-lucide="bullseye" class="mr-3 text-[var(--color-primary)]"></i> Propuestas de Valor Generadas</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="proposal-option-card">
                        <h3 class="text-[var(--color-primary)]"><i data-lucide="tag" class="mr-2"></i>Opción 1</h3>
                        <div class="mb-4">
                            <h4 class="text-lg font-semibold text-gray-700 mb-2">🇪🇸 Español:</h4>
                            <div class="message-box">${data.option1_es.replace(/\n/g, '<br>')}</div>
                            <div class="copy-btn-wrapper"><button class="btn-copy" data-copytarget-text="${encodeURIComponent(data.option1_es)}"><i data-lucide="copy"></i><span class="copy-text">Copiar</span></button></div>
                        </div>
                        <div>
                            <h4 class="text-lg font-semibold text-gray-700 mb-2">🇺🇸 English:</h4>
                            <div class="message-box">${data.option1_en.replace(/\n/g, '<br>')}</div>
                            <div class="copy-btn-wrapper"><button class="btn-copy" data-copytarget-text="${encodeURIComponent(data.option1_en)}"><i data-lucide="copy"></i><span class="copy-text">Copiar</span></button></div>
                        </div>
                    </div>
                    <div class="proposal-option-card">
                        <h3 class="text-[var(--color-primary)]"><i data-lucide="tag" class="mr-2"></i>Opción 2</h3>
                        <div class="mb-4">
                            <h4 class="text-lg font-semibold text-gray-700 mb-2">🇪🇸 Español:</h4>
                            <div class="message-box">${data.option2_es.replace(/\n/g, '<br>')}</div>
                            <div class="copy-btn-wrapper"><button class="btn-copy" data-copytarget-text="${encodeURIComponent(data.option2_es)}"><i data-lucide="copy"></i><span class="copy-text">Copiar</span></button></div>
                        </div>
                        <div>
                            <h4 class="text-lg font-semibold text-gray-700 mb-2">🇺🇸 English:</h4>
                            <div class="message-box">${data.option2_en.replace(/\n/g, '<br>')}</div>
                            <div class="copy-btn-wrapper"><button class="btn-copy" data-copytarget-text="${encodeURIComponent(data.option2_en)}"><i data-lucide="copy"></i><span class="copy-text">Copiar</span></button></div>
                        </div>
                    </div>
                </div>
            </div>`;
        
        lucide.createIcons();

        setTimeout(() => {
            resultContainer.style.opacity = '1';
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);

        resultContainer.querySelectorAll('.btn-copy').forEach(button => {
            button.addEventListener('click', function() {
                const textToCopy = decodeURIComponent(this.dataset.copytargetText);
                navigator.clipboard.writeText(textToCopy).then(() => {
                    const buttonContent = this;
                    const originalHTML = buttonContent.innerHTML;
                    buttonContent.innerHTML = '<i data-lucide="check"></i><span class="copy-text">Copiado</span>';
                    lucide.createIcons();
                    buttonContent.classList.add('copied');
                    showToast('Propuesta copiada al portapapeles.', 'success');
                    setTimeout(() => {
                        buttonContent.innerHTML = originalHTML;
                        buttonContent.classList.remove('copied');
                        lucide.createIcons({ nodes: [buttonContent] });
                    }, 2000);
                }).catch(err => {
                    console.error('Error al copiar:', err);
                    showToast('No se pudo copiar el texto.', 'error');
                });
            });
        });
    }
});
</script>

</body>
</html>