<?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 Why 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: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('img/bg03.webp'); 
    }
    .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 Why Preview */
    #why-preview {
        background-color: var(--brand-primary);
        background-size: cover;
        background-position: center;
        min-height: 400px;
    }
</style>
 
</head>
<body data-page-title="SiteFlow® Reviews Why"
      data-page-subtitle="Configura la sección que explica por qué es importante dejar una reseña"
      data-page-icon="message-circle-question">

    <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-why-form" action="cms/reviews-why-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/bg03.webp">
                            </label>
                            <p class="text-xs text-gray-500 mt-2">La imagen debe tener un fondo oscuro o de alto contraste para que los textos blancos se lean bien.</p>
                        </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> 
                                Títulos y Descripción
                            </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="list-checks" class="w-6 h-6 text-[var(--brand-primary)]"></i> 
                                Puntos Clave
                            </h3>
                            
                            <div id="items-editor-container" class="space-y-4">
                                <template id="item-template">
                                    <div class="p-4 border border-gray-200 rounded-lg space-y-2 item-card" data-id="0">
                                        <input type="hidden" class="item-id" value="0">
                                        <input type="hidden" class="sort-order-input" value="0">
                                        
                                        <div>
                                            <label class="block text-xs font-semibold uppercase text-gray-600">Título del Punto</label>
                                            <input type="text" class="item-title-input w-full p-2 border rounded text-sm" placeholder="Ej: You Help A Neighbor">
                                        </div>
                                        <div>
                                            <label class="block text-xs font-semibold uppercase text-gray-600">Descripción</label>
                                            <textarea class="item-description-input w-full p-2 border rounded text-sm" rows="2" placeholder="Ej: Your honest experience helps others in the community..."></textarea>
                                        </div>
                                        <div class="flex gap-2">
                                            <div class="flex-1">
                                                <label class="block text-xs font-semibold uppercase text-gray-600">Icono (Lucide)</label>
                                                <input type="text" class="item-icon-input w-full p-2 border rounded text-sm" placeholder="Ej: clock, users">
                                            </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-item-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-item-button" class="w-full btn-secondary font-bold uppercase 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 Nuevo Punto</span>
                                </button>
                            </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="why-preview" class="relative rounded-xl p-8 md:p-12 text-white shadow-xl">
                            <div class="absolute inset-0 bg-[rgba(4,13,26,0.78)] rounded-xl"></div> 

                            <div class="relative max-w-7xl mx-auto">
                                <div class="text-center mb-10">
                                    <p class="inline-flex items-center gap-2 px-4 py-1.5 rounded-md
                                                bg-white/10 text-[var(--brand-secondary)] font-extrabold
                                                tracking-[0.15em] ring-1 ring-white/20">
                                        <i data-lucide="sparkles" class="w-5 h-5"></i>
                                        <span id="preview-badge-text">A Small Action, A Big Impact</span>
                                    </p>

                                    <h2 class="font-extrabold leading-[0.92] tracking-tight mt-4">
                                        <span id="preview-title-1" class="block text-white text-4xl sm:text-4xl md:text-4xl">Your Voice, Our Motivation</span>
                                        <span id="preview-title-2" class="block text-[var(--brand-secondary)] text-4xl sm:text-4xl md:text-5xl">How Your Review Helps</span>
                                    </h2>

                                    <p id="preview-description" class="max-w-3xl mx-auto mt-6 text-lg text-white/90">
                                        More than just stars, your feedback shapes our service and helps your neighbors make confident decisions. Here’s the difference you make.
                                    </p>
                                </div>

                                <div id="preview-items-container" class="grid grid-cols-2 gap-4">
                                    </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-why-form');
    const itemsEditorContainer = document.getElementById('items-editor-container');
    const addItemButton = document.getElementById('add-item-button');
    const itemTemplate = document.getElementById('item-template');
    const previewItemsContainer = document.getElementById('preview-items-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 whyPreview = document.getElementById('why-preview');

    // --- ELEMENTOS DE PREVIEW ---
    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');
    
    // Almacenamiento de todos los ítems en el frontend
    let itemsData = []; 

    // 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 item en la previsualización
    const createPreviewItem = (item) => {
        const itemElement = document.createElement('div');
        itemElement.className = 'text-center p-6 rounded-2xl shadow-lg bg-white text-[var(--brand-primary)]';
        
        itemElement.innerHTML = `
            <div class="w-12 h-12 bg-[var(--brand-secondary)] rounded-md flex items-center justify-center mx-auto mb-4 shadow-md">
                <i data-lucide="${safeValue(item.item_icon) || 'star'}" class="w-6 h-6 text-[var(--brand-primary)]"></i>
            </div>
            <h3 class="font-extrabold tracking-wide text-md mb-2">${safeValue(item.item_title)}</h3>
            <p class="text-xs">${safeValue(item.item_description)}</p>
        `;
        
        lucide.createIcons({ element: itemElement });
        return itemElement;
    };
    
    // --- LÓGICA DE GESTIÓN DE ÍTEMS (CRUD y DOM) ---
    
    // 1. Renderizar la lista de edición y la previsualización
    const renderItems = () => {
        // 1. Limpiar contenedores
        itemsEditorContainer.innerHTML = '';
        previewItemsContainer.innerHTML = '';
        
        // 2. Ordenar itemsData por sort_order
        itemsData.sort((a, b) => a.sort_order - b.sort_order);

        // 3. Renderizar cada ítem
        itemsData.forEach((item, index) => {
            // Renderizar Editor
            const templateClone = itemTemplate.content.cloneNode(true).querySelector('.item-card');
            templateClone.dataset.id = item.id;
            
            // Asignar valores a los inputs del editor
            templateClone.querySelector('.item-id').value = item.id;
            templateClone.querySelector('.sort-order-input').value = item.sort_order;
            templateClone.querySelector('.item-title-input').value = safeValue(item.item_title);
            templateClone.querySelector('.item-description-input').value = safeValue(item.item_description);
            templateClone.querySelector('.item-icon-input').value = safeValue(item.item_icon);

            itemsEditorContainer.appendChild(templateClone);

            // Renderizar Preview
            previewItemsContainer.appendChild(createPreviewItem(item));
        });
        
        lucide.createIcons({ element: itemsEditorContainer });
    };
    
    // 2. Añadir nuevo ítem
    addItemButton.addEventListener('click', () => {
        const newItem = {
            id: 0, // 0 indica nuevo registro
            item_icon: 'plus-circle',
            item_title: 'Nuevo Punto Clave',
            item_description: 'Descripción breve de este punto.',
            sort_order: itemsData.length > 0 ? Math.max(...itemsData.map(l => l.sort_order)) + 1 : 1 // Siguiente orden disponible
        };
        itemsData.push(newItem);
        renderItems();
    });
    
    // 3. Manejar eventos de edición, borrado y ordenamiento
    itemsEditorContainer.addEventListener('input', (e) => {
        const itemCard = e.target.closest('.item-card');
        if (!itemCard) return;

        const id = parseInt(itemCard.querySelector('.item-id').value);
        let index = itemsData.findIndex(l => (l.id === id && id !== 0) || (l.id === 0 && itemCard.contains(e.target))); 
        
        if (index === -1 && id === 0) {
            const allItems = Array.from(itemsEditorContainer.querySelectorAll('.item-card'));
            index = allItems.indexOf(itemCard);
        }
        
        if (index === -1) return;

        // Actualizar el objeto de datos en tiempo real
        if (e.target.classList.contains('item-title-input')) itemsData[index].item_title = e.target.value;
        if (e.target.classList.contains('item-description-input')) itemsData[index].item_description = e.target.value;
        if (e.target.classList.contains('item-icon-input')) {
             itemsData[index].item_icon = e.target.value;
             renderItemsPreviewOnly(); // Actualiza el ícono en la preview inmediatamente
        }

        // Re-renderizar solo la previsualización (para texto y descripción)
        renderItemsPreviewOnly();
    });

    itemsEditorContainer.addEventListener('click', (e) => {
        const itemCard = e.target.closest('.item-card');
        if (!itemCard) return;

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

        if (e.target.closest('.move-up-btn')) {
            if (index > 0) {
                const prevItem = itemsData[index - 1];
                prevItem.sort_order = currentSort;
                itemsData[index].sort_order = currentSort - 1;
                renderItems();
            }
        } else if (e.target.closest('.move-down-btn')) {
            if (index < itemsData.length - 1) {
                const nextItem = itemsData[index + 1];
                nextItem.sort_order = currentSort;
                itemsData[index].sort_order = currentSort + 1;
                renderItems();
            }
        } else if (e.target.closest('.delete-item-btn')) {
            itemsData.splice(index, 1); // Eliminar del array
            itemsData.forEach((item, i) => item.sort_order = i + 1); // Reajustar órdenes
            renderItems();
        }
    });
    
    // Función optimizada para re-renderizar solo la preview
    const renderItemsPreviewOnly = () => {
        previewItemsContainer.innerHTML = '';
        itemsData.sort((a, b) => a.sort_order - b.sort_order); // Asegurar orden
        itemsData.forEach(item => {
            previewItemsContainer.appendChild(createPreviewItem(item));
        });
    }

    // --- 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;
    });
    
    // --- 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;
                // La preview del editor necesita el linear-gradient para simular la oscuridad
                bgImagePreview.style.backgroundImage = `linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('${imageUrl}')`;
                bgImagePreview.classList.add('has-image');
                
                whyPreview.style.backgroundImage = `url('${imageUrl}')`;
            };
            reader.readAsDataURL(file);
        }
    });


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

            if (result.success && result.data) {
                const { hero, items } = 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);
                
                // 2. Cargar Imagen de Fondo
                if (hero.background_image) {
                    const bgImagePath = hero.background_image;
                    // Necesitamos subir dos niveles para llegar a 'uploads/' o 'img/'
                    const finalBgPath = bgImagePath.startsWith('http') ? bgImagePath : `../${bgImagePath}`; 
                    
                    // Preview del editor (con filtro oscuro)
                    bgImagePreview.style.backgroundImage = `linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('${finalBgPath}')`;
                    bgImagePreview.classList.add('has-image');
                    
                    // Preview de la sección real (solo imagen)
                    whyPreview.style.backgroundImage = `url('${finalBgPath}')`;
                    currentBgImage.value = bgImagePath;
                }
                
                // 3. Cargar Ítems Dinámicos
                itemsData = items.map(item => ({
                    ...item, 
                    id: parseInt(item.id),
                    sort_order: parseInt(item.sort_order)
                }));
                renderItems();
                
                // 4. 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);
            }
        } catch (error) {
            console.error('Error al cargar datos:', error);
            showToast('Error al cargar los datos iniciales de Reviews Why.', false);
        } finally {
            lucide.createIcons();
        }
    };

    // --- LÓGICA DE SUBMIT DEL FORMULARIO ---
    form.addEventListener('submit', async e => {
        e.preventDefault();
        
        // 1. Recolectar datos de ítems
        const finalItemsData = [];
        // Usamos itemsData, ya que está actualizado en tiempo real con input y drag-and-drop
        itemsData.forEach(item => {
            finalItemsData.push({
                id: item.id,
                item_icon: item.item_icon,
                item_title: item.item_title,
                item_description: item.item_description,
                sort_order: item.sort_order
            });
        });
        
        const formData = new FormData(form);
        formData.append('items_data', JSON.stringify(finalItemsData)); // Adjuntar la lista de ítems

        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>