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

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

if (ob_get_level() > 0) { ob_end_clean(); }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generador De Descripciones Para Servicios 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>
        .step-header h2 {
            flex-direction: column;
            align-items: flex-start;
            text-align: left;
        }
        .step-header .step-number {
            font-size: 1.25rem;
            font-weight: 900;
            margin-right: 0;
            margin-bottom: 0.25rem;
            display: flex;
            align-items: center;
            color: var(--color-secondary);
            flex-shrink: 0;
        }
        .step-header .step-number i {
            margin-right: 0.5rem;
            font-size: 1.5rem;
        }
        .step-header .step-title {
            font-size: 1.4rem;
            font-weight: 900;
            color: #1e293b;
            line-height: 1.2;
            text-transform: uppercase;
            text-align: left;
            width: 100%;
        }
        @media (min-width: 768px) {
            .step-header h2 {
                flex-direction: row;
                align-items: center;
                justify-content: flex-start;
                text-align: left;
            }
            .step-header .step-number {
                font-size: 1.5rem;
                margin-right: 0.5rem;
                margin-bottom: 0;
            }
            .step-header .step-number i {
                font-size: 1.8rem;
            }
            .step-header .step-title {
                font-size: 1.5rem;
                width: auto;
            }
        }
        .saved-description-card {
            border: 1px solid #e5e7eb; border-radius: 0.75rem;
            margin-bottom: 1.5rem; overflow: hidden;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        .saved-description-header {
            background-color: #f9fafb; padding: 1rem 1.5rem;
            border-bottom: 1px solid #e5e7eb;
            display: flex; justify-content: space-between; align-items: center;
        }
        /* Estilos de Quill */
        .quill-container-wrapper {
            border: 1px solid #d1d5db;
            border-radius: 0.5rem;
            background-color: #fff;
            overflow: hidden; 
        }
        .ql-container {
            min-height: 150px;
            border: none !important;
        }
        .ql-container.ql-snow {
             border: none !important;
        }
        .ql-toolbar.ql-snow {
             border-top-left-radius: 0.5rem;
             border-top-right-radius: 0.5rem;
             border-bottom: 1px solid #d1d5db !important;
        }
        /* Ajuste de altura */
        .editor-purpose .ql-container { min-height: 80px; }
        .editor-lang .ql-container { min-height: 200px; }
        /* Para el textarea que no es Quill pero se edita */
        .plain-textarea-edit {
            width: 100%; padding: 0.75rem; border: 1px solid #d1d5db;
            border-radius: 0.5rem; background-color: #fff; min-height: 100px;
        }
    </style>
</head>
<body data-page-title="Generador De Descripciones Para Servicios"
      data-page-subtitle="Crea Textos Que Explican El Valor Y Los Detalles De Lo Que Ofreces"
      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="service-description-creator" class="dashboard-section">
                    <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                        <div class="lg:col-span-3">
                            <form id="service-form" class="space-y-8 bg-white p-8 rounded-xl shadow-md">
                                <input type="hidden" name="value_proposition" value="<?php echo htmlspecialchars($value_proposition); ?>">
                                <div>
                                    <div class="step-header">
                                        <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                            <span class="step-number"> <i data-lucide="pen-tool" class="mr-3 text-[var(--color-secondary)]"></i> PASO 1:
                                            </span>
                                            <span class="step-title"> Define Tu Servicio
                                            </span>
                                        </h2>
                                        <p class="step-subtitle uppercase">Describe tu servicio para que la IA lo haga irresistible.</p>
                                    </div>
                                    <div class="border-b border-gray-200 pb-4 mb-6"></div>
                                    <div class="space-y-6">
                                        <div>
                                            <label for="service_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre del Servicio:</label>
                                            <input type="text" id="service_name" name="service_name" placeholder="Ej: Servicio De Limpieza Profunda" 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="service_features" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué Incluye tu Servicio? (Descríbelo con viñetas)</label>
                                            <textarea id="service_features" name="service_features" rows="5" placeholder="Ej:\n- Limpieza De Pisos\n- Desinfección De Baños\n- Limpieza De Ventanas Y Espejos" 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></textarea>
                                        </div>
                                        <div>
                                            <label for="problem_solved" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Problema que Resuelve el Servicio:</label>
                                            <input type="text" id="problem_solved" name="problem_solved" placeholder="Ej: Falta De Tiempo Para Limpiar, Estrés Por La Suciedad" 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="key_benefit" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Beneficio Clave para el Cliente:</label>
                                            <input type="text" id="key_benefit" name="key_benefit" placeholder="Ej: Un Hogar Limpio Y Más Tiempo Libre Para La Familia" 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_profile_select" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Carga Un Perfil De Cliente Guardado (Opcional):</label>
                                            <select id="client_profile_select" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                                <option value="" data-resumen="">Selecciona Un Perfil</option>
                                                <?php foreach ($current_client_profiles as $profile): ?>
                                                    <option 
                                                        value="<?php echo htmlspecialchars($profile['id'] ?? ''); ?>"
                                                        data-resumen="<?php echo htmlspecialchars($profile['resumen_copiar'] ?? ''); ?>">
                                                        <?php echo htmlspecialchars($profile['titulo_perfil'] ?? 'Perfil sin título'); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>

                                        <div>
                                            <label for="target_audience" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Público Objetivo / Resumen del Cliente:</label>
                                            <textarea id="target_audience" name="target_audience" rows="3" placeholder="Ej: Familias Ocupadas, Profesionales. (Autocompletado desde el menú)" 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)]"></textarea>
                                        </div>
                                        
                                        <div>
                                            <label for="additional_details" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Detalles Adicionales (Opcional):</label>
                                            <textarea id="additional_details" name="additional_details" rows="3" placeholder="Ej: Puntos Específicos A Considerar, Ofertas Especiales, Etc." 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)]"></textarea>
                                        </div>
                                    </div>
                                </div>
                            </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-descriptions-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>Descripciones De Servicios</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="list-checks"></i></span>
                                        <div>
                                            <strong class="text-brand-dark uppercase">SÉ DETALLISTA:</strong> Describe exactamente lo que incluye tu servicio para que la IA lo traduzca a beneficios.
                                        </div>
                                    </li>
                                    <li class="instructions-list-item">
                                        <span class="icon-wrapper"><i data-lucide="zap"></i></span>
                                        <div>
                                            <strong class="text-brand-dark uppercase">PIENSA EN EL CLIENTE:</strong> Enfócate en el problema que resuelves, no solo en la tarea que realizas.
                                        </div>
                                    </li>
                                    <li class="instructions-list-item">
                                        <span class="icon-wrapper"><i data-lucide="edit"></i></span>
                                        <div>
                                            <strong class="text-brand-dark uppercase">GENERA VERSIONES:</strong> Obtén una descripción corta (para anuncios), una larga (para web) y un mensaje conversacional.
                                        </div>
                                    </li>
                                    <li class="instructions-list-item">
                                        <span class="icon-wrapper"><i data-lucide="trending-up"></i></span>
                                        <div>
                                            <strong class="text-brand-dark uppercase">VENDE MÁS:</strong> Una descripción persuasiva es la clave para que tus clientes te elijan a ti.
                                        </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">
                                    <span class="step-number"> <i data-lucide="brain" class="mr-3 text-[var(--color-secondary)]"></i> PASO 2:
                                    </span>
                                    <span class="step-title"> Obtén Descripciones que Vendan
                                    </span>
                                </h2>
                                <p class="step-subtitle uppercase">Transforma tus servicios en textos persuasivos.</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 id="processing-indicator" class="text-xs text-white mt-2 hidden"></div>
    </div>

    <div class="md:col-span-2 text-center md:text-left">
        
        <h3 class="text-2xl font-black text-gray-800 flex items-center justify-center md:justify-start mb-2 uppercase">
            <i data-lucide="bell-electric" class="w-6 h-6 text-[var(--color-secondary)] mr-2 flex-shrink-0"></i>
            Información Importante
        </h3>
        
        <p class="text-lg text-gray-700 mb-6">
            Para que la descripción de tus servicios sea efectiva, <b>es importante</b> que conozcas los beneficios que ofreces con tus productos o servicios. Con esa información, nuestra <b>inteligencia artificial</b> creará <b>Descripciones Para Tus Servicios</b>, para que tengas textos que explican el valor y los detalles de lo que ofreces con tus servicios.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="service-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 DESCRIPCIONES 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="descriptions-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>

