<?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';

$logo_url = htmlspecialchars($client_info['logo_url'] ?? '', ENT_QUOTES, 'UTF-8');

// Datos específicos de esta herramienta
$current_client_profiles = $ia_results['ideal_client_profiles'] ?? [];
$MAX_PROFILES = 3;

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, maximum-scale=1.0, user-scalable=no">
    <title>Generador De Perfil De Cliente Ideal 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="Generador De Perfil De Cliente Ideal"
      data-page-subtitle="Define Con Claridad A Quién Le Vendes Y Cómo Comunicarte Mejor"
      data-page-icon="users">

    <div id="toast-container" class="toast-container"></div>

    <?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex flex-col md:flex-row">

    <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 w-full">
        <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 p-2">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container flex-1 ml-2 md:ml-0">
                <h2 id="page-title" class="text-lg md:text-2xl font-bold truncate"></h2>
                <p id="page-subtitle" class="text-sm md:text-sm text-gray-500 hidden md:block"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <section id="ideal-client-tool" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-6 md:gap-8">

                    <div class="lg:col-span-3">
                        <form id="profile-generator-form" class="space-y-6 md:space-y-8 bg-white p-4 md:p-8 rounded-xl shadow-md">
                            <div>
                                <div class="step-header">
                                    <h2 class="text-xl md:text-2xl font-black pb-0 mb-0 flex items-center uppercase flex-wrap">
                                        <span class="step-number text-[var(--color-primary)] flex items-center shrink-0">
                                            <i data-lucide="scan-face" class="mr-2 md:mr-3 w-5 h-5 md:w-6 md:h-6 text-[var(--color-secondary)]"></i> PASO 1:
                                        </span>
                                        <span class="step-title ml-2">Describe Tu Servicio y Cliente</span>
                                    </h2>
                                    <p class="step-subtitle uppercase text-gray-500 font-bold mt-2 ml-1 text-sm md:text-sm">Ingresa los datos para crear el perfil de tu cliente ideal</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div class="form-group">
                                        <label for="service" class="block text-base md:text-lg font-bold capitalize text-gray-700 mb-2">¿Cuál Es Tu Servicio Principal?</label>
                                        <input type="text" id="service" name="service" placeholder="Ej: Mantenimiento De Jardines Para Residencias" 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)] text-base" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="client_desc" class="block text-base md:text-lg font-bold capitalize text-gray-700 mb-2">Describe Brevemente a Tus Clientes Actuales:</label>
                                        <textarea id="client_desc" name="client_desc" rows="4" placeholder="Ej: Familias Con Casas Grandes, Poco Tiempo Libre Y Que Valoran Un Hogar Bien Cuidado." 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)] text-base" required></textarea>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-6 md:space-y-8">
                        <?php if (!empty($logo_url)): ?>
                            <div class="bg-white p-4 rounded-xl shadow-md hidden md:block">
                                <img src="<?php echo htmlspecialchars($logo_url); ?>" 
                                          alt="Logotipo de tu Empresa" 
                                          class="block mx-auto object-contain h-24 max-w-[250px]">
                            </div>
                        <?php endif; ?>
                        
                        <button id="open-profiles-panel-btn" class="btn btn-primary w-full py-4 px-6 rounded-lg font-black text-base md:text-lg uppercase gap-2 hover:scale-102 transition-transform shadow-lg flex items-center justify-center">
                            <i data-lucide="users" class="w-5 h-5"></i> <span>Tus Perfiles Guardados</span>
                            <span class="ml-2 bg-white text-[var(--color-primary)] text-sm font-bold px-2 py-0.5 rounded-full" id="profile-counter-badge"><?php echo count($current_client_profiles); ?>/<?php echo $MAX_PROFILES; ?></span>
                        </button>
                    
                        <div class="w-full">
                            <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden shadow-lg">
                                <div class="relative w-full pb-[56.25%]">
                                    <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayer" controls controlslist="nodownload" preload="none" poster="img/VideoLeccion-IAMarketing.jpg">
                                        <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" class="absolute inset-0 w-full h-full object-cover">
                                        <div class="absolute inset-0 w-full h-full bg-black/70 transition-colors group-hover:bg-black/30"></div>
                                        <i data-lucide="play" class="relative w-12 h-12 md:w-16 md:h-16 text-white opacity-90 group-hover:opacity-100 transition-opacity"></i>
                                    </div>
                                </div>
                                <div class="p-3 md:p-4 text-white/90 text-sm md:text-sm flex flex-col md:flex-row md:items-center justify-between gap-2 bg-gray-900">
                                    <span class="inline-flex items-center gap-2">
                                        <i data-lucide="play-circle" class="w-4 h-4 text-[var(--color-highlight)]"></i>
                                        <b>VIDEO:</b> Cómo definir tu Avatar
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="bg-white text-brand-dark p-4 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 text-gray-500 font-bold mt-2">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 text-sm md:text-base">
    <li class="flex items-start gap-3">
        <span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)] shrink-0"><i data-lucide="sparkles" class="w-4 h-4"></i></span>
        <div>
            <strong class="text-[var(--color-primary)] font-black uppercase">SERVICIO CLAVE:</strong> Enfócate en el <b>resultado final</b> (beneficio) y no solo en la actividad que realizas.
        </div>
    </li>
    <li class="flex items-start gap-3">
        <span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)] shrink-0"><i data-lucide="file-text" class="w-4 h-4"></i></span>
        <div>
            <strong class="text-[var(--color-primary)] font-black uppercase">CLIENTES DETALLADOS:</strong> Menciona el <b>sector</b>, sus <b>problemas reales</b> y <b>nivel socioeconómico</b>.
        </div>
    </li>
    <li class="flex items-start gap-3">
        <span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)] shrink-0"><i data-lucide="layers" class="w-4 h-4"></i></span>
        <div>
            <strong class="text-[var(--color-primary)] font-black uppercase">LÍMITE MÁXIMO:</strong> El sistema permite guardar hasta <?php echo $MAX_PROFILES; ?> perfiles distintos para segmentación avanzada.
        </div>
    </li>
