<?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>Prueba De Resultados FlowCMS™  De OrozDesign Powered By OrozCO</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; 
    }
        #preview-wrapper {
            border: 1px solid #e5e7eb; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            overflow: hidden; width: 100%; background-color: #f9fafb;
        }
        #preview-thumbnails { max-height: 220px; overflow-y: auto; }
        .preview-thumb.active { ring: 2px solid red; }
        
        .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);
        }
        .file-upload-preview {
            width: 100%; height: 120px; 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;
        }
        .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; }
        .file-upload-preview input[type="file"] { display: none; }
        
    </style>
</head>
<body data-page-title="SiteFlow® Galería De Proyectos"
      data-page-subtitle="Gestiona las fotos y videos que muestran tus resultados"
      data-page-icon="images">

    <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="gallery-editor-form" action="cms/results-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 space-y-6">
                        
                        <div>
                            <h4 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2"><i data-lucide="text" class="w-6 h-6 text-[var(--color-primary)]"></i> ENCABEZADO DE LA SECCIÓN</h4>
                            <div class="space-y-4">
                                <div>
                                    <label for="gallery-badge" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Encabezado (Badge)</label>
                                    <input type="text" id="gallery-badge" name="gallery-badge" class="w-full p-3 border border-gray-300 rounded-lg" value="Real Work. Real Results.">
                                </div>
                                <div>
                                    <label for="gallery-title-1" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Título (Línea 1)</label>
                                    <input type="text" id="gallery-title-1" name="gallery-title-1" class="w-full p-3 border border-gray-300 rounded-lg" value="RESULTS THAT SPEAK FOR THEMSELVES">
                                </div>
                                <div>
                                    <label for="gallery-title-2" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Título (Línea 2)</label>
                                    <input type="text" id="gallery-title-2" name="gallery-title-2" class="w-full p-3 border border-gray-300 rounded-lg" value="SEE HOW WE TRANSFORM SPACES">
                                </div>
                            </div>
                        </div>

                        <div class="border-t border-gray-200 pt-6">
                             <div class="flex justify-between items-center mb-4">
                                 <h4 class="text-xl font-extrabold text-gray-700 flex items-center gap-2"><i data-lucide="gallery-horizontal-end" class="w-6 h-6 text-[var(--color-primary)]"></i> ELEMENTOS DE LA GALERÍA</h4>
                                 <span id="gallery-counter" class="text-sm font-bold text-gray-500">0 / 30</span>
                             </div>
                             <div id="gallery-repeater" class="space-y-4"></div>
                             <button type="button" id="add-gallery-item-btn" class="mt-4 btn-secondary font-bold py-2 px-4 rounded-lg flex items-center justify-center gap-2 uppercase text-sm"><i data-lucide="plus" class="w-4 h-4"></i> Añadir Elemento</button>
                             <input type="hidden" id="gallery-items-json" name="items_json">
                        </div>

                        <div class="border-t border-gray-200 pt-6 flex justify-end gap-4">
                            <button type="submit" 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 class="space-y-4">
                            <div id="preview-wrapper" class="rounded-lg p-6">
                                <div class="text-center mb-8">
                                    <p id="preview-badge" class="font-bold text-xs text-[var(--color-secondary)]">Real Work. Real Results</p>
                                    <h2 class="font-extrabold leading-tight mt-2 text-xl">
                                        <span id="preview-title-1" class="block text-[var(--color-primary)]">Results That Speak For Themselves</span>
                                        <span id="preview-title-2" class="block text-[var(--color-secondary)]">See How We Transform Spaces</span>
                                    </h2>
                                </div>
                                <div class="grid grid-cols-12 gap-4">
                                    <div id="preview-main-content" class="col-span-8 aspect-video bg-gray-200 rounded-lg flex items-center justify-center overflow-hidden">
                                        <span class="text-gray-400 text-sm">Vista Principal</span>
                                    </div>
                                    <div id="preview-thumbnails" class="col-span-4 space-y-2">
                                    </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(--color-highlight)] 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(--color-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(--color-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(--color-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(--color-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.toggle('hidden'); });
    }

    const form = document.getElementById('gallery-editor-form');
    const repeater = document.getElementById('gallery-repeater');
    const addBtn = document.getElementById('add-gallery-item-btn');
    const counterEl = document.getElementById('gallery-counter');
    const previewMain = document.getElementById('preview-main-content');
    const previewThumbs = document.getElementById('preview-thumbnails');
    const galleryItemsJsonInput = document.getElementById('gallery-items-json');
    let itemCounter = 0;
    let fileCounter = 0;
    const MAX_ITEMS = 30;

    const createGalleryItemHTML = (id, type = 'image', imageSrc = '', videoUrl = '', fileIndex = null) => {
        const isImageType = type === 'image';
        const fileInputName = `gallery_images_upload[${fileIndex}]`;

        // Generar un id único para cada input de archivo si es una imagen nueva
        const uniqueFileId = `gallery-image-upload-${fileIndex}`;
        const finalImageSrc = imageSrc ? (imageSrc.startsWith('http') ? imageSrc : `../${imageSrc}`) : '';

        return `
            <div class="gallery-item border border-gray-200 p-4 rounded-lg bg-gray-50 space-y-3" data-id="${id}" data-file-index="${fileIndex !== null ? fileIndex : ''}">
                <div class="flex justify-between items-center">
                    <div class="flex items-center gap-4">
                        <label class="text-gray-700 text-sm font-bold uppercase">Elemento #${id}</label>
                        <select class="item-type p-1 border border-gray-300 rounded-md bg-white text-sm" name="item_type-${id}">
                            <option value="image" ${isImageType ? 'selected' : ''}>Imagen</option>
                            <option value="video" ${!isImageType ? 'selected' : ''}>Video (YouTube)</option>
                        </select>
                    </div>
                    <button type="button" class="remove-item-btn text-red-500 hover:text-red-700"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
                </div>
                <div class="image-fields" style="display: ${isImageType ? 'block' : 'none'};">
                    <label for="${uniqueFileId}" class="file-upload-preview cursor-pointer ${finalImageSrc ? 'has-image' : ''}" style="background-image: url('${finalImageSrc}');">
                        <span class="upload-text bg-white/80 px-4 py-2 rounded-md">Subir Imagen</span>
                        <input type="file" id="${uniqueFileId}" name="${fileInputName}" class="gallery-image-upload" accept="image/*" data-current-src="${finalImageSrc}">
                    </label>
                </div>
                <div class="video-fields" style="display: ${!isImageType ? 'block' : 'none'};">
                    <input type="url" name="video_url-${id}" class="w-full p-2 border border-gray-300 rounded-md gallery-video-url" placeholder="https://www.youtube.com/watch?v=..." value="${videoUrl}">
                </div>
                <input type="hidden" name="item_path-${id}" class="item-path" value="${imageSrc || videoUrl}">
            </div>
        `;
    };
    const getYoutubeThumbnail = (url) => {
        if (!url) return '';
        let videoId;
        try {
            const urlObj = new URL(url);
            if (urlObj.hostname.includes('youtu.be')) {
                videoId = urlObj.pathname.slice(1);
            } else {
                videoId = urlObj.searchParams.get('v');
            }
        } catch (e) { return ''; }
        return videoId ? `https://img.youtube.com/vi/${videoId}/hqdefault.jpg` : '';
    };

    const updateRepeaterState = () => {
        const items = Array.from(repeater.querySelectorAll('.gallery-item'));
        counterEl.textContent = `${items.length} / ${MAX_ITEMS}`;
        addBtn.disabled = items.length >= MAX_ITEMS;
        addBtn.style.opacity = items.length >= MAX_ITEMS ? '0.5' : '1';
        
        const galleryItemsData = [];
        items.forEach((item, index) => {
            const type = item.querySelector('.item-type').value;
            let path = '';
            let fileIndex = null;
            if (type === 'image') {
                const imageInput = item.querySelector('.gallery-image-upload');
                if (imageInput.files.length > 0) {
                    fileIndex = Array.from(imageInput.form.elements).filter(el => el.type === 'file' && el.name.startsWith('gallery_images_upload')).findIndex(el => el === imageInput);
                    path = `[upload_image]`; // Marcador para el back-end
                } else {
                    path = imageInput.dataset.currentSrc;
                }
            } else {
                path = item.querySelector('.gallery-video-url').value;
            }
            if (path) {
                galleryItemsData.push({ type, path, file_index: fileIndex });
            }
        });
        galleryItemsJsonInput.value = JSON.stringify(galleryItemsData);
    };

    const renderGalleryPreview = () => {
        const items = Array.from(repeater.querySelectorAll('.gallery-item'));
        previewThumbs.innerHTML = '';
        if (items.length === 0) {
            previewMain.innerHTML = `<span class="text-gray-400 text-sm">Vista Principal</span>`;
            return;
        }

        let firstItemRendered = false;

        items.forEach((item, index) => {
            const type = item.querySelector('.item-type').value;
            let thumbSrc, mainSrc, isVideo = false;

            if (type === 'image') {
                thumbSrc = item.querySelector('.gallery-image-upload').dataset.currentSrc;
                mainSrc = thumbSrc;
            } else {
                const videoUrl = item.querySelector('.gallery-video-url').value;
                thumbSrc = getYoutubeThumbnail(videoUrl);
                mainSrc = videoUrl;
                isVideo = true;
            }

            if (thumbSrc) {
                previewThumbs.innerHTML += `
                    <button type="button" class="preview-thumb w-full aspect-video rounded-md overflow-hidden ring-2 ring-transparent hover:ring-red-500" data-index="${index}" data-src="${mainSrc}" data-is-video="${isVideo}">
                        <img src="${thumbSrc}" class="w-full h-full object-cover">
                    </button>
                `;
                 if (!firstItemRendered) {
                    updateMainPreview(mainSrc, isVideo);
                    firstItemRendered = true;
                }
            }
        });

        const firstThumb = previewThumbs.querySelector('.preview-thumb');
        if (firstThumb) {
            firstThumb.classList.add('active');
        }
        
        lucide.createIcons();
    };
    
    const updateMainPreview = (src, isVideo) => {
        if (isVideo) {
            const videoId = getYoutubeThumbnail(src).split('/')[4];
            previewMain.innerHTML = `<iframe class="w-full h-full" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
        } else {
            previewMain.innerHTML = `<img src="${src}" class="w-full h-full object-cover">`;
        }
    };
    
    previewThumbs.addEventListener('click', e => {
        const thumb = e.target.closest('.preview-thumb');
        if (thumb) {
            document.querySelectorAll('.preview-thumb.active').forEach(t => t.classList.remove('active'));
            thumb.classList.add('active');
            updateMainPreview(thumb.dataset.src, thumb.dataset.isVideo === 'true');
        }
    });

    addBtn.addEventListener('click', () => {
        if (repeater.querySelectorAll('.gallery-item').length < MAX_ITEMS) {
            itemCounter++;
            const newFileIndex = fileCounter++;
            repeater.insertAdjacentHTML('beforeend', createGalleryItemHTML(itemCounter, 'image', '', '', newFileIndex));
            lucide.createIcons();
            updateRepeaterState();
            renderGalleryPreview();
        }
    });

    repeater.addEventListener('click', e => {
        if (e.target.closest('.remove-item-btn')) {
            e.target.closest('.gallery-item').remove();
            updateRepeaterState();
            renderGalleryPreview();
        }
    });

    repeater.addEventListener('change', e => {
        const item = e.target.closest('.gallery-item');
        if (e.target.classList.contains('item-type')) {
            const isImage = e.target.value === 'image';
            item.querySelector('.image-fields').style.display = isImage ? 'block' : 'none';
            item.querySelector('.video-fields').style.display = isImage ? 'none' : 'block';
        }
        if (e.target.classList.contains('gallery-image-upload')) {
            const file = e.target.files[0];
            const previewEl = item.querySelector('.file-upload-preview');
            if(file) {
                const reader = new FileReader();
                reader.onload = event => { 
                    e.target.dataset.currentSrc = event.target.result;
                    if(previewEl) {
                        previewEl.style.backgroundImage = `url('${event.target.result}')`;
                        previewEl.classList.add('has-image');
                    }
                    updateRepeaterState();
                    renderGalleryPreview();
                };
                reader.readAsDataURL(file);
            }
        }
        updateRepeaterState();
        renderGalleryPreview();
    });

    repeater.addEventListener('input', e => {
        updateRepeaterState();
        renderGalleryPreview();
    });
    
    // --- BINDING DEL ENCABEZADO ---
    const headerBindings = {
        'gallery-badge': document.getElementById('preview-badge'),
        'gallery-title-1': document.getElementById('preview-title-1'),
        'gallery-title-2': document.getElementById('preview-title-2'),
    };
    form.addEventListener('input', e => { if (headerBindings[e.target.id]) { headerBindings[e.target.id].textContent = e.target.value; } });

    // Función para mostrar toasts de notificación
    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);
    };

    // Handle form submission with AJAX
    form.addEventListener('submit', async e => {
        e.preventDefault();
        const saveButton = form.querySelector('button[type="submit"]');
        const originalButtonText = saveButton.innerHTML;

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

        const formData = new FormData(form);
        updateRepeaterState(); // Asegurarse de que el JSON esté actualizado antes de enviar

        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>Revisa el archivo PHP.<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();
        }
    });

    // Load data from backend on page load
    const loadData = async () => {
        try {
            const response = await fetch('cms/results-read.php');
            const responseText = await response.text();

            let result;
            try {
                result = JSON.parse(responseText);
            } catch (jsonError) {
                showToast(`Error de servidor al cargar datos.<br><br>Revisa el archivo PHP.<br>Respuesta: ${responseText}`, false);
                console.error("Error al parsear JSON:", jsonError, "Respuesta del servidor:", responseText);
                return;
            }

            if (result.success && result.data) {
                const generalData = result.data.general;
                const itemsData = result.data.items;
                
                document.getElementById('gallery-badge').value = generalData.results_badge;
                document.getElementById('preview-badge').textContent = generalData.results_badge;
                document.getElementById('gallery-title-1').value = generalData.results_title_1;
                document.getElementById('preview-title-1').textContent = generalData.results_title_1;
                document.getElementById('gallery-title-2').value = generalData.results_title_2;
                document.getElementById('preview-title-2').textContent = generalData.results_title_2;

                repeater.innerHTML = '';
                itemCounter = 0;
                fileCounter = 0;
                itemsData.forEach(item => {
                    itemCounter++;
                    let imageSrc = '';
                    let videoUrl = '';
                    if(item.item_type === 'image') {
                        imageSrc = (item.item_path && !item.item_path.startsWith('http')) ? `../${item.item_path}` : item.item_path;
                    } else {
                        videoUrl = item.item_path;
                    }

                    repeater.insertAdjacentHTML('beforeend', createGalleryItemHTML(itemCounter, item.item_type, imageSrc, videoUrl, fileCounter++));
                });
                
                updateRepeaterState();
                renderGalleryPreview();
            }
        } catch (error) {
            console.error('Error al cargar los datos:', error);
            showToast('Error al cargar los datos.', false);
        } finally {
            lucide.createIcons();
        }
    };
    loadData();
});
</script>

</body>
</html>