<?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>Generador De Títulos Para Imágenes 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>
    
    <style>
        .title-card {
            background-color: #f8fafc;
            border: 1px solid #e2e8f0;
            border-left-width: 4px;
            border-radius: 0.75rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            opacity: 0;
            transform: translateY(20px);
            animation: slideInUp 0.5s ease-out forwards;
        }
        .title-card h3 {
            font-size: 1.25rem; font-weight: 800; color: #1e293b;
            display: flex; align-items: center; margin-bottom: 1rem;
        }
        .title-card h3 i { margin-right: 0.75rem; width: 1.5rem; height: 1.5rem; }
        .title-pair {
            display: flex; flex-direction: column; gap: 1rem;
        }
        @media (min-width: 768px) { .title-pair { flex-direction: row; } }
        .title-box {
            flex: 1; background-color: #fff; border: 1px solid #cbd5e1;
            border-radius: 0.5rem; padding: 1rem; position: relative;
        }
        .title-box h4 {
            font-size: 1rem; font-weight: 700; color: #475569;
            margin-bottom: 0.5rem;
        }
        .title-box p, .title-box input {
            font-size: 1.25rem; font-weight: 700; color: #0f172a;
            min-height: 3rem; width: 100%;
            padding-right: 40px; /* Espacio para el botón de copiar */
        }
        .title-box input {
            padding: 0; border: none; background: transparent;
            outline: none; box-shadow: none;
        }
        .title-box input:focus { outline: none; box-shadow: none; }
        .title-box .btn-copy-title {
            position: absolute; top: 0.75rem; right: 0.75rem;
            background: #e2e8f0; color: #475569; border: none;
            border-radius: 9999px; width: 32px; height: 32px;
            display: flex; align-items: center; justify-content: center;
            cursor: pointer; transition: all 0.2s;
        }
        .title-box .btn-copy-title:hover {
            background: var(--color-secondary); color: white;
        }
        @keyframes slideInUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .panel-title-card {
            border: 1px solid #e5e7eb; border-radius: 0.75rem;
            margin-bottom: 1.5rem; overflow: hidden;
        }
        .panel-title-header {
            background-color: #f9fafb; padding: 1rem 1.5rem;
            border-bottom: 1px solid #e5e7eb;
            display: flex; justify-content: space-between; align-items: center;
        }
        .panel-title-info {
            font-size: 0.9rem; color: #64748b;
        }
        .panel-title-info strong {
            color: #334155;
            font-size: 1.25rem; 
            font-weight: 900;
        }
        .panel-title-body { padding: 1.5rem; }
        .panel-edit-label {
            font-weight: 700; color: #374151; margin-bottom: 0.5rem; display: block;
        }
        .panel-edit-input {
            width: 100%; padding: 0.75rem; border: 1px solid #d1d5db;
            border-radius: 0.5rem; background-color: #fff;
            font-size: 1.1rem; font-weight: 600;
        }

        .btn-xs {
            padding: 0.6rem; 
            line-height: 1;
            border-radius: 0.375rem; 
        }
        .btn-xs i {
            width: 1rem; 
            height: 1rem; 
        }
        .btn-dark {
            background-color: #1f2937; 
            color: white;
        }
        .btn-dark:hover {
            background-color: #111827; 
        }
    </style>

