<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
require_once 'ia-marketing-results.php';
require_once 'media/videos-ia.php';

$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'] ?? '';
$logo_url = $client_info['logo_url'] ?? '';
$value_proposition = $ia_results['value_proposition'] ?? '';
$current_client_profiles = $ia_results['ideal_client_profiles'] ?? [];
$social_links = $client_info['social_links'] ?? [];

if (ob_get_level() > 0) { ob_end_clean(); }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Traductor De Inglés Inteligente Con <?php echo htmlspecialchars($branding['iamarketing_name']); ?> Powered_by <?php echo htmlspecialchars($branding['powered_by']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></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="Traductor De Inglés Inteligente"
      data-page-subtitle="Traduce Textos A Inglés Con Enfoque En Marketing Y Ventas"
      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="translator-tool" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <div class="lg:col-span-3">
                        <form id="translator-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="scan" class="mr-3 text-[var(--color-secondary)]"></i>
                                            PASO 1:
                                        </span>
                                        <span class="step-title"> Define Tu Texto y Estrategia
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Introduce el texto para traducirlo con enfoque en marketing</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="ad_text_es" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Texto En Español</label>
                                        <textarea id="ad_text_es" name="ad_text_es" placeholder="Pega Tu Mensaje, Email, Publicación o Anuncio..." 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="8" required></textarea>
                                    </div>
                                    <div>
                                        <label for="translation_type" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tipo De Traducción</label>
                                        <select id="translation_type" name="translation_type" 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>
                                            <option value="">Selecciona El Tipo De Traducción</option>
                                            <option value="Estrategica">Estratégica (Optimizada Para Marketing)</option>
                                            <option value="Literal">Literal (Traducción Exacta, Sin Alteraciones)</option>
                                        </select>
                                    </div>
                                    <div id="translation-tone-wrapper">
                                        <label for="translation_tone" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tono De Traducción Deseado</label>
                                        <select id="translation_tone" name="translation_tone" 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>
                                            <option value="">Selecciona Un Tono</option>
                                            <option value="Profesional y Formal">Profesional y Formal</option>
                                            <option value="Amigable y Cercano">Amigable y Cercano</option>
                                            <option value="Persuasivo y Vendedor">Persuasivo y Vendedor</option>
                                            <option value="Directo y Conciso">Directo y Conciso</option>
                                            <option value="Creativo y Original">Creativo y Original</option>
                                            <option value="Empático y Comprensivo">Empático y Comprensivo</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div id="form-error-message" class="hidden bg-[var(--color-secondary)] text-center p-3 text-white rounded-lg border border-[var(--color-secondary)]" role="alert">
                                Por Favor, Completa Todos Los Campos Requeridos.
                            </div>
                          <input type="hidden" name="value_proposition" value="<?php echo htmlspecialchars($value_proposition); ?>">
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        
                        <?php if (!empty($logo_url)): ?>
                            <div class="bg-white p-4 rounded-xl shadow-md">
                                <img src="<?php echo htmlspecialchars($logo_url); ?>" 
                                     alt="Logotipo de <?php echo htmlspecialchars($business_name); ?>" 
                                     class="block mx-auto" 
                                     style="max-width: 250px;">
                            </div>
                        <?php endif; ?>

                           <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 Tutorial
                                        </span>
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="clock" class="w-4 h-4"></i> 2:30 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="edit"></i></span><div><strong class="text-brand-dark uppercase">PEGA EL TEXTO COMPLETO:</strong> Introduce el mensaje completo para una traducción contextualizada.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="wrench"></i></span><div><strong class="text-brand-dark uppercase">TRADUCE CON ESTRATEGIA:</strong> La IA optimizará tu texto para el mercado inglés.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="lightbulb"></i></span><div><strong class="text-brand-dark uppercase">NOTAS INTELIGENTES:</strong> Recibirás consejos para maximizar el impacto de tu traducción.</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:</strong> Utiliza la traducción directamente en tus comunicaciones.</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="sparkles" class="mr-3 text-[var(--color-secondary)]"></i>
                                    PASO 2:
                                </span>
                                <span class="step-title">
                                    Obtén Tu Traducción Estratégica
                                </span>
                            </h2>
                            <p class="step-subtitle uppercase">Obtén una versión optimizada de tu texto en inglés con notas inteligentes.</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                        
<div class="grid grid-cols-1 md:grid-cols-3 gap-6 md:gap-8 items-center">

    <div class="flex flex-col justify-center items-center bg-[var(--color-primary)] p-6 rounded-xl">
        <i data-lucide="brain" class="w-24 h-24 md:w-32 md:h-32 text-white animate-pulse"></i>
        <p class="mt-4 text-white font-black text-xl uppercase tracking-wide">
            IA<span class="text-[var(--color-highlight)]">Marketing</span>™
        </p>
    </div>

    <div class="md:col-span-2 text-center md:text-left">
        
        <h3 class="text-2xl font-black text-gray-800 flex items-center justify-center md:justify-start mb-2 uppercase">
            <i data-lucide="bell-electric" class="w-6 h-6 text-[var(--color-secondary)] mr-2 flex-shrink-0"></i>
            Información Importante
        </h3>
        
        <p class="text-lg text-gray-700 mb-6">
            Para comunicarte con fluidez y persuasión, <b>únicamente</b> pega el texto completo en la casilla. Nuestra <b>inteligencia artificial</b> hará una <b>Traducción Al Inglés Inteligente</b>, con un enfoque en marketing y ventas que realmente sea persuasivo.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="translator-form" class="w-full sm:w-auto bg-[var(--color-highlight)] text-[var(--color-primary)] font-black py-4 px-6 rounded-lg hover:scale-105 transition-transform text-lg flex items-center justify-center uppercase">
                
                <i data-lucide="arrow-big-right-dash" class="w-6 h-6"></i>
                
                <span id="btn-text">TRADUCIR TUS TEXTOS CON IA</span>
                
                <div id="loader-container" class="hidden ml-3"></div>
            </button>
        </div>
    </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 form = document.getElementById('translator-form');
    const resultContainer = document.getElementById('result-container');
    const generateBtn = document.getElementById('generateBtn');
    const btnText = document.getElementById('btn-text');
    const loaderContainer = document.getElementById('loader-container');
    const formErrorMessage = document.getElementById('form-error-message');
    const translationTypeSelect = document.getElementById('translation_type');
    const translationToneWrapper = document.getElementById('translation-tone-wrapper');

    function toggleTranslationTone() {
        if (translationTypeSelect.value === 'Estrategica') {
            translationToneWrapper.style.display = 'block';
            translationToneWrapper.querySelector('select').setAttribute('required', 'true');
        } else {
            translationToneWrapper.style.display = 'none';
            translationToneWrapper.querySelector('select').removeAttribute('required');
            translationToneWrapper.querySelector('select').value = '';
        }
    }

    translationTypeSelect.addEventListener('change', toggleTranslationTone);
    toggleTranslationTone();

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

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

    function setProcessingState(isProcessing) {
        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 = '';
            resultContainer.style.opacity = '0';
            resultContainer.style.transform = 'scale(0.95)';

            const messages = ["Contactando Con OrozCO IA...", "Analizando Texto...", "Adaptando Tono...", "Generando Traducción...", "Casi Está 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);
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
            generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            btnText.textContent = 'TRADUCIR TEXTOS';
        }
    }

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

        setProcessingState(true);

        const formData = {
            ad_text_es: document.getElementById('ad_text_es').value,
            translation_type: translationTypeSelect.value,
            translation_tone: document.getElementById('translation_tone').value,
        };

        try {
            const response = await fetch('api/api-traductor-ingles-inteligente.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                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, translationTypeSelect.value);
            if (typeof showToast === 'function') {
                showToast('¡Traducción generada con éxito!', 'success');
            }

        } catch (error) {
            console.error("Error:", error);
            let errorMessage = "No se pudo generar la traducción. Por favor, revisa el texto 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-[var(--color-secondary)] text-center p-4 text-white rounded-lg border border-[var(--color-secondary)]"><p><strong>Error:</strong> ${errorMessage}</p></div>`;
            resultContainer.style.opacity = '1';
            if (typeof showToast === 'function') {
                showToast(errorMessage, 'error');
            }
        } finally {
            setProcessingState(false);
        }
    });

    function displayResult(data, translationType) {
        let notesHtml = '';
        if (translationType === 'Estrategica' && data.notas && data.notas.length > 0) {
            notesHtml = `
                <div class="border-t border-gray-200 pt-8">
                    <h3 class="ad-title text-xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="lightbulb" class="mr-3 text-[var(--color-highlight)]"></i>Notas Del Traductor Inteligente</h3>
                    <ul class="action-plan-list mt-4 space-y-3">
                        ${data.notas.map(n => `
                            <li class="action-plan-item bg-gray-50 p-3 rounded-md border border-gray-200 shadow-sm flex items-start">
                                <span class="icon-wrapper mt-1 mr-3"><i data-lucide="check-circle" class="text-[var(--color-highlight)]"></i></span>
                                <div class="flex-1 text-gray-700">${n}</div>
                            </li>
                        `).join('')}
                    </ul>
                </div>
            `;
        }

        resultContainer.innerHTML = `
            <div class="ai-response p-6 md:p-8 rounded-xl shadow-md space-y-8">
                <div>
                    <h3 class="ad-title text-xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="flag" class="mr-3 text-[var(--color-primary)]"></i>Versión ${translationType === 'Literal' ? 'Literal' : 'Estratégica'} En Inglés</h3>
                    <div class="relative mt-4">
                        <textarea readonly class="w-full h-64 p-4 bg-gray-100 text-gray-800 font-medium rounded-lg resize-none leading-relaxed text-lg border border-gray-300">${data.traduccion}</textarea>
                        <div class="absolute bottom-4 right-4">
                            <button class="btn-copy" data-copy-text="${encodeURIComponent(data.traduccion)}"><i data-lucide="copy"></i><span class="copy-text">Copiar</span></button>
                        </div>
                    </div>
                </div>
                ${notesHtml}
            </div>
        `;
        lucide.createIcons();
        setTimeout(() => { resultContainer.style.opacity = '1'; resultContainer.style.transform = 'scale(1)'; resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 100);

        resultContainer.querySelectorAll('.btn-copy').forEach(button => {
            button.addEventListener('click', function(e) {
                const textToCopy = decodeURIComponent(this.dataset.copyText);
                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('Texto copiado al portapapeles.', 'success');
                    setTimeout(() => {
                        buttonContent.innerHTML = originalHTML;
                        buttonContent.classList.remove('copied');
                        lucide.createIcons({ nodes: [buttonContent] });
                    }, 2000);
                }).catch(err => {
                    console.error('Error al copiar el texto: ', err);
                    showToast('Error al copiar el texto.', 'error');
                });
            });
        });
    }
});
</script>
<script src="files/toast.js"></script>
</body>
</html>