<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
require_once 'ia-marketing-results.php';
require_once 'media/videos-ia.php';

$client_name = $client_info['name'] ?? '';
$business_name = $client_info['business_name'] ?? '';
$phone = $client_info['phone'] ?? '';
$whatsapp = $client_info['whatsapp'] ?? '';
$email = $client_info['email'] ?? '';
$website = $client_info['website'] ?? '';
$operating_cities = $client_info['operating_cities'] ?? '';
$logo_url = $client_info['logo_url'] ?? '';
$value_proposition = $ia_results['value_proposition'] ?? '';
$current_client_profiles = $ia_results['ideal_client_profiles'] ?? [];
$social_links = $client_info['social_links'] ?? [];

if (ob_get_level() > 0) { ob_end_clean(); }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Creador De Propuestas De Proyectos Con <?php echo htmlspecialchars($branding['iamarketing_name']); ?> Powered_by <?php echo htmlspecialchars($branding['powered_by']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>
    <style>
        .proposal-rendered-content h3 {
            font-size: 1.25rem;
            font-weight: 800;
            color: var(--color-primary);
            margin-top: 1rem;
            margin-bottom: 0.5rem;
        }
        .proposal-rendered-content ul {
            list-style-type: disc;
            padding-left: 1.5rem;
            margin-top: 0.5rem;
        }
        .proposal-rendered-content li {
            margin-bottom: 0.25rem;
        }
        
        .tox-tinymce {
            border-radius: 0.5rem !important;
            border: 1px solid #d1d5db !important;
        }
    </style>
</head>
<body data-page-title="Creador De Propuestas De Proyectos"
      data-page-subtitle="Genera Propuestas Profesionales Para Ganar Nuevos Clientes"
      data-page-icon="brain">

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

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

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

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'ia-menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <section id="proposal-generator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <div class="lg:col-span-3">
                        <form id="proposal-form" class="space-y-8 bg-white p-8 rounded-xl shadow-md">
                            <div>
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                        <i data-lucide="clipboard-list" class="mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> Define Los Detalles De Tu Proyecto
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa la información detallada para generar tu propuesta de proyecto.</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>
                                <div class="space-y-6">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div><label for="your_name" class="block text-lg font-bold capitalize text-gray-700 mb-2">Tu Nombre</label><input type="text" id="your_name" name="your_name" placeholder="Ej: Juan Perez" 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)]" value="<?php echo htmlspecialchars($client_name); ?>"></div>
                                        <div><label for="your_company" class="block text-lg font-bold capitalize text-gray-700 mb-2">Nombre De Tu Empresa</label><input type="text" id="your_company" name="your_company" placeholder="Ej: Agencia Digital Orozco" 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)]" value="<?php echo htmlspecialchars($business_name); ?>"></div>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div><label for="client_name" class="block text-lg font-bold capitalize text-gray-700 mb-2">Nombre Del Cliente</label><input type="text" id="client_name" name="client_name" placeholder="Ej: Ana García" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required></div>
                                        <div><label for="client_company" class="block text-lg font-bold capitalize text-gray-700 mb-2">Nombre De La Empresa Del Cliente</label><input type="text" id="client_company" name="client_company" placeholder="Ej: Repostería Creativa" 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)]"></div>
                                    </div>
                                    <div>
                                        <label for="project_name" class="block text-lg font-bold capitalize text-gray-700 mb-2">Descripción Del Proyecto</label>
                                        <input type="text" id="project_name" name="project_name" placeholder="Ej: Desarrollo De Nuevo Sitio Web Ecommerce" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                    </div>
                                    <div>
                                        <label for="project_objective" class="block text-lg font-bold capitalize text-gray-700 mb-2">Objetivo Principal Del Proyecto</label>
                                        <textarea id="project_objective" name="project_objective" placeholder="Ej: Crear Una Tienda Online Para Vender Postres" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" rows="3" required></textarea>
                                    </div>
                                    <div>
                                        <label for="key_deliverables" class="block text-lg font-bold capitalize text-gray-700 mb-2">Entregables Clave (¿Qué Incluye?)</label>
                                        <textarea id="key_deliverables" name="key_deliverables" placeholder="Ej: Diseño Web, Catálogo Virtual, Pasarela De Pagos." class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" rows="4" required></textarea>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                                        <div><label for="timeline" class="block text-lg font-bold capitalize text-gray-700 mb-2">Plazo Estimado</label><input type="text" id="timeline" name="timeline" placeholder="Ej: 4 Semanas" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required></div>
                                        <div><label for="price" class="block text-lg font-bold capitalize text-gray-700 mb-2">Inversión ($)</label><input type="number" step="0.01" id="price" name="price" placeholder="Ej: 2,500" 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)]" min="1" required></div>
                                        <div><label for="validity_period" class="block text-lg font-bold capitalize text-gray-700 mb-2">Validez</VAlabel><input type="text" id="validity_period" name="validity_period" placeholder="Ej: 15 Días" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required></div>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" name="value_proposition" value="<?php echo htmlspecialchars($value_proposition); ?>">
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        
                        <?php if (!empty($logo_url)): ?>
                            <div class="bg-white p-4 rounded-xl shadow-md">
                                <img src="<?php echo htmlspecialchars($logo_url); ?>" 
                                     alt="Logotipo de <?php echo htmlspecialchars($business_name); ?>" 
                                     class="block mx-auto" 
                                     style="max-width: 250px;">
                            </div>
                        <?php endif; ?>
                        
                        <button id="open-proposal-panel-btn" class="btn-copy bg-[var(--color-secondary)] text-white flex items-center justify-center w-full py-4 px-6 rounded-lg font-black text-lg uppercase gap-2 hover:scale-102 transition-transform">
                            <i data-lucide="save" class="w-5 h-5"></i> <span>Tus Propuestas De Proyecto</span>
                        </button>
                        
                        <div class="w-full">
                                <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                                    <div class="relative w-full" style="padding-bottom: 56.25%;">
                                        <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayer" controls controlslist="nodownload fullscreen" preload="metadata">
                                            <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                                            TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                                        </video>
                                        <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                                            <img src="img/VideoLeccion-IAMarketing.jpg" alt="VideoLeccion - IAMarketing" class="absolute inset-0 w-full h-full object-cover">
                                            <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                                            <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                                        </div>
                                    </div>
                                    <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="play-circle" class="w-4 h-4"></i> Video Tutorial
                                        </span>
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="clock" class="w-4 h-4"></i> 2:30 min
                                        </span>
                                    </div>
                                </div>
                            </div>
                        <div class="bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-md">
                            <div class="step-header">
                                <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase justify-center md:justify-start">
                                    <i data-lucide="book-open" class="mr-3 text-[var(--color-highlight)]"></i>
                                    <span class="step-title">INSTRUCCIONES IMPORTANTES</span>
                                </h2>
                                <p class="step-subtitle text-center md:text-left uppercase">REVISA ESTOS PUNTOS DETALLADAMENTE</p>
                            </div>
                            <div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <ul class="space-y-4 text-gray-700">
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="file-edit"></i></span><div><strong class="text-brand-dark uppercase">COMPLETA LOS DATOS:</strong> Rellena todos los campos para dar el contexto completo a la IA.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="rocket"></i></span><div><strong class="text-brand-dark uppercase">GENERA TU PROPUESTA:</strong> Obtén un texto profesional y persuasivo en segundos.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="save"></i></span><div><strong class="text-brand-dark uppercase">GUARDA TUS PROPUESTAS:</strong> Puedes guardar hasta 3 propuestas para re-utilizarlas.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="send"></i></span><div><strong class="text-brand-dark uppercase">ENVIA A TU PROSPECTO:</strong> Una propuesta profesional aumenta tus probabilidades de ganar el proyecto.</div></li>
                            </ul>
                        </div>
                    </div>

                    <div class="lg:col-span-5 bg-white p-6 md:p-8 rounded-xl shadow-md mt-6">
                        <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                <i data-lucide="zap" class="mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> Recibe Tu Propuesta Profesional
                            </h2>
                            <p class="step-subtitle uppercase">Obtén una propuesta profesional y persuasiva para presentar tu servicio</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                        