</ul>
                        </div>
                    </div>

                    <div class="lg:col-span-5 bg-white p-4 md:p-8 rounded-xl shadow-md mt-4 md:mt-6">
                        <div class="step-header">
                            <h2 class="text-xl md:text-2xl font-black pb-0 mb-0 flex items-center uppercase flex-wrap">
                                <span class="step-number text-[var(--color-primary)] flex items-center shrink-0">
                                    <i data-lucide="target" class="mr-2 md:mr-3 w-5 h-5 md:w-6 md:h-6 text-[var(--color-secondary)]"></i> PASO 2:
                                </span>
                                <span class="step-title ml-2">Generar Perfil Estratégico</span>
                            </h2>
                            <p class="step-subtitle uppercase text-gray-500 font-bold mt-2 ml-1 text-sm md:text-sm">Crea el perfil de tu cliente ideal con un solo clic</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 shadow-lg order-first md:order-none">
                                <i data-lucide="brain" class="w-16 h-16 md:w-32 md:h-32 text-white animate-pulse"></i>
                                <p class="mt-4 text-white font-black text-lg md: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-xl md: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-base md:text-lg text-gray-700 mb-6">
                                    Para que obtengas los mejores resultados, <b>es importante</b> que los datos que envíes sean lo más precisos posible. Basado en tus detalles, nuestra <b>IA</b> generará un <b>Perfil De Cliente Ideal</b> estratégico.
                                </p>
                                
                                <div class="flex justify-center md:justify-start">
                                    <button id="generateBtn" type="submit" form="profile-generator-form" class="btn btn-primary w-full md:w-auto py-4 px-6 rounded-lg text-lg flex items-center justify-center uppercase shadow-xl hover:scale-105 transition-transform">
                                        <i data-lucide="arrow-big-right-dash" class="w-6 h-6 mr-2"></i>
                                        <span id="btn-text">GENERAR PERFIL 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-6 md:mt-8"></div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="proposal-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>
<div id="proposal-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-2xl md:text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase truncate">
            <i data-lucide="users" class="w-6 h-6 md:w-8 md:h-8 mr-2 text-white shrink-0"></i>
            Tus Perfiles De Clientes
        </h3>
        <button id="close-proposal-panel-btn" class="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-4 md:p-6 relative bg-gray-50">
        <div id="proposal-panel-content" class="min-h-[200px] space-y-4">
            </div>
    </div>

    <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10 pb-8 md:pb-4">
        <button type="button" onclick="document.getElementById('close-proposal-panel-btn').click()" class="w-full btn btn-secondary uppercase flex items-center justify-center gap-2 py-3 rounded-lg">
            <i data-lucide="x-circle" class="w-5 h-5"></i> CERRAR PANEL
        </button>
    </div>
</div>