<div id="descriptions-panel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col">
    
    <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
        <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase">
            <i data-lucide="save" class="w-8 h-8 mr-2 text-white"></i>
            DESCRIPCIONES
        </h3>
        <button id="close-descriptions-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="descriptions-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 descripciones...</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-descriptions-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">
    // Variables globales para Quill
    let quillInstances = {};
    // SOLO los campos que deben tener editor (texto enriquecido)
    const QUILL_FIELDS = ['text_es', 'text_en']; 

document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    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'); });

    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 al reproducir video: " + 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' });
    }

    const form = document.getElementById('service-form');
    const resultContainer = document.getElementById('result-container');
    const generateBtn = document.getElementById('generateBtn');
    const btnText = document.getElementById('btn-text');
    const loaderContainer = document.getElementById('loader-container');
    const processingIndicator = document.getElementById('processing-indicator');

    const MAX_DESCRIPTIONS = 5; 
    let generatedDescriptions = null; 
    let inputsGeneradosReciente = null;
    let saveButtons = {};
    const savedProfiles = <?php echo json_encode($current_client_profiles ?? []); ?>;
    let savedDescriptions = [];

    const openDescriptionsPanelBtn = document.getElementById('open-descriptions-panel-btn');
    const closeDescriptionsPanelBtn = document.getElementById('close-descriptions-panel-btn');
    const descriptionsPanelOverlay = document.getElementById('descriptions-panel-overlay');
    const descriptionsPanel = document.getElementById('descriptions-panel');
    const descriptionsPanelContent = document.getElementById('descriptions-panel-content');

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

    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;

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

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

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

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

    openDescriptionsPanelBtn.addEventListener('click', openDescriptionsPanel);
    closeDescriptionsPanelBtn.addEventListener('click', closeDescriptionsPanel);
    descriptionsPanelOverlay.addEventListener('click', closeDescriptionsPanel);

    function openDescriptionsPanel() {
        descriptionsPanel.classList.remove('translate-x-full');
        descriptionsPanelOverlay.classList.remove('hidden');
        fetchAndDrawDescriptions();
    }
    function closeDescriptionsPanel() {
        // Al cerrar el panel, destruir cualquier editor activo para evitar fugas de memoria.
        savedDescriptions.forEach(desc => {
            QUILL_FIELDS.forEach(field => {
                const editorId = `quill-editor-${field}-${desc.id}`;
                if (quillInstances[editorId]) {
                    const originalContent = document.getElementById(`edit-${field}-input-${desc.id}`).value;
                    const editorContainer = quillInstances[editorId].container.parentNode;
                    if (editorContainer) {
                        editorContainer.innerHTML = `<div id="${editorId}" class="ql-editor panel-edit-textarea">${originalContent}</div>`;
                    }
                    delete quillInstances[editorId];
                }
            });
        });

        descriptionsPanel.classList.add('translate-x-full');
        descriptionsPanelOverlay.classList.add('hidden');
    }

    const clientProfileSelect = document.getElementById('client_profile_select');
    const targetAudienceTextarea = document.getElementById('target_audience');

    if (clientProfileSelect) {
        clientProfileSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const resumen = selectedOption.getAttribute('data-resumen');

            if (resumen) {
                targetAudienceTextarea.value = resumen.trim();
                targetAudienceTextarea.dispatchEvent(new Event('input'));
                if (typeof showToast === 'function') showToast('Perfil de cliente cargado en el resumen.', 'success');
            } else {
                targetAudienceTextarea.value = '';
                targetAudienceTextarea.dispatchEvent(new Event('input'));
            }
        });
    }

    const descriptionEndpoints = {
        fetch: 'api-db/ia-services-descriptions-fetch.php',
        create: 'api-db/ia-services-descriptions-create.php',
        update: 'api-db/ia-services-descriptions-update.php',
        delete: 'api-db/ia-services-descriptions-delete.php'
    };
    
    async function fetchAndDrawDescriptions() {
        descriptionsPanelContent.innerHTML = '<div class="text-center p-4"><div class="w-8 h-8 border-4 border-t-transparent border-[var(--color-secondary)] rounded-full animate-spin mx-auto mb-3"></div><p class="text-gray-600">Cargando descripciones guardadas...</p></div>';
        try {
            const response = await fetch(descriptionEndpoints.fetch, { method: 'POST' });
            const result = await response.json();

            if (response.ok && result.success) {
                savedDescriptions = result.descriptions;
                if (savedDescriptions.length === 0) {
                    descriptionsPanelContent.innerHTML = `<div class="text-center p-4 border border-dashed rounded-lg"><i data-lucide="info" class="w-12 h-12 text-gray-400 mx-auto mb-3"></i><p class="text-gray-500">Aún no tienes descripciones guardadas.</p></div>`;
                } else {
                    let html = `<p class="text-gray-600 mb-4 uppercase font-black">Has guardado ${savedDescriptions.length} de ${MAX_DESCRIPTIONS} descripciones.</p>`;
                    html += '<div class="space-y-6">';
                    savedDescriptions.forEach((desc, index) => { html += createSavedDescriptionCard(desc, index); });
                    html += '</div>';
                    descriptionsPanelContent.innerHTML = html;
                }
            } else {
                throw new Error(result.message || 'Error al obtener descripciones.');
            }
        } catch (error) {
            descriptionsPanelContent.innerHTML = `<div class="bg-[var(--color-secondary)] text-center p-4 text-white rounded-lg border border-[var(--color-secondary)]"><p><strong>Error al cargar:</strong> ${error.message}</p></div>`;
        }
        lucide.createIcons();
    }
    
    // Función auxiliar para crear la estructura de Quill
    const createQuillStructure = (descId, fieldKey, content, type) => {
        const textareaId = `edit-${fieldKey}-input-${descId}`;
        const editorId = `quill-editor-${fieldKey}-${descId}`;
        const editorClass = type === 'purpose' ? 'editor-purpose' : 'editor-lang';

        return `
            <div id="${editorId}-quill-container" class="quill-container-wrapper ${editorClass}">
                <div id="${editorId}" class="ql-editor panel-edit-textarea">${content}</div>
            </div>
            <textarea id="${textareaId}" class="hidden">${content}</textarea>
        `;
    };

    function createSavedDescriptionCard(desc, index) {
        const full_text_es = desc.text_es;
        const full_text_en = desc.text_en;
        const full_purpose = desc.purpose_description;

        function formatText(text) {
            if (typeof text !== 'string') return '';
            let formattedText = text.replace(/\n\n/g, '<P_SEP>'); 
            
            formattedText = formattedText.replace(/^[-*] (.*)/gm, '<li>$1</li>');
            
            let tempHtml = formattedText.replace(/(<li>.*?<\/li>[\s\S]*?<li>.*?<\/li>)/g, '<LIST_BLOCK>$1</LIST_BLOCK>');
            
            tempHtml = tempHtml.replace(/<LIST_BLOCK>([\s\S]*?)<\/LIST_BLOCK>/g, '<ul>$1</ul>');
            
            tempHtml = tempHtml.replace(/^(<li>.*?<\/li>)$/gm, '<ul>$1</ul>');
            
            tempHtml = tempHtml.replace(/<P_SEP>/g, '<br><br>');
            tempHtml = tempHtml.replace(/\n/g, '<br>');

            return tempHtml;
        }

        const formatted_es = formatText(desc.text_es);
        const formatted_en = formatText(desc.text_en);
        const formatted_purpose = formatText(desc.purpose_description);

        return `
            <div class="border border-gray-200 rounded-xl overflow-hidden" data-desc-id="${desc.id}">
                <div class="bg-gray-50 p-4 flex justify-between items-center">
                    <div id="display-name-${desc.id}" class="flex-1">
                        <h4 class="text-xl font-black uppercase text-[var(--color-primary)]">${desc.type}</h4>
                    </div>
                    <div id="edit-name-area-${desc.id}" class="flex-1 hidden">
                        <h4 class="text-xl font-black uppercase text-[var(--color-primary)]">${desc.type}</h4>
                    </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="${desc.id}"><i data-lucide="edit"></i></button>
                        <button class="btn-copy btn-xs bg-[var(--color-secondary)] text-white btn-panel-delete" data-id="${desc.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="${desc.id}"><i data-lucide="save"></i></button>
                        <button class="btn-copy btn-xs bg-gray-500 text-white btn-panel-cancel hidden" data-id="${desc.id}"><i data-lucide="x"></i></button>
                    </div>
                </div>

                <div class="p-4">
                    <div id="display-content-${desc.id}" class="space-y-4">
                        <p class="text-gray-600 text-sm"><strong>Propósito:</strong> ${formatted_purpose}</p>
                        <div class="border-t pt-3 space-y-2">
                            <strong class="text-lg text-[var(--color-secondary)]">🇪🇸 Español:</strong>
                            <div class="text-gray-800">${formatted_es}</div>
                            <button class="btn-copy btn-xs bg-[var(--color-highlight)] text-[var(--color-primary)] mt-2" data-copy-text="${encodeURIComponent(full_text_es)}">
                                <i data-lucide="copy"></i> Copiar ES
                            </button>
                        </div>
                        <div class="border-t pt-3 space-y-2">
                            <strong class="text-lg text-[var(--color-primary)]">🇺🇸 English:</strong>
                            <div class="text-gray-800">${formatted_en}</div>
                            <button class="btn-copy btn-xs bg-blue-600 text-white mt-2" data-copy-text="${encodeURIComponent(full_text_en)}">
                                <i data-lucide="copy"></i> Copiar EN
                            </button>
                        </div>
                        <div class="text-xs text-gray-500 p-4 border-t border-gray-100">
                           Servicio: ${desc.service_name_input} | Creado: ${new Date(desc.created_at).toLocaleDateString()}
                        </div>
                    </div>

                    <div id="edit-content-area-${desc.id}" class="hidden space-y-4">
                         <p class="text-xs text-gray-500">Servicio: ${desc.service_name_input}</p>
                         <div>
                            <label class="font-bold text-gray-700">Propósito:</label>
                                                         <textarea id="edit-purpose-input-${desc.id}" class="plain-textarea-edit h-32">${full_purpose}</textarea>
                        </div>
                        <div>
                            <label class="font-bold text-gray-700">🇪🇸 Español:</label>
                             ${createQuillStructure(desc.id, 'text_es', full_text_es, 'lang')}
                        </div>
                        <div>
                            <label class="font-bold text-gray-700">🇺🇸 English:</label>
                             ${createQuillStructure(desc.id, 'text_en', full_text_en, 'lang')}
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    descriptionsPanelContent.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');
        const copyBtn = e.target.closest('[data-copy-text]');

        if (editBtn) {
            const id = editBtn.dataset.id;
            const originalDesc = savedDescriptions.find(d => d.id == id);
            
            // 1. Destruir cualquier editor activo en otras tarjetas
            savedDescriptions.forEach(desc => {
                if (desc.id != id) {
                    QUILL_FIELDS.forEach(field => {
                        const editorId = `quill-editor-${field}-${desc.id}`;
                        if (quillInstances[editorId]) {
                            const originalContent = document.getElementById(`edit-${field}-input-${desc.id}`).value;
                            const editorContainer = quillInstances[editorId].container.parentNode;
                            if (editorContainer) {
                                editorContainer.innerHTML = `<div id="${editorId}" class="ql-editor panel-edit-textarea">${originalContent}</div>`;
                            }
                            delete quillInstances[editorId];
                        }
                    });
                    toggleEditMode(desc.id, false);
                }
            });
            
            // 2. Mostrar modo edición de la tarjeta actual
            toggleEditMode(id, true);
            
            // 3. Inicializar Quill en los campos correspondientes
            QUILL_FIELDS.forEach(field => {
                const editorId = `quill-editor-${field}-${id}`;
                const textareaId = `edit-${field}-input-${id}`;
                const editorElement = document.getElementById(editorId);
                
                if (editorElement && !quillInstances[editorId]) {
                    // Quill reemplaza el DIV con su propia estructura (toolbar + container)
                    const quill = new Quill(editorElement.parentNode, { 
                        theme: 'snow',
                        modules: { toolbar: [['bold', 'italic', 'underline'], [{ 'list': 'ordered'}, { 'list': 'bullet' }]] },
                    });

                    // Sincronizar contenido con el textarea oculto
                    const textareaElement = document.getElementById(textareaId);
                    quill.on('text-change', () => {
                        textareaElement.value = quill.root.innerHTML;
                    });
                    
                    quillInstances[editorId] = quill;
                }
            });
        }
        
        if (cancelBtn) {
            const id = cancelBtn.dataset.id;
            const originalDesc = savedDescriptions.find(d => d.id == id);
            
            // 1. Destruir Quill y restaurar el DOM
            QUILL_FIELDS.forEach(field => {
                const editorId = `quill-editor-${field}-${id}`;
                const textareaId = `edit-${field}-input-${id}`;
                if (quillInstances[editorId]) {
                    const originalContent = originalDesc[field];
                    const editorContainer = quillInstances[editorId].container.parentNode;
                    
                    if (editorContainer) {
                         // Restaurar DIV de edición original con el contenido original
                        editorContainer.innerHTML = `<div id="${editorId}" class="ql-editor panel-edit-textarea">${originalContent}</div>`;
                    }
                    // Restaurar valor del textarea oculto
                    document.getElementById(textareaId).value = originalContent;
                    delete quillInstances[editorId]; 
                }
            });
            
            // 2. Restaurar valor del textarea simple (Propósito)
            document.getElementById(`edit-purpose-input-${id}`).value = originalDesc.purpose_description;

            // 3. Volver a modo visualización
            toggleEditMode(id, false);
        }
        
        if (saveBtn) {
            const id = saveBtn.dataset.id;
            handleUpdateDescription(id);
        }
        
        if (deleteBtn) {
            const id = deleteBtn.dataset.id;
            handleDeleteDescription(id);
        }

        if (copyBtn) {
            const textToCopy = decodeURIComponent(copyBtn.dataset.copyText);
            navigator.clipboard.writeText(textToCopy).then(() => {
                const originalHTML = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i data-lucide="check" class="w-4 h-4"></i> Copiado!';
                lucide.createIcons({ nodes: [copyBtn] });
                if (typeof showToast === 'function') showToast('Copiado al portapapeles.', 'success');
                setTimeout(() => { copyBtn.innerHTML = originalHTML; lucide.createIcons({ nodes: [copyBtn] }); }, 2000);
            }).catch(err => console.error('Error al copiar:', err));
        }
    });

    function toggleEditMode(id, isEditing) {
        const container = document.querySelector(`[data-desc-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);
    }

    async function saveIndividualDescription(descData, button) {
        setProcessingState(true, `Guardando ${descData.type}...`); 
        try {
            const checkResponse = await fetch(descriptionEndpoints.fetch, { method: 'POST' });
            const checkResult = await checkResponse.json();
            if (checkResult.success && checkResult.descriptions.length >= MAX_DESCRIPTIONS) {
                if (typeof showToast === 'function') showToast(`Límite de ${MAX_DESCRIPTIONS} descripciones alcanzado. Elimina una antes de guardar.`, 'warning');
                setProcessingState(false);
                return;
            }

            const response = await fetch(descriptionEndpoints.create, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(descData)
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                if (button) {
                    button.disabled = true;
                    button.classList.add('bg-green-600', 'opacity-50');
                    button.classList.remove('bg-[var(--color-primary)]');
                    button.innerHTML = '<i data-lucide="check"></i> <span>¡Guardado!</span>';
                    lucide.createIcons({ nodes: [button] });
                }
                openDescriptionsPanel();
            } else if (response.status === 409) {
                if (typeof showToast === 'function') showToast(result.message, 'warning');
            } else {
                throw new Error(result.message || `Error ${response.status}: Revisa la ruta de la API de CREATE (${descriptionEndpoints.create})`);
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al guardar: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    async function handleUpdateDescription(descId) {
        // Lectura de valores: Quill se lee del textarea oculto, purpose_description se lee del textarea visible
        const newData = {
            id: descId,
            // Campo no editable con Quill, se lee del textarea simple
            purpose_description: document.getElementById(`edit-purpose-input-${descId}`).value, 
            // Campos Quill, se leen de los textareas ocultos sincronizados
            text_es: document.getElementById(`edit-text_es-input-${descId}`).value, 
            text_en: document.getElementById(`edit-text_en-input-${descId}`).value
        };

        // 1. Destruir Quill y restaurar el DOM antes de guardar
        QUILL_FIELDS.forEach(field => {
            const editorId = `quill-editor-${field}-${descId}`;
            if (quillInstances[editorId]) {
                const originalDesc = savedDescriptions.find(d => d.id == descId);
                const editorContainer = quillInstances[editorId].container.parentNode;
                const newContent = newData[field]; // Usar el contenido que se va a guardar
                
                if (editorContainer) {
                    editorContainer.innerHTML = `<div id="${editorId}" class="ql-editor panel-edit-textarea">${newContent}</div>`;
                }
                delete quillInstances[editorId];
            }
        });
        
        openModal({
            title: 'CONFIRMAR ACTUALIZACIÓN',
            message: '¿Estás seguro de que quieres guardar estos cambios?',
            icon: 'save',
            confirmText: 'SÍ, GUARDAR',
            onConfirm: async () => {
                setProcessingState(true, 'Actualizando...');
                try {
                    const response = await fetch(descriptionEndpoints.update, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(newData)
                    });
                    const result = await response.json();
                    if (response.ok && result.success) {
                        if (typeof showToast === 'function') showToast(result.message, 'success');
                        await fetchAndDrawDescriptions();
                    } else {
                        throw new Error(result.message || 'Error desconocido al actualizar');
                    }
                } catch (error) {
                    if (typeof showToast === 'function') showToast(`Error al actualizar: ${error.message}`, 'error');
                    await fetchAndDrawDescriptions();
                } finally {
                    setProcessingState(false);
                }
            }
        });
    }
    
    async function handleDeleteDescription(descId) {
        openModal({
            title: 'CONFIRMAR ELIMINACIÓN',
            message: '¿Estás seguro de que quieres eliminar esta descripción? <br> Esta acción no se puede deshacer.',
            icon: 'alert-triangle',
            confirmText: 'SÍ, ELIMINAR',
            confirmClass: 'danger',
            onConfirm: async () => {
                setProcessingState(true, 'Eliminando...');
                try {
                    const response = await fetch(descriptionEndpoints.delete, {
                        method: 'POST', 
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: descId })
                    });
                    const result = await response.json();
                    if (response.ok && result.success) {
                        if (typeof showToast === 'function') showToast(result.message, 'success');
                        fetchAndDrawDescriptions();
                    } 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);
                }
            }
        });
    }
    

    function setProcessingState(isProcessing, customMessage = null) {
        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');
            resultContainer.style.opacity = '0';
            
            if (customMessage) {
                btnText.textContent = customMessage;
                if(window.loadingInterval) clearInterval(window.loadingInterval);
                window.loadingInterval = null;
                return;
            }
            const messages = ["Analizando tu servicio...", "Transformando tareas en beneficios...", "Redactando las descripciones...", "¡Casi listo!"];
            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);
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
            generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            btnText.textContent = 'GENERAR CON IA MARKETING';
            resultContainer.style.opacity = '1';
        }
    }

    form.addEventListener('submit', async function(event) {
        event.preventDefault();
        
        const requiredFields = ['service_name', 'service_features', 'problem_solved', 'key_benefit'];
        let allFieldsValid = true;
        requiredFields.forEach(id => {
            const input = document.getElementById(id);
            if (!input.value.trim()) {
                allFieldsValid = false;
                input.classList.add('border-[var(--color-secondary)]');
            } else {
                input.classList.remove('border-[var(--color-secondary)]');
            }
        });

        if (!allFieldsValid) {
            showToast('Por favor, completa todos los campos obligatorios.', 'warning');
            return;
        }

        setProcessingState(true);

        const formData = {
            service_name: document.getElementById('service_name').value,
            service_features: document.getElementById('service_features').value,
            value_proposition: document.querySelector('input[name="value_proposition"]').value,
            problem_solved: document.getElementById('problem_solved').value,
            key_benefit: document.getElementById('key_benefit').value,
            target_audience: document.getElementById('target_audience').value,
            additional_details: document.getElementById('additional_details').value
        };
        
        inputsGeneradosReciente = {
            service_name_input: formData.service_name,
            features_input: formData.service_features
        };

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

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || `Error del servidor: ${response.status}.`);
            }
            const data = await response.json();
            if(data.error) throw new Error(data.error);

            generatedDescriptions = data.descriptions;
            displayResult(data.descriptions);
            showToast('¡Descripciones generadas con éxito!', 'success');

        } catch (error) {
            console.error("Error:", error);
            let errorMessage = 'Hubo un problema al generar tus descripciones. Por favor, intenta 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';
            showToast(errorMessage, 'error');
        } finally {
            setProcessingState(false);
        }
    });

    function displayResult(descriptions) {
        resultContainer.innerHTML = '';
        saveButtons = {}; 
        
        descriptions.forEach((data, index) => {
            const resultCard = document.createElement('div');
            resultCard.className = 'ai-response p-6 md:p-8 rounded-xl shadow-md space-y-4';
            resultCard.style.animationDelay = `${index * 150}ms`;
            
            const text_en = data.text_en || "English translation not available.";

            resultCard.innerHTML = `
                <div>
                    <h3 class="text-xl font-bold text-gray-800 mb-2 flex items-center"><i data-lucide="message-square" class="mr-2 text-[var(--color-primary)]"></i>${data.type}</h3>
                    <p class="text-gray-600 mb-4">${data.description}</p>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <h4 class="font-semibold text-gray-700 mb-2">🇪🇸 Español</h4>
                            <div class="message-box bg-gray-50 p-4 rounded-lg border border-gray-200 shadow-sm whitespace-pre-wrap">${data.text_es.replace(/\n/g, '<br>')}</div>
                            <div class="copy-btn-wrapper mt-3">
                                <button class="btn-copy" data-copytarget-text="${encodeURIComponent(data.text_es)}">
                                    <i data-lucide="copy"></i><span class="copy-text">Copiar Texto</span>
                                </button>
                            </div>
                        </div>
                        
                        <div>
                            <h4 class="font-semibold text-gray-700 mb-2">🇺🇸 English</h4>
                            <div class="message-box bg-gray-50 p-4 rounded-lg border border-gray-200 shadow-sm whitespace-pre-wrap">${text_en.replace(/\n/g, '<br>')}</div>
                            <div class="copy-btn-wrapper mt-3">
                                <button class="btn-copy" data-copytarget-text="${encodeURIComponent(text_en)}">
                                    <i data-lucide="copy"></i><span class="copy-text">Copiar Texto</span>
                                </button>
                            </div>
                        </div>
                    </div>
                     <div class="mt-4 text-center">
                        <button class="btn-save-description btn-copy bg-[var(--color-primary)] text-white font-bold py-2 px-6 rounded-lg flex items-center justify-center mx-auto gap-2 hover:scale-105 transition-transform uppercase"
                                data-desc-type="${data.type}" data-desc-index="${index}">
                            <i data-lucide="save"></i> <span>Guardar Descripción</span>
                        </button>
                    </div>
                </div>
            `;
            resultContainer.appendChild(resultCard);
        });
        
        lucide.createIcons();
        setTimeout(() => { 
            resultContainer.style.opacity = '1'; 
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);
        
        resultContainer.querySelectorAll('.btn-copy').forEach(button => {
            button.addEventListener('click', function() {
                const textToCopy = decodeURIComponent(this.dataset.copytargetText);
                navigator.clipboard.writeText(textToCopy).then(() => {
                    const buttonContent = this;
                    const originalHTML = buttonContent.innerHTML;

                    buttonContent.innerHTML = '<i data-lucide="check"></i><span class="copy-text">Copiado!</span>';
                    lucide.createIcons();
                    buttonContent.classList.add('copied');
                    showToast('Texto copiado al portapapeles.', 'success');
                    
                    setTimeout(() => {
                        buttonContent.innerHTML = originalHTML;
                        buttonContent.classList.remove('copied');
                        lucide.createIcons({
                            nodes: [buttonContent]
                        });
                    }, 2000);
                }).catch(err => {
                    console.error('Error al copiar:', err);
                    showToast('No se pudo copiar el texto.', 'error');
                });
            });
        });

        resultContainer.querySelectorAll('.btn-save-description').forEach(button => {
            const type = button.dataset.descType;
            const index = parseInt(button.dataset.descIndex, 10);
            saveButtons[type] = button;
            
            button.addEventListener('click', function() {
                const descToSave = generatedDescriptions[index];
                
                const payload = {
                    type: descToSave.type,
                    purpose_description: descToSave.description,
                    text_es: descToSave.text_es,
                    text_en: descToSave.text_en,
                    service_name_input: inputsGeneradosReciente.service_name_input,
                    features_input: inputsGeneradosReciente.features_input
                };
                saveIndividualDescription(payload, this);
            });
        });
    }
});
</script>
<script src="files/toast.js"></script>
</body>
</html>