<div class="grid grid-cols-1 md:grid-cols-3 gap-6 md:gap-8 items-center">

    <div class="flex flex-col justify-center items-center bg-[var(--color-primary)] p-6 rounded-xl">
        <i data-lucide="brain" class="w-24 h-24 md:w-32 md:h-32 text-white animate-pulse"></i>
        <p class="mt-4 text-white font-black text-xl uppercase tracking-wide">
            IA<span class="text-[var(--color-highlight)]">Marketing</span>™
        </p>
    </div>

    <div class="md:col-span-2 text-center md:text-left">
        
        <h3 class="text-2xl font-black text-gray-800 flex items-center justify-center md:justify-start mb-2 uppercase">
            <i data-lucide="bell-electric" class="w-6 h-6 text-[var(--color-secondary)] mr-2 flex-shrink-0"></i>
            Información Importante
        </h3>
        
        <p class="text-lg text-gray-700 mb-6">
            Para ganar nuevos clientes potenciales, <b>es importante</b> que tu propuesta para nuevos proyectos se persiva como una propuesta profesional. Nuestra <b>inteligencia artificial</b> generará tu <b>Propuesta De Proyectos</b>, para que presentes propuestas profesionales y consigas cerrar más proyectos.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="proposal-form" class="w-full sm:w-auto bg-[var(--color-highlight)] text-[var(--color-primary)] font-black py-4 px-6 rounded-lg hover:scale-105 transition-transform text-lg flex items-center justify-center uppercase">
                
                <i data-lucide="arrow-big-right-dash" class="w-6 h-6"></i>
                
                <span id="btn-text">GENERAR PROPUESTA DE PROYECTO CON IA</span>
                
                <div id="loader-container" class="hidden ml-3"></div>
            </button>
        </div>
    </div>
    
