<?php include 'files/guardiankey.php'; ?>
<?php
ob_start();
session_start();
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);
ob_end_clean();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Reviews CTA Final FlowCMS™</title>
    <meta name="robots" content="noindex, nofollow">

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

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

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
<style>
    body {
        --brand-primary: #07162d; 
        --brand-secondary: #ffc857;
        --brand-accent: #9e1428; 
        --brand-light: #f5f5f5;
        --brand-dark: #040d1a; 
    }
    /* Estilos del Toast (copiados de tu CMS) */
    .toast-container {
        position: fixed; bottom: 20px; right: 20px; z-index: 1000;
        display: flex; flex-direction: column; gap: 10px;
    }
    .toast {
        background-color: #333; color: white; padding: 15px; border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); opacity: 0; transform: translateY(20px);
        transition: opacity 0.3s ease-out, transform 0.3s ease-out; min-width: 250px;
    }
    .toast.show { opacity: 1; transform: translateY(0); }
    
    /* Estilos del CTA Preview */
    #cta-preview {
        background-color: #000;
        position: relative;
    }
    #cta-preview .preview-glow {
        background: radial-gradient(closest-side, var(--brand-secondary), transparent 70%);
    }
    .badge-item-editor {
        display: grid;
        grid-template-columns: 4rem 1fr auto;
        gap: 10px;
        align-items: center;
    }
</style>
 
