<?php include 'files/guardiankey.php'; ?>
<?php
ob_start();
session_start();
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);
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>Reviews Hero FlowCMS™</title>
    <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
<style>
    body {
        --brand-primary: #07162d; 
        --brand-secondary: #ffc857;
        --brand-accent: #9e1428; 
        --brand-light: #f5f5f5;
        --brand-dark: #040d1a; 
    }
    /* Estilos del Toast (copiados de tu CMS) */
    .toast-container {
        position: fixed; bottom: 20px; right: 20px; z-index: 1000;
        display: flex; flex-direction: column; gap: 10px;
    }
    .toast {
        background-color: #333; color: white; padding: 15px; border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); opacity: 0; transform: translateY(20px);
        transition: opacity 0.3s ease-out, transform 0.3s ease-out; min-width: 250px;
    }
    .toast.show { opacity: 1; transform: translateY(0); }

    /* Estilos de Imagen de Fondo (Similar al cms-section-offer.php) */
    .file-upload-preview {
        width: 100%; height: 150px; border: 2px dashed #d1d5db; border-radius: 0.5rem;
        display: flex; align-items: center; justify-content: center;
        background-size: cover; background-position: center; position: relative;
        color: #6b7280; font-weight: 600;
        background-image: url('img/bg-reviews-sim.jpg'); /* Fondo de simulación */
    }
    .file-upload-preview.has-image::before {
        content: ''; position: absolute; inset: 0; background-color: rgba(0,0,0,0.5); border-radius: 0.5rem;
    }
    .file-upload-preview .upload-text { z-index: 10; background-color: rgba(255,255,255,0.7); padding: 8px 16px; border-radius: 8px; }
    .file-upload-preview input[type="file"] { display: none; }
    
    /* Estilos del Review Hero Preview */
    #hero-preview {
        background-color: var(--brand-primary);
        background-size: cover;
        background-position: center;
        min-height: 400px; /* Asegura un mínimo de altura */
    }
    #hero-preview .bg-logo {
        background-color: #fff;
        padding: 8px;
        border-radius: 8px;
        box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
    }
    .link-item-preview a {
        transition: transform 0.1s;
    }
    .link-item-preview a:active {
        transform: scale(0.95);
    }
</style>
 
