<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit | Creador De Respuestas A Reseñas</title>

    <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">
</head>
<body data-page-title="Creador De Respuestas A Reseñas"
      data-page-subtitle="Responde Reseñas Con Profesionalismo Y Cercanía Fácilmente"
      data-page-icon="star">

<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="review-response-creator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-3">
                        <form id="review-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-comment-alt mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> DETALLES DE LA RESEÑA
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa los datos de la reseña del cliente.</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="customer_name" class="block font-bold text-gray-700 mb-2">Nombre Del Cliente (Opcional)</label>
                                        <input type="text" id="customer_name" placeholder="Ej: Juan Pérez" class="w-full p-3 bg-white border border-gray-300 rounded-lg">
                                    </div>
                                    <div>
                                        <label for="customer_comment" class="block font-bold text-gray-700 mb-2">Comentario o Reseña Del Cliente</label>
                                        <textarea id="customer_comment" placeholder="Pega aquí el comentario o reseña del cliente..." class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="5" required></textarea>
                                    </div>
                                    <div>
                                        <label for="preferred_tone" class="block font-bold text-gray-700 mb-2">Tono De Comunicación Preferido</label>
                                        <select id="preferred_tone" class="w-full p-3 bg-white border border-gray-300 rounded-lg" required>
                                            <option value="">Selecciona un tono</option>
                                            <option value="Profesional">Profesional</option>
                                            <option value="Amigable">Amigable</option>
                                            <option value="Entusiasta">Entusiasta</option>
                                            <option value="Empático">Empático</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        <div class="bg-white rounded-xl shadow-md">
                            <div class="native-video-wrapper" id="videoWrapper">
                                <div class="play-overlay" id="playOverlay">
                                    <img src="https://placehold.co/600x337/07162d/ffc857?text=VIDEO" alt="Imagen de previsualización del video" class="absolute inset-0 w-full h-full object-cover rounded-xl">
                                    <i class="fas fa-play play-icon"></i>
                                </div>
                                <video class="w-full h-full object-cover" id="videoPlayer" controlslist="nodownload nofullscreen" 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>
                        </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-pencil-alt"></i></span><div><strong class="text-brand-dark">Copia la Reseña:</strong> Pega el comentario del cliente tal cual lo recibiste.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-smile"></i></span><div><strong class="text-brand-dark">Elige el Tono:</strong> Selecciona el estilo de respuesta que prefieras.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-robot"></i></span><div><strong class="text-brand-dark">Genera Respuestas:</strong> La IA te dará 2 opciones en diferentes tonos.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-clipboard"></i></span><div><strong class="text-brand-dark">Copia y Pega:</strong> Utiliza la respuesta que mejor se adapte a tu marca.</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 class="fas fa-magic mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> GENERAR RESPUESTAS
                            </h2>
                            <p class="step-subtitle uppercase">Obtén respuestas profesionales y atractivas para tus reseñas.</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">Basado en la reseña y tu tono preferido, <strong class="font-black">CLIENT3 IA</strong>, generará <b>dos opciones de respuesta únicas y efectivas</b>, listas para usar en español e inglés, que te ayudarán a fortalecer tu relación con los clientes.</p>
                            <button id="generateBtn" type="submit" form="review-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="lg:col-span-5 mt-8"></div>
                </div>
            </section>
        </div>
    </main>
</div>

<script src="files/header-manager.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();

    // --- Lógica del Video Player ---
    const videoPlayer = document.getElementById('videoPlayer');
    const playOverlay = document.getElementById('playOverlay');
    if (videoPlayer && playOverlay) {
        videoPlayer.controls = false;
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.controls = true;
            videoPlayer.play().catch(e => console.error("Error al reproducir video:", e));
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }

    // --- Lógica del Generador ---
    const form = document.getElementById('review-form');
    const resultContainer = document.getElementById('result-container');
    const generateBtn = document.getElementById('generateBtn');
    const btnText = document.getElementById('btn-text');
    const loaderContainer = document.getElementById('loader-container');

    form.addEventListener('submit', async function(event) {
        event.preventDefault();
        btnText.textContent = 'Generando Respuestas...';
        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;
        resultContainer.innerHTML = '';
        resultContainer.style.opacity = '0'; // Reinicia la opacidad para la animación

        const formData = {
            customer_name: document.getElementById('customer_name').value,
            customer_comment: document.getElementById('customer_comment').value,
            preferred_tone: document.getElementById('preferred_tone').value
        };

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

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

            const data = await response.json();
            if(data.error) {
                throw new Error(data.error);
            }
            displayResult(data.responses);

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

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

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

    function displayResult(responses) {
        let allResponsesHtml = '';
        responses.forEach((response, index) => {
            allResponsesHtml += `
                <div class="bg-white p-6 rounded-xl shadow-lg mb-8">
                    <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-reply mr-3 text-[var(--color-secondary)]"></i>Respuesta ${index + 1}: Tono ${response.tone}
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <h4 class="text-lg font-semibold text-gray-700 mb-3">🇪🇸 Español</h4>
                            <textarea readonly class="w-full h-32 p-3 bg-gray-100 rounded-md leading-relaxed text-gray-800 resize-y border border-gray-300 mb-3">${response.es}</textarea>
                            <button class="copy-response-btn bg-[var(--color-primary)] text-white px-3 py-1 rounded-md text-sm hover:opacity-90 transition-opacity" data-copy-text="${encodeURIComponent(response.es)}"><i class="fas fa-copy mr-1"></i>Copiar</button>
                        </div>
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <h4 class="text-lg font-semibold text-gray-700 mb-3">🇺🇸 English</h4>
                            <textarea readonly class="w-full h-32 p-3 bg-gray-100 rounded-md leading-relaxed text-gray-800 resize-y border border-gray-300 mb-3">${response.en}</textarea>
                            <button class="copy-response-btn bg-[var(--color-secondary)] text-white px-3 py-1 rounded-md text-sm hover:opacity-90 transition-opacity" data-copy-text="${encodeURIComponent(response.en)}"><i class="fas fa-copy mr-1"></i>Copy</button>
                        </div>
                    </div>
                </div>
            `;
        });

        resultContainer.innerHTML = `<div class="ai-response p-6 md:p-8 rounded-xl shadow-md space-y-8">${allResponsesHtml}</div>`;
        setTimeout(() => { resultContainer.style.opacity = '1'; resultContainer.style.transform = 'scale(1)'; }, 100);

        resultContainer.querySelectorAll('.copy-response-btn').forEach(button => {
            button.addEventListener('click', function() {
                const textToCopy = decodeURIComponent(this.dataset.copyText);
                navigator.clipboard.writeText(textToCopy).then(() => {
                    const originalContent = this.innerHTML;
                    this.innerHTML = '<i class="fas fa-check"></i> Copiado';
                    this.classList.add('copied');
                    setTimeout(() => {
                        this.innerHTML = originalContent;
                        this.classList.remove('copied');
                    }, 2000);
                }).catch(err => {
                    console.error('Error al copiar el texto: ', err);
                });
            });
        });
    }
});
</script>

</body>
</html>