</div>
                           
                    </div>

                    <div id="result-container" class="lg:col-span-5 mt-8"></div>
                </div>
            </section>
        </div>
    </main>
</div>

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

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

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

</div>

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

<div id="input-modal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-[100]">
    <div class="bg-white p-8 rounded-xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-left">
        <h3 id="input-modal-title" class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase"></h3>
        <p id="input-modal-message" class="text-gray-700 mb-4"></p>
        <input type="text" id="input-modal-field" 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)]" placeholder="Escribe aquí...">
        <p id="input-modal-error" class="text-[var(--color-secondary)] text-sm mt-1 hidden">El nombre no puede estar vacío.</p>
        <div class="flex justify-end space-x-4 mt-6">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" id="input-modal-cancel-btn">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold text-white py-2 px-4 rounded-lg uppercase" id="input-modal-confirm-btn">GUARDAR</button>
        </div>
    </div>
</div>


<script type="module">
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    // --- MANEJADORES DE MENÚ Y UI BÁSICA ---
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');

    mobileMenuButton.addEventListener('click', () => {
        sidebar.classList.toggle('-translate-x-full');
        sidebarOverlay.classList.toggle('hidden');
    });

    sidebarOverlay.addEventListener('click', () => {
        sidebar.classList.add('-translate-x-full');
        sidebarOverlay.classList.add('hidden');
    });

    // NOTIFICACIONES TOAST
    const urlParams = new URLSearchParams(window.location.search);
    const notificationType = urlParams.get('notification_type');
    const notificationMessage = urlParams.get('notification_message');

    if (notificationType && notificationMessage) {
        if (typeof showToast === 'function') {
            showToast(notificationMessage, notificationType);
        }
    }
    
    // VIDEO PLAYER
    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 al reproducir video: " + e.message, 'error');
                }
            });
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }
    
    // MASCARA DEL TELEFONO
    const phoneInput = document.getElementById('contact_phone');
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }
    
    // --- ELEMENTOS DE LA HERRAMIENTA ---
    const form = document.getElementById('proposal-form');
    const generateBtn = document.getElementById('generateBtn');
    const resultContainer = document.getElementById('result-container');
    let generatedProposals = null; // Para guardar los datos de la IA

    // --- ELEMENTOS DEL 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');
    let savedProposals = []; // Array para las propuestas guardadas

    // --- ELEMENTOS DEL MODAL DE CONFIRMACIÓN (SÍ/NO) ---
    const confirmationModal = document.getElementById('confirmation-modal');
    const confirmationModalBox = confirmationModal.querySelector('div:first-of-type');
    const confirmationModalIcon = document.getElementById('modal-icon');
    const confirmationModalTitle = document.getElementById('modal-title');
    const confirmationModalMessage = document.getElementById('modal-message');
    const confirmationModalCancelBtn = document.getElementById('modal-cancel-btn');
    const confirmationModalConfirmBtn = document.getElementById('modal-confirm-btn');
    let onConfirmCallback = null;

    // --- ELEMENTOS DEL MODAL DE INPUT ---
    const inputModal = document.getElementById('input-modal');
    const inputModalBox = inputModal.querySelector('div:first-of-type');
    const inputModalTitle = document.getElementById('input-modal-title');
    const inputModalMessage = document.getElementById('input-modal-message');
    const inputModalField = document.getElementById('input-modal-field');
    const inputModalError = document.getElementById('input-modal-error');
    const inputModalCancelBtn = document.getElementById('input-modal-cancel-btn');
    const inputModalConfirmBtn = document.getElementById('input-modal-confirm-btn');
    let onInputConfirmCallback = null;


    // --- LÓGICA DEL MODAL DE CONFIRMACIÓN (SÍ/NO) ---
    function openModal({ title, message, icon, confirmText, confirmClass, onConfirm }) {
        confirmationModalTitle.textContent = title;
        confirmationModalMessage.innerHTML = message;
        confirmationModalIcon.setAttribute('data-lucide', icon);
        lucide.createIcons({ nodes: [confirmationModalIcon] });

        confirmationModalConfirmBtn.textContent = confirmText || 'CONFIRMAR';
        confirmationModalConfirmBtn.className = 'btn-secondary font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto text-white'; 
        
        if (confirmClass === 'danger') {
            confirmationModalConfirmBtn.classList.add('bg-[var(--color-secondary)]', 'hover:bg-[var(--color-secondary)]');
            confirmationModalConfirmBtn.classList.remove('btn-secondary');
        } else if (confirmClass === 'primary') {
             confirmationModalConfirmBtn.classList.add('bg-[var(--color-primary)]');
             confirmationModalConfirmBtn.classList.remove('btn-secondary');
        }

        onConfirmCallback = onConfirm; 
        confirmationModal.classList.remove('hidden');
        setTimeout(() => confirmationModalBox.classList.remove('scale-95', 'opacity-0'), 50);
        document.body.style.overflow = 'hidden';
    }

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

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

    // --- LÓGICA DEL MODAL DE INPUT ---
    function openInputModal({ title, message, placeholder, defaultValue, confirmText, onConfirm }) {
        inputModalTitle.textContent = title;
        inputModalMessage.textContent = message;
        inputModalField.placeholder = placeholder || "Escribe aquí...";
        inputModalField.value = defaultValue || "";
        inputModalConfirmBtn.textContent = confirmText || 'GUARDAR';
        onInputConfirmCallback = onConfirm;
        
        inputModalError.classList.add('hidden');
        inputModal.classList.remove('hidden');
        setTimeout(() => {
            inputModalBox.classList.remove('scale-95', 'opacity-0');
            inputModalField.focus();
        }, 50);
        document.body.style.overflow = 'hidden';
    }

    function closeInputModal() {
        inputModalBox.classList.add('scale-95', 'opacity-0');
        setTimeout(() => {
            inputModal.classList.add('hidden');
            document.body.style.overflow = '';
        }, 300);
        onInputConfirmCallback = null;
    }

    inputModalCancelBtn.addEventListener('click', closeInputModal);
    inputModalConfirmBtn.addEventListener('click', () => {
        const value = inputModalField.value.trim();
        if (value === "") {
            inputModalError.classList.remove('hidden');
        } else {
            inputModalError.classList.add('hidden');
            if (typeof onInputConfirmCallback === 'function') {
                onInputConfirmCallback(value);
            }
            closeInputModal();
        }
    });

    // --- LÓGICA DEL PANEL LATERAL ---
    async function openProposalPanel() {
        proposalPanel.classList.remove('translate-x-full');
        panelOverlay.classList.remove('hidden');
        await 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);

    // Cargar y renderizar datos en el panel
    async function loadDataIntoPanel() {
        panelContent.innerHTML = '<div class="text-center"><div class="w-8 h-8 border-4 border-t-transparent border-[var(--color-primary)] rounded-full animate-spin mx-auto"></div><p class="mt-2">Cargando...</p></div>';
        try {
            const response = await fetch('api-db/ia-project-proposals-fetch.php');
            const result = await response.json();
            
            if (response.ok && result.success) {
                savedProposals = result.data;
                renderPanelContent();
            } else {
                throw new Error(result.message || 'Error al cargar propuestas');
            }
        } catch (error) {
            panelContent.innerHTML = `<p class="text-[var(--color-secondary)]">${error.message}</p>`;
            if (typeof showToast === 'function') showToast(error.message, 'error');
        }
    }
    
    // Renderizar el contenido del panel
    function renderPanelContent() {
        if (savedProposals.length > 0) {
            let html = '<div class="space-y-6">';
            savedProposals.forEach(proposal => {
                html += `
                <div class="border border-gray-200 rounded-xl overflow-hidden" data-proposal-id="${proposal.id}">
                    <div class="bg-gray-50 p-4 flex justify-between items-center">
                        <div id="display-name-${proposal.id}" class="flex-1">
                            <h4 class="text-xl font-black uppercase text-[var(--color-primary)]">${proposal.proposal_name}</h4>
                        </div>
                        <div id="edit-name-area-${proposal.id}" class="flex-1 hidden">
                            <input type="text" id="edit-name-input-${proposal.id}" value="${proposal.proposal_name}" class="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)]">
                        </div>
                        <div class="flex space-x-2 ml-4">
                            <button class="btn-copy btn-xs bg-[var(--color-primary)] text-white btn-panel-edit" data-id="${proposal.id}"><i data-lucide="edit"></i></button>
                            <button class="btn-copy btn-xs bg-[var(--color-secondary)] text-white btn-panel-delete" data-id="${proposal.id}"><i data-lucide="trash-2"></i></button>
                            <button class="btn-copy btn-xs bg-green-600 text-white btn-panel-save hidden" data-id="${proposal.id}"><i data-lucide="save"></i></button>
                            <button class="btn-copy btn-xs bg-gray-500 text-white btn-panel-cancel hidden" data-id="${proposal.id}"><i data-lucide="x"></i></button>
                        </div>
                    </div>
                    
                    <div class="p-4">
                        <div id="display-content-${proposal.id}" class="space-y-4">
                            <div>
                                <h5 class="font-bold text-gray-700 mb-2">🇪🇸 Español:</h5>
                                <div class="bg-gray-50 p-4 rounded-lg border-l-4 border-[var(--color-highlight)] shadow-inner proposal-rendered-content">
                                    ${proposal.proposal_spanish} 
                                </div>
                            </div>
                             <div>
                                <h5 class="font-bold text-gray-700 mt-4 mb-2">🇺🇸 English:</h5>
                                <div class="bg-gray-50 p-4 rounded-lg border-l-4 border-[var(--color-highlight)] shadow-inner proposal-rendered-content">
                                    ${proposal.proposal_english}
                                </div>
                            </div>
                        </div>
                        <div id="edit-content-area-${proposal.id}" class="hidden space-y-4">
                            <div>
                                <label class="font-bold text-gray-700">🇪🇸 Español:</label>
                                <textarea id="edit-es-input-${proposal.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-48 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">${proposal.proposal_spanish}</textarea>
                            </div>
                            <div>
                                <label class="font-bold text-gray-700">🇺🇸 English:</label>
                                <textarea id="edit-en-input-${proposal.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-48 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">${proposal.proposal_english}</textarea>
                            </div>
                        </div>
                    </div>
                </div>
                `;
            });
            html += '</div>';
            panelContent.innerHTML = html;
        } else {
            panelContent.innerHTML = `
                <div class="text-center p-4 border border-dashed rounded-lg">
                    <i data-lucide="info" class="w-12 h-12 text-gray-400 mx-auto mb-3"></i>
                    <p class="text-gray-500">
                        Aún no has guardado ninguna propuesta. (Máx. 3)
                    </p>
                </div>
            `;
        }
        lucide.createIcons();
    }

    // Asignar eventos a los botones del panel (delegación)
    panelContent.addEventListener('click', 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) {
            const id = editBtn.dataset.id;
            toggleEditMode(id, true);
            
            // --- UNIFICACIÓN: INICIALIZAR TinyMCE ---
            if (typeof tinymce !== 'undefined') {
                tinymce.init({
                    selector: `#edit-es-input-${id}, #edit-en-input-${id}`,
                    menubar: false,
                    statusbar: false,
                    height: 300,
                    plugins: 'lists link', // Plugins simples
                    toolbar: 'bold italic underline | h3 h4 | bullist numlist | removeformat',
                    language: 'es',
                    skin: 'oxide',
                    content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px; color:#333; }'
                });
            }
            // --- FIN UNIFICACIÓN ---
        }
        
        if (cancelBtn) {
            const id = cancelBtn.dataset.id;
            
            // --- UNIFICACIÓN: ELIMINAR TinyMCE ---
            if (typeof tinymce !== 'undefined') {
                tinymce.remove(`#edit-es-input-${id}`);
                tinymce.remove(`#edit-en-input-${id}`);
            }
            // --- FIN UNIFICACIÓN ---
            
            toggleEditMode(id, false);
            // Reset fields to original values
            const proposal = savedProposals.find(p => p.id == id);
            document.getElementById(`edit-name-input-${id}`).value = proposal.proposal_name;
            // No es necesario resetear textareas, loadDataIntoPanel() lo hará al recargar
        }
        
        if (saveBtn) {
            const id = saveBtn.dataset.id;
            const newName = document.getElementById(`edit-name-input-${id}`).value;
            
            // --- UNIFICACIÓN: OBTENER DATOS DE TinyMCE ---
            let newEs, newEn;
            if (typeof tinymce !== 'undefined' && tinymce.get(`edit-es-input-${id}`)) {
                newEs = tinymce.get(`edit-es-input-${id}`).getContent();
                newEn = tinymce.get(`edit-en-input-${id}`).getContent();
            } else {
                // Fallback por si acaso no cargó
                newEs = document.getElementById(`edit-es-input-${id}`).value;
                newEn = document.getElementById(`edit-en-input-${id}`).value;
            }
            // --- FIN UNIFICACIÓN ---
            
            openModal({
                title: 'CONFIRMAR ACTUALIZACIÓN',
                message: '¿Estás seguro de que quieres guardar estos cambios?',
                icon: 'save',
                confirmText: 'SÍ, GUARDAR',
                onConfirm: () => {
                    // --- UNIFICACIÓN: ELIMINAR TinyMCE ANTES DE GUARDAR ---
                    if (typeof tinymce !== 'undefined') {
                        tinymce.remove(`#edit-es-input-${id}`);
                        tinymce.remove(`#edit-en-input-${id}`);
                    }
                    // --- FIN UNIFICACIÓN ---
                    updateProposalInDB(id, newName, newEs, newEn);
                }
            });
        }
        
        if (deleteBtn) {
            const id = deleteBtn.dataset.id;
            openModal({
                title: 'CONFIRMAR ELIMINACIÓN',
                message: '¿Estás seguro de que quieres eliminar esta propuesta? <br> Esta acción no se puede deshacer.',
                icon: 'alert-triangle',
                confirmText: 'SÍ, ELIMINAR',
                confirmClass: 'danger',
                onConfirm: () => deleteProposalFromDB(id)
            });
        }
    });

    function toggleEditMode(id, isEditing) {
        const container = document.querySelector(`[data-proposal-id="${id}"]`);
        if (!container) return;

        container.querySelector(`#display-name-${id}`).classList.toggle('hidden', isEditing);
        container.querySelector(`#edit-name-area-${id}`).classList.toggle('hidden', !isEditing);
        container.querySelector(`#display-content-${id}`).classList.toggle('hidden', isEditing);
        container.querySelector(`#edit-content-area-${id}`).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);
    }

    // --- LÓGICA DE BASE DE DATOS ---

    async function createProposalInDB(name, spanish, english) {
        if (savedProposals.length >= 3) {
            openModal({
                title: 'LÍMITE ALCANZADO',
                message: 'Ya has guardado el máximo de 3 propuestas. <br>Por favor, elimina una para guardar esta nueva.',
                icon: 'alert-circle',
                confirmText: 'ENTENDIDO',
                confirmClass: 'primary',
                onConfirm: () => {}
            });
            return;
        }

        setProcessingState(true, 'Guardando...');
        try {
            const response = await fetch('api-db/ia-project-proposals-create.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    proposal_name: name,
                    proposal_spanish: spanish,
                    proposal_english: english
                })
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                await loadDataIntoPanel();
                openProposalPanel();
            } else {
                throw new Error(result.message || 'Error desconocido al guardar');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al guardar: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    async function updateProposalInDB(id, name, spanish, english) {
        setProcessingState(true, 'Actualizando...');
        try {
            const response = await fetch('api-db/ia-project-proposals-update.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    id: id,
                    proposal_name: name,
                    proposal_spanish: spanish, 
                    proposal_english: english 
                })
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                await loadDataIntoPanel(); 
            } else {
                throw new Error(result.message || 'Error desconocido al actualizar');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al actualizar: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    async function deleteProposalFromDB(id) {
        setProcessingState(true, 'Eliminando...');
        try {
            const response = await fetch('api-db/ia-project-proposals-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(result.message, 'success');
                await loadDataIntoPanel(); 
            } else {
                throw new Error(result.message || 'Error desconocido al eliminar');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al eliminar: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    // --- LÓGICA DE LA HERRAMIENTA IA ---

    function validateForm() {
        const requiredInputs = form.querySelectorAll('[required]');
        let allValid = true;
        requiredInputs.forEach(input => {
            if (!input.value.trim() || (input.tagName === 'SELECT' && input.value === '')) {
                input.classList.add('border-[var(--color-secondary)]');
                allValid = false;
            } else {
                input.classList.remove('border-[var(--color-secondary)]');
            }
        });
        if (!allValid) {
            if (typeof showToast === 'function') {
                showToast('Por favor, completa todos los campos requeridos.', 'warning');
            }
        }
        return allValid;
    }

    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);
                window.loadingInterval = null;
                return;
            }
            
            resultContainer.innerHTML = '';
            const messages = ["Contactando Con OrozCO IA...", "Analizando Tu Proyecto...", "Redactando La Propuesta...", "Casi Está Lista..."];
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];
            
            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);

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

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

        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        try {
            const response = await fetch('api/api-project-proposals.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });

            const result = await response.json();
            if (!response.ok) {
                throw new Error(result.error || `Error del servidor: ${response.status}`);
            }
            
            generatedProposals = result; // Guardar globalmente
            displayResult(result);

        } catch (error) {
            let errorMessage = error.message || "No se pudo generar la propuesta. Inténtalo de nuevo.";
            resultContainer.innerHTML = `<div class="bg-[var(--color-secondary)] text-center p-4 text-white rounded-lg border border-[var(--color-secondary)]"><p><strong>Error:</strong> ${errorMessage}</p></div>`;
            resultContainer.style.opacity = '1';
            if (typeof showToast === 'function') {
                showToast(errorMessage, 'error');
            }
        } finally {
            setProcessingState(false);
        }
    });

    function displayResult(data) {
        resultContainer.innerHTML = `
            <div class="ai-response p-6 md:p-8 rounded-xl shadow-xl">
                <div class="mb-6 border-b border-gray-200">
                    <nav class="flex space-x-4 -mb-px" aria-label="Tabs">
                        <button id="tab-es" class="tab-button tab-active">🇪🇸 Propuesta En Español</button>
                        <button id="tab-en" class="tab-button">🇺🇸 Propuesta En Inglés</button>
                    </nav>
                </div>

                <div id="content-es" class="tab-content">
                    <div class="flex flex-col sm:flex-row justify-between items-start mb-4 gap-2">
                        <h3 class="text-2xl font-black text-gray-800 flex items-center"><i data-lucide="file-text" class="mr-2 text-[var(--color-secondary)]"></i>Propuesta Personalizada</h3>
                        <div class="flex space-x-2">
                            <button class="btn-copy" data-lang="es">
                                <i data-lucide="copy"></i><span class="copy-text">Copiar</span>
                            </button>
                            <button class="btn-save btn-copy bg-[var(--color-secondary)] text-white">
                                <i data-lucide="save"></i><span class="copy-text">Guardar</span>
                            </button>
                        </div>
                    </div>
                    <div class="proposal-text-container message-box proposal-rendered-content">${data.proposal_spanish}</div>
                </div>

                <div id="content-en" class="tab-content hidden">
                    <div class="flex flex-col sm:flex-row justify-between items-start mb-4 gap-2">
                        <h3 class="text-2xl font-black text-gray-800 flex items-center"><i data-lucide="file-text" class="mr-2 text-[var(--color-secondary)]"></i>Generated Personalized Proposal</h3>
                         <div class="flex space-x-2">
                            <button class="btn-copy" data-lang="en">
                                <i data-lucide="copy"></i><span class="copy-text">Copy</span>
                            </button>
                             <button class="btn-save btn-copy bg-[var(--color-secondary)] text-white">
                                <i data-lucide="save"></i><span class="copy-text">Save</span>
                            </button>
                        </div>
                    </div>
                    <div class="proposal-text-container message-box proposal-rendered-content">${data.proposal_english}</div>
                </div>
            </div>`;
            
        lucide.createIcons();

        // Lógica de Tabs
        const tabEs = document.getElementById('tab-es');
        const tabEn = document.getElementById('tab-en');
        const contentEs = document.getElementById('content-es');
        const contentEn = document.getElementById('content-en');

        if (tabEs && tabEn && contentEs && contentEn) {
            tabEs.addEventListener('click', () => {
                contentEs.classList.remove('hidden');
                contentEn.classList.add('hidden');
                tabEs.classList.add('tab-active');
                tabEn.classList.remove('tab-active');
            });
            tabEn.addEventListener('click', () => {
                contentEn.classList.remove('hidden');
                contentEs.classList.add('hidden');
                tabEn.classList.add('tab-active');
                tabEs.classList.remove('tab-active');
            });
        }
        
        // Lógica de Copiar y Guardar (Delegada)
        resultContainer.addEventListener('click', function(e) {
            const copyButton = e.target.closest('.btn-copy:not(.btn-save)');
            const saveButton = e.target.closest('.btn-save');

            if (copyButton) {
                // Para copiar, revertimos el HTML a texto plano simple
                const textToCopy = (copyButton.dataset.lang === 'es' ? generatedProposals.proposal_spanish : generatedProposals.proposal_english)
                    .replace(/<br\s*\/?>/gi, '\n')
                    .replace(/<h3>/gi, '\n## ')
                    .replace(/<\/h3>/gi, ' ##\n')
                    .replace(/<ul>/gi, '\n')
                    .replace(/<\/ul>/gi, '\n')
                    .replace(/<li>/gi, '- ')
                    .replace(/<\/li>/gi, '\n')
                    .replace(/<p>/gi, '')
                    .replace(/<\/p>/gi, '\n')
                    .trim();

                navigator.clipboard.writeText(textToCopy).then(() => {
                    const originalHTML = copyButton.innerHTML;
                    copyButton.innerHTML = '<i data-lucide="check" class="mr-2"></i><span>¡Copiado!</span>';
                    lucide.createIcons({ nodes: [copyButton] });
                    if (typeof showToast === 'function') {
                        showToast('Propuesta copiada al portapapeles.', 'success');
                    }
                    setTimeout(() => { 
                        copyButton.innerHTML = originalHTML; 
                        lucide.createIcons({ nodes: [copyButton] });
                    }, 2000);
                }).catch(err => {
                    if (typeof showToast === 'function') {
                        showToast('Error al copiar el texto.', 'error');
                    }
                });
            }

            if (saveButton) {
                openInputModal({
                    title: 'GUARDAR PROPUESTA',
                    message: 'Dale un nombre a esta propuesta para identificarla:',
                    defaultValue: document.getElementById('project_name').value || "Nueva Propuesta",
                    confirmText: 'GUARDAR',
                    onConfirm: (name) => {
                         if (name && name.trim() !== "") {
                             // Guardamos el HTML tal cual vino de la IA
                            createProposalInDB(name.trim(), generatedProposals.proposal_spanish, generatedProposals.proposal_english);
                        }
                    }
                });
            }
        });

        resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
});
</script>
<script src="files/toast.js"></script>
</body>
</html>