<?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 = htmlspecialchars($client_info['name'] ?? '', ENT_QUOTES, 'UTF-8');
$business_name = htmlspecialchars($client_info['business_name'] ?? '', ENT_QUOTES, 'UTF-8');
$phone = $client_info['phone'] ?? '';
$whatsapp = $client_info['whatsapp'] ?? '';
$email = $client_info['email'] ?? '';
$website = $client_info['website'] ?? '';
$operating_cities = htmlspecialchars($client_info['operating_cities'] ?? '', ENT_QUOTES, 'UTF-8');
$logo_url = htmlspecialchars($client_info['logo_url'] ?? '', ENT_QUOTES, 'UTF-8');

$value_proposition = $ia_results['value_proposition'] ?? '';
$social_links = $client_info['social_links'] ?? '';

// Define esto al inicio o en tu archivo de configuración
$allowed_tags = '<p><br><strong><b><em><i><u><ul><ol><li><h1><h2><h3><blockquote><span>';
$texto_limpio = strip_tags($raw_input, $allowed_tags);

// Obtener datos del video
$video_data = get_ia_video_by_id('ia-value-propositions');

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>Creador De Propuesta De Valor 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>
    <script src="files/editor.js"></script>
    
</head>
<body data-page-title="Creador De Propuesta De Valor"
      data-page-subtitle="Crea Una Propuesta Comercial Impresionante Para Tu Negocio"
      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 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-xs md:text-sm text-gray-500 hidden md:block"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <section id="proposal-generator-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="proposal-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="lightbulb" 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 Negocio y Cliente Ideal</span>
                                    </h2>
                                    <p class="step-subtitle uppercase text-gray-500 font-bold mt-2 ml-1 text-xs md:text-sm">Ingresa los datos para que la IA entienda tu negocio</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="business-name" class="block text-base md:text-lg font-bold capitalize text-gray-700 mb-2">Nombre del Negocio:</label>
                                        <input type="text" id="business-name" name="businessName" placeholder="Ej: Rod Cleaning Services" 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" value="<?php echo htmlspecialchars($business_name); ?>">
                                    </div>
                                    <div class="form-group">
                                        <label for="client-types" class="block text-base md:text-lg font-bold capitalize text-gray-700 mb-2">Tipo de Clientes (separados por comas):</label>
                                        <input type="text" id="client-types" name="clientTypes" placeholder="Ej: Profesionales Ocupados, Familias Con Hijos, Jubilados" 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="cities" class="block text-base md:text-lg font-bold capitalize text-gray-700 mb-2">Ciudades donde Trabaja (separadas por comas):</label>
                                        <input type="text" id="cities" name="cities" placeholder="Ej: Miami, Orlando, Tampa" 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" value="<?php echo htmlspecialchars($operating_cities); ?>">
                                    </div>
                                    <div class="form-group">
                                        <label for="business-description" class="block text-base md:text-lg font-bold capitalize text-gray-700 mb-2">Descripción del Negocio (Mínimo 250 caracteres):</label>
                                        <textarea id="business-description" name="businessDescription" rows="6" placeholder="Qué Hace Tu Negocio, Qué Problemas Resuelve, Etc." minlength="250" maxlength="1500" 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 class="char-count text-right text-xs md:text-sm text-gray-500 mt-1" id="description-char-count">0 / 1500 Caracteres</div>
                                        <div class="error-message text-red-500 text-xs md:text-sm font-black mt-1" id="description-error"></div>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" name="value_proposition" value="<?php echo htmlspecialchars($value_proposition); ?>">
                        </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 <?php echo htmlspecialchars($business_name); ?>" 
                                     class="block mx-auto object-contain h-24 max-w-[250px]">
                            </div>
                        <?php endif; ?>
                        
                        <button id="open-proposal-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="save" class="w-5 h-5"></i> <span>Tu Propuesta De Valor</span>
                        </button>
                    
                        <?php if ($video_data): ?>
                        <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="<?= htmlspecialchars($video_data['poster_url']) ?>">
                                        <source src="<?= htmlspecialchars($video_data['video_url']) ?>" 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="<?= htmlspecialchars($video_data['poster_url']) ?>" alt="VideoLeccion - FlowCRM" 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-xs 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> <?= htmlspecialchars($video_data['title'] ?? 'Tutorial') ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <div class="bg-white text-brand-dark p-4 md:p-8 rounded-xl shadow-md">
                            <div class="step-header">
                                <h2 class="text-xl md:text-2xl font-black pb-0 mb-0 flex items-center uppercase justify-center md:justify-start">
                                    <i data-lucide="shield-alert" class="mr-3 w-6 h-6 text-[var(--color-secondary)]"></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 ml-1 text-xs md:text-sm">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="lightbulb" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">DESCRIPCIÓN CLARA:</strong> Cuanto más detalles des, mejor serán las propuestas.</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="bot" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">GENERA Y PERFECCIONA:</strong> La IA te dará 2 opciones. Revísalas y adáptalas.</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="handshake" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">IMPRESIONA:</strong> Una propuesta clara te ayuda a vender más.</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">Genera tu Propuesta de Valor</span>
                            </h2>
                            <p class="step-subtitle uppercase text-gray-500 font-bold mt-2 ml-1 text-xs md:text-sm">Crea tu propuesta estratégica y persuasiva para tu negocio</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 crear una propuesta de valor que conecte, <b>es muy importante</b> tener información clara. Con esa base, nuestra <b>inteligencia artificial</b> generará tu <b>Propuesta De Valor</b> persuasiva.
                                </p>
                                
                                <div class="flex justify-center md:justify-start">
                                    <button id="generateBtn" type="submit" form="proposal-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 TU PROPUESTA 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="book-marked" class="w-6 h-6 md:w-8 md:h-8 mr-2 text-white shrink-0"></i>
            Tu Propuesta De Valor
        </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]">
            </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-xs font-black text-gray-500 tracking-wider"> 
                ESTA ACCIÓN NO SE PUREDE REVERTIR
            </p>
         </div>
        </div>
    </div>
