<?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>Diferenciadores Claves 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;
        }

        .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 Subida de Archivo */
        .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;
             /* Fallback visual inicial */
            background-image: url('img/default-preview-bg.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; }
        .file-upload-preview input[type="file"] { display: none; }
        
        /* Estilos de Galería */
        .icon-gallery-btn {
            display: flex; align-items: center; justify-content: center;
            border: 2px solid transparent; border-radius: 0.5rem;
            padding: 0.5rem; cursor: pointer; transition: all 0.2s;
        }
        .icon-gallery-btn:hover { background-color: #e5e7eb; }
        .differentiator-icon-input.is-active { border-color: var(--color-primary); }
    </style>
</head>
<body data-page-title="SiteFlow® Los Diferenciadores Claves"
      data-page-subtitle="Modifica los textos y la lista de ventajas competitivas"
      data-page-icon="gem">

    <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="differentiators-editor-form" action="cms/differentiators-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> CONTENIDO PRINCIPAL</h4>
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Imagen de Fondo</label>
                                                                         <label for="differentiators-bg-image-upload" class="file-upload-preview cursor-pointer has-image" id="differentiators-bg-image-preview">
                                        <span class="upload-text bg-white/80 px-4 py-2 rounded-md">Cambiar Imagen</span>
                                        <input type="file" id="differentiators-bg-image-upload" name="differentiators-bg-image-upload" accept="image/*">
                                                                             <input type="hidden" id="current-differentiators-bg-image" name="current-differentiators-bg-image" value="">
                                    </label>
                                </div>
                                <div>
                                    <label for="differentiators-badge" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Encabezado (Badge)</label>
                                    <input type="text" id="differentiators-badge" name="differentiators-badge" class="w-full p-3 border border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label for="differentiators-title" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Título Principal</label>
                                    <input type="text" id="differentiators-title" name="differentiators-title" class="w-full p-3 border border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label for="differentiators-description" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Texto (Descripción)</label>
                                    <textarea id="differentiators-description" name="differentiators-description" rows="3" class="w-full p-3 border border-gray-300 rounded-lg"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="border-t border-gray-200 pt-6">
                             <h4 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2"><i data-lucide="list-checks" class="w-6 h-6 text-[var(--color-primary)]"></i> LISTA DE DIFERENCIADORES</h4>
                             <div id="differentiators-repeater" class="space-y-4">
                                 </div>
                             <button type="button" id="add-differentiator-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 Diferenciador
                             </button>
                             <input type="hidden" id="items-json-input" name="items_json">
                        </div>

                        <div class="border-t border-gray-200 pt-6">
                            <h4 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2"><i data-lucide="app-window" class="w-6 h-6 text-[var(--color-primary)]"></i> GALERÍA DE ICONOS</h4>
                            <p class="text-sm text-gray-500 mb-4">Haz clic en un campo de "Icono" de arriba y luego selecciona un icono de esta galería.</p>
                            <div id="icon-gallery" class="grid grid-cols-8 md:grid-cols-6 gap-2 bg-gray-100 p-4 rounded-lg">
                                </div>
                        </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">
                                <section id="preview-section" class="relative py-12 px-4 text-center text-white" 
                    style="background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('img/default-bg.webp'); background-size: cover; background-position: center;">
                    
                    <div class="mb-8">
                        <p id="preview-badge" class="text-xs font-bold text-[var(--color-highlight)]">What makes us different?</p>
                        <h2 id="preview-title" class="mt-2 text-2xl font-black text-white">Trusted. Flexible. Guaranteed.</h2>
                        <p id="preview-description" class="mt-3 text-sm text-white/90 max-w-md mx-auto">We earn your trust with professional standards, protected service, and a schedule that adapts to you—backed by a clear guarantee.</p>
                    </div>
                    <div id="preview-differentiators-grid" class="grid grid-cols-2 gap-4 text-left">
                    </div>
                </section>
                            </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', () => {
    // --- MANEJO BÁSICO DEL MENÚ Y LUCIDE ---
    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');
        });
    }

    // --- ELEMENTOS PRINCIPALES ---
    const form = document.getElementById('differentiators-editor-form');
    const repeaterContainer = document.getElementById('differentiators-repeater');
    const addDifferentiatorBtn = document.getElementById('add-differentiator-btn');
    const previewGrid = document.getElementById('preview-differentiators-grid');
    const iconGallery = document.getElementById('icon-gallery');
    const itemsJsonInput = document.getElementById('items-json-input');
    const differentiatorsBgImagePreview = document.getElementById('differentiators-bg-image-preview');
    const currentDifferentiatorsBgImage = document.getElementById('current-differentiators-bg-image');
    const previewSection = document.getElementById('preview-section');
    
    let itemCounter = 0;
    let activeIconInput = null;

    // --- LÓGICA DE UTILIDADES ---
    const getFinalPath = (dbPath) => {
        if (!dbPath) return '';
        // Si ya es una URL absoluta, la devuelve. Si no, antepone '../' 
        return dbPath.startsWith('http') ? dbPath : `../${dbPath}`;
    };
    const safeValue = (value) => value ?? '';

    // --- Galería de Iconos ---
    const iconList = ['handshake', 'shield-check', 'calendar-check-2', 'badge-check', 'award', 'thumbs-up', 'star', 'gem', 'sparkles', 'zap', 'rocket', 'medal', 'trophy', 'crown', 'verified', 'lock'];
    iconGallery.innerHTML = iconList.map(iconName => `
        <button type="button" class="icon-gallery-btn" data-icon-name="${iconName}">
            <i data-lucide="${iconName}" class="w-6 h-6 text-gray-600"></i>
        </button>
    `).join('');

    iconGallery.addEventListener('click', e => {
        const btn = e.target.closest('.icon-gallery-btn');
        if (btn && activeIconInput) {
            activeIconInput.value = btn.dataset.iconName;
            activeIconInput.dispatchEvent(new Event('input', { bubbles: true }));
            activeIconInput.classList.remove('is-active');
            activeIconInput = null;
        }
    });

    // --- Lógica del Repetidor ---
    const createItemHTML = (id, icon = '', title = '', description = '') => `
        <div class="differentiator-item border border-gray-200 p-4 rounded-lg bg-gray-50 space-y-2" data-id="${id}">
            <div class="flex justify-between items-center">
                <label class="text-gray-700 text-sm font-bold uppercase">Diferenciador #${id}</label>
                <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>
            <input type="text" name="item-icon-${id}" class="w-full p-2 border border-gray-300 rounded-md differentiator-icon-input" placeholder="Clic para seleccionar un icono" value="${icon}" readonly>
            <input type="text" name="item-title-${id}" class="w-full p-2 border border-gray-300 rounded-md differentiator-title" placeholder="Título" value="${title}">
            <textarea name="item-description-${id}" class="w-full p-2 border border-gray-300 rounded-md differentiator-description" rows="2" placeholder="Descripción">${description}</textarea>
        </div>
    `;

    const renderPreview = () => {
        previewGrid.innerHTML = '';
        const itemsData = [];
        repeaterContainer.querySelectorAll('.differentiator-item').forEach(item => {
            const icon = item.querySelector('.differentiator-icon-input').value || 'check';
            const title = item.querySelector('.differentiator-title').value;
            const description = item.querySelector('.differentiator-description').value;
            const itemId = item.dataset.id;
            
            if (title || description) {
                itemsData.push({ id: itemId, icon, title, description });
                previewGrid.innerHTML += `
                    <div class="bg-white/15 p-4 rounded-lg">
                        <div class="flex items-start gap-3">
                            <span class="shrink-0 inline-flex h-8 w-8 items-center justify-center rounded-lg bg-white/15">
                                <i data-lucide="${icon}" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                            </span>
                            <div>
                                <h4 class="font-bold text-sm text-white">${title}</h4>
                                <p class="mt-1 text-xs text-white/80">${description}</p>
                            </div>
                        </div>
                    </div>
                `;
            }
        });
        itemsJsonInput.value = JSON.stringify(itemsData);
        lucide.createIcons();
    };

    addDifferentiatorBtn.addEventListener('click', () => {
        itemCounter++;
        repeaterContainer.insertAdjacentHTML('beforeend', createItemHTML(itemCounter));
        lucide.createIcons();
        renderPreview();
    });

    repeaterContainer.addEventListener('click', e => {
        if (e.target.closest('.remove-item-btn')) {
            e.target.closest('.differentiator-item').remove();
            renderPreview();
        }
    });

    repeaterContainer.addEventListener('focusin', e => {
        if (e.target.classList.contains('differentiator-icon-input')) {
            document.querySelectorAll('.differentiator-icon-input.is-active').forEach(el => el.classList.remove('is-active'));
            activeIconInput = e.target;
            activeIconInput.classList.add('is-active');
        }
    });

    repeaterContainer.addEventListener('input', renderPreview);

    // --- Lógica de Manejo de Imágenes Locales ---
    const handleLocalImagePreview = (fileInputId, previewElement, previewTarget) => {
        const fileInput = document.getElementById(fileInputId);
        
        if (!fileInput || !previewElement) return;

        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = event => {
                    const imageUrl = event.target.result;
                    // Preview del editor
                    previewElement.style.backgroundImage = `url('${imageUrl}')`;
                    previewElement.classList.add('has-image');
                    // Preview de la sección (Asegurando el gradiente)
                    previewTarget.style.backgroundImage = `linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('${imageUrl}')`;
                };
                reader.readAsDataURL(file);
            }
        });
    };
    
    // Aplicar la lógica de subida local a la imagen de fondo
    handleLocalImagePreview('differentiators-bg-image-upload', differentiatorsBgImagePreview, previewSection);


    // --- BINDING GENERAL (TEXTO) ---
    const bindings = {
        'differentiators-badge': { element: document.getElementById('preview-badge'), type: 'text' },
        'differentiators-title': { element: document.getElementById('preview-title'), type: 'text' },
        'differentiators-description': { element: document.getElementById('preview-description'), type: 'text' },
    };

    form.addEventListener('input', e => {
        const id = e.target.id;
        if (bindings[id] && bindings[id].type === 'text') {
            bindings[id].element.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.textContent = 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
    document.getElementById('differentiators-editor-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        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();

        try {
            const response = await fetch('cms/differentiators-update.php', {
                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();
        }
    });

    // Load data from backend on page load
    const loadData = async () => {
        try {
            const response = await fetch('cms/differentiators-read.php');
            const result = await response.json();
            
            if (result.success && result.data) {
                // Asumiendo que los datos vienen anidados en .data.general y .data.items
                const generalData = result.data.general || result.data;
                const itemsData = result.data.items || [];
                
                // 1. Cargar datos generales
                document.getElementById('differentiators-badge').value = safeValue(generalData.differentiators_badge);
                document.getElementById('preview-badge').textContent = safeValue(generalData.differentiators_badge);
                document.getElementById('differentiators-title').value = safeValue(generalData.differentiators_title);
                document.getElementById('preview-title').textContent = safeValue(generalData.differentiators_title);
                document.getElementById('differentiators-description').value = safeValue(generalData.differentiators_description);
                document.getElementById('preview-description').textContent = safeValue(generalData.differentiators_description);
                
                // 2. Cargar imagen de fondo (CORRECCIÓN APLICADA)
                if (generalData.differentiators_bg_image) {
                    const bgUrl = getFinalPath(generalData.differentiators_bg_image);
                    
                    differentiatorsBgImagePreview.style.backgroundImage = `url('${bgUrl}')`;
                    differentiatorsBgImagePreview.classList.add('has-image');
                    previewSection.style.backgroundImage = `linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('${bgUrl}')`;
                    currentDifferentiatorsBgImage.value = generalData.differentiators_bg_image;
                } else {
                    differentiatorsBgImagePreview.style.backgroundImage = `url('img/default-preview-bg.webp')`;
                    differentiatorsBgImagePreview.classList.remove('has-image');
                    previewSection.style.backgroundImage = `linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('img/default-bg.webp')`;
                    currentDifferentiatorsBgImage.value = '';
                }

                // 3. Cargar diferenciadores
                repeaterContainer.innerHTML = '';
                itemCounter = 0;
                itemsData.forEach(item => {
                    itemCounter++;
                    repeaterContainer.insertAdjacentHTML('beforeend', createItemHTML(itemCounter, item.item_icon, item.item_title, item.item_description));
                });
                
                renderPreview();
            } else {
                showToast(result.message || 'Error al cargar los datos de diferenciadores.', false);
            }
        } catch (error) {
            console.error('Error al cargar los datos:', error);
            showToast('Error al cargar los datos.', false);
        } finally {
            lucide.createIcons();
        }
    };
    loadData();

    // La lógica de re-bind fue eliminada ya que la carga de datos maneja la actualización del UI.
    // Solo quedan los listeners de carga local y texto.
});
</script>

</body>
</html>