</head>
<body data-page-title="SiteFlow® Reviews Hero"
      data-page-subtitle="Configura el texto de la página de reseñas y los enlaces a tus plataformas"
      data-page-icon="message-square-text">

    <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 'cms-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">
            <form id="reviews-hero-form" action="cms/reviews-hero-update.php" method="POST" enctype="multipart/form-data">
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    
                    <div class="lg:col-span-1 bg-white p-6 rounded-xl shadow-md h-fit space-y-6">
                        
                        <div>
                            <h4 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2 border-b pb-2"><i data-lucide="image" class="w-6 h-6 text-[var(--brand-primary)]"></i> IMAGEN DE FONDO</h4>
                            <label for="bg_image_upload" class="file-upload-preview cursor-pointer" id="bg-image-preview">
                                <span class="upload-text">Cambiar Imagen</span>
                                <input type="file" id="bg_image_upload" name="bg_image_upload" accept="image/*">
                                <input type="hidden" id="current-bg-image" name="current_bg_image" value="img/bg-reviews-sim.jpg">
                            </label>
                        </div>
                        
                        <div class="border-t border-gray-200 pt-6 space-y-4">
                            <h3 class="text-xl font-extrabold uppercase text-gray-700 flex items-center gap-2 border-b pb-2">
                                <i data-lucide="text-select" class="w-6 h-6 text-[var(--brand-primary)]"></i> 
                                Textos Principales
                            </h3>
                            
                            <div>
                                <label for="badge_text" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Texto de Insignia Superior</label>
                                <input type="text" id="badge_text" name="badge_text" class="w-full p-3 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label for="title_1" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Título (Línea 1)</label>
                                <input type="text" id="title_1" name="title_1" class="w-full p-3 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label for="title_2" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Título (Línea 2 - Resaltado)</label>
                                <input type="text" id="title_2" name="title_2" class="w-full p-3 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label for="description" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Descripción</label>
                                <textarea id="description" name="description" rows="2" class="w-full p-3 border border-gray-300 rounded-lg"></textarea>
                            </div>
                        </div>

                        <div class="border-t border-gray-200 pt-6 space-y-4">
                            <h3 class="text-xl font-extrabold uppercase text-gray-700 flex items-center gap-2 border-b pb-2">
                                <i data-lucide="link" class="w-6 h-6 text-[var(--brand-primary)]"></i> 
                                Plataformas de Reseñas
                            </h3>
                            
                            <div id="link-editor-container" class="space-y-4">
                                <template id="link-template">
                                    <div class="p-4 border border-gray-200 rounded-lg space-y-2 link-item" data-id="0">
                                        <input type="hidden" class="link-id" value="0">
                                        <input type="hidden" class="sort-order-input" value="0">
                                        
                                        <div>
                                            <label class="block text-xs font-semibold uppercase text-gray-600">Nombre Plataforma</label>
                                            <input type="text" class="platform-name-input w-full p-2 border rounded text-sm" placeholder="Ej: Google, Yelp">
                                        </div>
                                        <div>
                                            <label class="block text-xs font-semibold uppercase text-gray-600">Texto del Botón</label>
                                            <input type="text" class="button-text-input w-full p-2 border rounded text-sm" placeholder="Ej: REVIEW ON GOOGLE">
                                        </div>
                                        <div>
                                            <label class="block text-xs font-semibold uppercase text-gray-600">URL del Enlace</label>
                                            <input type="url" class="link-url-input w-full p-2 border rounded text-sm" placeholder="https://google.com/search?q=MiNegocio+Reviews">
                                        </div>
                                        <div class="flex gap-2">
                                            <div class="flex-1">
                                                <label class="block text-xs font-semibold uppercase text-gray-600">Color (Hex)</label>
                                                <input type="color" class="button-color-input w-full h-10 border rounded text-sm" value="#DC2626">
                                            </div>
                                            <div class="flex-1">
                                                <label class="block text-xs font-semibold uppercase text-gray-600">Icono (Lucide)</label>
                                                <input type="text" class="icon-lucide-input w-full p-2 border rounded text-sm" placeholder="Ej: star, thumbs-up">
                                            </div>
                                        </div>
                                        <div class="pt-2 flex justify-end gap-2">
                                            <button type="button" class="move-up-btn text-gray-500 hover:text-gray-800" title="Subir"><i data-lucide="arrow-up" class="w-5 h-5"></i></button>
                                            <button type="button" class="move-down-btn text-gray-500 hover:text-gray-800" title="Bajar"><i data-lucide="arrow-down" class="w-5 h-5"></i></button>
                                            <button type="button" class="delete-link-btn text-red-500 hover:text-red-700" title="Eliminar"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
                                        </div>
                                    </div>
                                </template>
                            </div>
                            
                            <div class="pt-4 border-t border-gray-200">
                                <button type="button" id="add-link-button" class="w-full btn-secondary font-bold py-2 px-4 rounded-lg text-sm flex items-center justify-center gap-2">
                                    <i data-lucide="plus-circle" class="w-5 h-5"></i>
                                    <span>Añadir Enlace</span>
                                </button>
                            </div>
                        </div>

                        <div class="border-t border-gray-200 pt-6 space-y-4">
                            <h3 class="text-xl font-extrabold uppercase text-gray-700 flex items-center gap-2 border-b pb-2">
                                <i data-lucide="clipboard-type" class="w-6 h-6 text-[var(--brand-primary)]"></i> 
                                Textos de la Tarjeta
                            </h3>
                            <div>
                                <label for="card_title" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Título de Tarjeta</label>
                                <input type="text" id="card_title" name="card_title" class="w-full p-3 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label for="card_subtitle" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Subtítulo de Tarjeta</label>
                                <input type="text" id="card_subtitle" name="card_subtitle" class="w-full p-3 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label for="footer_text" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Texto de Pie de Tarjeta</label>
                                <input type="text" id="footer_text" name="footer_text" class="w-full p-3 border border-gray-300 rounded-lg">
                            </div>
                        </div>

                        <div class="border-t border-gray-200 pt-6 flex justify-end">
                            <button type="submit" id="save-button" class="btn-primary font-bold py-3 px-8 rounded-lg uppercase text-sm flex items-center justify-center gap-2">
                                <i data-lucide="save" class="w-5 h-5"></i>
                                <span>Guardar Cambios</span>
                            </button>
                        </div>
                    </div>
                    
                    <div class="lg:col-span-1 space-y-8">
                        
                        <div id="hero-preview" class="rounded-xl p-6 md:p-12 text-white shadow-xl">
                            <div class="grid gap-8 items-center">
                                
                                <div class="text-center md:text-left text-white">
                                    <div class="flex justify-center md:justify-start mb-8">
                                        <img src="img/BusinessLogo.webp" alt="Logo de FlowClean" id="preview-logo-img" class="h-16 bg-logo">
                                    </div>
                                    
                                    <div class="inline-flex items-center justify-center gap-3 px-4 py-2 rounded-xl bg-black/40 text-[var(--brand-secondary)] font-extrabold shadow-lg mb-6 ring-1 ring-white/20">
                                        <i data-lucide="sparkles" class="w-5 h-5"></i>
                                        <span id="preview-badge-text" class="tracking-wider">Thank You For Your Trust</span>
                                    </div>

                                    <h1 class="font-black uppercase leading-tight">
                                        <span id="preview-title-1" class="block text-4xl sm:text-4xl">PLEASE SHARE</span>
                                        <span id="preview-title-2" class="block text-4xl sm:text-6xl text-[var(--brand-secondary)]"> YOUR EXPERIENCE</span>
                                    </h1>
                                    
                                    <p class="mt-4 text-lg text-white/90 max-w-lg mx-auto md:mx-0">
                                        <span id="preview-description">Loved our service? Your 2-minute review helps our local business grow and guides others to a service they can trust.</span>
                                    </p>
                                </div>

                                <div class="bg-white rounded-2xl shadow-2xl p-8 text-[var(--brand-primary)]">
                                    <h2 id="preview-card-title" class="text-2xl font-extrabold text-center">Leave A Review In 60 Seconds</h2>
                                    <p id="preview-card-subtitle" class="text-center text-sm text-gray-600 mb-6">Choose Your Preferred Platform Below</p>
                                    
                                    <div class="space-y-4" id="preview-links-container">
                                        </div>

                                    <div class="mt-6 text-center">
                                        <p id="preview-footer-text" class="text-sm font-bold text-gray-700">Your Feedback Makes All The Difference!</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div id="video-instrucciones" class="space-y-6">
                            <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–3 min
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow-md">
                                <div class="text-center md:text-left mb-6">
                                    <h4 class="text-2xl font-black uppercase text-black flex items-center justify-center md:justify-start">
                                        <i data-lucide="book-open" class="mr-3 text-[var(--brand-secondary)] w-7 h-7"></i>
                                        INSTRUCCIONES IMPORTANTES
                                    </h4>
                                    <p class="step-subtitle uppercase text-sm mt-1 text-gray-500">REVISA ESTOS PUNTOS DETALLADAMENTE</p>
                                </div>

                                <div class="space-y-4">
                                    <div class="flex items-start gap-3">
                                        <i data-lucide="play-circle" class="w-5 h-5 mt-0.5" style="color: var(--brand-secondary);"></i>
                                        <div>
                                            <h5 class="font-black text-gray-800">REVISA EL VIDEO DE INSTRUCCIONES</h5>
                                            <p class="text-sm text-gray-600">Comprende cómo utilizar la plataforma y sácale el máximo provecho a todas sus herramientas.</p>
                                        </div>
                                    </div>

                                    <div class="flex items-start gap-3">
                                        <i data-lucide="target" class="w-5 h-5 mt-0.5" style="color: var(--brand-secondary);"></i>
                                        <div>
                                            <h5 class="font-black text-gray-800">DEFINE BIEN LOS OBJETIVOS</h5>
                                            <p class="text-sm text-gray-600">Identifica qué quieres lograr con esta sección de la página web para una estrategia más efectiva.</p>
                                        </div>
                                    </div>

                                    <div class="flex items-start gap-3">
                                        <i data-lucide="file-text" class="w-5 h-5 mt-0.5" style="color: var(--brand-secondary);"></i>
                                        <div>
                                            <h5 class="font-black text-gray-800">SÉ PRECISO Y CONCISO</h5>
                                            <p class="text-sm text-gray-600">Redacta textos persuasivos y enfocados en el valor que ofreces para impulsar tus ventas.</p>
                                        </div>
                                    </div>

                                    <div class="flex items-start gap-3">
                                        <i data-lucide="refresh-cw" class="w-5 h-5 mt-0.5" style="color: var(--brand-secondary);"></i>
                                        <div>
                                            <h5 class="font-black text-gray-800">MANTÉN LA INFORMACIÓN ACTUALIZADA</h5>
                                            <p class="text-sm text-gray-600">Actualiza la información regularmente (al menos cada 3 meses) para mantener tu contenido relevante y dinámico.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </main>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', () => {
    // --- SETUP BÁSICO ---
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    if (mobileMenuButton && sidebar && sidebarOverlay) {
        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 form = document.getElementById('reviews-hero-form');
    const linkEditorContainer = document.getElementById('link-editor-container');
    const addLinkButton = document.getElementById('add-link-button');
    const linkTemplate = document.getElementById('link-template');
    const previewLinksContainer = document.getElementById('preview-links-container');
    const saveButton = document.getElementById('save-button');
    const bgImageUpload = document.getElementById('bg_image_upload');
    const bgImagePreview = document.getElementById('bg-image-preview');
    const currentBgImage = document.getElementById('current-bg-image');
    const heroPreview = document.getElementById('hero-preview');


    // --- ELEMENTOS DE PREVIEW ---
    const previewLogoImg = document.getElementById('preview-logo-img');
    const previewBadgeText = document.getElementById('preview-badge-text');
    const previewTitle1 = document.getElementById('preview-title-1');
    const previewTitle2 = document.getElementById('preview-title-2');
    const previewDescription = document.getElementById('preview-description');
    const previewCardTitle = document.getElementById('preview-card-title');
    const previewCardSubtitle = document.getElementById('preview-card-subtitle');
    const previewFooterText = document.getElementById('preview-footer-text');
    
    // Almacenamiento de todos los enlaces en el frontend
    let linksData = []; 

    // Función para mostrar toasts de notificación (Copiado de tu CMS)
    const showToast = (message, isSuccess) => {
        const toastContainer = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast ${isSuccess ? 'bg-green-500' : 'bg-red-500'}`;
        toast.innerHTML = message;
        toastContainer.appendChild(toast);
        setTimeout(() => toast.classList.add('show'), 10);
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    };

    // --- UTILIDADES ---
    const safeValue = (value) => value ?? '';
    
    // Función para crear el elemento de enlace en la previsualización
    const createPreviewLink = (link) => {
        const linkWrapper = document.createElement('div');
        linkWrapper.className = 'link-item-preview';
        
        const linkElement = document.createElement('a');
        linkElement.href = safeValue(link.link_url);
        linkElement.target = '_blank';
        linkElement.rel = 'noopener';
        // Aseguramos que el color de fondo y texto se apliquen
        linkElement.className = 'w-full font-extrabold text-lg uppercase py-4 rounded-lg shadow-lg flex items-center justify-center gap-3 hover:brightness-110 transition-transform active:scale-95';
        linkElement.style.backgroundColor = safeValue(link.button_color) || '#000000';
        linkElement.style.color = '#ffffff'; 

        // Crea y añade el ícono
        const iconContainer = document.createElement('i');
        iconContainer.dataset.lucide = safeValue(link.icon_lucide) || 'star';
        iconContainer.className = 'w-5 h-5';
        linkElement.appendChild(iconContainer);
        
        // Crea y añade el texto
        const textSpan = document.createElement('span');
        textSpan.textContent = safeValue(link.button_text);
        linkElement.appendChild(textSpan);
        
        linkWrapper.appendChild(linkElement);
        lucide.createIcons({ element: linkWrapper });
        
        return linkWrapper;
    };
    
    // --- LÓGICA DE GESTIÓN DE ENLACES (CRUD y DOM) ---
    
    // 1. Renderizar la lista de edición y la previsualización
    const renderLinks = () => {
        // 1. Limpiar contenedores
        linkEditorContainer.innerHTML = '';
        previewLinksContainer.innerHTML = '';
        
        // 2. Ordenar linksData por sort_order
        linksData.sort((a, b) => a.sort_order - b.sort_order);

        // 3. Renderizar cada enlace
        linksData.forEach((link, index) => {
            // Renderizar Editor
            const templateClone = linkTemplate.content.cloneNode(true).querySelector('.link-item');
            templateClone.dataset.id = link.id;
            
            // Asignar valores a los inputs del editor
            templateClone.querySelector('.link-id').value = link.id;
            templateClone.querySelector('.sort-order-input').value = link.sort_order; // Usamos el sort_order del objeto
            templateClone.querySelector('.platform-name-input').value = safeValue(link.platform_name);
            templateClone.querySelector('.button-text-input').value = safeValue(link.button_text);
            templateClone.querySelector('.link-url-input').value = safeValue(link.link_url);
            templateClone.querySelector('.button-color-input').value = safeValue(link.button_color);
            templateClone.querySelector('.icon-lucide-input').value = safeValue(link.icon_lucide);

            linkEditorContainer.appendChild(templateClone);

            // Renderizar Preview
            previewLinksContainer.appendChild(createPreviewLink(link));
        });
        
        lucide.createIcons({ element: linkEditorContainer });
    };
    
    // 2. Añadir nuevo enlace
    addLinkButton.addEventListener('click', () => {
        const newLink = {
            id: 0, // 0 indica nuevo registro
            platform_name: 'Nueva Plataforma',
            link_url: 'https://',
            button_text: 'ESCRIBE AQUÍ',
            button_color: '#3B82F6',
            icon_lucide: 'star',
            sort_order: linksData.length > 0 ? Math.max(...linksData.map(l => l.sort_order)) + 1 : 1 // Siguiente orden disponible
        };
        linksData.push(newLink);
        renderLinks();
    });
    
    // 3. Manejar eventos de edición, borrado y ordenamiento
    linkEditorContainer.addEventListener('input', (e) => {
        const linkItem = e.target.closest('.link-item');
        if (!linkItem) return;

        const id = parseInt(linkItem.querySelector('.link-id').value);
        let index = linksData.findIndex(l => (l.id === id && id !== 0) || (l.id === 0 && linkItem.contains(e.target))); 
        
        // Si el índice no se encuentra, usamos la posición en el DOM para nuevos elementos (ID=0)
        if (index === -1 && id === 0) {
            const allItems = Array.from(linkEditorContainer.querySelectorAll('.link-item'));
            index = allItems.indexOf(linkItem);
        }
        
        if (index === -1) return;

        // Actualizar el objeto de datos en tiempo real
        if (e.target.classList.contains('platform-name-input')) linksData[index].platform_name = e.target.value;
        if (e.target.classList.contains('link-url-input')) linksData[index].link_url = e.target.value;
        if (e.target.classList.contains('button-text-input')) linksData[index].button_text = e.target.value;
        if (e.target.classList.contains('button-color-input')) linksData[index].button_color = e.target.value;
        if (e.target.classList.contains('icon-lucide-input')) linksData[index].icon_lucide = e.target.value;

        // Re-renderizar solo la previsualización
        renderLinksPreviewOnly();
    });

    linkEditorContainer.addEventListener('click', (e) => {
        const linkItem = e.target.closest('.link-item');
        if (!linkItem) return;

        const id = parseInt(linkItem.querySelector('.link-id').value);
        let index = linksData.findIndex(l => (l.id === id && id !== 0));
        
        if (index === -1 && id === 0) {
            const allItems = Array.from(linkEditorContainer.querySelectorAll('.link-item'));
            index = allItems.indexOf(linkItem);
        }
        if (index === -1) return;
        
        const currentSort = linksData[index].sort_order;

        if (e.target.closest('.move-up-btn')) {
            if (index > 0) {
                // Intercambiar orden con el elemento anterior
                const prevItem = linksData[index - 1];
                prevItem.sort_order = currentSort;
                linksData[index].sort_order = currentSort - 1;
                renderLinks();
            }
        } else if (e.target.closest('.move-down-btn')) {
            if (index < linksData.length - 1) {
                // Intercambiar orden con el elemento siguiente
                const nextItem = linksData[index + 1];
                nextItem.sort_order = currentSort;
                linksData[index].sort_order = currentSort + 1;
                renderLinks();
            }
        } else if (e.target.closest('.delete-link-btn')) {
            linksData.splice(index, 1); // Eliminar del array
            // Reajustar órdenes para rellenar el hueco
            linksData.forEach((link, i) => link.sort_order = i + 1);
            renderLinks();
        }
    });
    
    // Función optimizada para re-renderizar solo la preview
    const renderLinksPreviewOnly = () => {
        previewLinksContainer.innerHTML = '';
        linksData.sort((a, b) => a.sort_order - b.sort_order); // Asegurar orden
        linksData.forEach(link => {
            previewLinksContainer.appendChild(createPreviewLink(link));
        });
    }

    // --- BINDING DE TEXTOS PRINCIPALES ---
    form.addEventListener('input', (e) => {
        const id = e.target.id;
        const value = e.target.value;

        if (id === 'badge_text') previewBadgeText.textContent = value;
        if (id === 'title_1') previewTitle1.textContent = value;
        if (id === 'title_2') previewTitle2.textContent = value;
        if (id === 'description') previewDescription.textContent = value;
        if (id === 'card_title') previewCardTitle.textContent = value;
        if (id === 'card_subtitle') previewCardSubtitle.textContent = value;
        if (id === 'footer_text') previewFooterText.textContent = value;
    });
    
    // --- BINDING DE SUBIDA DE IMAGEN ---
    bgImageUpload.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event) => {
                const imageUrl = event.target.result;
                bgImagePreview.style.backgroundImage = `url('${imageUrl}')`;
                bgImagePreview.classList.add('has-image');
                
                // Actualizar el preview hero con la imagen local
                heroPreview.style.backgroundImage = `url('${imageUrl}')`;
            };
            reader.readAsDataURL(file);
        }
    });


    // --- LÓGICA DE CARGA DE DATOS ---
    const loadData = async () => {
        try {
            const response = await fetch('cms/reviews-hero-read.php');
            const result = await response.json();

            if (result.success && result.data) {
                const { hero, links, business } = result.data;
                
                // 1. Cargar Textos Principales
                document.getElementById('badge_text').value = safeValue(hero.badge_text);
                document.getElementById('title_1').value = safeValue(hero.title_1);
                document.getElementById('title_2').value = safeValue(hero.title_2);
                document.getElementById('description').value = safeValue(hero.description);
                document.getElementById('card_title').value = safeValue(hero.card_title);
                document.getElementById('card_subtitle').value = safeValue(hero.card_subtitle);
                document.getElementById('footer_text').value = safeValue(hero.footer_text);
                
                // 2. Cargar Imagen de Fondo
                if (hero.background_image) {
                    const bgImagePath = hero.background_image;
                    const finalBgPath = bgImagePath.startsWith('http') ? bgImagePath : `../${bgImagePath}`;
                    bgImagePreview.style.backgroundImage = `url('${finalBgPath}')`;
                    bgImagePreview.classList.add('has-image');
                    heroPreview.style.backgroundImage = `url('${finalBgPath}')`;
                    currentBgImage.value = bgImagePath;
                }
                
                // 3. Cargar Logo
                if (business && business.logo_url) {
                    const logoUrl = business.logo_url.startsWith('http') ? business.logo_url : `../${business.logo_url}`;
                    previewLogoImg.src = logoUrl;
                }
                
                // 4. Cargar Enlaces Dinámicos
                linksData = links.map(link => ({
                    ...link, 
                    id: parseInt(link.id),
                    sort_order: parseInt(link.sort_order)
                }));
                renderLinks();
                
                // 5. Actualizar Preview inicial
                previewBadgeText.textContent = safeValue(hero.badge_text);
                previewTitle1.textContent = safeValue(hero.title_1);
                previewTitle2.textContent = safeValue(hero.title_2);
                previewDescription.textContent = safeValue(hero.description);
                previewCardTitle.textContent = safeValue(hero.card_title);
                previewCardSubtitle.textContent = safeValue(hero.card_subtitle);
                previewFooterText.textContent = safeValue(hero.footer_text);
            }
        } catch (error) {
            console.error('Error al cargar datos:', error);
            showToast('Error al cargar los datos iniciales de Reviews Hero.', false);
        } finally {
            lucide.createIcons();
        }
    };

    // --- LÓGICA DE SUBMIT DEL FORMULARIO ---
    form.addEventListener('submit', async e => {
        e.preventDefault();
        
        // 1. Recolectar datos de enlaces
        const finalLinksData = [];
        const linkItems = linkEditorContainer.querySelectorAll('.link-item');
        linkItems.forEach((item, index) => {
            finalLinksData.push({
                id: parseInt(item.querySelector('.link-id').value),
                platform_name: item.querySelector('.platform-name-input').value,
                link_url: item.querySelector('.link-url-input').value,
                button_text: item.querySelector('.button-text-input').value,
                button_color: item.querySelector('.button-color-input').value,
                icon_lucide: item.querySelector('.icon-lucide-input').value,
                sort_order: parseInt(item.querySelector('.sort-order-input').value) // Usar el valor del campo oculto que maneja el JS
            });
        });
        
        const formData = new FormData(form);
        formData.append('links_data', JSON.stringify(finalLinksData)); // Adjuntar la lista de enlaces

        saveButton.disabled = true;
        const originalButtonText = saveButton.innerHTML;
        saveButton.innerHTML = '<i data-lucide="loader" class="w-5 h-5 animate-spin"></i><span>Guardando...</span>';
        lucide.createIcons();

        try {
            const response = await fetch(form.action, {
                method: 'POST',
                body: formData
            });
            const responseText = await response.text();
            
            let result;
            try {
                result = JSON.parse(responseText);
            } catch (jsonError) {
                showToast(`Error de servidor: Respuesta inesperada.<br><br>Respuesta: ${responseText}`, false);
                console.error("Error al parsear JSON:", jsonError, "Respuesta del servidor:", responseText);
                return;
            }
            
            showToast(result.message, result.success);

            if (result.success) {
                loadData();
            }
        } catch (error) {
            console.error('Error:', error);
            showToast('Ocurrió un error al guardar los cambios.', false);
        } finally {
            saveButton.disabled = false;
            saveButton.innerHTML = originalButtonText;
            lucide.createIcons();
        }
    });

    // Iniciar carga de datos
    loadData();
});
</script>

</body>
</html>