<?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>Centro De Servicios 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);
            overflow: hidden; width: 100%; background-color: #fff;
        }
        #preview-map-container iframe {
            width: 100%;
            height: 100%;
            border: 0;
        }

        .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; }
        
        .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; }
        .service-icon-input.is-active { border-color: var(--color-primary); }

    </style>
</head>
<body data-page-title="SiteFlow® Portafolio De Servicios"
      data-page-subtitle="Modifica el encabezado y la lista de servicios ofrecidos"
      data-page-icon="briefcase">

    <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="services-editor-form" action="cms/services-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="services-badge" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Encabezado (Badge)</label>
                                    <input type="text" id="services-badge" name="services-badge" class="w-full p-3 border border-gray-300 rounded-lg" value="Built for Homes & Apartments">
                                </div>
                                <div>
                                    <label for="services-title-1" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Título (Línea 1)</label>
                                    <input type="text" id="services-title-1" name="services-title-1" class="w-full p-3 border border-gray-300 rounded-lg" value="THE RIGHT CLEAN FOR EVERY SPACE">
                                </div>
                                <div>
                                    <label for="services-title-2" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Título (Línea 2)</label>
                                    <input type="text" id="services-title-2" name="services-title-2" class="w-full p-3 border border-gray-300 rounded-lg" value="LESS HASSLE, MORE FREE TIME">
                                </div>
                                <div>
                                    <label for="services-description" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Texto (Descripción)</label>
                                    <textarea id="services-description" name="services-description" rows="4" class="w-full p-3 border border-gray-300 rounded-lg">Pick the service that fits your life—quick essentials, deep resets, or specialty care. Every option is delivered by trained pros with a clear checklist and a final inspection, so results are consistent and your weekends stay yours.</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 SERVICIOS</h4>
                             <div id="services-repeater" class="space-y-4">
                                 </div>
                             <button type="button" id="add-service-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 Servicio
                             </button>
                             <input type="hidden" id="services-json-input" name="services_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 (PARA SERVICIOS SIN IMAGEN)</h4>
                             <p class="text-sm text-gray-500 mb-4">Haz clic en un campo de "Icono" y luego selecciona uno de la 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 p-6">
                                <div class="text-center">
                                    <p id="preview-badge" class="font-bold text-xs text-[var(--brand-accent)]">Built for Homes & Apartments</p>
                                    <h2 class="font-extrabold leading-tight mt-2 text-2xl">
                                        <span id="preview-title-1" class="block text-black">The Right Clean For Every Space</span>
                                        <span id="preview-title-2" class="block text-[var(--color-secondary)]">Less Hassle, More Free Time</span>
                                    </h2>
                                    <p id="preview-description" class="mt-3 text-sm text-gray-600 max-w-lg mx-auto">Pick the service that fits your life...</p>
                                </div>
                                <div id="preview-services-grid" class="mt-8 grid grid-cols-1 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(--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', () => {
    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('services-editor-form');
    const repeaterContainer = document.getElementById('services-repeater');
    const addServiceBtn = document.getElementById('add-service-btn');
    const previewGrid = document.getElementById('preview-services-grid');
    const iconGallery = document.getElementById('icon-gallery');
    
    let itemCounter = 0;
    let activeIconInput = null;

    const iconList = [ 'list-checks', 'trash', 'wind', 'sun', 'plug', 'home', 'building-2', 'car', 'ship', 'briefcase', 'wrench', 'sparkles' ];
    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;
        }
    });
    
    // Función de ayuda para generar un beneficio (checkmark)
    const createBenefitItemHTML = (index, text = '') => `
        <div class="flex items-center gap-2 mb-2 benefit-item" data-index="${index}">
            <input type="text" name="service_benefits[${index}][]" 
                   class="w-full p-2 border border-gray-300 rounded-md text-sm benefit-input" 
                   placeholder="E.g., Deep scrub of showers, tubs, and sinks." value="${text}" />
            <button type="button" class="remove-benefit-btn text-[var(--color-secondary)] hover:text-[var(--color-secondary)] p-1" aria-label="Eliminar beneficio">
                <i data-lucide="x" class="w-4 h-4"></i>
            </button>
        </div>
    `;

    // Función para obtener todos los beneficios de un servicio
    const getBenefitsData = (itemElement) => {
        const benefits = [];
        itemElement.querySelectorAll('.benefit-input').forEach(input => {
            benefits.push(input.value);
        });
        return benefits;
    };


    const createServiceItemHTML = (id, imageSrc = '', icon = '', title = '', description = '', benefits = []) => {
        let benefitsHtml = benefits.map((text, index) => createBenefitItemHTML(id, text)).join('');
        
        return `
            <div class="service-item border border-gray-200 p-4 rounded-lg bg-gray-50 space-y-3" data-id="${id}">
                <input type="hidden" name="current_service_images[]" value="${imageSrc}">
                <div class="flex justify-between items-center">
                    <label class="text-gray-700 text-sm font-bold uppercase">Servicio #${id}</label>
                    <button type="button" class="remove-item-btn text-[var(--color-secondary)] hover:text-[var(--color-secondary)]"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
                </div>
                <div>
                    <label class="block text-gray-700 text-xs font-bold mb-1 uppercase">Imagen del Servicio</label>
                    <label for="service-image-upload-${id}" class="file-upload-preview cursor-pointer ${imageSrc ? 'has-image' : ''}" data-preview-for="service-image-upload-${id}" style="background-image: url('${imageSrc}');">
                        <span class="upload-text bg-white/80 px-4 py-2 rounded-md">Cambiar Imagen</span>
                        <input type="file" id="service-image-upload-${id}" name="service-image-upload-${id}[]" class="service-image-upload" accept="image/*">
                    </label>
                </div>
                <input type="text" name="service_icons[]" class="w-full p-2 border border-gray-300 rounded-md service-icon-input" placeholder="Icono (si no hay imagen)" value="${icon}" readonly>
                <input type="text" name="service_titles[]" class="w-full p-2 border border-gray-300 rounded-md service-title" placeholder="Título del Servicio" value="${title}">
                <textarea name="service_descriptions[]" class="w-full p-2 border border-gray-300 rounded-md service-description" rows="3" placeholder="Descripción del Servicio">${description}</textarea>
                
                <div class="pt-3 border-t border-gray-200">
                    <label class="block text-gray-700 text-xs font-bold mb-2 uppercase flex justify-between items-center">
                        BENEFICIOS (Checkmarks)
                        <button type="button" class="add-benefit-btn btn-secondary py-1 px-2 rounded text-xs text-green-700 bg-green-100/70 hover:bg-green-100" data-service-id="${id}">
                            <i data-lucide="plus" class="w-4 h-4 inline-block align-text-bottom"></i> Añadir
                        </button>
                    </label>
                    <div class="benefits-repeater-container" data-service-id="${id}">
                        ${benefitsHtml}
                    </div>
                </div>
            </div>
        `;
    };

    // =========================================================================
    // 🚨 FUNCIÓN CORREGIDA: renderServicesPreview (Frontend Structure)
    // =========================================================================
    const renderServicesPreview = () => {
        previewGrid.innerHTML = '';

        // Configura la grilla de 3 columnas para la vista previa, usando el diseño del frontend
        previewGrid.className = 'mt-8 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6';

        let previewItemCount = 0;
        
        // Al generar el JSON aquí, puedes usar los datos de beneficios
        const serviceDataArray = [];

        repeaterContainer.querySelectorAll('.service-item').forEach(item => {
            const currentImageInput = item.querySelector('input[name="current_service_images[]"]');
            const imageSrc = currentImageInput ? currentImageInput.value : '';
            const icon = item.querySelector('input[name="service_icons[]"]').value || 'sparkles';
            const title = item.querySelector('input[name="service_titles[]"]').value;
            const description = item.querySelector('textarea[name="service_descriptions[]"]').value;
            const benefits = getBenefitsData(item); // Obtener los beneficios del servicio

            // Almacenar para el JSON final
            serviceDataArray.push({
                item_image: imageSrc,
                item_icon: icon,
                item_title: title,
                item_description: description,
                item_benefits: benefits
            });
            
            if (title || description) {
                previewItemCount++;
                
                // Simulación del estilo "Destacado" (anillo rojo para el ítem #2)
                const isFeatured = (previewItemCount === 2) ? 'ring-2 ring-[var(--color-secondary)]' : '';
                
                // Ajuste de la ruta de la imagen (quitamos el '..')
                const finalImageSrc = imageSrc.startsWith('..') ? imageSrc.substring(3) : imageSrc;
                
                // Simulación de descripción corta y viñetas para la vista previa
                const shortDescription = description.substring(0, 70) + (description.length > 70 ? '...' : '');
                
                // Generar viñetas dinámicas para el preview
                const bulletPointsHtml = benefits.length > 0 ? benefits.map(text => `
                    <li class="flex items-start gap-2 text-xs text-gray-600"><i data-lucide="circle-check-big" class="w-4 h-4 text-green-500 flex-shrink-0"></i><span>${text}</span></li>
                `).join('') : '<li class="text-xs text-gray-400">No benefits added yet.</li>';

                // Estructura HTML de la tarjeta (simula fielmente el frontend)
                previewGrid.innerHTML += `
                    <article class="bg-white rounded-xl shadow-lg overflow-hidden flex flex-col ${isFeatured}">
                        
                        <div class="w-full h-36 relative flex items-center justify-center overflow-hidden bg-cover bg-center" 
                            style="background-image: url('${finalImageSrc}'); background-color: ${finalImageSrc ? 'transparent' : '#e5e7eb'};">
                            <span class="absolute inset-0 bg-black/40"></span>
                            <span class="relative inline-flex h-12 w-12 items-center justify-center rounded-xl bg-white/80 ring-1 ring-black/5 shadow-md">
                                <i data-lucide="${icon}" class="w-6 h-6 text-[var(--color-secondary)]"></i>
                            </span>
                        </div>
                        
                        <div class="p-4 flex flex-col flex-grow">
                            <h3 class="font-extrabold tracking-wide text-[var(--color-secondary)] 0 text-lg text-center">
                                ${title}
                            </h3>
                            <p class="mt-1 text-gray-700 text-sm text-center">
                                ${shortDescription}
                            </p>
                            
                            <ul class="mt-4 space-y-2 text-left flex-grow">
                                ${bulletPointsHtml}
                            </ul>
                        </div>
                    </article>
                `;
            }
        });

        // Actualizar el campo oculto con el JSON
        document.getElementById('services-json-input').value = JSON.stringify(serviceDataArray);
        
        // Vuelve a dibujar los íconos de Lucide
        lucide.createIcons();
    };
    // =========================================================================
    // FIN DE LA FUNCIÓN CORREGIDA
    // =========================================================================
    
    // --- MANEJADORES DE EVENTOS PARA BENEFICIOS ---
    
    // Delegación de eventos para añadir y eliminar beneficios
    repeaterContainer.addEventListener('click', e => {
        const addBtn = e.target.closest('.add-benefit-btn');
        const removeBtn = e.target.closest('.remove-benefit-btn');
        
        if (addBtn) {
            const serviceItem = addBtn.closest('.service-item');
            const serviceId = serviceItem.dataset.id;
            const container = serviceItem.querySelector('.benefits-repeater-container');
            const newIndex = container.children.length;

            container.insertAdjacentHTML('beforeend', createBenefitItemHTML(serviceId, ''));
            lucide.createIcons();
            renderServicesPreview();
        } else if (removeBtn) {
            removeBtn.closest('.benefit-item').remove();
            renderServicesPreview();
        } else if (e.target.closest('.remove-item-btn')) {
            // Maneja la eliminación del servicio principal
            e.target.closest('.service-item').remove();
            renderServicesPreview();
        }
    });

    // Delegación para actualizar el preview cuando se escribe en un beneficio
    repeaterContainer.addEventListener('input', e => {
        if (e.target.classList.contains('benefit-input') || e.target.classList.contains('service-title') || e.target.classList.contains('service-description')) {
            renderServicesPreview();
        }
    });

    // --- FIN DE MANEJADORES DE BENEFICIOS ---


    // ************************************************************
    // RESTO DEL CÓDIGO (Sin cambios, solo refactorizado para claridad)
    // ************************************************************

    addServiceBtn.addEventListener('click', () => {
        itemCounter++;
        repeaterContainer.insertAdjacentHTML('beforeend', createServiceItemHTML(itemCounter));
        lucide.createIcons();
        renderServicesPreview();
    });


    repeaterContainer.addEventListener('focusin', e => {
        if (e.target.classList.contains('service-icon-input')) {
            document.querySelectorAll('.service-icon-input.is-active').forEach(el => el.classList.remove('is-active'));
            activeIconInput = e.target;
            activeIconInput.classList.add('is-active');
        }
    });
    
    repeaterContainer.addEventListener('change', e => {
        if (e.target.classList.contains('service-image-upload')) {
            const file = e.target.files[0];
            const previewEl = e.target.closest('.file-upload-preview');
            // Usamos la nueva convención para obtener el ID de servicio
            const hiddenInput = e.target.closest('.service-item').querySelector('input[name^="current_service_images"]'); 
            if (file) {
                const reader = new FileReader();
                reader.onload = event => {
                    const imageUrl = event.target.result;
                    if(previewEl) {
                        previewEl.style.backgroundImage = `url('${imageUrl}')`;
                        previewEl.classList.add('has-image');
                    }
                    // El valor del input oculto se actualiza con la nueva imagen (base64 temporal)
                    hiddenInput.value = imageUrl;
                    renderServicesPreview();
                };
                reader.readAsDataURL(file);
            }
        }
    });


    // =========================================================================
    // CORRECCIÓN: VINCULACIÓN DEL ENCABEZADO PARA PREVIEW EN TIEMPO REAL
    // =========================================================================
    const headerBindings = {
        'services-badge': document.getElementById('preview-badge'),
        'services-title-1': document.getElementById('preview-title-1'),
        'services-title-2': document.getElementById('preview-title-2'),
        'services-description': document.getElementById('preview-description'),
    };
    
    const updateHeaderPreview = () => {
        for (const id in headerBindings) {
            const input = document.getElementById(id);
            const preview = headerBindings[id];
            if (input && preview) {
                preview.textContent = input.value;
                if (id === 'services-badge') {
                    preview.style.color = '#9e1428';
                }
            }
        }
        if (window.lucide) lucide.createIcons();
        renderServicesPreview(); 
    };

    // Aplicar la actualización inmediata al escribir en el formulario principal
    form.addEventListener('input', updateHeaderPreview);


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

    // La función de submit debe ser revisada para manejar el JSON de beneficios
    // 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();
        
        // Generamos el JSON final antes de enviar
        renderServicesPreview(); // Esto asegura que services-json-input esté actualizado.

        const formData = new FormData(form);
        
        // Añadimos los archivos (File objects) al FormData
        repeaterContainer.querySelectorAll('.service-item').forEach((item) => {
            const fileInput = item.querySelector('input[type="file"]');
            if (fileInput.files.length > 0) {
                // Añade el archivo usando el ID de servicio para identificarlo en el backend
                formData.append(`service-image-upload-${item.dataset.id}`, fileInput.files[0]);
            }
        });
        
        try {
            const response = await fetch(form.action, {
                method: 'POST',
                // No establecemos Content-Type, FormData lo hace automáticamente para archivos
                body: formData
            });
            
            const result = await response.json();
            
            showToast(result.message, result.success);

            if (result.success) {
                // Volver a cargar los datos para reflejar los cambios
                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 {
            // El endpoint de lectura debe ser revisado para que devuelva la nueva estructura de beneficios
            const response = await fetch('cms/services-read.php'); 
            const result = await response.json();
            
            if (result.success && result.data) {
                const generalData = result.data.general;
                // Asumimos que itemsData ahora incluye un campo 'item_benefits' que es un array de strings.
                const itemsData = result.data.items || [];
                
                document.getElementById('services-badge').value = generalData.services_badge;
                document.getElementById('services-title-1').value = generalData.services_title_1;
                document.getElementById('services-title-2').value = generalData.services_title_2;
                document.getElementById('services-description').value = generalData.services_description;
                
                // Cargar preview inicial del encabezado
                updateHeaderPreview();
                
                repeaterContainer.innerHTML = '';
                itemCounter = 0;
                itemsData.forEach(item => {
                    itemCounter++;
                    let finalImageSrc = '';
                    if (item.item_image) {
                        finalImageSrc = item.item_image.startsWith('http') ? item.item_image : `../${item.item_image}`;
                    }
                    const benefitsArray = item.item_benefits || []; // Usamos el array de beneficios si existe
                    repeaterContainer.insertAdjacentHTML('beforeend', createServiceItemHTML(itemCounter, finalImageSrc, item.item_icon, item.item_title, item.item_description, benefitsArray));
                });
                renderServicesPreview();
            }
        } catch (error) {
            console.error('Error al cargar los datos:', error);
            showToast('Error al cargar los datos.', false);
        } finally {
            lucide.createIcons();
        }
    };
    loadData();
});
</script>

</body>
</html>