</div>

<script type="module">
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;
        });
    }
    
    const phoneInput = document.getElementById('contact_phone');
    if (phoneInput) IMask(phoneInput, { mask: '(000) 000-0000' });

    // --- ELEMENTS ---
    const proposalForm = document.getElementById('proposal-form');
    const resultContainer = document.getElementById('result-container');
    const generateBtn = document.getElementById('generateBtn');
    const businessDescriptionInput = document.getElementById('business-description');
    const descriptionCharCount = document.getElementById('description-char-count');
    const descriptionError = document.getElementById('description-error');

    businessDescriptionInput.addEventListener('input', function() {
        const currentLength = this.value.length;
        descriptionCharCount.textContent = `${currentLength} / ${this.maxLength} Caracteres`;
        descriptionError.textContent = currentLength < this.minLength ? `Mínimo ${this.minLength} caracteres.` : '';
    });
    businessDescriptionInput.dispatchEvent(new Event('input'));

    // --- PANEL LATERAL ---
    const openPanelBtn = document.getElementById('open-proposal-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');
    
    // --- 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 propuestaGuardadaActual = <?php echo json_encode($value_proposition); ?>;

    // --- MODAL LOGIC ---
    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 openProposalPanel() {
        proposalPanel.classList.remove('translate-x-full');
        panelOverlay.classList.remove('hidden');
        loadDataIntoPanel(); 
    }

    function closeProposalPanel() {
        proposalPanel.classList.add('translate-x-full');
        panelOverlay.classList.add('hidden');
    }

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

    // --- PANEL RENDERER ---
    function loadDataIntoPanel() {
        if (propuestaGuardadaActual && propuestaGuardadaActual.trim() !== '') {
            panelContent.innerHTML = `
                <div class="panel-profile-card border border-gray-200 rounded-lg p-4 mb-4 bg-white" data-prop-id="1">
                    <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)]">Propuesta Actual</h4>
                        <div class="flex space-x-2">
                            <button class="btn-copy btn-xs bg-gray-800 text-white btn-panel-edit p-1 rounded" title="Editar"><i data-lucide="edit" class="w-5 h-5"></i></button>
                            <button class="btn-copy btn-xs bg-[var(--color-secondary)] text-white btn-panel-delete p-1 rounded" title="Eliminar"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
                            <button class="btn-copy btn-xs bg-green-600 text-white btn-panel-save hidden p-1 rounded" title="Guardar"><i data-lucide="save" class="w-5 h-5"></i></button>
                            <button class="btn-copy btn-xs bg-gray-500 text-white btn-panel-cancel hidden p-1 rounded" title="Cancelar"><i data-lucide="x" class="w-5 h-5"></i></button>
                        </div>
                    </div>

                    <div class="panel-display-mode">
                         <div class="proposal-rendered-content text-gray-700 text-base leading-relaxed">${propuestaGuardadaActual}</div>
                    </div>
                    
                    <div class="panel-edit-mode hidden mt-2">
                        <div class="quill-container-wrapper">
                            <div id="editor-de-texto-quill" class="bg-white"></div>
                        </div>
                        <textarea id="contenido-oculto" class="hidden">${propuestaGuardadaActual}</textarea>
                        <div id="contador-caracteres" class="text-right text-xs text-gray-500 mt-1"></div>
                    </div>
                </div>
            `;
            assignPanelButtonEvents();
        } else {
            panelContent.innerHTML = `
                <div class="text-center p-8 border-2 border-dashed border-gray-300 rounded-xl bg-white">
                    <i data-lucide="file-x-2" 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 una propuesta guardada.
                    </p>
                    <button onclick="document.getElementById('close-proposal-panel-btn').click(); document.getElementById('generateBtn').scrollIntoView({behavior: 'smooth'});" class="mt-4 text-[var(--color-highlight)] font-bold hover:underline">
                        ¡Genera una ahora!
                    </button>
                </div>
            `;
        }
        lucide.createIcons();
    }

    function assignPanelButtonEvents() {
        panelContent.removeEventListener('click', panelContentClickListener);
        panelContent.addEventListener('click', panelContentClickListener);
    }
    
    const panelContentClickListener = function(e) {
        const editBtn = e.target.closest('.btn-panel-edit');
        const deleteBtn = e.target.closest('.btn-panel-delete');
        const saveBtn = e.target.closest('.btn-panel-save');
        const cancelBtn = e.target.closest('.btn-panel-cancel');

        if (editBtn) {
            // CORRECCIÓN CLAVE: Destruir el contenido anterior para evitar doble toolbar
            const wrapper = document.querySelector('.quill-container-wrapper');
            if (wrapper) {
                // Forzamos un div limpio cada vez que se entra en edición
                wrapper.innerHTML = '<div id="editor-de-texto-quill" class="bg-white"></div>';
            }

            toggleEditMode(true);
            // Disparar evento para que editor.js se ejecute sobre el div limpio
            document.dispatchEvent(new Event('DOMContentLoaded'));
        }
        
        if (cancelBtn) {
            toggleEditMode(false);
            loadDataIntoPanel(); // Recargar limpia el DOM
        }

        if (saveBtn) {
            handleUpdateProposal();
        }

        if (deleteBtn) {
            openModal({
                title: 'ADVERTENCIA',
                message: '¿ELIMINAR ESTA PROPUESTA?',
                icon: 'alert-triangle',
                confirmText: 'ELIMINAR',
                confirmClass: 'danger',
                onConfirm: async () => {
                    await deleteProposalFromDB();
                    loadDataIntoPanel();
                }
            });
        }
    }

    function toggleEditMode(isEditing) {
        const container = document.querySelector(`[data-prop-id="1"]`);
        if (!container) return;

        container.querySelector('.panel-display-mode').classList.toggle('hidden', isEditing);
        container.querySelector('.panel-edit-mode').classList.toggle('hidden', !isEditing);
        
        container.querySelector('.btn-panel-edit').classList.toggle('hidden', isEditing);
        container.querySelector('.btn-panel-delete').classList.toggle('hidden', isEditing);
        container.querySelector('.btn-panel-save').classList.toggle('hidden', !isEditing);
        container.querySelector('.btn-panel-cancel').classList.toggle('hidden', !isEditing);
    }

    async function handleUpdateProposal() {
        // Leemos del input oculto que editor.js actualiza
        const newText = document.getElementById('contenido-oculto').value;

        openModal({
            title: 'CONFIRMACIÓN',
            message: '¿GUARDAR LOS CAMBIOS?',
            icon: 'save',
            confirmText: 'GUARDAR',
            confirmClass: 'secondary',
            onConfirm: async () => {
                await updateProposalInDB(newText);
                toggleEditMode(false);
                loadDataIntoPanel();
            }
        });
    }

    // --- CRUD ---
    async function updateProposalInDB(proposalText) {
        setProcessingState(true, 'Actualizando...');
        try {
            const response = await fetch('api-db/ia-value-propositions-update.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ value_proposition: proposalText })
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast('Propuesta actualizada.', 'success');
                propuestaGuardadaActual = proposalText;
            } else {
                throw new Error(result.message || 'Error al actualizar');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(error.message, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    async function deleteProposalFromDB() {
        setProcessingState(true, 'Eliminando...');
        try {
            const response = await fetch('api-db/ia-value-propositions-delete.php', {
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' }
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast('Propuesta eliminada.', 'success');
                propuestaGuardadaActual = '';
            } else {
                throw new Error(result.message || 'Error al eliminar');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(error.message, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    async function executeSave(proposalText) {
        setProcessingState(true, 'Guardando...');
        try {
            const response = await fetch('api-db/ia-value-propositions-create.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ value_proposition: proposalText })
            });
            const result = await response.json();
            
            if (response.ok) {
                if (result.success) {
                    if (typeof showToast === 'function') showToast('Propuesta guardada.', 'success');
                    propuestaGuardadaActual = proposalText;
                    loadDataIntoPanel();
                    openProposalPanel();
                } else {
                    if (response.status === 409) throw new Error('Ya existe una propuesta guardada.');
                    throw new Error(result.message);
                }
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(error.message, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    async function createProposalInDB(proposalText) {
        if (propuestaGuardadaActual && propuestaGuardadaActual.trim() !== '') {
            openModal({
                title: 'ADVERTENCIA',
                message: '¿REEMPLAZAR PROPUESTA ACTUAL?',
                icon: 'refresh-cw',
                confirmText: 'REEMPLAZAR',
                confirmClass: 'danger',
                onConfirm: async () => {
                    await updateProposalInDB(proposalText);
                    loadDataIntoPanel();
                    openProposalPanel();
                }
            });
        } else {
            executeSave(proposalText);
        }
    }
    
    // --- 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 = ["Conectando con IA...", "Analizando datos...", "Redactando...", "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 TU PROPUESTA CON IA';
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
            generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        }
    }

    proposalForm.addEventListener('submit', async function(event) {
        event.preventDefault();
        if (!proposalForm.checkValidity() || businessDescriptionInput.value.length < businessDescriptionInput.minLength) {
            proposalForm.reportValidity();
            if (typeof showToast === 'function') showToast('Completa los campos correctamente.', 'warning');
            return;
        }

        setProcessingState(true);

        const formData = {
            businessName: document.getElementById('business-name').value,
            clientTypes: document.getElementById('client-types').value,
            cities: document.getElementById('cities').value,
            businessDescription: document.getElementById('business-description').value
        };

        try {
            const response = await fetch('api/api-value-propositions.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                body: JSON.stringify(formData)
            });
            const data = await response.json();
            
            if (response.ok) {
                if (data.option1_es && data.option2_es) {
                    displayResult(data);
                    if (typeof showToast === 'function') showToast('¡Propuestas generadas!', '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) {
        resultContainer.innerHTML = `
            <div class="ai-response p-6 md:p-8 rounded-xl space-y-8 bg-white shadow-lg">
                <h3 class="text-3xl font-black text-gray-800 mb-6 flex items-center justify-center md:justify-start">
                    <i data-lucide="sparkles" class="mr-3 text-[var(--color-primary)]"></i> Propuestas Generadas
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    ${createOptionCard(1, data.option1_es, data.option1_en)}
                    ${createOptionCard(2, data.option2_es, data.option2_en)}
                </div>
            </div>`;
        
        lucide.createIcons();
        setTimeout(() => {
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);
    }

    function createOptionCard(index, esText, enText) {
        return `
            <div class="proposal-option-card border border-gray-200 rounded-xl p-5 hover:shadow-md transition-shadow bg-gray-50">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-xl font-black text-[var(--color-primary)] uppercase flex items-center">
                        <i data-lucide="tag" class="w-5 h-5 mr-2"></i>Opción ${index}
                    </h3>
                    <button class="btn-save-option btn-copy bg-[var(--color-secondary)] text-white px-3 py-1.5 rounded-lg text-sm font-bold flex items-center hover:bg-red-800 transition-colors" data-proposal-text="${encodeURIComponent(esText)}">
                        <i data-lucide="save" class="w-4 h-4 mr-1"></i> GUARDAR
                    </button>
                </div>
                
                <div class="mb-6">
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-xs font-bold text-gray-500 uppercase tracking-wider flex items-center gap-1">🇪🇸 Español</span>
                        <button class="text-gray-400 hover:text-gray-600 btn-copy" data-copytarget-text="${encodeURIComponent(esText)}" title="Copiar Español">
                            <i data-lucide="copy" class="w-4 h-4"></i>
                        </button>
                    </div>
                    <div class="bg-white p-4 rounded-lg border border-gray-200 text-gray-700 text-base leading-relaxed">
                        ${esText}
                    </div>
                </div>

                <div>
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-xs font-bold text-gray-500 uppercase tracking-wider flex items-center gap-1">🇺🇸 English</span>
                        <button class="text-gray-400 hover:text-gray-600 btn-copy" data-copytarget-text="${encodeURIComponent(enText)}" title="Copiar Inglés">
                            <i data-lucide="copy" class="w-4 h-4"></i>
                        </button>
                    </div>
                    <div class="bg-white p-4 rounded-lg border border-gray-200 text-gray-700 text-base leading-relaxed italic">
                        ${enText}
                    </div>
                </div>
            </div>
        `;
    }

    resultContainer.addEventListener('click', function(e) {
        const copyButton = e.target.closest('.btn-copy:not(.btn-save-option)');
        const saveButton = e.target.closest('.btn-save-option');

        if (copyButton) {
            const textToCopy = decodeURIComponent(copyButton.dataset.copytargetText);
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = textToCopy.replace(/<br\s*\/?>/gi, '\n');
            const plainText = tempDiv.textContent || tempDiv.innerText || '';
            
            navigator.clipboard.writeText(plainText).then(() => {
                const originalIcon = copyButton.innerHTML;
                copyButton.innerHTML = '<i data-lucide="circle-check" class="w-4 h-4 text-green-600"></i>';
                lucide.createIcons();
                if (typeof showToast === 'function') showToast('Copiado.', 'success');
                setTimeout(() => { copyButton.innerHTML = originalIcon; lucide.createIcons(); }, 2000);
            });
        }

        if (saveButton) {
            const textToSave = decodeURIComponent(saveButton.dataset.proposalText);
            createProposalInDB(textToSave);
        }
    });

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