</head>
<body data-page-title="SiteFlow® Reviews CTA Final"
      data-page-subtitle="Configura la llamada a la acción final para dirigir tráfico a tus plataformas de reseña"
      data-page-icon="rocket">

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

    <?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'cms-menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <form id="reviews-cta-form" action="cms/reviews-cta-update.php" method="POST">
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    
                    <div class="lg:col-span-1 bg-white p-6 rounded-xl shadow-md h-fit space-y-6">
                        
                        <div>
                            <h3 class="text-xl font-extrabold text-gray-700 flex items-center gap-2 border-b pb-2">
                                <i data-lucide="text-select" class="w-6 h-6 text-[var(--brand-primary)]"></i> 
                                Textos y Títulos
                            </h3>
                            
                            <div class="space-y-4 pt-4">
                                <div>
                                    <label for="badge_text" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Texto de Insignia Superior</label>
                                    <input type="text" id="badge_text" name="badge_text" class="w-full p-3 border border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label for="title_1" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Título (Línea 1)</label>
                                    <input type="text" id="title_1" name="title_1" class="w-full p-3 border border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label for="title_2" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Título (Línea 2 - Resaltado)</label>
                                    <input type="text" id="title_2" name="title_2" class="w-full p-3 border border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label for="description" class="block text-gray-700 text-sm font-bold mb-1 uppercase">Descripción</label>
                                    <textarea id="description" name="description" rows="2" class="w-full p-3 border border-gray-300 rounded-lg"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="border-t border-gray-200 pt-6 space-y-4">
                            <h3 class="text-xl font-extrabold text-gray-700 flex items-center gap-2 border-b pb-2">
                                <i data-lucide="award" class="w-6 h-6 text-[var(--brand-primary)]"></i> 
                                Badges de Beneficio (Pie de Sección)
                            </h3>
                            
                            <div id="badges-editor-container" class="space-y-4">
                                <template id="badge-template">
                                    <div class="p-3 border border-gray-200 rounded-lg space-y-2 badge-item" data-id="0">
                                        <input type="hidden" class="badge-id" value="0">
                                        <input type="hidden" class="sort-order-input" value="0">
                                        
                                        <div class="badge-item-editor">
                                            <div class="flex-1">
                                                <label class="block text-xs font-semibold uppercase text-gray-600">Icono</label>
                                                <input type="text" class="badge-icon-input w-full p-2 border rounded text-sm" placeholder="Ej: badge-check">
                                            </div>
                                            <div class="flex-1 col-span-2">
                                                <label class="block text-xs font-semibold uppercase text-gray-600">Texto del Badge</label>
                                                <input type="text" class="badge-text-input w-full p-2 border rounded text-sm" placeholder="Ej: Honest Feedback Is Valued">
                                            </div>
                                            <div class="flex justify-end col-span-1 gap-1">
                                                <button type="button" class="move-up-btn text-gray-500 hover:text-gray-800 p-1" title="Subir"><i data-lucide="arrow-up" class="w-5 h-5"></i></button>
                                                <button type="button" class="move-down-btn text-gray-500 hover:text-gray-800 p-1" title="Bajar"><i data-lucide="arrow-down" class="w-5 h-5"></i></button>
                                                <button type="button" class="delete-badge-btn text-red-500 hover:text-red-700 p-1" title="Eliminar"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </div>
                            
                            <div class="pt-4 border-t border-gray-200">
                                <button type="button" id="add-badge-button" class="w-full btn-secondary font-bold py-2 px-4 rounded-lg text-sm flex items-center justify-center gap-2">
                                    <i data-lucide="plus-circle" class="w-5 h-5"></i>
                                    <span>Añadir Nuevo Badge</span>
                                </button>
                            </div>
                        </div>

                        <div class="border-t border-gray-200 pt-6 flex justify-end">
                            <button type="submit" id="save-button" class="btn-primary font-bold py-3 px-8 rounded-lg uppercase text-sm flex items-center justify-center gap-2">
                                <i data-lucide="save" class="w-5 h-5"></i>
                                <span>Guardar Cambios</span>
                            </button>
                        </div>
                    </div>
                    
                    <div class="lg:col-span-1 space-y-8">
                        
                        <div id="cta-preview" class="py-16 md:py-20 px-6 rounded-xl shadow-xl">
                            <div aria-hidden="true" class="absolute inset-0 z-0 overflow-hidden pointer-events-none">
                                <div class="absolute top-0 right-0 translate-x-1/4 -translate-y-1/4 w-[25rem] h-[25rem] rounded-md blur-3xl opacity-20 preview-glow" style="background: radial-gradient(closest-side, var(--brand-secondary), transparent 70%);"></div>
                            </div>

                            <div class="relative z-10 max-w-7xl mx-auto text-center">
                                <p class="inline-flex items-center gap-2 px-4 py-1.5 rounded-md bg-white/10 text-[var(--brand-secondary)] font-extrabold tracking-[0.15em] ring-1 ring-white/20">
                                    <span id="preview-badge-text">Ready To Help Us?</span>
                                </p>

                                <h2 class="font-extrabold leading-[0.92] tracking-tight mt-4">
                                    <span id="preview-title-1" class="block text-4xl sm:text-4xl md:text-4xl text-white">Ready To Share Your Story?</span>
                                    <span id="preview-title-2" class="block text-[var(--brand-secondary)] text-4xl sm:text-4xl md:text-5xl">Pick Your Favorite Platform</span>
                                </h2>

                                <p id="preview-description" class="max-w-3xl mt-6 text-lg md:text-xl text-white/90 mx-auto">
                                    We truly appreciate you taking a moment to share your experience. Click one of the buttons below to get started.
                                </p>

                                <div id="preview-links-container" class="mt-10 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 max-w-4xl mx-auto">
                                    <div class="p-4 text-sm text-white/70 bg-gray-800 rounded-lg sm:col-span-3">Cargando enlaces de Google, Facebook, Yelp... (Datos de la tabla `cms_review_links`)</div>
                                </div>

                                <div id="preview-badges-container" class="mt-12 flex flex-wrap gap-3 text-sm justify-center">
                                    </div>
                            </div>
                        </div>

                        <div id="video-instrucciones" class="space-y-6">
                            <div class="w-full">
                                <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                                    <div class="relative w-full" style="padding-bottom: 56.25%;">
                                        <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayer" controls controlslist="nodownload fullscreen" preload="metadata">
                                            <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                                            TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                                        </video>
                                        <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                                            <img src="img/VideoLeccion-IAMarketing.jpg" alt="VideoLeccion - IAMarketing" class="absolute inset-0 w-full h-full object-cover">
                                            <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                                            <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                                        </div>
                                    </div>
                                    <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="play-circle" class="w-4 h-4"></i> Video Tutorial
                                        </span>
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="clock" class="w-4 h-4"></i> 2–3 min
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow-md">
                                <div class="text-center md:text-left mb-6">
                                    <h4 class="text-2xl font-black uppercase text-black flex items-center justify-center md:justify-start">
                                        <i data-lucide="book-open" class="mr-3 text-[var(--brand-secondary)] w-7 h-7"></i>
                                        INSTRUCCIONES IMPORTANTES
                                    </h4>
                                    <p class="step-subtitle uppercase text-sm mt-1 text-gray-500">REVISA ESTOS PUNTOS DETALLADAMENTE</p>
                                </div>

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

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

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

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

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

