<?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 Publicaciones Sociales 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;
            justify-content: 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;
            text-align: left;
        }
        .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;
                text-align: left;
            }
            .step-header .step-title {
                font-size: 1.5rem;
                width: auto;
                text-align: left;
            }
        }
        .panel-edit-input {
            width: 100%; padding: 0.5rem; border: 1px solid #d1d5db;
            border-radius: 0.375rem; background-color: #fff;
            font-size: 0.875rem; line-height: 1.25rem;
        }
        .tox-tinymce {
            border-radius: 0.5rem !important;
            border: 1px solid #d1d5db !important;
        }
    </style>
</head>
<body data-page-title="Creador De Publicaciones Sociales"
      data-page-subtitle="Crea Posts Que Abordan El Problema, La Solución Y Tu Servicio"
      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 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="social-post-creator-tool" class="dashboard-section">
                    <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                        <div class="lg:col-span-3">
                            <form id="social-post-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">
                                            <span class="step-number"> <i data-lucide="briefcase" class="mr-3 text-[var(--color-secondary)]"></i> PASO 1:
                                            </span>
                                            <span class="step-title"> Contexto de tu Negocio
                                            </span>
                                        </h2>
                                        <p class="step-subtitle uppercase">Completa la información para personalizar tus publicaciones</p>
                                    </div>
                                    <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                    <div class="space-y-6">
                                        <div class="form-group">
                                            <label for="business_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre De Tu Negocio:</label>
                                            <input type="text" id="business_name" name="business_name" 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="Ej: Rod Cleaning Services" value="<?php echo htmlspecialchars($business_name); ?>">
                                        </div>
                                        <div class="form-group">
                                            <label for="website_url" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Página Web O Perfil Social (Opcional):</label>
                                            <input type="text" id="website_url" name="website_url" placeholder="Ej: LocalGarden.com" 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($website); ?>">
                                        </div>
                                        <div class="form-group">
                                            <label for="phone_whatsapp" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Teléfono / WhatsApp:</label>
                                            <input type="text" id="phone_whatsapp" name="phone_whatsapp" placeholder="Ej: (555) 123-4567" 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($phone); ?>">
                                        </div>
                                        <div class="form-group">
                                            <label for="service_zone" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Zona Geográfica De Servicio (Opcional):</label>
                                            <input type="text" id="service_zone" name="service_zone" placeholder="Ej: Miami, Orlando, Tampa" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($operating_cities); ?>">
                                        </div>
                                        </div>
                                </div>
                                <div class="pt-8">
                                    <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="lightbulb" class="mr-3 text-[var(--color-secondary)]"></i>
                                                    PASO 2:
                                            </span>
                                            <span class="step-title"> El Corazón de tu Mensaje
                                            </span>
                                        </h2>
                                        <p class="step-subtitle uppercase">Define el problema que resuelves y para quién lo haces</p>
                                    </div>
                                    <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                    <div class="space-y-6">
                                        <div class="form-group">
                                            <label for="product_service_description_simplified" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Describe Tu Producto o Servicio:</label>
                                            <textarea id="product_service_description_simplified" name="product_service_description_simplified" rows="6" placeholder="Ej: Mantenimiento De Jardines Para Hogares Y Oficinas" minlength="50" maxlength="1500" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required></textarea>
                                            <div class="char-count text-right text-sm text-gray-500 mt-1" id="product-char-count">0 / 1500 Caracteres</div>
                                        </div>
                                        
                                        <div class="form-group">
                                            <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 De Cliente...</option>
                                                <?php foreach ($ideal_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 class="form-group">
                                            <label for="client_description_simplified" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Describe A Tu Cliente Ideal:</label>
                                            <textarea id="client_description_simplified" name="client_description_simplified" rows="6" placeholder="Ej: Familias Ocupadas Y Empresas En El Área de Miami que buscan calidad. (Puedes autocompletar esto con el menú de arriba)" minlength="50" maxlength="1500" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required></textarea>
                                            <div class="char-count text-right text-sm text-gray-500 mt-1" id="client-char-count">0 / 1500 Caracteres</div>
                                        </div>
                                    </div>
                                </div>
                               <input type="hidden" name="value_proposition" id="value_proposition_input" 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-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 Publicaciones Sociales</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">SÉ DESCRIPTIVO:</strong> Cuanto más detalles des sobre tu oferta y tus clientes, mejores y más relevantes serán las publicaciones.</div></li>
                                        <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="scan"></i></span><div><strong class="text-brand-dark uppercase">ANALIZA TUS POSTS:</strong> La herramienta creará posts en español e inglés con un enfoque estratégico.</div></li>
                                        <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="link"></i></span><div><strong class="text-brand-dark uppercase">HASHTAGS Y LLAMADOS A LA ACCIÓN:</strong> Cada post vendrá con sugerencias de hashtags y CTAs listos para usarse.</div></li>
                                        <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="copy"></i></span><div><strong class="text-brand-dark uppercase">COPIA Y PUBLICA:</strong> Elige el post que más te guste, cópialo con un clic y súbelo directamente a tus redes sociales.</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="share-2" class="mr-3 text-[var(--color-secondary)]"></i>
                                        PASO 3:
                                    </span>
                                    <span class="step-title">
                                        GENERA PUBLICACIONES QUE CONECTEN
                                    </span>
                                </h2>
                                <p class="step-subtitle text-center md:text-left uppercase">Obtén contenido estratégico y atractivo para publicar en tus redes sociales</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 crear publicaciones para tus redes socialea que atraigan clientes potenciales, <b>es importante</b> que definas el problema que tu servicio resuelve. Con esos datos, nuestra <b>inteligencia artificial</b>, creará tus <b>Publicaciones Sociales</b>, para que abordes el problema, ofrezces la solución y presentes tu servicio de manera persuasiva.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="social-post-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 PUBLICACIONES SOCIALES 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="post-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>

<div id="post-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="share-2" class="w-8 h-8 mr-2 text-white"></i>
            TUS PUBLICACIONES
        </h3>
        <button id="close-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="post-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 publicaciones...</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-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();
    
    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('phone_whatsapp');
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }
    
    const productDescInput = document.getElementById('product_service_description_simplified');
    const clientDescInput = document.getElementById('client_description_simplified');
    [productDescInput, clientDescInput].forEach(input => {
        if (input) {
            input.addEventListener('input', function() {
                const currentLength = this.value.length;
                const charCountElement = document.getElementById(this.id === 'product_service_description_simplified' ? 'product-char-count' : 'client-char-count');
                charCountElement.textContent = `${currentLength} / ${this.maxLength} Caracteres`;
            });
            input.dispatchEvent(new Event('input'));
        }
    });

    const form = document.getElementById('social-post-form');
    const resultContainer = document.getElementById('result-container');
    const generateBtn = document.getElementById('generateBtn');
    const openPanelBtn = document.getElementById('open-panel-btn');
    const closePanelBtn = document.getElementById('close-panel-btn');
    const panelOverlay = document.getElementById('post-panel-overlay');
    const postPanel = document.getElementById('post-panel');
    const panelContent = document.getElementById('post-panel-content');
    const clientProfileSelect = document.getElementById('client_profile_select');
    
    let postsDecodificados = null;
    let postsGeneradosRecientemente = null; 
    let inputsGeneradosRecientemente = {}; 
    const POST_LIMIT = 5;

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

            if (resumen) {
                clientDescInput.value = resumen.trim();
                clientDescInput.dispatchEvent(new Event('input'));
            } else {
                clientDescInput.value = '';
                clientDescInput.dispatchEvent(new Event('input'));
            }
        });
    }
    
    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:bg-[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') {
            modalConfirmBtn.disabled = true;
            onConfirmCallback();
        }
        closeModal(); 
        modalConfirmBtn.disabled = false;
    });

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

    function openPostPanel() {
        postPanel.classList.remove('translate-x-full');
        panelOverlay.classList.remove('hidden');
        fetchAndLoadDataIntoPanel();
    }

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

    openPanelBtn.addEventListener('click', openPostPanel);
    closePanelBtn.addEventListener('click', closePostPanel); 
    panelOverlay.addEventListener('click', closePostPanel);
    
    async function fetchAndLoadDataIntoPanel() {
        panelContent.innerHTML = '<div class="text-center p-8"><div class="w-8 h-8 border-4 border-t-transparent border-[var(--color-primary)] rounded-full animate-spin mx-auto"></div><p class="text-gray-500 mt-3">Cargando publicaciones guardadas...</p></div>';
        
        try {
            const response = await fetch('api-db/ia-social-post-creator-fetch.php');
            const result = await response.json();
            
            if (response.ok && result.success) {
                postsDecodificados = result.posts;
            } else {
                console.error("Error al obtener posts guardados:", result.message);
                postsDecodificados = [];
            }
        } catch (error) {
            console.error("Error de red al obtener posts guardados:", error);
            postsDecodificados = [];
        }
        loadDataIntoPanel(); 
    }

    function createPostCardInPanel(post) {
        const postTitle = (post.post_type === 'problem') ? 'Problema' :
                          (post.post_type === 'solution') ? 'Solución/Deseo' :
                          (post.post_type === 'service') ? 'Servicio/Beneficios' :
                          'General';
        const postIcon = (post.post_type === 'problem') ? 'alert-triangle' :
                         (post.post_type === 'solution') ? 'star' :
                         (post.post_type === 'service') ? 'badge-check' :
                         'megaphone';
        const postIconColor = (post.post_type === 'problem') ? 'text-[var(--color-secondary)]' :
                              (post.post_type === 'solution') ? 'text-yellow-500' :
                              (post.post_type === 'service') ? 'text-green-500' :
                              'text-gray-500';

        let esHashtagsArray = [];
        let enHashtagsArray = [];
        try {
            esHashtagsArray = post.es_hashtags && post.es_hashtags.trim() ? JSON.parse(post.es_hashtags) : [];
            enHashtagsArray = post.en_hashtags && post.en_hashtags.trim() ? JSON.parse(post.en_hashtags) : [];
        } catch (e) {
            esHashtagsArray = post.es_hashtags ? post.es_hashtags.split('#').map(t => t.trim()).filter(t => t.length > 0) : [];
            enHashtagsArray = post.en_hashtags ? post.en_hashtags.split('#').map(t => t.trim()).filter(t => t.length > 0) : [];
        }
        
        const formattedEsHashtags = (Array.isArray(esHashtagsArray) ? esHashtagsArray : []).map(tag => `#${tag}`).join(' ');
        const formattedEnHashtags = (Array.isArray(enHashtagsArray) ? enHashtagsArray : []).map(tag => `#${tag}`).join(' ');

        const esHashtagsRaw = esHashtagsArray.join('#');
        const enHashtagsRaw = enHashtagsArray.join('#');

        const full_es_text = `${post.es_copy}\n\n${formattedEsHashtags}`;
        const full_en_text = `${post.en_copy}\n\n${formattedEnHashtags}`;
        
        return `
            <div class="border border-gray-200 rounded-xl overflow-hidden" data-post-id="${post.id}">
                <div class="bg-gray-50 p-4 flex justify-between items-center">
                    <div id="display-name-${post.id}" class="flex-1">
                        <h4 class="text-xl font-black uppercase text-[var(--color-primary)] flex items-center">
                           <i data-lucide="${postIcon}" class="${postIconColor} w-5 h-5 mr-3"></i>
                           POST: ${postTitle}
                        </h4>
                    </div>
                    <div id="edit-name-area-${post.id}" class="flex-1 hidden">
                         <h4 class="text-xl font-black uppercase text-[var(--color-primary)] flex items-center">
                           <i data-lucide="${postIcon}" class="${postIconColor} w-5 h-5 mr-3"></i>
                           POST: ${postTitle}
                        </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="${post.id}"><i data-lucide="edit"></i></button>
                        <button class="btn-copy btn-xs bg-[var(--color-secondary)] text-white btn-panel-delete" data-id="${post.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="${post.id}"><i data-lucide="save"></i></button>
                        <button class="btn-copy btn-xs bg-gray-500 text-white btn-panel-cancel hidden" data-id="${post.id}"><i data-lucide="x"></i></button>
                    </div>
                </div>

                <div class="p-4">
                    <div id="display-content-${post.id}" class="space-y-4">
                        <div class="bg-gray-50 p-3 rounded-lg border">
                            <h6 class="font-semibold text-gray-700 mb-1">🇪🇸 Español:</h6>
                            <p class="text-gray-800 text-sm leading-relaxed whitespace-pre-wrap" data-lang="es">${post.es_copy.replace(/\n/g, '<br>')}</p>
                            <p class="text-xs text-[var(--color-secondary)] font-medium mt-1" data-hashtags-lang="es">${formattedEsHashtags}</p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg border">
                            <h6 class="font-semibold text-gray-700 mb-1">🇺🇸 English:</h6>
                            <p class="text-gray-800 text-sm leading-relaxed whitespace-pre-wrap" data-lang="en">${post.en_copy.replace(/\n/g, '<br>')}</p>
                            <p class="text-xs text-[var(--color-primary)] font-medium mt-1" data-hashtags-lang="en">${formattedEnHashtags}</p>
                        </div>
                        <div class="mt-3 flex gap-2 justify-center">
                            <button class="btn-copy btn-xs bg-[var(--color-highlight)] text-[var(--color-primary)]" data-copy-text="${encodeURIComponent(full_es_text)}">
                                <i data-lucide="copy"></i> COPIAR 
                            </button>
                        </div>
                    </div>

                    <div id="edit-content-area-${post.id}" class="hidden space-y-4">
                        <label class="block text-sm font-medium text-gray-700">🇪🇸 Copy Español:</label>
                        <textarea id="edit-es-copy-${post.id}" class="panel-edit-input" rows="5">${post.es_copy}</textarea>
                        
                        <label class="block text-sm font-medium text-gray-700">🇪🇸 Hashtags (separados por #):</label>
                        <textarea id="edit-es-hashtags-${post.id}" class="panel-edit-input" rows="2">${esHashtagsRaw}</textarea>
                        
                        <label class="block text-sm font-medium text-gray-700">🇺🇸 Copy English:</label>
                        <textarea id="edit-en-copy-${post.id}" class="panel-edit-input" rows="5">${post.en_copy}</textarea>

                        <label class="block text-sm font-medium text-gray-700">🇺🇸 Hashtags (separated by #):</label>
                        <textarea id="edit-en-hashtags-${post.id}" class="panel-edit-input" rows="2">${enHashtagsRaw}</textarea>
                    </div>
                </div>
            </div>
        `;
    }
    
    function loadDataIntoPanel() {
        panelContent.innerHTML = ''; 
        
        if (postsDecodificados && postsDecodificados.length > 0) {
            panelContent.innerHTML += `
                <div class="text-center pb-4 border-b border-gray-200 mb-6">
                    <h4 class="text-xl font-black uppercase text-[var(--color-primary)]">PUBLICACIONES GUARDADAS (${postsDecodificados.length} / ${POST_LIMIT})</h4>
                </div>
                <div class="space-y-6">
            `;
            
            postsDecodificados.forEach(post => {
                panelContent.innerHTML += createPostCardInPanel(post);
            });

            panelContent.innerHTML += `</div>`;
            lucide.createIcons();
        } else {
            panelContent.innerHTML = `
                <div class="text-center p-8 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">
                        No hay publicaciones guardadas. ¡Genera algunas y guárdalas!
                    </p>
                </div>
            `;
            lucide.createIcons();
        }
    }

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

        if (editBtn) {
            const id = editBtn.dataset.id;
            toggleEditMode(id, true);
            
            if (typeof tinymce !== 'undefined') {
                tinymce.init({
                    selector: `#edit-es-copy-${id}, #edit-en-copy-${id}`,
                    menubar: false,
                    statusbar: false,
                    height: 200,
                    plugins: 'lists link',
                    toolbar: 'bold italic underline | bullist numlist | removeformat',
                    language: 'es',
                    skin: 'oxide',
                    content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px; color:#333; }'
                });
            }
        }
        
        if (cancelBtn) {
            const id = cancelBtn.dataset.id;
            
            if (typeof tinymce !== 'undefined') {
                tinymce.remove(`#edit-es-copy-${id}`);
                tinymce.remove(`#edit-en-copy-${id}`);
            }
            toggleEditMode(id, false);
        }
        
        if (saveBtn) {
            const id = saveBtn.dataset.id;
            
            let esCopy, enCopy;
            if (typeof tinymce !== 'undefined' && tinymce.get(`edit-es-copy-${id}`)) {
                esCopy = tinymce.get(`edit-es-copy-${id}`).getContent();
                enCopy = tinymce.get(`edit-en-copy-${id}`).getContent();
                tinymce.remove(`#edit-es-copy-${id}`);
                tinymce.remove(`#edit-en-copy-${id}`);
            } else {
                esCopy = document.getElementById(`edit-es-copy-${id}`).value;
                enCopy = document.getElementById(`edit-en-copy-${id}`).value;
            }

            const esHashtagsRaw = document.getElementById(`edit-es-hashtags-${id}`).value;
            const enHashtagsRaw = document.getElementById(`edit-en-hashtags-${id}`).value;

            const esHashtagsArray = esHashtagsRaw.split('#').map(t => t.trim()).filter(t => t.length > 0);
            const enHashtagsArray = enHashtagsRaw.split('#').map(t => t.trim()).filter(t => t.length > 0);

            const payload = {
                id: parseInt(id, 10),
                es_copy: esCopy,
                es_hashtags: JSON.stringify(esHashtagsArray),
                en_copy: enCopy,
                en_hashtags: JSON.stringify(enHashtagsArray)
            };

            openModal({
                title: 'CONFIRMAR ACTUALIZACIÓN',
                message: '¿Estás seguro de que quieres guardar los cambios?',
                icon: 'save',
                confirmText: 'SÍ, ACTUALIZAR',
                onConfirm: async () => {
                    await updatePostInDB(payload);
                    await fetchAndLoadDataIntoPanel(); 
                }
            });
        }
        
        if (deleteBtn) {
            const id = deleteBtn.dataset.id;
            openModal({
                title: 'CONFIRMAR ELIMINACIÓN',
                message: '¿Estás seguro de que quieres eliminar esta publicación? <br> Esta acción no se puede deshacer.',
                icon: 'alert-triangle',
                confirmText: 'SÍ, ELIMINAR',
                confirmClass: 'danger',
                onConfirm: async () => {
                    await deletePostFromDB(parseInt(id, 10));
                    await fetchAndLoadDataIntoPanel(); 
                }
            });
        }

        if (copyBtn) {
             const textToCopy = decodeURIComponent(copyBtn.dataset.copyText);
            navigator.clipboard.writeText(textToCopy).then(() => {
                const originalHTML = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i data-lucide="check"></i><span class="copy-text">Copiado!</span>';
                lucide.createIcons({ nodes: [copyBtn] });
                copyBtn.classList.add('copied');
                showToast('Texto copiado al portapapeles.', 'success');
                setTimeout(() => {
                    copyBtn.innerHTML = originalHTML;
                    copyBtn.classList.remove('copied');
                    lucide.createIcons({ nodes: [copyBtn] });
                }, 2000);
            }).catch(err => showToast('Error al copiar el texto.', 'error'));
        }
    });

    function toggleEditMode(id, isEditing) {
        const container = document.querySelector(`[data-post-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 saveIndividualPost(post) {
        setProcessingState(true, 'Guardando Publicación...');
        
        const inputs = {
            product_service_description_simplified: document.getElementById('product_service_description_simplified').value,
            client_description_simplified: document.getElementById('client_description_simplified').value,
        };

        const payload = {
            post_type: post.type,
            es_copy: post.es_copy,
            es_hashtags: JSON.stringify(post.es_hashtags),
            en_copy: post.en_copy,
            en_hashtags: JSON.stringify(post.en_hashtags),
            inputs: inputs
        };

        try {
            const current_count = postsDecodificados ? postsDecodificados.length : 0;
            if (current_count >= POST_LIMIT) {
                if (typeof showToast === 'function') showToast(`Límite de ${POST_LIMIT} publicaciones individuales alcanzado. Elimina una para guardar la nueva.`, 'warning');
                return false;
            }

            const response = await fetch('api-db/ia-social-post-creator-create.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            
            const result = await response.json();
            
            if (response.ok) {
                if (result.success) {
                    if (typeof showToast === 'function') showToast(result.message, 'success');
                    fetchAndLoadDataIntoPanel(); 
                    openPostPanel();
                    return true;
                } else {
                     if (typeof showToast === 'function') showToast(result.message, 'warning');
                     return false;
                }
            } else {
                 throw new Error(result.message || 'Error desconocido al guardar el post individual.');
            }

        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al guardar: ${error.message}`, 'error');
            console.error(error);
            return false;
        } finally {
            setProcessingState(false);
        }
    }
    
    async function updatePostInDB(payload) {
        setProcessingState(true, 'Actualizando Publicación...');
        try {
            const response = await fetch('api-db/ia-social-post-creator-update.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
            } 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 deletePostFromDB(postId) {
        setProcessingState(true, 'Eliminando...');
        try {
            const response = await fetch('api-db/ia-social-post-creator-delete.php', {
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: postId })
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
            } 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);
        }
    }


    const btnText = document.getElementById('btn-text');
    const loaderContainer = document.getElementById('loader-container');

    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');
            
            if (customMessage) {
                btnText.textContent = customMessage;
                if (window.loadingInterval) clearInterval(window.loadingInterval);
                window.loadingInterval = null;
                return;
            }

            const messages = ["Contactando Con OrozCO IA...", "Analizando Tu Negocio...", "Redactando Publicaciones...", "Afinando El Contenido...", "¡Listas Para Publicar!"];
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];
            
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            
            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);

        } else {
            if (window.loadingInterval) {
                clearInterval(window.loadingInterval);
                window.loadingInterval = null;
            }
            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();
        
        const requiredInputs = form.querySelectorAll('[required]');
        let allValid = true;
        requiredInputs.forEach(input => {
            if (!input.value.trim() || input.value.length < input.minLength) {
                allValid = false;
                input.classList.add('border-[var(--color-secondary)]');
            } else {
                 input.classList.remove('border-[var(--color-secondary)]');
            }
        });
        if (!allValid) {
            if (typeof showToast === 'function') {
                showToast('Por favor, completa todos los campos obligatorios.', 'error');
            }
            return;
        }

        setProcessingState(true);

        const formData = {
            business_name: document.getElementById('business_name').value,
            website_url: document.getElementById('website_url').value,
            phone_whatsapp: document.getElementById('phone_whatsapp').value,
            service_zone: document.getElementById('service_zone').value,
            product_service_description_simplified: document.getElementById('product_service_description_simplified').value,
            client_description_simplified: document.getElementById('client_description_simplified').value,
            
            value_proposition: document.getElementById('value_proposition_input').value
        };
        
        inputsGeneradosRecientemente = formData;

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

            const data = await response.json();

            if (!response.ok || data.error) {
                throw new Error(data.error || `El servidor respondió con un error ${response.status}.`);
            }
            
            if (data.posts && Array.isArray(data.posts)) {
                postsGeneradosRecientemente = data.posts;
                displayResult(data.posts);
                showToast('¡Publicaciones generadas con éxito!', 'success');
            } else {
                throw new Error('La IA no devolvió un formato válido de publicaciones.');
            }

        } catch (error) {
            let errorMessage = "No se pudieron generar las publicaciones. Por favor, revisa los datos e inténtalo de nuevo.";

            try {
                const jsonStartIndex = error.message.indexOf('{');
                if (jsonStartIndex !== -1) {
                    const errorJsonString = error.message.substring(jsonStartIndex);
                    const errorDetails = JSON.parse(errorJsonString);
                    if (errorDetails.error) {
                        errorMessage = errorDetails.error; 
                    } else if (errorDetails.details) {
                        errorMessage += ` Detalles: ${errorDetails.details}`;
                    }
                } else {
                    errorMessage += ` Detalles: ${error.message}`;
                }
            } catch (parseError) {
                errorMessage += ` Detalles: ${error.message}`;
            }

            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(posts) {
        let allPostsHtml = '';
        posts.forEach((post, index) => {
            const postTitle = (post.type === 'problem') ? 'Enfocada En El Problema' :
                              (post.type === 'solution') ? 'Enfocada En La Solución/Deseo' :
                              (post.type === 'service') ? 'Enfocada En El Servicio/Beneficios' :
                              'Publicación General';
            const postIcon = (post.type === 'problem') ? 'alert-triangle' :
                             (post.type === 'solution') ? 'star' :
                             (post.type === 'service') ? 'badge-check' :
                             'megaphone';
            const postIconColor = (post.type === 'problem') ? 'text-[var(--color-secondary)]' :
                                  (post.type === 'solution') ? 'text-yellow-500' :
                                  (post.type === 'service') ? 'text-green-500' :
                                  'text-gray-500';

            const formattedEsHashtags = (post.es_hashtags || []).map(tag => `#${tag}`).join(' ');
            const formattedEnHashtags = (post.en_hashtags || []).map(tag => `#${tag}`).join(' ');

            const full_es_text = `${post.es_copy}\n\n${formattedEsHashtags}`;
            const full_en_text = `${post.en_copy}\n\n${formattedEnHashtags}`;

            allPostsHtml += `
                <div class="bg-white p-6 rounded-xl shadow-lg mb-8" data-post-index="${index}">
                    <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                        <i data-lucide="${postIcon}" class="${postIconColor} mr-3"></i>Publicación ${index + 1}: ${postTitle}
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="flex justify-between items-center mb-3">
                                <h4 class="text-lg font-semibold text-gray-700">🇪🇸 Español</h4>
                                <button class="btn-copy btn-xs" data-copy-text="${encodeURIComponent(full_es_text)}">
                                    <i data-lucide="copy"></i><span class="copy-text">Copiar</span>
                                </button>
                            </div>
                            <div class="space-y-3">
                                <p class="text-gray-800 leading-relaxed whitespace-pre-wrap">${post.es_copy.replace(/\n/g, '<br>')}</p>
                                <p class="text-sm text-[var(--color-secondary)] font-medium">${formattedEsHashtags}</p>
                            </div>
                        </div>
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="flex justify-between items-center mb-3">
                                <h4 class="text-lg font-semibold text-gray-700">🇺🇸 English</h4>
                                <button class="btn-copy btn-xs" data-copy-text="${encodeURIComponent(full_en_text)}">
                                    <i data-lucide="copy"></i><span class="copy-text">Copy</span>
                                </button>
                            </div>
                            <div class="space-y-3">
                                <p class="text-gray-800 leading-relaxed whitespace-pre-wrap">${post.en_copy.replace(/\n/g, '<br>')}</p>
                                <p class="text-sm text-[var(--color-primary)] font-medium">${formattedEnHashtags}</p>
                            </div>
                        </div>
                    </div>
                    <div class="mt-4 text-center">
                        <button class="btn-save-individual btn-copy bg-[var(--color-primary)] text-white font-bold py-2 px-6 rounded-lg flex items-center justify-center mx-auto gap-2 hover:scale-105 transition-transform uppercase"
                                data-post-index="${index}">
                            <i data-lucide="save"></i> <span>Guardar Esta Publicación</span>
                        </button>
                    </div>
                </div>
            `;
        });
        
        resultContainer.innerHTML = `
            <div class="ai-response p-6 md:p-8 rounded-xl shadow-md">
                <div class="flex justify-between items-center pb-4 mb-4 border-b border-gray-200">
                    <h3 class="text-2xl font-bold text-gray-800 flex items-center"><i data-lucide="bullseye" class="mr-3 text-[var(--color-primary)]"></i> Resultados Generados</h3>
                </div>
                ${allPostsHtml}
            </div>`;
        
        lucide.createIcons();
        setTimeout(() => {
            resultContainer.style.opacity = '1';
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);

        resultContainer.querySelectorAll('.btn-save-individual').forEach(button => {
            button.addEventListener('click', async function() {
                const index = parseInt(this.dataset.postIndex, 10);
                const postToSave = postsGeneradosRecientemente[index];
                
                this.disabled = true;
                this.classList.add('opacity-50', 'cursor-not-allowed');
                this.innerHTML = '<i data-lucide="loader" class="w-4 h-4 animate-spin"></i> Guardando...';
                lucide.createIcons({ nodes: [this] });

                const success = await saveIndividualPost(postToSave);
                
                if (success) {
                    this.innerHTML = '<i data-lucide="check"></i> <span>¡Guardado!</span>';
                    this.classList.add('bg-green-600');
                    this.classList.remove('bg-[var(--color-primary)]');
                } else {
                    this.disabled = false;
                    this.classList.remove('opacity-50', 'cursor-not-allowed');
                    this.innerHTML = '<i data-lucide="save"></i> <span>Guardar Esta Publicación</span>';
                }
                lucide.createIcons({ nodes: [this] });
            });
        });
    }

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

        if (copyButton && copyButton.dataset.copyText) {
            const textToCopy = decodeURIComponent(copyButton.dataset.copyText);
            navigator.clipboard.writeText(textToCopy).then(() => {
                const buttonContent = copyButton;
                const originalHTML = buttonContent.innerHTML;
                buttonContent.innerHTML = '<i data-lucide="check"></i><span class="copy-text">Copiado!</span>';
                lucide.createIcons({ nodes: [buttonContent] });
                buttonContent.classList.add('copied');
                if (typeof showToast === 'function') {
                     showToast('Publicación copiada al portapapeles.', 'success');
                }
                setTimeout(() => {
                    buttonContent.innerHTML = originalHTML;
                    buttonContent.classList.remove('copied');
                    lucide.createIcons({ nodes: [buttonContent] });
                }, 2000);
            }).catch(err => {
                console.error('Error al copiar:', err);
                if (typeof showToast === 'function') {
                    showToast('No se pudo copiar el texto.', 'error');
                }
            });
        }
    });
});
</script>
<script src="files/toast.js"></script>
</body>
</html>