<?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>CTA Persuasivo 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: #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);
        }
        .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; }
        .badge-icon-input.is-active { border-color: var(--color-primary); }
    </style>
</head>
<body data-page-title="SiteFlow® CTA Persuasivo Final"
      data-page-subtitle="Modifica los textos persuasivos y las insignias de confianza"
      data-page-icon="mouse-pointer-click">

    <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="cta-editor-form" action="cms/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 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> TEXTOS PRINCIPALES</h4>
                            <div class="space-y-4">
                                <div>
                                    <label for="cta-badge" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Encabezado (Badge)</label>
                                    <input type="text" id="cta-badge" name="cta-badge" class="w-full p-3 border border-gray-300 rounded-lg" value="Make it easy on yourself — start today">
                                </div>
                                <div>
                                    <label for="cta-title-1" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Título (Línea 1)</label>
                                    <input type="text" id="cta-title-1" name="cta-title-1" class="w-full p-3 border border-gray-300 rounded-lg" value="READY TO LOVE YOUR SPACE AGAIN?">
                                </div>
                                <div>
                                    <label for="cta-title-2" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Título (Línea 2)</label>
                                    <input type="text" id="cta-title-2" name="cta-title-2" class="w-full p-3 border border-gray-300 rounded-lg" value="CHOOSE HOW YOU’D LIKE TO START">
                                </div>
                                <div>
                                    <label for="cta-description" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Texto (Descripción)</label>
                                    <textarea id="cta-description" name="cta-description" rows="3" class="w-full p-3 border border-gray-300 rounded-lg">No pressure. No hassle. Pick what’s easiest for you—get a quick quote, call us, or drop an email. Do it today and enjoy the result as soon as tomorrow.</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="box-select" class="w-6 h-6 text-[var(--color-primary)]"></i> BOTONES Y TARJETAS DE CONTACTO</h4>
                            <div class="space-y-4">
                                <p class="text-sm text-gray-500 bg-[var(--color-highlight)]-50 border border-yellow-200 p-3 rounded-lg">Nota: Los números de teléfono y el email se toman de la configuración general. Aquí solo puedes editar las etiquetas de texto.</p>
                                <div>
                                    <label for="cta-main-button-text" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Botón Principal - Texto Principal</label>
                                    <input type="text" id="cta-main-button-text" name="cta-main-button-text" class="w-full p-3 border border-gray-300 rounded-lg" value="Request A Free Quote">
                                </div>
                                <div>
                                    <label for="cta-main-button-subtext" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Botón Principal - Texto Secundario</label>
                                    <input type="text" id="cta-main-button-subtext" name="cta-main-button-subtext" class="w-full p-3 border border-gray-300 rounded-lg" value="Takes about 60 seconds.">
                                </div>
                                <div>
                                    <label for="cta-card-phone1-text" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Tarjeta Teléfono 1 - Texto</label>
                                    <input type="text" id="cta-card-phone1-text" name="cta-card-phone1-text" class="w-full p-3 border border-gray-300 rounded-lg" value="Call Us Now">
                                </div>
                                <div>
                                    <label for="cta-card-phone2-text" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Tarjeta Teléfono 2 - Texto</label>
                                    <input type="text" id="cta-card-phone2-text" name="cta-card-phone2-text" class="w-full p-3 border border-gray-300 rounded-lg" value="Our Second Phone">
                                </div>
                                <div>
                                    <label for="cta-card-email-text" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Tarjeta Email - Texto</label>
                                    <input type="text" id="cta-card-email-text" name="cta-card-email-text" class="w-full p-3 border border-gray-300 rounded-lg" value="Send Us An Email">
                                </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="shield-check" class="w-6 h-6 text-[var(--color-primary)]"></i> INSIGNIAS DE CONFIANZA</h4>
                             <div id="badges-repeater" class="space-y-4"></div>
                             <button type="button" id="add-badge-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 Insignia</button>
                             <input type="hidden" id="badges-json-input" name="badges_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" y luego selecciona uno 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="bg-gray-800 text-white p-6">
                                    <p id="preview-badge" class="text-xs font-bold text-[var(--color-highlight)]">Make It Easy On Yourself — Start Today</p>
                                    <h2 class="font-extrabold leading-tight mt-2 text-2xl">
                                        <span id="preview-title-1" class="block">Ready To Love Your Space Again?</span>
                                        <span id="preview-title-2" class="block text-[var(--color-highlight)]">Choose How You’d Like To Start</span>
                                    </h2>
                                    <p id="preview-description" class="text-white/90 mt-3 text-sm">No pressure. No hassle. Pick what’s easiest for you—get a quick quote, call us, or drop an email. Do it today and enjoy the result as soon as tomorrow.</p>
                                    <div class="mt-6 grid grid-cols-1 gap-4">
                                        <a href="#" class="w-full flex flex-col items-center justify-center p-3 rounded-lg bg-[var(--color-highlight)] text-gray-800 font-bold text-center">
                                            <span id="preview-main-button-text">Request A Free Quote</span>
                                            <span id="preview-main-button-subtext" class="text-xs font-normal">Takes about 60 seconds.</span>
                                        </a>
                                        <div class="grid grid-cols-3 gap-2 text-xs">
                                            <a id="preview-card-phone1-link" href="#" class="bg-white/10 p-2 rounded-md flex flex-col items-center justify-center"><i data-lucide="phone" class="w-4 h-4 text-[var(--color-highlight)] mb-1"></i><span id="preview-card-phone1-text">Call Us Now</span><span id="preview-card-phone1-value" class="opacity-80">(123) 456-7890</span></a>
                                            <a id="preview-card-phone2-link" href="#" class="bg-white/10 p-2 rounded-md flex flex-col items-center justify-center"><i data-lucide="phone-call" class="w-4 h-4 text-[var(--color-highlight)] mb-1"></i><span id="preview-card-phone2-text">Our Second Phone</span><span id="preview-card-phone2-value" class="opacity-80">(098) 765-4321</span></a>
                                            <a id="preview-card-email-link" href="#" class="bg-white/10 p-2 rounded-md flex flex-col items-center justify-center"><i data-lucide="mail" class="w-4 h-4 text-[var(--color-highlight)] mb-1"></i><span id="preview-card-email-text">Send Us An Email</span><span id="preview-card-email-value" class="opacity-80">info@email.com</span></a>
                                        </div>
                                    </div>
                                    <div id="preview-badges-container" class="mt-4 flex flex-wrap gap-2 text-xs"></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', () => {
    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('cta-editor-form');

    // --- REPEATER DE INSIGNIAS ---
    const badgesRepeater = document.getElementById('badges-repeater');
    const addBadgeBtn = document.getElementById('add-badge-btn');
    const previewBadgesContainer = document.getElementById('preview-badges-container');
    const iconGallery = document.getElementById('icon-gallery');
    const badgesJsonInput = document.getElementById('badges-json-input');

    let badgeCounter = 0;
    let activeIconInput = null;

    const iconList = ['badge-check', 'calendar-check-2', 'handshake', 'shield-check', 'award', 'thumbs-up', 'star', 'gem', 'sparkles', 'verified', 'lock', 'clock' ];
    iconGallery.innerHTML = iconList.map(name => `<button type="button" class="icon-gallery-btn" data-icon-name="${name}"><i data-lucide="${name}" 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;
        }
    });

    const createBadgeItemHTML = (id, icon = '', text = '') => `
        <div class="badge-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">Insignia #${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="badge-icon-${id}" class="w-full p-2 border border-gray-300 rounded-md badge-icon-input" placeholder="Clic para seleccionar icono" value="${icon}" readonly>
            <input type="text" name="badge-text-${id}" class="w-full p-2 border border-gray-300 rounded-md badge-text" placeholder="Texto de la insignia" value="${text}">
        </div>
    `;

    const renderBadgesPreview = () => {
        previewBadgesContainer.innerHTML = '';
        const badgesData = [];
        badgesRepeater.querySelectorAll('.badge-item').forEach(item => {
            const icon = item.querySelector('.badge-icon-input').value || 'check';
            const text = item.querySelector('.badge-text').value;
            if (text) {
                badgesData.push({ icon, text });
                previewBadgesContainer.innerHTML += `<span class="inline-flex items-center gap-2 px-2 py-1 rounded-md bg-white/10"><i data-lucide="${icon}" class="w-3 h-3 text-[var(--color-highlight)]"></i> ${text}</span>`;
            }
        });
        badgesJsonInput.value = JSON.stringify(badgesData);
        lucide.createIcons();
    };

    addBadgeBtn.addEventListener('click', () => { badgeCounter++; badgesRepeater.insertAdjacentHTML('beforeend', createBadgeItemHTML(badgeCounter)); lucide.createIcons(); renderBadgesPreview(); });
    badgesRepeater.addEventListener('click', e => { if (e.target.closest('.remove-item-btn')) { e.target.closest('.badge-item').remove(); renderBadgesPreview(); } });
    badgesRepeater.addEventListener('focusin', e => { if (e.target.classList.contains('badge-icon-input')) { document.querySelectorAll('.badge-icon-input.is-active').forEach(el => el.classList.remove('is-active')); activeIconInput = e.target; activeIconInput.classList.add('is-active'); } });
    badgesRepeater.addEventListener('input', renderBadgesPreview);

    // --- BINDING DE TEXTOS ---
    const bindings = {
        'cta-badge': document.getElementById('preview-badge'),
        'cta-title-1': document.getElementById('preview-title-1'),
        'cta-title-2': document.getElementById('preview-title-2'),
        'cta-description': document.getElementById('preview-description'),
        'cta-main-button-text': document.getElementById('preview-main-button-text'),
        'cta-main-button-subtext': document.getElementById('preview-main-button-subtext'),
        'cta-card-phone1-text': document.getElementById('preview-card-phone1-text'),
        'cta-card-phone2-text': document.getElementById('preview-card-phone2-text'),
        'cta-card-email-text': document.getElementById('preview-card-email-text'),
    };
    const updatePreview = (input) => { if (bindings[input.id]) { bindings[input.id].textContent = input.value; } };
    form.addEventListener('input', e => updatePreview(e.target));
    
    // Función para mostrar toasts de notificación
    const showToast = (message, isSuccess) => {
        const toastContainer = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast ${isSuccess ? 'bg-green-500' : 'bg-red-500'}`;
        toast.innerHTML = message;
        toastContainer.appendChild(toast);
        setTimeout(() => toast.classList.add('show'), 10);
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    };

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

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

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

            showToast(result.message, result.success);

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

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

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

            if (result.success && result.data) {
                const generalData = result.data.general;
                const badgesData = result.data.badges;
                const contactData = result.data.business_contact; // NUEVO: Datos de contacto

                // 1. Cargar textos generales
                document.getElementById('cta-badge').value = generalData.cta_badge;
                document.getElementById('preview-badge').textContent = generalData.cta_badge;
                document.getElementById('cta-title-1').value = generalData.cta_title_1;
                document.getElementById('preview-title-1').textContent = generalData.cta_title_1;
                document.getElementById('cta-title-2').value = generalData.cta_title_2;
                document.getElementById('preview-title-2').textContent = generalData.cta_title_2;
                document.getElementById('cta-description').value = generalData.cta_description;
                document.getElementById('preview-description').textContent = generalData.cta_description;
                document.getElementById('cta-main-button-text').value = generalData.cta_main_button_text;
                document.getElementById('preview-main-button-text').textContent = generalData.cta_main_button_text;
                document.getElementById('cta-main-button-subtext').value = generalData.cta_main_button_subtext;
                document.getElementById('preview-main-button-subtext').textContent = generalData.cta_main_button_subtext;
                document.getElementById('cta-card-phone1-text').value = generalData.cta_card_phone1_text;
                document.getElementById('preview-card-phone1-text').textContent = generalData.cta_card_phone1_text;
                document.getElementById('cta-card-phone2-text').value = generalData.cta_card_phone2_text;
                document.getElementById('preview-card-phone2-text').textContent = generalData.cta_card_phone2_text;
                document.getElementById('cta-card-email-text').value = generalData.cta_card_email_text;
                document.getElementById('preview-card-email-text').textContent = generalData.cta_card_email_text;

                // 2. Cargar datos de contacto en las tarjetas de previsualización (NUEVO)
                if (contactData) {
                    const phone1 = contactData.phone_primary || '(123) 456-7890';
                    const phone2 = contactData.phone_secondary || '(098) 765-4321';
                    const email = contactData.site_email || 'info@email.com';

                    document.getElementById('preview-card-phone1-value').textContent = phone1;
                    document.getElementById('preview-card-phone2-value').textContent = phone2;
                    document.getElementById('preview-card-email-value').textContent = email;
                    
                    // Asegurar que los enlaces también usen los números
                    document.getElementById('preview-card-phone1-link').href = `tel:${phone1.replace(/\D/g, '')}`;
                    document.getElementById('preview-card-phone2-link').href = `tel:${phone2.replace(/\D/g, '')}`;
                    document.getElementById('preview-card-email-link').href = `mailto:${email}`;
                }

                // 3. Cargar insignias
                badgesRepeater.innerHTML = '';
                badgeCounter = 0;
                badgesData.forEach(badge => {
                    badgeCounter++;
                    badgesRepeater.insertAdjacentHTML('beforeend', createBadgeItemHTML(badgeCounter, badge.badge_icon, badge.badge_text));
                });
                renderBadgesPreview();
            }
        } catch (error) {
            console.error('Error al cargar los datos:', error);
            showToast('Error al cargar los datos.', false);
        } finally {
            lucide.createIcons();
        }
    };
    loadData();
});
</script>

</body>
</html>