<script>
document.addEventListener('DOMContentLoaded', () => {
    // --- SETUP BÁSICO ---
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    if (mobileMenuButton && sidebar && sidebarOverlay) {
        mobileMenuButton.addEventListener('click', () => { sidebar.classList.toggle('-translate-x-full'); sidebarOverlay.classList.toggle('hidden'); });
        sidebarOverlay.addEventListener('click', () => { sidebar.classList.add('-translate-x-full'); sidebarOverlay.classList.add('hidden'); });
    }

    const form = document.getElementById('reviews-cta-form');
    const badgesEditorContainer = document.getElementById('badges-editor-container');
    const addBadgeButton = document.getElementById('add-badge-button');
    const badgeTemplate = document.getElementById('badge-template');
    const previewBadgesContainer = document.getElementById('preview-badges-container');
    const previewLinksContainer = document.getElementById('preview-links-container');
    const saveButton = document.getElementById('save-button');


    // --- ELEMENTOS DE PREVIEW ---
    const previewBadgeText = document.getElementById('preview-badge-text');
    const previewTitle1 = document.getElementById('preview-title-1');
    const previewTitle2 = document.getElementById('preview-title-2');
    const previewDescription = document.getElementById('preview-description');
    
    // Almacenamiento de todos los ítems en el frontend
    let badgesData = []; 

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

    // --- UTILIDADES ---
    const safeValue = (value) => value ?? '';
    
    // Función para crear el elemento de badge en la previsualización
    const createPreviewBadge = (badge) => {
        const badgeElement = document.createElement('span');
        badgeElement.className = 'inline-flex items-center gap-2 px-3 py-1.5 rounded-md bg-white/10 text-white ring-1 ring-white/15';
        
        badgeElement.innerHTML = `
            <i data-lucide="${safeValue(badge.badge_icon) || 'badge-check'}" class="w-4 h-4 text-[var(--brand-secondary)]"></i>
            ${safeValue(badge.badge_text)}
        `;
        
        lucide.createIcons({ element: badgeElement });
        return badgeElement;
    };
    
    // Función para crear el botón de reseña (Links de cms_review_links)
    const createPreviewLinkButton = (link) => {
        const linkElement = document.createElement('a');
        linkElement.href = safeValue(link.link_url);
        linkElement.target = '_blank';
        linkElement.rel = 'noopener';
        
        // Uso de clases y estilos dinámicos para el botón
        linkElement.className = 'group flex flex-col items-center justify-center gap-2 px-8 py-5 rounded-2xl font-extrabold text-white shadow-lg transition text-center hover:brightness-110';
        linkElement.style.backgroundColor = safeValue(link.button_color) || '#000000';
        
        // Determinar el texto a mostrar (asumiendo que platform_name es Google, Facebook, Yelp)
        const platformName = safeValue(link.platform_name);
        const textContent = `Leave a Review on<br><b>${platformName}</b>`;

        linkElement.innerHTML = `
            <i data-lucide="${safeValue(link.icon_lucide) || 'star'}" class="w-8 h-8"></i>
            <span>${textContent}</span>
        `;
        
        lucide.createIcons({ element: linkElement });
        return linkElement;
    };


    // --- LÓGICA DE GESTIÓN DE BADGES ---
    
    // 1. Renderizar la lista de edición y la previsualización
    const renderBadges = () => {
        // 1. Limpiar contenedores
        badgesEditorContainer.innerHTML = '';
        previewBadgesContainer.innerHTML = '';
        
        // 2. Ordenar badgesData por sort_order
        badgesData.sort((a, b) => a.sort_order - b.sort_order);

        // 3. Renderizar cada badge
        badgesData.forEach((badge, index) => {
            // Renderizar Editor
            const templateClone = badgeTemplate.content.cloneNode(true).querySelector('.badge-item');
            templateClone.dataset.id = badge.id;
            
            // Asignar valores a los inputs del editor
            templateClone.querySelector('.badge-id').value = badge.id;
            templateClone.querySelector('.sort-order-input').value = badge.sort_order;
            templateClone.querySelector('.badge-text-input').value = safeValue(badge.badge_text);
            templateClone.querySelector('.badge-icon-input').value = safeValue(badge.badge_icon);

            badgesEditorContainer.appendChild(templateClone);

            // Renderizar Preview
            previewBadgesContainer.appendChild(createPreviewBadge(badge));
        });
        
        lucide.createIcons({ element: badgesEditorContainer });
    };
    
    // 2. Añadir nuevo badge
    addBadgeButton.addEventListener('click', () => {
        const newBadge = {
            id: 0, 
            badge_icon: 'award',
            badge_text: 'Nuevo Beneficio Agregado',
            sort_order: badgesData.length > 0 ? Math.max(...badgesData.map(l => l.sort_order)) + 1 : 1 
        };
        badgesData.push(newBadge);
        renderBadges();
    });
    
    // 3. Manejar eventos de edición, borrado y ordenamiento
    badgesEditorContainer.addEventListener('input', (e) => {
        const badgeItem = e.target.closest('.badge-item');
        if (!badgeItem) return;

        const id = parseInt(badgeItem.querySelector('.badge-id').value);
        let index = badgesData.findIndex(l => (l.id === id && id !== 0)); 
        
        if (index === -1 && id === 0) {
            const allItems = Array.from(badgesEditorContainer.querySelectorAll('.badge-item'));
            index = allItems.indexOf(badgeItem);
        }
        
        if (index === -1) return;

        // Actualizar el objeto de datos en tiempo real
        if (e.target.classList.contains('badge-text-input')) badgesData[index].badge_text = e.target.value;
        if (e.target.classList.contains('badge-icon-input')) {
             badgesData[index].badge_icon = e.target.value;
             renderBadgesPreviewOnly();
        }

        renderBadgesPreviewOnly();
    });

    badgesEditorContainer.addEventListener('click', (e) => {
        const badgeItem = e.target.closest('.badge-item');
        if (!badgeItem) return;

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

        if (e.target.closest('.move-up-btn')) {
            if (index > 0) {
                const prevItem = badgesData[index - 1];
                prevItem.sort_order = currentSort;
                badgesData[index].sort_order = currentSort - 1;
                renderBadges();
            }
        } else if (e.target.closest('.move-down-btn')) {
            if (index < badgesData.length - 1) {
                const nextItem = badgesData[index + 1];
                nextItem.sort_order = currentSort;
                badgesData[index].sort_order = currentSort + 1;
                renderBadges();
            }
        } else if (e.target.closest('.delete-badge-btn')) {
            badgesData.splice(index, 1);
            badgesData.forEach((badge, i) => badge.sort_order = i + 1);
            renderBadges();
        }
    });
    
    // Función optimizada para re-renderizar solo la preview
    const renderBadgesPreviewOnly = () => {
        previewBadgesContainer.innerHTML = '';
        badgesData.sort((a, b) => a.sort_order - b.sort_order);
        badgesData.forEach(badge => {
            previewBadgesContainer.appendChild(createPreviewBadge(badge));
        });
    }

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

        if (id === 'badge_text') previewBadgeText.textContent = value;
        if (id === 'title_1') previewTitle1.textContent = value;
        if (id === 'title_2') previewTitle2.textContent = value;
        if (id === 'description') previewDescription.textContent = value;
    });

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

            if (result.success && result.data) {
                const { hero, badges, links } = result.data;
                
                // 1. Cargar Textos Principales
                document.getElementById('badge_text').value = safeValue(hero.badge_text);
                document.getElementById('title_1').value = safeValue(hero.title_1);
                document.getElementById('title_2').value = safeValue(hero.title_2);
                document.getElementById('description').value = safeValue(hero.description);
                
                // 2. Cargar Badges Dinámicos
                badgesData = badges.map(badge => ({
                    ...badge, 
                    id: parseInt(badge.id),
                    sort_order: parseInt(badge.sort_order)
                }));
                renderBadges();
                
                // 3. Cargar Links de Reseña (Solo para Preview)
                previewLinksContainer.innerHTML = '';
                if (links.length > 0) {
                    links.forEach(link => {
                        previewLinksContainer.appendChild(createPreviewLinkButton(link));
                    });
                } else {
                     previewLinksContainer.innerHTML = '<div class="p-4 text-sm text-white/70 bg-gray-800 rounded-lg sm:col-span-3">Advertencia: No hay enlaces definidos en la sección Reviews Hero.</div>';
                }
                
                // 4. Actualizar Preview inicial
                previewBadgeText.textContent = safeValue(hero.badge_text);
                previewTitle1.textContent = safeValue(hero.title_1);
                previewTitle2.textContent = safeValue(hero.title_2);
                previewDescription.textContent = safeValue(hero.description);
            }
        } catch (error) {
            console.error('Error al cargar datos:', error);
            showToast('Error al cargar los datos iniciales de Reviews CTA Final.', false);
        } finally {
            lucide.createIcons();
        }
    };

    // --- LÓGICA DE SUBMIT DEL FORMULARIO ---
    form.addEventListener('submit', async e => {
        e.preventDefault();
        
        // 1. Recolectar datos de badges
        const finalBadgesData = [];
        badgesData.forEach(badge => {
            finalBadgesData.push({
                id: badge.id,
                badge_icon: badge.badge_icon,
                badge_text: badge.badge_text,
                sort_order: badge.sort_order
            });
        });
        
        const formData = new FormData(form);
        formData.append('badges_data', JSON.stringify(finalBadgesData)); // Adjuntar la lista de badges

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

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

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

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

</body>
</html>