<div id="confirmation-modal" 
     class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-[100]"
     onclick="if(event.target === this) document.getElementById('modal-cancel-btn').click()">
    
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        
        <div class="modal-header-container rounded-t-xl pt-6">
            <h3 id="modal-title" class="modal-primary-title text-4xl font-black text-[var(--color-highlight)] uppercase leading-none">ADVERTENCIA</h3>
        </div>

        <div class="p-8">
            <div class="flex justify-center mb-6">
                <i id="modal-icon" data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
            </div>

            <p class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">
                <span id="modal-message-static">¿ESTÁS SEGURO(A) DE QUERER
                <span id="modal-message" class="font-black text-[var(--color-secondary)] text-xl block mt-2 uppercase"></span>
            </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-[var(--color-primary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2" id="modal-cancel-btn">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                
                <button type="button" class="bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2" id="modal-confirm-btn">
                    <i data-lucide="circle-check" class="w-5 h-5"></i> CONFIRMAR
                </button>
            </div>

            <p class="mt-6 uppercase text-sm font-black text-gray-500 tracking-wider"> 
                ESTA ACCIÓN NO SE PUEDE REVERTIR
            </p>
         </div>
    </div>
</div>

<script type="module">
// Almacén para las instancias de Quill. Usamos una clave por cada tarjeta en modo edición.
window.quillInstances = window.quillInstances || {};
window.activeQuillId = null;

/**
 * Función que encapsula la lógica de inicialización de Quill
 * para poder llamarla por cada editor en el panel.
 * @param {HTMLElement} editorContainer - El DIV donde se inicializará Quill.
 * @param {HTMLElement} hiddenInput - El TEXTAREA oculto a sincronizar.
 * @param {HTMLElement} charCountDisplay - El contador de caracteres.
 * @param {number} maxLength - La longitud máxima.
 * @param {string} instanceId - ID único para la instancia de Quill.
 */
function initializeQuillInstance(editorContainer, hiddenInput, charCountDisplay, maxLength, instanceId) {
    // Si ya existe una instancia para este ID, la limpiamos antes de re-inicializar
    // ya que Quill no tiene un método destroy simple y nativo.
    if (window.quillInstances[instanceId]) {
        console.warn(`Quill instance ${instanceId} already exists. Forcing cleanup.`);
        // Eliminar la referencia antigua antes de la limpieza del DOM
        delete window.quillInstances[instanceId];
        // Limpiar el contenido del DIV (esto remueve el DOM generado por Quill)
        // **ESTA ES LA CORRECCIÓN CLAVE EN LA INICIALIZACIÓN**
        editorContainer.innerHTML = ''; 
    }

    // CONFIGURACIÓN ACTUALIZADA DE QUILL (Copia de editor.js)
    const quill = new Quill(editorContainer, {
        theme: 'snow', 
        placeholder: 'Escribe Aquí...',
        modules: {
            toolbar: [
                // Estilos de texto básicos
                ['bold', 'italic', 'underline'],
                // Citas
                ['blockquote'],
                // Encabezados (H1, H2, H3 y Texto Normal)
                [{ 'header': [1, 2, 3, false] }],
                // Listas
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                // Botón para limpiar formato
                ['clean']
            ]
        }
    });

    window.quillInstances[instanceId] = quill;

    // Cargar contenido inicial si existe
    const initialContent = hiddenInput.value;
    if (initialContent) {
        quill.clipboard.dangerouslyPasteHTML(initialContent);
    }
    
    // Lógica del contador de caracteres (Copia de editor.js)
    const updateCharCount = () => {
        const text = quill.getText();
        const length = text.replace(/\s+$/, '').length; 
        
        charCountDisplay.textContent = `${length} / ${maxLength}`;
        
        if (length > maxLength) {
            charCountDisplay.classList.add('text-red-600', 'font-black'); 
        } else if (length > maxLength - 100) {
            charCountDisplay.classList.add('text-[var(--color-secondary)]', 'font-black'); 
            charCountDisplay.classList.remove('text-red-600');
        } else {
            charCountDisplay.classList.remove('text-[var(--color-secondary)]', 'text-red-600', 'font-black');
        }
    };

    // Sincronización con el input oculto (Copia de editor.js)
    quill.on('text-change', function() {
        let html = quill.root.innerHTML;
        // Limpieza de párrafo vacío por defecto de Quill
        if (html === '<p><br></p>') {
            html = '';
        }
        
        hiddenInput.value = html;
        updateCharCount();
    });

    // Inicializar contador
    updateCharCount();
}

document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    // --- UI BASICS ---
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');

    if(mobileMenuButton && sidebar) {
        mobileMenuButton.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            if(sidebarOverlay) sidebarOverlay.classList.toggle('hidden');
        });
    }
    if(sidebarOverlay) {
        sidebarOverlay.addEventListener('click', () => {
            if(sidebar) 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) {
        videoPlayer.controls = false;
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.controls = true;
            videoPlayer.play().catch(e => {
                if (typeof showToast === 'function') showToast("Error: " + e.message, 'error');
            });
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }

    // --- ELEMENTS ---
    const form = document.getElementById('profile-generator-form');
    const resultContainer = document.getElementById('result-container');
    const generateBtn = document.getElementById('generateBtn');
    
    // --- PANEL LATERAL ---
    const openPanelBtn = document.getElementById('open-profiles-panel-btn');
    const closePanelBtn = document.getElementById('close-proposal-panel-btn');
    const panelOverlay = document.getElementById('proposal-panel-overlay');
    const proposalPanel = document.getElementById('proposal-panel');
    const panelContent = document.getElementById('proposal-panel-content');
    const counterBadge = document.getElementById('profile-counter-badge');
    
    // --- MODAL ---
    const modal = document.getElementById('confirmation-modal');
    const modalBox = modal.querySelector('div:first-of-type');
    const modalTitle = document.getElementById('modal-title');
    const modalMessage = document.getElementById('modal-message'); 
    const modalIcon = document.getElementById('modal-icon');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    const modalConfirmBtn = document.getElementById('modal-confirm-btn');
    let onConfirmCallback = null;

    // --- DATA ---
    let savedClientProfiles = <?php echo json_encode($current_client_profiles); ?>;
    const MAX_PROFILES = <?php echo $MAX_PROFILES; ?>;
    let profileGeneradoReciente = null;

    // --- MODAL LOGIC (COPIA EXACTA DEL ESTÁNDAR) ---
    function openModal({ title, message, icon, confirmText, confirmClass, onConfirm }) {
        modalTitle.textContent = title || 'ADVERTENCIA';
        modalMessage.innerHTML = message; 
        
        modalIcon.setAttribute('data-lucide', icon);
        lucide.createIcons({ nodes: [modalIcon] });
        
        modalConfirmBtn.innerHTML = `<i data-lucide="circle-check" class="w-5 h-5"></i> ${confirmText || 'CONFIRMAR'}`;
        
        modalConfirmBtn.className = 'font-black py-2.5 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all duration-200 text-white';
        
        if (confirmClass === 'danger') {
            modalConfirmBtn.classList.add('bg-[var(--color-secondary)]', 'hover:opacity-90');
            modalMessage.classList.add('text-[var(--color-secondary)]');
        } else {
            modalConfirmBtn.classList.add('bg-[var(--color-primary)]', 'hover:opacity-90');
            modalMessage.classList.remove('text-[var(--color-secondary)]');
            modalMessage.classList.add('text-[var(--color-primary)]');
        }
        
        lucide.createIcons({ nodes: [modalConfirmBtn] });

        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();
    });

    // --- PANEL LOGIC ---
    function updateCounter() {
        if(counterBadge) counterBadge.textContent = `${savedClientProfiles.length}/${MAX_PROFILES}`;
    }

    function openProposalPanel() {
        proposalPanel.classList.remove('translate-x-full');
        panelOverlay.classList.remove('hidden');
        loadDataIntoPanel(); 
    }

    function closeProposalPanel() {
        // Al cerrar el panel, aseguramos la limpieza de cualquier editor activo.
        document.querySelectorAll('.panel-profile-card').forEach(card => {
            if (!card.querySelector('.panel-edit-mode').classList.contains('hidden')) {
                // Forzamos la limpieza y reseteo del Quill al cerrar el panel
                toggleEditMode(card, false, card.querySelector('.btn-panel-cancel')); 
            }
        });
        proposalPanel.classList.add('translate-x-full');
        panelOverlay.classList.add('hidden');
    }

    openPanelBtn.addEventListener('click', openProposalPanel);
    closePanelBtn.addEventListener('click', closeProposalPanel);
    panelOverlay.addEventListener('click', closeProposalPanel);

    // --- PANEL RENDERER (ADAPTADO PARA LISTA) ---
    function loadDataIntoPanel() {
        updateCounter();
        
        if (savedClientProfiles.length > 0) {
            let html = '';
            savedClientProfiles.forEach(profile => {
                html += createProfileCardHTML(profile);
            });
            panelContent.innerHTML = html;
            assignPanelButtonEvents();
        } else {
            panelContent.innerHTML = `
                <div class="text-center p-8 border-2 border-dashed border-gray-300 rounded-xl bg-white">
                    <i data-lucide="users" class="w-16 h-16 text-gray-300 mx-auto mb-4"></i>
                    <p class="text-gray-500 font-medium text-lg">
                        Aún no tienes perfiles guardados.
                    </p>
                </div>
            `;
        }
        lucide.createIcons();
    }

   function createProfileCardHTML(profile) {
        // Preparamos el contenido combinado para el editor Quill (único ID permitido)
        const combinedContentForEditor = `
            <h3>El Problema (Dolor)</h3>
            ${profile.problema}
            <br>
            <h3>El Deseo (Placer)</h3>
            ${profile.deseo}
        `;
        const profileId = profile.id;
        const editorContainerId = `editor-quill-${profileId}`;
        const hiddenInputId = `content-hidden-${profileId}`;
        const charCountId = `char-count-${profileId}`;
        const maxLength = 1500; // Hardcoded max length for now, or get from a global var/data attribute

        return `
            <div class="panel-profile-card border border-gray-200 rounded-lg p-4 bg-white shadow-sm mb-4" data-id="${profileId}">
                <div class="flex justify-between items-center mb-4 pb-2 border-b border-gray-100">
                    <h4 class="text-lg font-black uppercase text-[var(--color-primary)] truncate pr-2">${profile.titulo_perfil}</h4>
                    <div class="flex space-x-2 shrink-0">
                        <button class="btn-copy btn-sm bg-gray-800 text-white btn-panel-edit p-1 rounded" title="Editar"><i data-lucide="edit" class="w-4 h-4"></i></button>
                        <button class="btn-copy btn-sm bg-[var(--color-secondary)] text-white btn-panel-delete p-1 rounded" title="Eliminar"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
                        <button class="btn-copy btn-sm bg-green-600 text-white btn-panel-save hidden p-1 rounded" title="Guardar"><i data-lucide="save" class="w-4 h-4"></i></button>
                        <button class="btn-copy btn-sm bg-gray-500 text-white btn-panel-cancel hidden p-1 rounded" title="Cancelar"><i data-lucide="x" class="w-4 h-4"></i></button>
                    </div>
                </div>

                <div class="panel-display-mode text-sm text-gray-700 space-y-3">
                    <div>
                        <strong class="text-[var(--color-primary)] uppercase text-sm">Problema:</strong>
                        <div class="proposal-rendered-content pl-2 border-l-2 border-gray-200">${profile.problema}</div>
                    </div>
                    <div>
                        <strong class="text-[var(--color-primary)] uppercase text-sm">Deseo:</strong>
                        <div class="proposal-rendered-content pl-2 border-l-2 border-gray-200">${profile.deseo}</div>
                    </div>
                    <div>
                        <strong class="text-[var(--color-primary)] uppercase text-sm">Frase Clave:</strong>
                        <p class="italic">"${profile.frase_marketing}"</p>
                    </div>
                </div>
                
                <div class="panel-edit-mode hidden mt-2 space-y-3">
                    <div>
                        <label class="block text-sm font-bold uppercase text-gray-500 mb-1">Título:</label>
                        <input type="text" class="edit-titulo-input w-full p-2 border rounded bg-gray-50 text-sm" value="${profile.titulo_perfil}">
                    </div>
                    <div>
                           <label class="block text-sm font-bold uppercase text-gray-500 mb-1">Detalles (Problema y Deseo):</label>
                           <div class="editor-container-placeholder">
                               <div class="quill-container-wrapper">
                                   <div id="${editorContainerId}" class="bg-white" style="height: 200px;"></div>
                               </div>
                               <textarea id="${hiddenInputId}" class="hidden" maxlength="${maxLength}">${combinedContentForEditor}</textarea>
                               <p class="text-right text-sm font-mono mt-1"><span id="${charCountId}">0 / ${maxLength}</span></p>
                             </div>
                    </div>
                     <div>
                         <label class="block text-sm font-bold uppercase text-gray-500 mb-1">Frase Marketing:</label>
                         <input type="text" class="edit-frase-input w-full p-2 border rounded bg-gray-50 text-sm" value="${profile.frase_marketing || ''}">
                     </div>
                    
                    <textarea class="hidden original-content-storage">${combinedContentForEditor}</textarea>
                </div>
            </div>
        `;
    }

    function assignPanelButtonEvents() {
        panelContent.removeEventListener('click', panelContentClickListener);
        panelContent.addEventListener('click', panelContentClickListener);
    }
    
    const panelContentClickListener = function(e) {
        const btn = e.target.closest('button');
        if (!btn) return;
        
        const card = btn.closest('.panel-profile-card');
        const profileId = parseInt(card.dataset.id);
        
        if (btn.classList.contains('btn-panel-edit')) {
            // Aseguramos que solo un editor esté activo a la vez
            document.querySelectorAll('.panel-profile-card').forEach(c => {
                if (c !== card && !c.querySelector('.panel-edit-mode').classList.contains('hidden')) {
                    // Limpiar y cancelar otros editores (pasamos el botón 'cancelar' como referencia para la lógica interna)
                    const cancelBtn = c.querySelector('.btn-panel-cancel');
                    if (cancelBtn) {
                         toggleEditMode(c, false, cancelBtn);
                    }
                }
            });
            toggleEditMode(card, true, btn); // Pasamos el botón 'editar' como referencia
        }
        
        if (btn.classList.contains('btn-panel-cancel')) {
            toggleEditMode(card, false, btn); // Pasamos el botón 'cancelar' como referencia
        }

        if (btn.classList.contains('btn-panel-save')) {
            handleUpdateProfile(card, profileId, btn);
        }

        if (btn.classList.contains('btn-panel-delete')) {
            openModal({
                title: 'ADVERTENCIA',
                message: 'ELIMINAR ESTE PERFIL DE CLIENTE?',
                icon: 'alert-triangle',
                confirmText: 'ELIMINAR',
                confirmClass: 'danger',
                onConfirm: async () => {
                    await deleteProfileFromDB(profileId);
                }
            });
        }
    }

    function toggleEditMode(card, isEditing, triggeringBtn) {
        const displayMode = card.querySelector('.panel-display-mode');
        const editMode = card.querySelector('.panel-edit-mode');
        const profileId = card.dataset.id;
        const editorContainer = card.querySelector(`#editor-quill-${profileId}`);
        const hiddenInput = card.querySelector(`#content-hidden-${profileId}`);
        const charCountDisplay = card.querySelector(`#char-count-${profileId}`);

        // Toggle botones
        card.querySelector('.btn-panel-edit').classList.toggle('hidden', isEditing);
        card.querySelector('.btn-panel-delete').classList.toggle('hidden', isEditing);
        card.querySelector('.btn-panel-save').classList.toggle('hidden', !isEditing);
        card.querySelector('.btn-panel-cancel').classList.toggle('hidden', !isEditing);

        displayMode.classList.toggle('hidden', isEditing);
        editMode.classList.toggle('hidden', !isEditing);
        
        const quillInstanceId = `quill-instance-${profileId}`;

        if (isEditing) {
            // Activar modo edición
            if (editorContainer && hiddenInput && charCountDisplay) {
                const maxLength = parseInt(hiddenInput.getAttribute('maxlength')) || 1500;
                // Inicialización de Quill usando la función aislada.
                initializeQuillInstance(editorContainer, hiddenInput, charCountDisplay, maxLength, quillInstanceId);
                window.activeQuillId = quillInstanceId;
            }
        } else {
            // Desactivar modo edición/cancelar/guardar
            // Forzamos la limpieza si se cancela, se guarda, o si es una limpieza de editor anterior
            const isCleanupRequired = !triggeringBtn || 
                                     triggeringBtn.classList.contains('btn-panel-save') || 
                                     triggeringBtn.classList.contains('btn-panel-cancel') ||
                                     triggeringBtn.classList.contains('btn-panel-edit'); // Limpiar anterior al abrir uno nuevo
            
            if (isCleanupRequired) {
                // Si se canceló, restaurar el contenido original en el textarea oculto
                if (triggeringBtn && triggeringBtn.classList.contains('btn-panel-cancel')) {
                    const originalContent = card.querySelector('.original-content-storage').value;
                    hiddenInput.value = originalContent;
                    // También restaurar otros campos
                    const profileData = savedClientProfiles.find(p => p.id == profileId);
                    if(profileData) {
                         card.querySelector('.edit-titulo-input').value = profileData.titulo_perfil;
                         card.querySelector('.edit-frase-input').value = profileData.frase_marketing || '';
                    }
                }
                
                // Limpiar el contenedor de Quill para remover todo el DOM generado por la librería.
                // **ESTA ES LA CORRECCIÓN CLAVE EN LA LIMPIEZA**
                if (editorContainer) editorContainer.innerHTML = ''; 

                if (window.quillInstances[quillInstanceId]) {
                    // Eliminar la referencia a la instancia de Quill
                    delete window.quillInstances[quillInstanceId];
                }
                if (window.activeQuillId === quillInstanceId) {
                    window.activeQuillId = null;
                }
            }
        }
    }

    // --- CRUD ---
    async function handleUpdateProfile(card, id, triggeringBtn) {
        // Aseguramos la limpieza del editor después de guardar.
        // La limpieza se hará en toggleEditMode, por lo que primero leemos los valores
        // y luego llamamos a toggleEditMode(false, triggeringBtn)
        
        // Leer datos ANTES de llamar a toggleEditMode
        const titulo = card.querySelector('.edit-titulo-input').value;
        const frase = card.querySelector('.edit-frase-input').value;
        // El contenido HTML viene del textarea oculto
        const hiddenInputId = `content-hidden-${id}`;
        const htmlContent = document.getElementById(hiddenInputId).value;

        // Intento simple de separación (Fragil pero necesario para el modelo de datos)
        let problema = htmlContent; 
        let deseo = ""; 
        
        // Limpiar el contenido del editor antes de enviarlo
        problema = problema.replace('<h3>El Problema (Dolor)</h3>', '');
        deseo = deseo.replace('<h3>El Deseo (Placer)</h3>', '');

        if(htmlContent.includes('<h3>El Deseo (Placer)</h3>')) {
            const parts = htmlContent.split('<h3>El Deseo (Placer)</h3>');
            problema = parts[0].replace('<h3>El Problema (Dolor)</h3>', '');
            deseo = parts[1];
        }
        
        // Se asegura que no haya un 'undefined' o 'null' en la estructura.
        problema = problema || '';
        deseo = deseo || '';

        const currentOldProfile = savedClientProfiles.find(p => p.id === id);
        
        const profileData = {
            id: id,
            titulo_perfil: titulo,
            problema: problema,
            deseo: deseo,
            frase_marketing: frase,
            // Mantener datos viejos no editables
            sugerencias: currentOldProfile ? currentOldProfile.sugerencias : [],
            resumen_copiar: currentOldProfile ? currentOldProfile.resumen_copiar : ''
        };

        // Salir del modo edición y LIMPIAR el editor
        toggleEditMode(card, false, triggeringBtn); 

        setProcessingState(true, 'Actualizando...');
        try {
            const response = await fetch('api-db/ia-ideal-client-generator-update.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(profileData)
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast('Perfil actualizado.', 'success');
                // Actualizar array local
                const index = savedClientProfiles.findIndex(p => p.id === id);
                if(index !== -1) savedClientProfiles[index] = profileData;
                loadDataIntoPanel(); // Recargar vista
            } else {
                throw new Error(result.message || 'Error al actualizar');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(error.message, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    async function deleteProfileFromDB(id) {
        setProcessingState(true, 'Eliminando...');
        try {
            const response = await fetch('api-db/ia-ideal-client-generator-delete.php', {
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: id })
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast('Perfil eliminado.', 'success');
                savedClientProfiles = savedClientProfiles.filter(p => p.id !== id);
                loadDataIntoPanel();
            } else {
                throw new Error(result.message || 'Error al eliminar');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(error.message, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    async function createProfileInDB(profileData) {
        setProcessingState(true, 'Guardando...');
        try {
            const response = await fetch('api-db/ia-ideal-client-generator-create.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(profileData)
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast('Perfil guardado.', 'success');
                // Añadir ID retornado
                profileData.id = result.new_profile_id;
                savedClientProfiles.push(profileData);
                loadDataIntoPanel();
                openProposalPanel();
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(error.message, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    // --- MAIN FORM LOGIC ---
    function setProcessingState(isProcessing, customMessage = null) {
        const btnText = document.getElementById('btn-text');
        const loaderContainer = document.getElementById('loader-container');
        
        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');
            
            if (customMessage) {
                btnText.textContent = customMessage;
                if(window.loadingInterval) clearInterval(window.loadingInterval);
                return;
            }

            const messages = ["Contactando IA...", "Analizando Cliente...", "Redactando Perfil...", "Finalizando..."];
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];
            
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);

        } else {
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            btnText.textContent = 'GENERAR PERFIL CON IA';
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
            generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        }
    }

    form.addEventListener('submit', async function(event) {
        event.preventDefault();
        
        // Validación manual simple
        const requiredInputs = form.querySelectorAll('[required]');
        let valid = true;
        requiredInputs.forEach(input => {
            if(!input.value.trim()) {
                input.classList.add('border-red-500');
                valid = false;
            } else {
                input.classList.remove('border-red-500');
            }
        });
        
        if (!valid) {
            if (typeof showToast === 'function') showToast('Completa los campos requeridos.', 'warning');
            return;
        }

        setProcessingState(true);

        const formData = {
            service: document.getElementById('service').value,
            client_desc: document.getElementById('client_desc').value
        };

        try {
            const response = await fetch('api/api-ideal-client-generator.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });
            const data = await response.json();
            
            if (response.ok) {
                if (data.problema && data.deseo) {
                    profileGeneradoReciente = data;
                    displayResult(data);
                    if (typeof showToast === 'function') showToast('¡Perfil generado!', 'success');
                } else {
                    throw new Error('Respuesta incompleta de la IA.');
                }
            } else {
                throw new Error(data.error || 'Error del servidor.');
            }
        } catch (error) {
            console.error(error);
            if (typeof showToast === 'function') showToast(error.message, 'error');
        } finally {
            setProcessingState(false);
        }
    });

    function displayResult(data) {
        // Renderizar sugerencias
        const suggestionsList = (data.sugerencias || []).map(s => `
            <li class="flex items-start gap-3">
                <span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)] shrink-0"><i data-lucide="check" class="w-4 h-4"></i></span>
                <span class="text-sm md:text-base">${s}</span>
            </li>
        `).join('');

        resultContainer.innerHTML = `
            <div class="ai-response p-6 md:p-8 rounded-xl space-y-8 bg-white shadow-lg">
                <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                     <h3 class="text-3xl font-black text-gray-800 flex items-center">
                        <i data-lucide="sparkles" class="mr-3 text-[var(--color-primary)]"></i> ${data.titulo_perfil}
                    </h3>
                    <button id="save-new-profile-btn" class="btn btn-primary py-2 px-4 rounded-lg font-bold uppercase shadow-md flex items-center gap-2 hover:scale-105 transition-transform">
                        <i data-lucide="save" class="w-5 h-5"></i> Guardar Perfil
                    </button>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div class="space-y-6">
                        <div class="bg-gray-50 p-5 rounded-xl border border-gray-100">
                             <h4 class="text-lg font-black text-[var(--color-primary)] uppercase mb-3 flex items-center"><i data-lucide="frown" class="w-5 h-5 mr-2"></i> Problema (Dolor)</h4>
                             <div class="text-gray-700 leading-relaxed">${data.problema}</div>
                        </div>
                        <div class="bg-gray-50 p-5 rounded-xl border border-gray-100">
                             <h4 class="text-lg font-black text-[var(--color-primary)] uppercase mb-3 flex items-center"><i data-lucide="smile" class="w-5 h-5 mr-2"></i> Deseo (Placer)</h4>
                             <div class="text-gray-700 leading-relaxed">${data.deseo}</div>
                        </div>
                    </div>
                    
                    <div class="space-y-6">
                             <div class="bg-[var(--color-background)] p-5 rounded-xl border-l-4 border-[var(--color-secondary)]">
                                 <h4 class="text-lg font-black text-gray-800 uppercase mb-3">Frase Clave</h4>
                                 <p class="text-xl italic font-serif text-gray-700">"${data.frase_marketing}"</p>
                             </div>
                             
                             <div>
                                 <h4 class="text-lg font-black text-gray-800 uppercase mb-3">Sugerencias Estratégicas</h4>
                                 <ul class="space-y-3">${suggestionsList}</ul>
                             </div>
                    </div>
                </div>

                <div class="mt-8 bg-gray-100 p-6 rounded-xl">
                     <div class="flex justify-between items-center mb-4">
                        <h4 class="text-lg font-black text-gray-700 uppercase flex items-center"><i data-lucide="copy" class="w-5 h-5 mr-2"></i> Resumen para Copiar</h4>
                        <button class="btn-copy text-gray-500 hover:text-gray-800" data-copy-content="${encodeURIComponent(data.resumen_copiar_plano)}"><i data-lucide="clipboard-copy" class="w-5 h-5"></i></button>
                    </div>
                    <div class="bg-white p-4 rounded border border-gray-300 font-mono text-sm text-gray-600 max-h-40 overflow-y-auto">
                        ${data.resumen_copiar_plano}
                    </div>
                </div>
            </div>`;
        
        lucide.createIcons();
        setTimeout(() => {
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);

        // Evento Guardar Nuevo
        document.getElementById('save-new-profile-btn').addEventListener('click', () => {
             if (savedClientProfiles.length >= MAX_PROFILES) {
                 openModal({
                     title: 'LÍMITE ALCANZADO',
                     message: `Solo puedes guardar hasta ${MAX_PROFILES} perfiles.<br>Elimina uno existente para guardar este nuevo.`,
                     icon: 'alert-circle',
                     confirmText: 'VER PERFILES',
                     confirmClass: 'primary',
                     onConfirm: () => openProposalPanel()
                 });
             } else {
                 createProfileInDB(profileGeneradoReciente);
             }
        });

        // Evento Copiar
        resultContainer.querySelector('.btn-copy').addEventListener('click', function() {
            const text = decodeURIComponent(this.dataset.copyContent);
            navigator.clipboard.writeText(text).then(() => {
                if (typeof showToast === 'function') showToast('Copiado al portapapeles', 'success');
            });
        });
    }
    
    // Cargar datos al inicio
    loadDataIntoPanel();

});
</script>
<script src="files/toast.js"></script>
</body>
</html>