</head>
<body data-page-title="Generador De Títulos Para Imágenes"
      data-page-subtitle="Crea Títulos Y Textos Cortos Y Potentes Para Tus Imágenes De Post"
      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="hook-generator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-3">
                        <form id="hook-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 data-lucide="target" class="mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> Define el Objetivo del Post
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa los datos para generar títulos que capten la atención.</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="service" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué Servicio Ofreces?</label>
                                        <input type="text" id="service" name="service" placeholder="Ej: Seguros De Vida" 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="profile_selector" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Cliente Ideal</label>
                                        <select id="profile_selector" name="profile_selector" 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)]">
                                            <option value="">Selecciona Un Perfil De Cliente...</option>
                                            <option value="manual">-- Escribir Manualmente --</option>
                                            <?php foreach ($current_client_profiles as $profile): ?>
                                                <option value="<?php echo htmlspecialchars($profile['id']); ?>">
                                                    <?php echo htmlspecialchars($profile['titulo_perfil']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div>
                                        <label for="ideal_client_summary" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Describe a Tu Cliente Ideal</label>
                                        <textarea id="ideal_client_summary" name="ideal_client_summary" placeholder="Ej: Padres De Familia Jóvenes Que Buscan Proteger El Futuro Financiero De Sus Hijos. (Puedes autocompletar esto con el menú de arriba)" 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="6" required></textarea>
                                    </div>
                                    
                                </div>
                            </div>
                            <div id="form-error-message" class="hidden bg-red-100 text-center p-3 text-red-700 rounded-lg border border-red-300" 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; ?>
                        
                        <button id="open-titles-panel-btn" class="btn-copy bg-[var(--color-secondary)] text-white flex items-center justify-center w-full py-4 px-6 rounded-lg font-black text-lg uppercase gap-2 hover:scale-102 transition-transform">
                            <i data-lucide="save" class="w-5 h-5"></i> <span>Tus Títulos PARA IMÁGENES</span>
                        </button>

                        <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="user-check"></i></span><div><strong class="text-brand-dark uppercase">CARGA TU PERFIL:</strong> Usa el menú desplegable para cargar un perfil de cliente que ya hayas guardado.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="edit-3"></i></span><div><strong class="text-brand-dark uppercase">O ESCRIBE MANUALMENTE:</strong> Si prefieres, puedes escribir la descripción de tu cliente directamente en el cuadro de texto.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="image"></i></span><div><strong class="text-brand-dark uppercase">TÍTULOS PARA IMÁGENES:</strong> Los resultados son cortos y directos, diseñados para poner sobre tus fotos o videos.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="save"></i></span><div><strong class="text-brand-dark uppercase">GUARDA TUS MEJORES 5:</strong> Puedes guardar hasta 5 títulos individuales en tu panel de guardados.</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="edit" class="mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> Genera Títulos Que Captan Atención
                            </h2>
                            <p class="step-subtitle uppercase">Crea textos cortos y potentes para las imágenes de tus posts.</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 que los títulos capten la atención de tu audiencia, <b>es importante</b> que sepas qué quieres transmitir con el diseño publicitario. Con esa idea, nuestra <b>inteligencia artificial</b> creará <b>Títulos Para Tus Publicaciones</b>, para que tengas textos cortos y potentes que hagan que tus posts destaquen.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="hook-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">GENERAR TÍTULOS PARA POST 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>

<div id="titles-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>

<div id="titles-panel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col">
    
    <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
        <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase">
            <i data-lucide="save" class="w-8 h-8 mr-2 text-white"></i>
            TÍTULOS GUARDADOS
        </h3>
        <button id="close-titles-panel-btn" class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200">
            <i data-lucide="x" class="w-8 h-8"></i>
        </button>
    </div>

    <div class="flex-grow overflow-y-auto p-6 relative">
        
        <div id="titles-panel-content" class="bg-white p-6 rounded-xl shadow-md transition duration-300 min-h-[200px]">
            <div class="flex flex-col items-center justify-center h-40 text-gray-400">
                <i data-lucide="loader-2" class="w-8 h-8 animate-spin mb-2"></i>
                <span class="text-sm font-bold uppercase">Cargando títulos...</span>
            </div>
        </div>
        
    </div>

    <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
        <button type="button" onclick="document.getElementById('close-titles-panel-btn').click()" class="w-full btn-cancel uppercase flex items-center justify-center gap-2">
            <i data-lucide="x-circle" class="w-5 h-5"></i> CERRAR PANEL DE RESULTADOS
        </button>
    </div>

</div>

<div id="confirmation-modal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-[100]"> <div class="bg-white p-8 rounded-xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        <div class="flex justify-center mb-4">
            <i id="modal-icon" data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
        </div>
        <h3 id="modal-title" class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">CONFIRMAR ACCIÓN</h3>
        <p id="modal-message" class="text-gray-700 mb-6 uppercase">¿Estás seguro?</p>
        <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto" id="modal-cancel-btn">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold text-white py-2 px-4 rounded-lg uppercase w-full sm:w-auto" id="modal-confirm-btn">CONFIRMAR</button>
        </div>
    </div>
</div>


<script type="module">
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    // --- UI BÁSICA (MENÚ, VIDEO, TOASTS) ---
    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.addEventListener('click', () => sidebar.classList.add('-translate-x-full'));

    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) 0-000' });
    }
    
    // --- ELEMENTOS DE LA HERRAMIENTA ---
    const form = document.getElementById('hook-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');
    
    // --- DATOS GLOBALES ---
    const savedProfiles = <?php echo json_encode($current_client_profiles); ?>;
    let savedTitleSets = <?php echo json_encode($current_title_sets); ?>; 
    let titleSetGeneradoReciente = null; 
    let inputsGeneradosReciente = null; 
    const MAX_TITLES = 5; 
    let individualSaveButtons = {}; 

    // --- PANEL LATERAL ---
    const openTitlesPanelBtn = document.getElementById('open-titles-panel-btn');
    const closeTitlesPanelBtn = document.getElementById('close-titles-panel-btn');
    const titlesPanelOverlay = document.getElementById('titles-panel-overlay');
    const titlesPanel = document.getElementById('titles-panel');
    const titlesPanelContent = document.getElementById('titles-panel-content');

    // --- MODAL DE CONFIRMACIÓN ---
    const modal = document.getElementById('confirmation-modal');
    const modalBox = modal.querySelector('div:first-of-type');
    const modalIcon = document.getElementById('modal-icon');
    const modalTitle = document.getElementById('modal-title');
    const modalMessage = document.getElementById('modal-message');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    const modalConfirmBtn = document.getElementById('modal-confirm-btn');
    let onConfirmCallback = null;

    // --- LÓGICA DE AUTOCOMPLETADO DE PERFIL ---
    const profileSelector = document.getElementById('profile_selector');
    const clientSummaryTextarea = document.getElementById('ideal_client_summary');
    profileSelector.addEventListener('change', (e) => {
        const selectedValue = e.target.value;
        if (selectedValue === 'manual') {
            clientSummaryTextarea.value = '';
            clientSummaryTextarea.focus();
        } else if (selectedValue) {
            const selectedId = parseInt(selectedValue, 10);
            const selectedProfile = savedProfiles.find(p => p.id === selectedId);
            if (selectedProfile && selectedProfile.resumen_copiar) {
                // Usamos el 'resumen_copiar' que es el texto completo del perfil
                // UNIFICACIÓN: Decodificar el HTML para el textarea
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = selectedProfile.resumen_copiar;
                clientSummaryTextarea.value = tempDiv.textContent || tempDiv.innerText || '';
                
                clientSummaryTextarea.classList.remove('border-red-500');
                if (typeof showToast === 'function') showToast('Perfil cargado en el formulario.', 'success');
            }
        } else {
            clientSummaryTextarea.value = '';
        }
    });

    // --- LÓGICA DEL MODAL ---
    function openModal({ title, message, icon, confirmText, confirmClass, onConfirm }) {
        modalTitle.textContent = title;
        modalMessage.innerHTML = message;
        modalIcon.setAttribute('data-lucide', icon);
        lucide.createIcons({ nodes: [modalIcon] });
        modalConfirmBtn.textContent = confirmText || 'CONFIRMAR';
        modalConfirmBtn.className = 'btn-secondary font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto text-white'; 
        if (confirmClass === 'danger') {
            modalConfirmBtn.classList.add('bg-red-600', 'hover:bg-red-700');
            modalConfirmBtn.classList.remove('btn-secondary');
        } else if (confirmClass === 'primary') {
             modalConfirmBtn.classList.add('bg-[var(--color-primary)]');
             modalConfirmBtn.classList.remove('btn-secondary');
        }
        onConfirmCallback = onConfirm; 
        modal.classList.remove('hidden');
        setTimeout(() => modalBox.classList.remove('scale-95', 'opacity-0'), 50);
        document.body.style.overflow = 'hidden';
    }

    function closeModal() {
        modalBox.classList.add('scale-95', 'opacity-0');
        setTimeout(() => {
            modal.classList.add('hidden');
            document.body.style.overflow = '';
        }, 300);
        onConfirmCallback = null;
    }

    modalCancelBtn.addEventListener('click', closeModal);
    modalConfirmBtn.addEventListener('click', () => {
        if (typeof onConfirmCallback === 'function') {
            onConfirmCallback();
        }
        closeModal();
    });

    // --- LÓGICA DEL PANEL LATERAL (LECTURA Y DIBUJO) ---
    function openTitlesPanel() {
        titlesPanel.classList.remove('translate-x-full');
        titlesPanelOverlay.classList.remove('hidden');
        fetchAndDrawTitles(); 
    }

    function closeTitlesPanel() {
        titlesPanel.classList.add('translate-x-full');
        titlesPanelOverlay.classList.add('hidden');
    }

    openTitlesPanelBtn.addEventListener('click', openTitlesPanel);
    closeTitlesPanelBtn.addEventListener('click', closeTitlesPanel);
    titlesPanelOverlay.addEventListener('click', closeTitlesPanel);
    
    // Fetch de títulos y renderizado
    async function fetchAndDrawTitles() {
        titlesPanelContent.innerHTML = '<div class="text-center p-4"><div class="w-8 h-8 border-4 border-t-transparent border-[var(--color-secondary)] rounded-full animate-spin mx-auto mb-3"></div><p class="text-gray-600">Cargando títulos guardados...</p></div>';

        try {
            const response = await fetch('api-db/ia-post-title-generator-fetch.php', { method: 'POST' });
            const result = await response.json();

            if (response.ok && result.success) {
                const titles = result.titles;
                savedTitleSets = titles; 
                
                if (titles.length === 0) {
                    titlesPanelContent.innerHTML = `
                        <div class="text-center p-4 border border-dashed rounded-lg">
                            <i data-lucide="info" class="w-12 h-12 text-gray-400 mx-auto mb-3"></i>
                            <p class="text-gray-500">
                                Aún no tienes títulos guardados. ¡Genera y guarda uno!
                            </p>
                        </div>
                    `;
                } else {
                    let html = `<p class="text-gray-600 mb-4 uppercase font-black">Has guardado ${titles.length} de ${MAX_TITLES} títulos.</p>`;
                    titles.forEach(titleRecord => {
                        html += createTitlePanelCard(titleRecord);
                    });
                    titlesPanelContent.innerHTML = html;
                }
            } else {
                throw new Error(result.message || 'Error al obtener los títulos.');
            }
        } catch (error) {
            titlesPanelContent.innerHTML = `<div class="bg-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300"><p><strong>Error al cargar:</strong> ${error.message}</p></div>`;
            if (typeof showToast === 'function') showToast(`Error al cargar títulos: ${error.message}`, 'error');
        }
        lucide.createIcons();
        assignPanelButtonEvents(); // Asignar eventos DESPUÉS de dibujar
    }
    
    // Función para renderizar una tarjeta en el panel
    function createTitlePanelCard(titleRecord) {
        // UNIFICACIÓN: Ahora la tarjeta tiene modo display y modo edit
        const icon = titleRecord.type === 'Problema' ? 'frown' : (titleRecord.type === 'Solución' ? 'smile' : 'zap');
        const colorClass = titleRecord.type === 'Problema' ? 'text-red-600' : (titleRecord.type === 'Solución' ? 'text-green-600' : 'text-blue-600');
        
        return `
        <div class="panel-title-card" data-title-id="${titleRecord.id}">
            <div class="panel-title-header">
                
                <span class="panel-title-info-display flex-1">
                    <span class="panel-title-info">
                        <i data-lucide="${icon}" class="w-4 h-4 mr-2 ${colorClass}"></i>
                        Tipo: <strong class="uppercase">${titleRecord.type}</strong>
                    </span>
                </span>
                
                <div class="panel-title-info-edit flex-1 hidden">
                     <input type="text" id="edit-type-${titleRecord.id}" class="panel-edit-input" value="${titleRecord.type}">
                </div>

                <div class="flex space-x-2 ml-4">
                    <button class="btn-copy btn-xs btn-dark panel-btn-edit" data-action="edit" title="Editar">
                        <i data-lucide="edit"></i>
                    </button>
                    <button class="btn-copy btn-xs bg-green-600 hover:bg-green-700 text-white hidden panel-btn-save" data-action="save" title="Guardar">
                        <i data-lucide="save"></i>
                    </button>
                    <button class="btn-copy btn-xs bg-gray-500 hover:bg-gray-600 text-white hidden panel-btn-cancel" data-action="cancel" title="Cancelar">
                        <i data-lucide="x"></i>
                    </button>
                    <button class="btn-copy btn-xs bg-red-600 hover:bg-red-700 text-white panel-btn-delete" data-action="delete" title="Eliminar">
                        <i data-lucide="trash-2"></i>
                    </button>
                </div>
            </div>
            <div class="panel-title-body space-y-3">
                <div id="display-body-${titleRecord.id}">
                    <p><strong class="text-gray-700">ES:</strong> ${titleRecord.es}</p>
                    <p><strong class="text-gray-700">EN:</strong> ${titleRecord.en}</p>
                    <p class="text-xs text-gray-500">Generado para: ${titleRecord.service_input} | Creado: ${new Date(titleRecord.created_at).toLocaleDateString()}</p>
                </div>
                <div id="edit-body-${titleRecord.id}" class="hidden space-y-3">
                    <div>
                        <label class="panel-edit-label" for="edit-es-${titleRecord.id}">ES:</label>
                        <input type="text" id="edit-es-${titleRecord.id}" class="panel-edit-input" value="${titleRecord.es}">
                    </div>
                    <div>
                        <label class="panel-edit-label" for="edit-en-${titleRecord.id}">EN:</label>
                        <input type="text" id="edit-en-${titleRecord.id}" class="panel-edit-input" value="${titleRecord.en}">
                    </div>
                </div>
            </div>
        </div>
        `;
    }

    // Asigna eventos a los botones (Delegación)
    function assignPanelButtonEvents() {
        // Limpiar listener anterior para evitar duplicados
        titlesPanelContent.removeEventListener('click', panelClickListener);
        titlesPanelContent.addEventListener('click', panelClickListener);
    }
    
    // UNIFICACIÓN: Listener delegado para el panel
    const panelClickListener = e => {
        const button = e.target.closest('button[data-action]');
        if (!button) return;

        const action = button.dataset.action;
        const card = button.closest('.panel-title-card');
        const titleId = parseInt(card.dataset.titleId, 10);

        // Desactivar otros modos de edición
        document.querySelectorAll('.panel-title-card').forEach(c => {
            if (c !== card) {
                toggleEditMode(c, false);
            }
        });

        if (action === 'delete') {
            handleDeleteTitleSet(titleId);
        } else if (action === 'edit') {
            toggleEditMode(card, true);
        } else if (action === 'cancel') {
            toggleEditMode(card, false);
            // Resetear valores (opcional, ya que fetchAndDraw lo hace)
            const titleRecord = savedTitleSets.find(t => t.id === titleId);
            if (titleRecord) {
                card.querySelector(`#edit-type-${titleId}`).value = titleRecord.type;
                card.querySelector(`#edit-es-${titleId}`).value = titleRecord.es;
                card.querySelector(`#edit-en-${titleId}`).value = titleRecord.en;
            }
        } else if (action === 'save') {
            handleUpdateTitle(card, titleId);
        }
    };

    // UNIFICACIÓN: Función para alternar visibilidad
    function toggleEditMode(cardElement, isEditing) {
        cardElement.querySelector('.panel-title-info-display').classList.toggle('hidden', isEditing);
        cardElement.querySelector('.panel-title-info-edit').classList.toggle('hidden', !isEditing);
        cardElement.querySelector(`#display-body-${cardElement.dataset.titleId}`).classList.toggle('hidden', isEditing);
        cardElement.querySelector(`#edit-body-${cardElement.dataset.titleId}`).classList.toggle('hidden', !isEditing);
        
        cardElement.querySelector('.panel-btn-edit').classList.toggle('hidden', isEditing);
        cardElement.querySelector('.panel-btn-delete').classList.toggle('hidden', isEditing);
        
        cardElement.querySelector('.panel-btn-save').classList.toggle('hidden', !isEditing);
        cardElement.querySelector('.panel-btn-cancel').classList.toggle('hidden', !isEditing);
    }

    
    // --- LÓGICA CRUD (TÍTULOS INDIVIDUALES) ---
    const titleEndpoints = {
        fetch: 'api-db/ia-post-title-generator-fetch.php',
        create: 'api-db/ia-post-title-generator-create.php',
        update: 'api-db/ia-post-title-generator-update.php',
        delete: 'api-db/ia-post-title-generator-delete.php'
    };
    
    // (CREATE) Llama al script de creación de título individual
    async function createTitleRecordInDB(payload) {
        setProcessingState(true, 'Guardando Título...'); 
        let success = false;
        
        try {
            const response = await fetch(titleEndpoints.create, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                
                const titleType = payload.title_type;
                if (individualSaveButtons[titleType]) {
                    individualSaveButtons[titleType].disabled = true;
                    individualSaveButtons[titleType].classList.add('opacity-50', 'cursor-not-allowed');
                    individualSaveButtons[titleType].innerHTML = '<i data-lucide="check"></i> <span>¡Guardado!</span>';
                    lucide.createIcons({ nodes: [individualSaveButtons[titleType]] });
                }

                openTitlesPanel(); 
                success = true;

            } else {
                if (response.status === 409) {
                     if (typeof showToast === 'function') showToast(result.message, 'warning');
                     throw new Error(result.message); 
                }
                throw new Error(result.message || 'Error desconocido al guardar el título.');
            }
        } catch (error) {
            throw error;
        } finally {
            setProcessingState(false); 
            return success;
        }
    }
    
    // (UPDATE) Llama al script de actualización
    async function handleUpdateTitle(cardElement, titleId) {
        const payload = {
            id: titleId,
            title_type: cardElement.querySelector(`#edit-type-${titleId}`).value,
            title_es: cardElement.querySelector(`#edit-es-${titleId}`).value,
            title_en: cardElement.querySelector(`#edit-en-${titleId}`).value
        };

        openModal({
            title: 'CONFIRMAR ACTUALIZACIÓN',
            message: '¿Estás seguro de que quieres guardar estos cambios?',
            icon: 'save',
            confirmText: 'SÍ, GUARDAR',
            confirmClass: 'primary',
            onConfirm: async () => {
                await updateTitleInDB(payload);
            }
        });
    }

    async function updateTitleInDB(payload) {
        setProcessingState(true, 'Actualizando...');
        try {
            const response = await fetch(titleEndpoints.update, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const result = await response.json();
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                fetchAndDrawTitles(); // Recargar el panel
            } else {
                throw new Error(result.message || 'Error desconocido al actualizar');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al actualizar: ${error.message}`, 'error');
            fetchAndDrawTitles(); // Recargar igualmente para resetear
        } finally {
            setProcessingState(false);
        }
    }

    // (DELETE) Llama al script de eliminación individual
    async function handleDeleteTitleSet(titleId) {
        openModal({
            title: 'CONFIRMAR ELIMINACIÓN',
            message: '¿Estás seguro de que quieres eliminar este título individual? <br> Esta acción no se puede deshacer.',
            icon: 'alert-triangle',
            confirmText: 'SÍ, ELIMINAR',
            confirmClass: 'danger',
            onConfirm: async () => {
                setProcessingState(true, 'Eliminando...');
                try {
                    const response = await fetch(titleEndpoints.delete, {
                        method: 'POST', 
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: titleId })
                    });
                    const result = await response.json();
                    if (response.ok && result.success) {
                        if (typeof showToast === 'function') showToast(result.message, 'success');
                        fetchAndDrawTitles(); // Recargar la lista después de eliminar
                    } else {
                        throw new Error(result.message || 'Error desconocido al eliminar');
                    }
                } catch (error) {
                    if (typeof showToast === 'function') showToast(`Error al eliminar: ${error.message}`, 'error');
                } finally {
                    setProcessingState(false);
                }
            }
        });
    }

    // --- LÓGICA DE LA HERRAMIENTA IA (GENERACIÓN) ---

    function validateForm() {
        const requiredInputs = form.querySelectorAll('[required]');
        let allValid = true;
        requiredInputs.forEach(input => {
            if (!input.value.trim()) {
                input.classList.add('border-red-500');
                allValid = false;
            } else {
                input.classList.remove('border-red-500');
            }
        });
        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, customMessage = null) {
        const btnText = document.getElementById('btn-text');
        const loaderContainer = document.getElementById('loader-container');
        
        generateBtn.disabled = isProcessing;
        generateBtn.classList.toggle('opacity-50', isProcessing);
        generateBtn.classList.toggle('cursor-not-allowed', isProcessing);
        loaderContainer.classList.toggle('hidden', !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>';
            
            if (customMessage) {
                btnText.textContent = customMessage;
                if(window.loadingInterval) clearInterval(window.loadingInterval);
                window.loadingInterval = null;
                return;
            }
            
            const messages = ["Analizando contexto...", "Buscando el 'Problema'...", "Buscando la 'Solución'...", "Generando Títulos...", "Casi Está Listo..."];
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];

            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2000);

        } else {
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            window.loadingInterval = null;
            btnText.textContent = 'GENERAR CON IA MARKETING';
        }
    }

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

        setProcessingState(true);

        const formData = {
            service: document.getElementById('service').value,
            ideal_client_summary: document.getElementById('ideal_client_summary').value,
            value_proposition: document.querySelector('input[name="value_proposition"]').value
        };

        try {
            const response = await fetch('api/api-post-title-generator.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                body: JSON.stringify(formData)
            });

            const data = await response.json();
            if (!response.ok) {
                let errorMsg = data.error || `Error del servidor: ${response.status}.`;
                if(data.api_response_body && data.api_response_body.error) {
                    errorMsg = `Error de Google API: ${data.api_response_body.error.message}`;
                } else if (data.curl_error) {
                    errorMsg = `Error de cURL: ${data.curl_error}`;
                }
                throw new Error(errorMsg);
            }
            
            titleSetGeneradoReciente = data; 
            inputsGeneradosReciente = formData; 
            
            displayResult(data, true); 
            if (typeof showToast === 'function') {
                showToast('¡Títulos generados con éxito!', 'success');
            }

        } catch (error) {
            console.error("Error:", error);
            let errorMessage = error.message || "No se pudieron generar los títulos.";
            
            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);
        }
    });
    
    // Función de renderizado
    function displayResult(data, showSaveButton = false) {
        individualSaveButtons = {};

        resultContainer.innerHTML = `
            ${createTitleCard('Enfoque: El Problema', 'frown', 'border-red-500', data.problema, 'problema')}
            ${createTitleCard('Enfoque: La Solución', 'smile', 'border-green-500', data.solucion, 'solucion')}
            ${createTitleCard('Enfoque: El Servicio', 'zap', 'border-blue-500', data.servicio, 'servicio')}
            <div id="action-buttons-container" class="mt-4 text-center">
                <p class="text-lg text-gray-600">Puedes guardar cada título individualmente.</p>
            </div>
            `;
        
        lucide.createIcons();
        resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });

        resultContainer.querySelectorAll('.btn-save-individual').forEach(button => {
            const titleType = button.dataset.titleType;
            individualSaveButtons[titleType] = button;

            button.addEventListener('click', function() {
                handleSaveIndividualTitle(titleType);
            });
        });

        resultContainer.querySelectorAll('.btn-copy-title').forEach(button => {
            button.addEventListener('click', function() {
                const textToCopy = decodeURIComponent(this.dataset.copyText);
                navigator.clipboard.writeText(textToCopy).then(() => {
                    this.innerHTML = '<i data-lucide="check" class="w-5 h-5"></i>';
                    lucide.createIcons({ nodes: [this] });
                    if (typeof showToast === 'function') {
                        showToast('Título copiado al portapapeles.', 'success');
                    }
                    setTimeout(() => { 
                        this.innerHTML = '<i data-lucide="copy" class="w-5 h-5"></i>'; 
                        lucide.createIcons({ nodes: [this] });
                    }, 2000);
                }).catch(err => console.error('Error al copiar:', err));
            });
        });
    }

    // Función helper para crear cada tarjeta de título
    function createTitleCard(title, icon, borderColor, data, titleType) {
        return `
        <div class="title-card ${borderColor}" style="animation-delay: 100ms;">
            <h3><i data-lucide="${icon}" class="text-${borderColor.replace('border-','')}"></i>${title}</h3>
            <div class="title-pair">
                <div class="title-box">
                    <h4>🇪🇸 Español</h4>
                    <p>${data.es}</p>
                    <button class="btn-copy-title" data-copy-text="${encodeURIComponent(data.es)}">
                        <i data-lucide="copy" class="w-5 h-5"></i>
                    </button>
                </div>
                <div class="title-box">
                    <h4>🇺🇸 English</h4>
                    <p>${data.en}</p>
                    <button class="btn-copy-title" data-copy-text="${encodeURIComponent(data.en)}">
                        <i data-lucide="copy" class="w-5 h-5"></i>
                    </button>
                </div>
            </div>
            <div class="mt-4 text-center">
                <button class="btn-save-individual btn-copy bg-[var(--color-primary)] text-white font-bold py-2 px-6 rounded-lg flex items-center justify-center mx-auto gap-2 hover:scale-105 transition-transform uppercase"
                        data-title-type="${titleType}">
                    <i data-lucide="save"></i> <span>Guardar Este Título</span>
                </button>
            </div>
        </div>
        `;
    }
    
    // --- LÓGICA DE GUARDADO INDIVIDUAL ---
    function handleSaveIndividualTitle(titleType) {
        if (!titleSetGeneradoReciente || !inputsGeneradosReciente) {
            if (typeof showToast === 'function') showToast("No hay un set de títulos reciente para guardar.", "error");
            return;
        }

        let titleData = titleSetGeneradoReciente[titleType]; 
        
        const payload = {
            title_type: titleType,
            title_es: titleData.es,
            title_en: titleData.en,
            inputs: inputsGeneradosReciente
        };

        createTitleRecordInDB(payload)
            .catch((error) => {
                if (typeof showToast === 'function' && !error.message.includes('Límite de')) {
                    showToast(`Error al guardar: ${error.message}`, "error");
                }
            });
    }
    
});
</script>
<script src="files/toast.js"></script>
</body>
</html>