<?php include 'files/guardiankey.php'; ?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit Dashboard | Asistente Inteligente De Ventas</title>
        <meta name="description" content="Gestiona tus prospectos y potenciales clientes con el LocalCRM ToolKit Dashboard de OrozDesign Multimedia.">
    <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">

    <style>
        .copy-btn-assistant {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            padding: 0.75rem 1rem;
            margin-top: 0.75rem;
            background-color: var(--color-primary); /* Color de fondo azul oscuro */
            color: white;
            font-weight: 600;
            border-radius: 0.5rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease-in-out;
            text-transform: uppercase;
            font-size: 0.9rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .copy-btn-assistant:hover {
            background-color: #1a2b42; /* Azul primario más oscuro */
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }
        .copy-btn-assistant.copied {
            background-color: #16a34a; /* Verde éxito */
            transform: translateY(0);
        }
    </style>

</head>
<body data-page-title="Asistente Inteligente De Ventas" 
      data-page-subtitle="Tu Copiloto De IA Que Te Dice Qué Responder Para Cerrar Más Ventas" 
      data-page-icon="messages-square">
<?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>

    <?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="sales-copilot" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <div class="lg:col-span-3">
                        <form id="copilot-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">
                                        <i class="fas fa-book-open mr-3 text-[var(--color-secondary)]"></i> 
                                        <span class="text-[var(--color-secondary)] mr-2">Paso 1:</span> CONTEXTO
                                    </h2>
                                    <p class="step-subtitle uppercase">Define los detalles para que la IA entienda la situación.</p>
                                </div>
                                <div class="border-b border-[var(--color-primary)] pb-4 mb-6"></div>
                                <div id="context-section" class="space-y-6">
                                    <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 Prospecto/Cliente</label><input type="text" id="client_name" placeholder="Ej: Sebastian" class="w-full p-3 bg-white border border-gray-300 rounded-lg" required></div>
                                        <div><label for="ad_copy" class="block font-bold capitalize text-gray-700 mb-2">Copy Del Anuncio</label><textarea id="ad_copy" placeholder="Pega el texto del anuncio..." class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="3" required></textarea></div>
                                    </div>
                                    <div><label for="ideal_client_summary" class="block font-bold capitalize text-gray-700 mb-2">Resumen Del Cliente Ideal</label><textarea id="ideal_client_summary" placeholder="Pega aquí el resumen de tu cliente ideal..." class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="5" required></textarea></div>
                                </div>
                            </div>
                            <div>
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                        <i class="fas fa-comments mr-3 text-[var(--color-secondary)]"></i> 
                                        <span class="text-[var(--color-secondary)] mr-2">Paso 2:</span> CONVERSACIÓN
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa el mensaje más reciente de tu cliente.</p>
                                </div>
                                <div class="border-b border-[var(--color-primary)] pb-4 mb-6"></div>
                                <div id="conversation-section" class="space-y-6">
                                    <div><label for="client_message" class="block font-bold capitalize text-gray-700 mb-2">Mensaje Del Cliente</label><textarea id="client_message" placeholder="Pega aquí la objeción o pregunta del cliente..." class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="4" required></textarea></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="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"></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">
                                    <i class="fas fa-book mr-3 text-[var(--color-highlight)]"></i> 
                                    INSTRUCCIONES
                                </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>Contexto:</strong> Rellena todos los campos para que la IA te entienda.</div></li><li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-comments"></i></span><div><strong>Mensaje:</strong> Pega la pregunta u objeción del cliente.</div></li><li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-rocket"></i></span><div><strong>Genera:</strong> Obtén 2 respuestas estratégicas al instante.</div></li><li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-copy"></i></span><div><strong>Usa y Adapta:</strong> Copia la que más te guste y ajústala a tu estilo.</div></li><li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-reply"></i></span><div><strong>Continúa:</strong> Pega la nueva respuesta del cliente para seguir la conversación.</div></li></ul></div>
                    </div>
                </div>
                <div class="bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-md mt-8"><div class="step-header"><h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase"><i class="fas fa-magic-wand-sparkles mr-3 text-[var(--color-secondary)]"></i><span class="text-[var(--color-secondary)] mr-2">Paso 3:</span> GENERA TU RESPUESTA</h2><p class="step-subtitle uppercase">Deja que tu copiloto de IA te ayude a cerrar la venta.</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 mb-0">Cuando completes los campos, haz clic aquí. <strong class="font-black">CLIENT3 IA</strong> analizará la situación y te dará las mejores respuestas.</p><button id="generateBtn" type="submit" form="copilot-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 Respuestas</span><div id="loader-container" class="hidden ml-3"></div></button></div></div>
                <div id="result-container" class="mt-8 space-y-8"></div>
            </section>
        </div>
    </main>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('copilot-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 contextSection = document.getElementById('context-section');
    
    let conversationHistory = [];
    
    function initialize() {
        setupHeader();
        setupVideoPlayer();
        form.addEventListener('submit', handleFormSubmit);
        setupCopyButtons();
        lucide.createIcons();
    }

    function setupHeader() {
        const pageTitleElement = document.getElementById('page-title');
        const pageSubtitleElement = document.getElementById('page-subtitle');
        if (!pageTitleElement || !pageSubtitleElement) return;
        const body = document.body;
        const iconClass = body.getAttribute('data-page-icon');
        const iconHTML = iconClass ? `<i data-lucide="${iconClass}" class="w-7 h-7"></i>` : '';
        pageTitleElement.innerHTML = `${iconHTML} ${body.getAttribute('data-page-title') || 'Dashboard'}`;
        pageSubtitleElement.textContent = body.getAttribute('data-page-subtitle') || 'Gestión General';
        if(iconHTML) lucide.createIcons();
    }

    function setupVideoPlayer() {
        const videoPlayer = document.getElementById('videoPlayer');
        const playOverlay = document.getElementById('playOverlay');
        if (!videoPlayer || !playOverlay) return;
        videoPlayer.controls = false; 
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.controls = true;      
            videoPlayer.play();                 
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;    
        });
    }

    function setupCopyButtons() {
        resultContainer.addEventListener('click', function(e) {
            const button = e.target.closest('.copy-btn-assistant');
            if (!button) return;

            const column = button.closest('.flex-1');
            const textarea = column.querySelector('.ai-textarea');
            if (!textarea) return;

            navigator.clipboard.writeText(textarea.value).then(() => {
                const originalContent = button.innerHTML;
                button.innerHTML = '<i class="fas fa-check mr-2"></i> ¡Copiado!';
                button.classList.add('copied');
                
                setTimeout(() => {
                    button.innerHTML = originalContent;
                    button.classList.remove('copied');
                }, 2000);
            }).catch(err => {
                console.error('Error al copiar el texto: ', err);
                button.textContent = 'Error al copiar';
            });
        });
    }

    async function handleFormSubmit(event) {
        event.preventDefault();
        btnText.textContent = 'Pensando...';
        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;

        const clientMessageInput = document.getElementById('client_message');
        const currentClientMessage = clientMessageInput.value;
        conversationHistory.push({ role: 'user', text: currentClientMessage });

        resultContainer.querySelectorAll('.ai-response').forEach(el => el.remove());
        addClientMessageToUI(currentClientMessage);

        const context = {
            client_name: document.getElementById('client_name').value,
            ad_copy: document.getElementById('ad_copy').value,
            ideal_client_summary: document.getElementById('ideal_client_summary').value,
        };

        try {
            const payload = { context, history: conversationHistory };
            const response = await fetch("api/API-Asistente-Inteligente-De-Ventas.php", {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`Error del servidor ${response.status}: ${errorText}`);
            }

            const data = await response.json();
            if (data.error) throw new Error(data.error);

            const suggestions = data.sugerencias || [];
            if (suggestions.length > 0) {
                conversationHistory.push({ role: 'model', text: suggestions[0].respuesta.es });
            }
            
            displayResult(suggestions);
            clientMessageInput.value = '';
            lockContext();

        } catch (error) {
            console.error("Error al generar respuesta:", error);
            showError(error.message);
            conversationHistory.pop();
        } finally {
            btnText.textContent = 'Generar Respuestas';
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
        }
    }

    function addClientMessageToUI(message) {
        const messageCard = document.createElement('div');
        messageCard.className = 'client-message-card'; 
        messageCard.innerHTML = `<h3><i class="icon fas fa-user-circle text-[var(--color-primary)]"></i>MENSAJE DEL CLIENTE</h3><p class="whitespace-pre-wrap">${message}</p>`;
        resultContainer.appendChild(messageCard);
        scrollToElement(messageCard);
    }

    function displayResult(sugerencias) {
        sugerencias.forEach((sug, index) => {
            const card = createSuggestionCard(sug, index);
            resultContainer.appendChild(card);
        });
        scrollToElement(resultContainer.lastChild);
    }
    
    function createSuggestionCard(sug, index) {
        const card = document.createElement('div');
        card.className = 'ai-response animate-slideInUp';
        card.style.animationDelay = `${index * 150}ms`;
        card.innerHTML = `
            <h3><i class="icon fas fa-lightbulb text-[var(--color-secondary)]"></i> ${sug.titulo_estrategia}</h3>
            <p class="ai-explanation"><strong class="text-[var(--color-primary)]">Por qué funciona:</strong> ${sug.explicacion}</p>
            <div class="mt-4 flex flex-col md:flex-row gap-6">
                <div class="flex-1">
                    <h4>🇪🇸 Respuesta Sugerida (Español)</h4>
                    <textarea readonly class="ai-textarea">${sug.respuesta.es}</textarea>
                    <button class="copy-btn-assistant">
                        <i class="fas fa-copy mr-2"></i>Copiar Respuesta
                    </button>
                </div>
                <div class="flex-1">
                    <h4>🇺🇸 Suggested Reply (English)</h4>
                    <textarea readonly class="ai-textarea">${sug.respuesta.en}</textarea>
                    <button class="copy-btn-assistant">
                        <i class="fas fa-copy mr-2"></i>Copy Reply
                    </button>
                </div>
            </div>`;
        return card;
    }

    function showError(message) {
        const errorCard = document.createElement('div');
        errorCard.className = 'bg-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300';
        let displayMessage = "No se pudo generar la respuesta. Por favor, revisa los datos que ingresaste e inténtalo de nuevo.";

        // Intenta parsear el mensaje de error para buscar el código 503
        try {
            // Se asume que el mensaje podría empezar con "Error del servidor XXX: " antes del JSON
            const jsonStartIndex = message.indexOf('{');
            if (jsonStartIndex !== -1) {
                const errorJsonString = message.substring(jsonStartIndex);
                const errorDetails = JSON.parse(errorJsonString);
                if (errorDetails.error && errorDetails.error.code === 503) {
                    displayMessage = "LO SENTIMOS En Este Momento, Nuestra Inteligencia Artificial Está Saturada. Por favor, Inténtalo De Nuevo En Unos Minutos.";
                } else {
                    displayMessage += ` Detalles: ${message}`; // Mantener detalles si es otro error
                }
            } else {
                displayMessage += ` Detalles: ${message}`; // Si no hay JSON, solo añadir el mensaje completo
            }
        } catch (parseError) {
            // Si no se puede parsear, es un error inesperado, mostrar el mensaje completo
            displayMessage += ` Detalles: ${message}`;
        }

        errorCard.innerHTML = `<p><strong>Error:</strong> ${displayMessage}</p>`;
        resultContainer.appendChild(errorCard);
        scrollToElement(errorCard);
    }

    function lockContext() {
        if (contextSection.classList.contains('context-locked')) return;
        contextSection.classList.add('context-locked');
        contextSection.querySelectorAll('input, textarea').forEach(el => {
            el.disabled = true;
            el.classList.add('bg-gray-100');
        });
    }

    function scrollToElement(element) {
        if (!element) return;
        setTimeout(() => {
            element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }, 200);
    }

    initialize();
});
</script>
</body>
</html>