


<?php
/**
 * MÓDULO: WebBuilder Studio Ultimate 2026
 * Arquitectura: Full-Canvas 50/50 | Modular | AJAX API
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }

// 1. VALIDACIÓN DE SEGURIDAD
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { 
    die("Acceso Denegado"); 
}

$idu_sesion = $_SESSION['IDUg'] ?? 'ANONIMO';
$db_name = "MS_Datos"; // Variable maestra de la base de datos
$idu=$idu_sesion;
?>


    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;800&family=Fira+Code:wght@400;500&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --ui-accent: #4f46e5;
            --ui-bg: #ffffff;
            --ui-toolbar: #f8fafc;
            --ui-border: #e2e8f0;
            --editor-bg: #0d0f14;
            --ui-danger: #ef4444;
        }

        * { box-sizing: border-box; outline: none; }
        body, html { height: 100vh; width: 100vw; margin: 0; padding: 0; overflow: hidden; font-family: 'Inter', sans-serif; }

        .app-canvas { display: flex; flex-direction: column; height: 100vh; width: 100vw; }

        /* CAPA A: GESTIÓN SUPERIOR */
        .nav-management {
            height: 60px; background: #fff; border-bottom: 1px solid var(--ui-border);
            display: flex; align-items: center; padding: 0 25px; justify-content: space-between;
            z-index: 1000;
        }

        /* CAPA B: SUB-NAVBAR DE COMPONENTES */
        .nav-components {
            height: 50px; background: var(--ui-toolbar); border-bottom: 1px solid var(--ui-border);
            display: flex; align-items: center; padding: 0 15px; gap: 8px; z-index: 999;
        }

        /* DROPDOWNS DE CATEGORÍAS */
        .category-dropdown { position: relative; display: inline-block; }
        .drop-btn {
            background: white; border: 1px solid var(--ui-border); padding: 7px 14px;
            border-radius: 10px; font-size: 11px; font-weight: 700; cursor: pointer;
            display: flex; align-items: center; gap: 6px; text-transform: uppercase; color: #475569; transition: 0.2s;
        }
        .drop-btn:hover { border-color: var(--ui-accent); color: var(--ui-accent); box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
        
        .drop-content {
            display: none; position: absolute; background: white; min-width: 250px;
            box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); border-radius: 14px;
            padding: 10px; z-index: 1001; border: 1px solid var(--ui-border);
            top: 110%; left: 0; max-height: 80vh; overflow-y: auto;
        }
        .category-dropdown:hover .drop-content { display: block; }
        
        .snippet-item {
            width: 100%; text-align: left; padding: 10px 14px; border: none;
            background: transparent; font-size: 12px; border-radius: 8px;
            cursor: pointer; display: flex; align-items: center; gap: 12px; transition: 0.2s;
            color: #1e293b; font-weight: 500;
        }
        .snippet-item:hover { background: #f1f5f9; color: var(--ui-accent); padding-left: 18px; }
        .snippet-item i { width: 16px; opacity: 0.6; }

        /* CAPA C: CANVAS 50/50 */
        .workspace { flex: 1; display: grid; grid-template-columns: 1fr 1fr; overflow: hidden; background: #000; }

        .pane-code { background: var(--editor-bg); display: flex; flex-direction: column; border-right: 1px solid #222; }
        #html_editor {
            flex: 1; width: 100%; height: 100%; background: transparent; color: #a5d6ff;
            border: none; padding: 30px; font-family: 'Fira Code', monospace;
            font-size: 14px; outline: none; resize: none; line-height: 1.7;
            scrollbar-width: thin; scrollbar-color: #333 transparent;
        }

        .pane-preview { background: white; position: relative; }
        iframe { width: 100%; height: 100%; border: none; }

        /* UI ELEMENTS */
        .input-ui { border: 1px solid var(--ui-border); border-radius: 10px; padding: 8px 15px; font-size: 14px; outline: none; font-weight: 600; transition: 0.2s; }
        .input-ui:focus { border-color: var(--ui-accent); box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1); }
        .btn-publish { background: var(--ui-accent); color: white; border: none; padding: 10px 25px; border-radius: 12px; font-weight: 800; cursor: pointer; transition: 0.3s; box-shadow: 0 10px 15px -3px rgba(79, 70, 229, 0.3); }
        .btn-publish:hover { transform: translateY(-2px); filter: brightness(1.1); }
        
        .btn-delete-page { background: white; color: var(--ui-danger); border: 1px solid var(--ui-danger); padding: 10px 15px; border-radius: 12px; font-weight: 700; cursor: pointer; transition: 0.3s; margin-right: 10px; display: none; }
        .btn-delete-page:hover { background: var(--ui-danger); color: white; }

        .token-tag { background: #f1f5f9; color: var(--ui-accent); padding: 6px 14px; border-radius: 8px; font-family: monospace; font-weight: 900; font-size: 13px; }
        .divider-v { width: 1px; height: 25px; background: var(--ui-border); margin: 0 10px; }
   
   
</style>


<div class="app-canvas">
    
    <nav class="nav-management">
        <div class="d-flex align-items-center" style="display:flex; align-items:center;">
            <h4 class="mb-0 font-weight-bold mr-4 text-indigo-600" style="letter-spacing:-1.5px; margin:0 20px 0 0;">WebBuilder <span class="text-dark">Studio</span></h4>
            <select id="sel_proyectos" class="input-ui" style="width: 380px;" onchange="gestionarSeleccion(this.value)">
                <option value="NEW">+ CREAR NUEVO PROYECTO WEB</option>
            </select>
        </div>
        
        <div class="d-flex align-items-center" style="display:flex; align-items:center;">
            <div class="mr-4 text-right" style="margin-right: 20px; text-align:right;">
                <small class="text-muted d-block font-weight-bold" style="font-size: 10px;">URL TOKEN</small>
                <span id="t_token" class="token-tag">-------</span>
            </div>
            
            <button id="btn_delete_trigger" class="btn-delete-page" onclick="eliminarPagina()">
                <i class="fas fa-trash-alt"></i>
            </button>

            <button class="btn-publish" onclick="guardarTodo()">
                <i class="fas fa-rocket mr-2"></i> PUBLICAR PÁGINA
            </button>
        </div>
    </nav>

    <div class="nav-components">
        <div class="category-dropdown">
            <div class="drop-btn"><i class="fas fa-bars"></i> Menús</div>
            <div class="drop-content">
                <button class="snippet-item" onclick="add('nav_glass')"><i class="fas fa-border-all"></i> Glassmorphism (Flotante)</button>
                <button class="snippet-item" onclick="add('nav_modern')"><i class="fas fa-minus"></i> Moderno (Fijo)</button>
                <button class="snippet-item" onclick="add('nav_dark')"><i class="fas fa-moon"></i> Dark UI (Full-width)</button>
                <button class="snippet-item" onclick="add('nav_center')"><i class="fas fa-align-center"></i> Logo Centrado</button>
            </div>
        </div>

        <div class="category-dropdown">
            <div class="drop-btn"><i class="fas fa-image"></i> Portadas</div>
            <div class="drop-content">
                <button class="snippet-item" onclick="add('hero_video')"><i class="fas fa-play-circle"></i> Hero con Video</button>
                <button class="snippet-item" onclick="add('hero_mesh')"><i class="fas fa-wave-square"></i> Mesh Gradient (Pro)</button>
                <button class="snippet-item" onclick="add('hero_split')"><i class="fas fa-columns"></i> Split (Texto + Imagen)</button>
                <button class="snippet-item" onclick="add('hero_typed')"><i class="fas fa-keyboard"></i> Hero Animado</button>
                <button class="snippet-item" onclick="add('hero_minimal')"><i class="fas fa-square-full"></i> Centro Minimalista</button>
            </div>
        </div>

        <div class="category-dropdown">
            <div class="drop-btn"><i class="fas fa-th-large"></i> Servicios</div>
            <div class="drop-content">
                <button class="snippet-item" onclick="add('bento_apple')"><i class="fas fa-apple-alt"></i> Bento Grid (Estilo Apple)</button>
                <button class="snippet-item" onclick="add('feat_3col')"><i class="fas fa-columns"></i> 3 Columnas Modernas</button>
                <button class="snippet-item" onclick="add('feat_list')"><i class="fas fa-list-check"></i> Lista de Beneficios</button>
                <button class="snippet-item" onclick="add('feat_icon_left')"><i class="fas fa-align-left"></i> Iconos Laterales</button>
                <button class="snippet-item" onclick="add('feat_steps')"><i class="fas fa-route"></i> Proceso Paso a Paso</button>
            </div>
        </div>

        <div class="category-dropdown">
            <div class="drop-btn"><i class="fas fa-photo-video"></i> Media</div>
            <div class="drop-content">
                <button class="snippet-item" onclick="add('gal_masonry')"><i class="fas fa-images"></i> Galería Masonry</button>
                <button class="snippet-item" onclick="add('img_parallax')"><i class="fas fa-arrows-alt-v"></i> Efecto Parallax</button>
                <button class="snippet-item" onclick="add('img_compare')"><i class="fas fa-adjust"></i> Antes y Después</button>
                <button class="snippet-item" onclick="add('logo_cloud')"><i class="fas fa-cloud"></i> Nube de Marcas</button>
            </div>
        </div>

        <div class="category-dropdown">
            <div class="drop-btn"><i class="fas fa-star"></i> Confianza</div>
            <div class="drop-content">
                <button class="snippet-item" onclick="add('testi_grid')"><i class="fas fa-quote-right"></i> Testimonios (Grid)</button>
                <button class="snippet-item" onclick="add('team_cards')"><i class="fas fa-users"></i> Nuestro Equipo</button>
                <button class="snippet-item" onclick="add('stats_counter')"><i class="fas fa-tachometer-alt"></i> Contadores de Éxito</button>
                <button class="snippet-item" onclick="add('faq_accord')"><i class="fas fa-question-circle"></i> Preguntas Frecuentes</button>
            </div>
        </div>

        <div class="category-dropdown">
            <div class="drop-btn"><i class="fas fa-rocket"></i> Conversión</div>
            <div class="drop-content">
                <button class="snippet-item" onclick="add('price_3tiers')"><i class="fas fa-tags"></i> Planes de Precios (3)</button>
                <button class="snippet-item" onclick="add('form_contact')"><i class="fas fa-paper-plane"></i> Formulario de Contacto</button>
                <button class="snippet-item" onclick="add('cta_full')"><i class="fas fa-bullhorn"></i> CTA Pantalla Completa</button>
                <button class="snippet-item" onclick="add('newsletter')"><i class="fas fa-envelope-open-text"></i> Suscripción Newsletter</button>
            </div>
        </div>

        <div class="divider-v"></div>

        <div class="d-flex align-items-center gap-2" style="display:flex; align-items:center; gap:8px;">
            <small class="font-weight-bold text-muted" style="font-size:10px">COLOR:</small>
            <input type="color" id="cfg_color" value="#4f46e5" oninput="updatePreview()" style="border:none; width:30px; height:25px; cursor:pointer; background:none;">
            <select id="cfg_font" class="input-ui py-1" style="height:32px; font-size:12px; border-radius:8px" onchange="updatePreview()">
                <option value="Inter, sans-serif">Inter (Moderno)</option>
                <option value="'Playfair Display', serif">Playfair (Lujoso)</option>
                <option value="'Poppins', sans-serif">Poppins (Suave)</option>
            </select>
        </div>

        <button class="snippet-item text-danger ml-auto" onclick="limpiarTodo()" style="width:auto; margin-left:auto;">
            <i class="fas fa-trash-alt"></i> Borrar Todo
        </button>
    </div>

    <div class="workspace">
        <div class="pane-code">
            <div class="px-4 py-2 bg-dark text-muted d-flex justify-content-between align-items-center" style="font-size:10px; border-bottom: 1px solid #1a1a1a; display:flex; justify-content:space-between; padding:8px 15px; background:#111;">
                <span><i class="fas fa-terminal mr-2"></i> HTML SOURCE CODE</span>
                <span class="text-indigo-500 font-weight-bold" style="color:#6366f1;">● VISTA EN VIVO</span>
            </div>
            <textarea id="html_editor" spellcheck="false" oninput="updatePreview()"></textarea>
        </div>

        <div class="pane-preview">
            <iframe id="frame_preview"></iframe>
        </div>
    </div>
</div>



<script>
    // --- VARIABLES DE ENTORNO ---
    const DB = "<?php echo $db_name; ?>"; // USANDO $db_name de PHP
    const IDU_USER = "<?php echo $idu_sesion; ?>"; 
    let id_actual = null;

       const SNIPPETS = {
        nav_glass: `<nav class="fixed top-6 inset-x-6 h-20 bg-white/60 backdrop-blur-2xl border border-white/20 rounded-[2rem] flex items-center justify-between px-12 z-50 shadow-2xl">\n  <div class="text-2xl font-black tracking-tighter uppercase">Studio<span class="text-indigo-600">.</span></div>\n  <div class="hidden md:flex gap-10 font-bold text-sm text-slate-800"><a>Proyectos</a><a>Servicios</a><a>Nosotros</a><a class="bg-indigo-600 text-white px-6 py-2.5 rounded-full shadow-lg">Contacto</a></div>\n</nav>\n<div class="h-32"></div>\n`,
        nav_modern: `<nav class="sticky top-0 w-full h-16 bg-white border-b border-slate-100 flex items-center justify-between px-8 z-50">\n  <div class="font-bold text-xl tracking-tight">PLATFORM</div>\n  <div class="flex gap-6 text-sm font-medium"><a>Soluciones</a><a>Precios</a><a>Docs</a><button class="bg-black text-white px-4 py-2 rounded-lg">Empezar</button></div>\n</nav>\n`,
        nav_dark: `<nav class="w-full h-20 bg-slate-900 text-white flex items-center justify-between px-10">\n  <div class="text-2xl font-light italic">Minimal<span class="font-bold">Dark</span></div>\n  <div class="flex gap-8 items-center text-sm uppercase tracking-widest"><a class="opacity-70 hover:opacity-100 cursor-pointer">Work</a><a class="opacity-70 hover:opacity-100 cursor-pointer">Contact</a></div>\n</nav>\n`,
        nav_center: `<nav class="py-8 bg-white flex flex-col items-center gap-6 border-b">\n  <div class="text-3xl font-black">LOGO</div>\n  <div class="flex gap-10 text-xs font-black uppercase tracking-[0.2em] text-slate-400"><a>Home</a><a>Gallery</a><a>About</a><a>Shop</a></div>\n</nav>\n`,
        hero_video: `<header class="relative h-[90vh] flex items-center justify-center overflow-hidden bg-slate-900 rounded-[3rem] m-4 shadow-3xl">\n  <video autoplay muted loop class="absolute w-full h-full object-cover opacity-50"><source src="https://assets.mixkit.co/videos/preview/mixkit-digital-animation-of-a-blue-mesh-background-24458-large.mp4"></video>\n  <div class="relative z-10 text-center px-6 max-w-4xl">\n    <h1 class="text-8xl font-black text-white tracking-tighter mb-8 leading-none">REIMAGINA EL <span class="text-indigo-400 italic font-serif">FUTURO</span></h1>\n    <p class="text-xl text-white/80 mb-12 font-medium">Diseñamos soluciones digitales que trascienden el tiempo y la tecnología.</p>\n    <button class="bg-white text-slate-900 px-12 py-5 rounded-2xl font-black text-lg hover:scale-105 transition-all shadow-2xl shadow-indigo-500/40">EXPLORAR UNIVERSO</button>\n  </div>\n</header>\n`,
        hero_mesh: `<section class="relative h-[85vh] flex items-center justify-center bg-indigo-600 overflow-hidden rounded-[4rem] m-6 shadow-2xl">\n  <div class="absolute inset-0 opacity-40" style="background-image: radial-gradient(at 0% 0%, #ff0080 0px, transparent 50%), radial-gradient(at 50% 0%, #7928ca 0px, transparent 50%), radial-gradient(at 100% 0%, #4f46e5 0px, transparent 50%); filter: blur(80px); animation: pulse 8s infinite alternate;"></div>\n  <div class="relative z-10 text-center text-white p-10">\n    <h2 class="text-[12vw] font-black leading-none tracking-tighter">IMPACTO<br>DIGITAL</h2>\n    <p class="mt-6 text-2xl font-light opacity-80">Software de alto rendimiento para mentes creativas.</p>\n  </div>\n</section>\n`,
        hero_split: `<section class="min-h-screen grid grid-cols-1 md:grid-cols-2">\n  <div class="flex flex-col justify-center p-20 bg-white">\n    <span class="text-indigo-600 font-bold tracking-widest uppercase mb-4">Nueva Era 2026</span>\n    <h1 class="text-7xl font-black text-slate-900 mb-8 leading-tight">Tu visión, nuestra ejecución.</h1>\n    <p class="text-xl text-slate-500 mb-10">Construimos plataformas que escalan con tu negocio.</p>\n    <div class="flex gap-4"><button class="bg-indigo-600 text-white px-8 py-4 rounded-xl font-bold">Empezar</button><button class="px-8 py-4 border-2 border-slate-200 rounded-xl font-bold text-slate-600">Saber más</button></div>\n  </div>\n  <div class="bg-slate-100 flex items-center justify-center p-10">\n    <img src="https://images.unsplash.com/photo-1498050108023-c5249f4df085?auto=format&fit=crop&w=800&q=80" class="rounded-[3rem] shadow-2xl rotate-3 hover:rotate-0 transition-transform duration-700">\n  </div>\n</section>\n`,
        hero_typed: `<section class="py-32 px-10 text-center bg-white">\n  <h1 class="text-6xl font-black mb-6">Expertos en <span class="text-indigo-600 border-r-4 border-indigo-600 animate-pulse">Desarrollo Web</span></h1>\n  <p class="text-slate-500 text-xl max-w-2xl mx-auto">Creamos interfaces que tus clientes amarán.</p>\n</section>\n`,
        hero_minimal: `<section class="h-[60vh] flex flex-col items-center justify-center bg-white border-b">\n  <h1 class="text-4xl font-light tracking-[0.3em] uppercase mb-8">Minimalism</h1>\n  <div class="w-20 h-1 bg-black"></div>\n</section>\n`,
        bento_apple: `<section class="p-8 grid grid-cols-1 md:grid-cols-4 grid-rows-2 gap-6 h-auto md:h-[750px] bg-white">\n  <div class="md:col-span-2 md:row-span-2 bg-slate-50 rounded-[3rem] p-12 border border-slate-100 flex flex-col justify-end group hover:bg-white transition-all shadow-sm hover:shadow-xl"> <div class="text-indigo-600 text-5xl mb-6"><i class="fas fa-microchip"></i></div> <h3 class="text-5xl font-black mb-4 tracking-tighter">Neural Engine</h3> <p class="text-slate-500 text-lg">Procesamiento masivo de datos en tiempo real con IA nativa.</p> </div>\n  <div class="md:col-span-2 bg-indigo-600 rounded-[3rem] p-12 text-white shadow-2xl flex flex-col justify-between"> <h3 class="text-3xl font-bold">Infinite Cloud</h3> <i class="fas fa-cloud text-7xl opacity-30 self-end"></i> </div>\n  <div class="bg-slate-900 rounded-[3rem] p-10 flex flex-col justify-center items-center text-white"> <span class="text-6xl font-black">99.9%</span> <p class="uppercase text-[10px] font-bold tracking-widest mt-2 text-indigo-400">Eficiencia</p> </div>\n  <div class="bg-indigo-50 rounded-[3rem] p-10 flex flex-col justify-center items-center border border-indigo-100"> <i class="fas fa-bolt text-4xl text-indigo-600 mb-4"></i> <h4 class="font-bold text-xl text-indigo-900 text-center leading-none">Ultra Fast Speed</h4> </div>\n</section>\n`,
        feat_3col: `<section class="py-24 px-12">\n  <div class="grid grid-cols-1 md:grid-cols-3 gap-16">\n    <div class="p-8 bg-white border border-slate-100 rounded-[2.5rem] shadow-sm hover:shadow-2xl transition-all"> <div class="h-16 w-16 bg-indigo-50 text-indigo-600 rounded-2xl flex items-center justify-center text-2xl mb-8"><i class="fas fa-shield-alt"></i></div> <h4 class="text-2xl font-bold mb-4">Seguridad</h4> <p class="text-slate-500 leading-relaxed">Protección de grado bancario para todos tus activos digitales.</p> </div>\n    <div class="p-8 bg-white border border-slate-100 rounded-[2.5rem] shadow-sm hover:shadow-2xl transition-all"> <div class="h-16 w-16 bg-indigo-50 text-indigo-600 rounded-2xl flex items-center justify-center text-2xl mb-8"><i class="fas fa-magic"></i></div> <h4 class="text-2xl font-bold mb-4">Escalabilidad</h4> <p class="text-slate-500 leading-relaxed">Crecemos contigo, desde una startup hasta un unicornio global.</p> </div>\n    <div class="p-8 bg-white border border-slate-100 rounded-[2.5rem] shadow-sm hover:shadow-2xl transition-all"> <div class="h-16 w-16 bg-indigo-50 text-indigo-600 rounded-2xl flex items-center justify-center text-2xl mb-8"><i class="fas fa-code"></i></div> <h4 class="text-2xl font-bold">API Nativa</h4> <p class="text-slate-500 leading-relaxed">Integraciones sin costuras con cualquier stack tecnológico moderno.</p> </div>\n  </div>\n</section>\n`,
        feat_list: `<section class="py-20 px-10 bg-white"><div class="max-w-4xl mx-auto space-y-6">\n  <div class="flex items-center gap-6 p-6 bg-slate-50 rounded-2xl"><div class="h-12 w-12 bg-indigo-600 rounded-full flex items-center justify-center text-white font-bold">1</div><p class="text-lg font-bold">Análisis profundo de requerimientos.</p></div>\n  <div class="flex items-center gap-6 p-6 bg-slate-50 rounded-2xl"><div class="h-12 w-12 bg-indigo-600 rounded-full flex items-center justify-center text-white font-bold">2</div><p class="text-lg font-bold">Diseño UI/UX centrado en el usuario.</p></div>\n  <div class="flex items-center gap-6 p-6 bg-slate-50 rounded-2xl"><div class="h-12 w-12 bg-indigo-600 rounded-full flex items-center justify-center text-white font-bold">3</div><p class="text-lg font-bold">Despliegue continuo y mantenimiento.</p></div>\n</div></section>\n`,
        feat_icon_left: `<section class="py-20 px-10"><div class="grid grid-cols-2 gap-10">\n  <div class="flex gap-4"><i class="fas fa-check text-green-500 text-xl"></i><div><h5 class="font-bold">Alta Calidad</h5><p class="text-sm text-slate-500">Resultado premium garantizado.</p></div></div>\n  <div class="flex gap-4"><i class="fas fa-check text-green-500 text-xl"></i><div><h5 class="font-bold">Soporte 24/7</h5><p class="text-sm text-slate-500">Estamos para ayudarte siempre.</p></div></div>\n</div></section>\n`,
        feat_steps: `<section class="py-20 px-10 bg-slate-900 text-white rounded-[4rem] m-6">\n  <div class="grid grid-cols-4 gap-4 text-center">\n    <div><div class="text-4xl font-black opacity-20 mb-4">01</div><h6 class="font-bold">Idea</h6></div>\n    <div><div class="text-4xl font-black opacity-20 mb-4">02</div><h6 class="font-bold">Diseño</h6></div>\n    <div><div class="text-4xl font-black opacity-20 mb-4">03</div><h6 class="font-bold">Código</h6></div>\n    <div><div class="text-4xl font-black opacity-20 mb-4">04</div><h6 class="font-bold">Éxito</h6></div>\n  </div>\n</section>\n`,
        gal_masonry: `<section class="p-8 columns-1 md:columns-3 gap-6 space-y-6">\n  <img class="w-full rounded-3xl shadow-lg" src="https://images.unsplash.com/photo-1460925895917-afdab827c52f?auto=format&fit=crop&w=500&q=80">\n  <img class="w-full rounded-3xl shadow-lg" src="https://images.unsplash.com/photo-1522202176988-66273c2fd55f?auto=format&fit=crop&w=500&q=80">\n  <img class="w-full rounded-3xl shadow-lg" src="https://images.unsplash.com/photo-1497366216548-37526070297c?auto=format&fit=crop&w=500&q=80">\n  <img class="w-full rounded-3xl shadow-lg" src="https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=500&q=80">\n</section>\n`,
        img_parallax: `<section class="relative h-[60vh] overflow-hidden flex items-center justify-center">\n  <div class="absolute inset-0 bg-fixed bg-center bg-cover" style="background-image: url('https://images.unsplash.com/photo-1451187580459-43490279c0fa?auto=format&fit=crop&w=1200&q=80');"></div>\n  <h2 class="relative text-white text-6xl font-black uppercase tracking-widest drop-shadow-2xl">Parallax View</h2>\n</section>\n`,
        img_compare: `<section class="p-10 flex gap-4">\n  <div class="flex-1 rounded-2xl overflow-hidden border-4 border-slate-200"><img src="https://images.unsplash.com/photo-1504384308090-c894fdcc538d?auto=format&fit=crop&w=400&q=80" class="w-full h-full object-cover grayscale"></div>\n  <div class="flex-1 rounded-2xl overflow-hidden border-4 border-indigo-600"><img src="https://images.unsplash.com/photo-1504384308090-c894fdcc538d?auto=format&fit=crop&w=400&q=80" class="w-full h-full object-cover"></div>\n</section>\n`,
        logo_cloud: `<section class="py-12 bg-white border-y">\n  <div class="max-w-6xl mx-auto flex flex-wrap justify-center gap-16 opacity-30 grayscale">\n    <img src="https://upload.wikimedia.org/wikipedia/commons/a/a9/Amazon_logo.svg" class="h-8">\n    <img src="https://upload.wikimedia.org/wikipedia/commons/2/2f/Google_2015_logo.svg" class="h-8">\n    <img src="https://upload.wikimedia.org/wikipedia/commons/0/05/Facebook_Logo_%282019%29.png" class="h-8">\n    <img src="https://upload.wikimedia.org/wikipedia/commons/b/b9/Slack_Technologies_Logo.svg" class="h-8">\n  </div>\n</section>\n`,
        testi_grid: `<section class="py-24 px-10 bg-slate-50">\n  <div class="grid grid-cols-1 md:grid-cols-2 gap-8">\n    <div class="p-10 bg-white rounded-3xl shadow-sm italic text-slate-600 border border-slate-100"> "El mejor partner tecnológico que hemos tenido jamás. Su visión es de otro planeta." <br><br> <strong class="text-indigo-600 not-italic">- CEO, FutureCorp</strong></div>\n    <div class="p-10 bg-white rounded-3xl shadow-sm italic text-slate-600 border border-slate-100"> "Un diseño que dejó a nuestra competencia años atrás. Simplemente increíble." <br><br> <strong class="text-indigo-600 not-italic">- CTO, InnovaSoft</strong></div>\n  </div>\n</section>\n`,
        team_cards: `<section class="py-20 px-10 grid grid-cols-3 gap-8 text-center">\n  <div class="group"> <img src="https://i.pravatar.cc/300?img=1" class="w-40 h-40 rounded-full mx-auto mb-6 grayscale group-hover:grayscale-0 transition duration-500"> <h5 class="font-bold text-xl">Elena Vance</h5> <p class="text-slate-400">Lead Designer</p> </div>\n  <div class="group"> <img src="https://i.pravatar.cc/300?img=2" class="w-40 h-40 rounded-full mx-auto mb-6 grayscale group-hover:grayscale-0 transition duration-500"> <h5 class="font-bold text-xl">Marcus Fenix</h5> <p class="text-slate-400">CTO</p> </div>\n  <div class="group"> <img src="https://i.pravatar.cc/300?img=3" class="w-40 h-40 rounded-full mx-auto mb-6 grayscale group-hover:grayscale-0 transition duration-500"> <h5 class="font-bold text-xl">Sarah Kerrigan</h5> <p class="text-slate-400">CEO</p> </div>\n</section>\n`,
        stats_counter: `<section class="py-20 bg-indigo-600 text-white"><div class="grid grid-cols-4 gap-4 text-center">\n  <div><div class="text-5xl font-black mb-2">500+</div><p class="uppercase text-xs font-bold tracking-widest opacity-60">Clientes</p></div>\n  <div><div class="text-5xl font-black mb-2">10k+</div><p class="uppercase text-xs font-bold tracking-widest opacity-60">Horas Código</p></div>\n  <div><div class="text-5xl font-black mb-2">120</div><p class="uppercase text-xs font-bold tracking-widest opacity-60">Premios</p></div>\n  <div><div class="text-5xl font-black mb-2">24/7</div><p class="uppercase text-xs font-bold tracking-widest opacity-60">Soporte</p></div>\n</div></section>\n`,
        faq_accord: `<section class="py-20 px-10 max-w-2xl mx-auto">\n  <h2 class="text-3xl font-black mb-10 text-center">Preguntas Frecuentes</h2>\n  <details class="mb-4 border-b pb-4"><summary class="font-bold cursor-pointer">¿Cuál es el tiempo de entrega?</summary><p class="mt-4 text-slate-500">Normalmente de 2 a 4 semanas dependiendo del proyecto.</p></details>\n  <details class="mb-4 border-b pb-4"><summary class="font-bold cursor-pointer">¿Ofrecen soporte post-lanzamiento?</summary><p class="mt-4 text-slate-500">Sí, tenemos planes de mantenimiento premium.</p></details>\n</section>\n`,
        price_3tiers: `<section class="py-32 px-10 bg-slate-50 rounded-[4rem]">\n  <div class="max-w-6xl mx-auto grid grid-cols-3 gap-8">\n    <div class="p-12 bg-white rounded-[2.5rem] border border-slate-100 shadow-sm flex flex-col h-full hover:scale-105 transition-all"> <h4 class="font-bold text-slate-400">STARTER</h4> <div class="text-5xl font-black my-8">$0<span class="text-lg text-slate-400 font-normal">/mo</span></div> <ul class="space-y-4 text-slate-600 mb-10 flex-grow"> <li><i class="fas fa-check text-indigo-600 mr-2"></i> 1 Proyecto</li> <li><i class="fas fa-check text-indigo-600 mr-2"></i> Dominio Gratis</li> </ul> <button class="w-full py-4 border-2 border-indigo-600 text-indigo-600 rounded-2xl font-black hover:bg-indigo-50">COMENZAR</button> </div>\n    <div class="p-12 bg-indigo-600 text-white rounded-[2.5rem] shadow-2xl scale-110 flex flex-col h-full ring-8 ring-indigo-600/10"> <h4 class="font-bold opacity-60">PRO</h4> <div class="text-5xl font-black my-8">$49<span class="text-lg opacity-60 font-normal">/mo</span></div> <ul class="space-y-4 mb-10 flex-grow"> <li><i class="fas fa-check mr-2"></i> Proyectos Ilimitados</li> <li><i class="fas fa-check mr-2"></i> Soporte VIP 24/7</li> <li><i class="fas fa-check mr-2"></i> Inteligencia Artificial</li> </ul> <button class="w-full py-4 bg-white text-indigo-600 rounded-2xl font-black shadow-xl">ELEGIR PLAN</button> </div>\n    <div class="p-12 bg-white rounded-[2.5rem] border border-slate-100 shadow-sm flex flex-col h-full hover:scale-105 transition-all"> <h4 class="font-bold text-slate-400">BUSINESS</h4> <div class="text-5xl font-black my-8">$99<span class="text-lg text-slate-400 font-normal">/mo</span></div> <ul class="space-y-4 text-slate-600 mb-10 flex-grow"> <li><i class="fas fa-check text-indigo-600 mr-2"></i> Todo lo de Pro</li> <li><i class="fas fa-check text-indigo-600 mr-2"></i> Consultoría Técnica</li> </ul> <button class="w-full py-4 border-2 border-indigo-600 text-indigo-600 rounded-2xl font-black hover:bg-indigo-50">COMENZAR</button> </div>\n  </div>\n</section>\n`,
        form_contact: `<section class="py-20 px-10 max-w-4xl mx-auto">\n  <div class="bg-white p-12 rounded-[3rem] shadow-3xl border border-slate-100">\n    <h2 class="text-4xl font-black mb-8 text-center">Hablemos</h2>\n    <div class="grid grid-cols-2 gap-6 mb-6">\n      <input type="text" placeholder="Tu Nombre" class="p-4 border-none bg-slate-50 rounded-2xl focus:ring-2 ring-indigo-500">\n      <input type="email" placeholder="Tu Email" class="p-4 border-none bg-slate-50 rounded-2xl focus:ring-2 ring-indigo-500">\n    </div>\n    <textarea placeholder="Cuéntanos tu proyecto" class="w-full h-40 p-4 border-none bg-slate-50 rounded-2xl focus:ring-2 ring-indigo-500 mb-6"></textarea>\n    <button class="w-full bg-indigo-600 text-white py-5 rounded-2xl font-black text-xl shadow-2xl shadow-indigo-200">ENVIAR MENSAJE</button>\n  </div>\n</section>\n`,
        cta_full: `<section class="py-20 bg-indigo-600 text-white text-center p-20 rounded-[4rem] m-10 shadow-3xl shadow-indigo-500/50">\n  <h2 class="text-6xl font-black mb-6 leading-tight">¿Listo para el siguiente paso?</h2>\n  <p class="text-xl mb-12 opacity-80">Únete a cientos de marcas que ya transformaron su presencia digital.</p>\n  <button class="bg-white text-indigo-600 px-16 py-6 rounded-full font-black text-2xl hover:scale-110 transition">EMPIEZA GRATIS</button>\n</section>\n`,
        newsletter: `<section class="py-20 bg-slate-900 text-white text-center rounded-[3rem] m-6">\n  <h3 class="text-2xl font-bold mb-8">Suscríbete para recibir noticias de impacto</h3>\n  <div class="max-w-md mx-auto flex gap-2"><input type="email" placeholder="email@example.com" class="flex-1 p-4 bg-white/10 border-none rounded-xl text-white"><button class="bg-white text-black px-6 rounded-xl font-bold">Unirse</button></div>\n</section>\n`,
        footer_dark: `<footer class="bg-slate-900 text-white pt-24 pb-12 px-12 mt-20">\n  <div class="grid grid-cols-1 md:grid-cols-4 gap-20 mb-20">\n    <div class="col-span-2"><h3 class="text-3xl font-black mb-8 italic uppercase tracking-tighter">Studio<span class="text-indigo-400">.</span></h3><p class="text-slate-500 max-w-sm">La agencia líder en diseño digital y desarrollo de software de alto impacto.</p></div>\n    <div><h6 class="font-bold mb-6 text-indigo-400">Explorar</h6><ul class="space-y-4 opacity-70"><li>Proyectos</li><li>Servicios</li><li>Acerca</li></ul></div>\n    <div><h6 class="font-bold mb-6 text-indigo-400">Social</h6><ul class="space-y-4 opacity-70"><li>Instagram</li><li>Twitter</li><li>LinkedIn</li></ul></div>\n  </div>\n  <div class="border-t border-white/5 pt-10 text-center text-xs opacity-30 font-bold uppercase tracking-widest">© 2026 WebBuilder Studio. Todos los derechos reservados.</div>\n</footer>\n`,
        footer_minimal: `<footer class="py-10 border-t text-center text-sm font-bold text-slate-400 uppercase tracking-widest">Studio Max v3.0</footer>\n`,
        footer_links: `<footer class="py-20 bg-white border-t px-10 flex justify-between items-center">\n  <div class="font-black text-xl">BRAND.</div>\n  <div class="flex gap-10 font-medium"><a>Terms</a><a>Privacy</a><a>Support</a></div>\n</footer>\n`
    };


    // --- LÓGICA DE DATOS ---
    async function cargarLista() {
        const sql = `SELECT IDP, Nombre FROM \`<?php echo $idu;?>-WebPaginas\` WHERE IDU = '${IDU_USER}' ORDER BY FechaActualizacion DESC`;
        try {
            const res = await fetch('../librerias/AJAX/Select.php', { 
                method: 'POST', 
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
                body: `sql=${encodeURIComponent(sql)}&db=${DB}` 
            }).then(r => r.json());
            
            const sel = document.getElementById('sel_proyectos');
            sel.innerHTML = '<option value="NEW">+ CREAR NUEVO PROYECTO WEB</option>';
            if(res.data) res.data.forEach(p => { sel.innerHTML += `<option value="${p.IDP}">${p.Nombre}</option>`; });
            if(id_actual) sel.value = id_actual;
        } catch(e) { console.error("Error al cargar lista:", e); }
    }

    async function cargarDetalle(id) {
        if(!id || id === 'NEW') return;
        const sql = `SELECT * FROM \`<?php echo $idu;?>-WebPaginas\` WHERE IDP = ${id} AND IDU = '${IDU_USER}' LIMIT 1`;
        try {
            const res = await fetch('../librerias/AJAX/Select.php', { 
                method: 'POST', 
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
                body: `sql=${encodeURIComponent(sql)}&db=${DB}` 
            }).then(r => r.json());
            
            if(res.data && res.data[0]) {
                const d = res.data[0];
                const cfg = JSON.parse(d.Config || '{}');
                id_actual = d.IDP;
                document.getElementById('t_token').innerText = d.Token;
                document.getElementById('html_editor').value = d.HTML;
                document.getElementById('cfg_color').value = cfg.accent || '#4f46e5';
                document.getElementById('cfg_font').value = cfg.font || "Inter, sans-serif";
                document.getElementById('btn_delete_trigger').style.display = 'block'; // Mostrar eliminar
                console.log("✅ Cargado ID:", id_actual);
                updatePreview();
            }
        } catch(e) { console.error("Error al cargar:", e); }
    }

    function gestionarSeleccion(val) { (val === 'NEW') ? limpiarTodo() : cargarDetalle(val); }

    function limpiarTodo() { 
        id_actual = null; 
        document.getElementById('html_editor').value = ""; 
        document.getElementById('t_token').innerText = Math.random().toString(36).substring(2, 11).toUpperCase();
        document.getElementById('btn_delete_trigger').style.display = 'none'; // Ocultar eliminar
        updatePreview(); 
    }

    // --- VISTA PREVIA ---
function updatePreview() {
    const html = document.getElementById('html_editor').value;
    const color = document.getElementById('cfg_color').value;
    const font = document.getElementById('cfg_font').value;

    // Inyectamos un script de escucha dentro del Iframe
    const inspectorScript = `
        <script>
            document.addEventListener('click', function(e) {
                // Evitamos que los enlaces nos saquen de la página
                e.preventDefault();
                e.stopPropagation();

                // Obtenemos un fragmento único del elemento para buscarlo
                // Usamos el outerHTML pero solo el inicio (la etiqueta de apertura)
                const tagSnippet = e.target.outerHTML.split('>')[0];
                
                // Enviamos el mensaje al editor padre
                window.parent.postMessage({
                    type: 'inspect',
                    snippet: tagSnippet
                }, '*');
            }, true);

            // Estilo visual para saber qué estamos tocando (opcional)
            document.body.style.cursor = 'crosshair';
        <\/script>
    `;

    const content = `<!DOCTYPE html><html lang="es"><head><meta charset="UTF-8"><script src="https://cdn.tailwindcss.com"><\/script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&family=Playfair+Display:wght@900&family=Poppins:wght@400;700&display=swap" rel="stylesheet"><style>body{font-family:${font}; background:white; min-height:100vh; margin:0; -webkit-font-smoothing: antialiased;} :root{--primary:${color};} .bg-indigo-600{background-color:var(--primary)!important;} .text-indigo-600, .text-indigo-400{color:var(--primary)!important;} .border-indigo-600{border-color:var(--primary)!important;}</style></head><body>${html}${inspectorScript}</body></html>`;
    
    const doc = document.getElementById('frame_preview').contentWindow.document;
    doc.open(); doc.write(content); doc.close();
}

	// --- ESCUCHADOR DEL INSPECTOR ---
window.addEventListener('message', function(event) {
    if (event.data.type === 'inspect') {
        const snippet = event.data.snippet;
        const editor = document.getElementById('html_editor');
        const contenido = editor.value;

        // Buscamos la posición del fragmento en el texto del editor
        const index = contenido.indexOf(snippet);

        if (index !== -1) {
            // 1. Hacemos focus al textarea
            editor.focus();

            // 2. Seleccionamos el texto encontrado
            editor.setSelectionRange(index, index + snippet.length + 1);

            // 3. Calculamos el scroll para que el editor se mueva a esa línea
            // Un pequeño truco para centrar la vista en el editor
            const lineas = contenido.substr(0, index).split("\n").length;
            const lineHeight = 24; // Aproximadamente el line-height en px
            editor.scrollTop = (lineas - 5) * lineHeight; 

            console.log("📍 Elemento localizado en línea:", lineas);
        }
    }
});
	
    function add(type) {
        const editor = document.getElementById('html_editor');
        editor.setRangeText(SNIPPETS[type] || '', editor.selectionStart, editor.selectionEnd, 'end');
        updatePreview();
    }

    // --- GUARDAR (INSERT/UPDATE) ---
    async function guardarTodo() {
        const html = document.getElementById('html_editor').value;
        if(!html) return;
        
        let token = document.getElementById('t_token').innerText;
        if(token.includes('-')) {
            token = Math.random().toString(36).substring(2, 11).toUpperCase();
            document.getElementById('t_token').innerText = token;
        }

        const configRaw = { accent: document.getElementById('cfg_color').value, font: document.getElementById('cfg_font').value };
        const htmlEscapado = html.replace(/'/g, "''");
        const configEscapado = JSON.stringify(configRaw).replace(/'/g, "''");

        let sql = "";
        let nombre = "";

        if (id_actual) {
            console.log("🚀 UPDATE ID:", id_actual);
            sql = `UPDATE \`<?php echo $idu;?>-WebPaginas\` SET HTML='${htmlEscapado}', Config='${configEscapado}', FechaActualizacion=NOW() WHERE IDP=${id_actual} AND IDU='${IDU_USER}'`;
        } else {
            nombre = prompt("Nombre de la nueva página:", "Mi Proyecto Épico");
            if(nombre === null) return;
            sql = `INSERT INTO \`<?php echo $idu;?>-WebPaginas\` (IDU, Token, Nombre, HTML, Config) VALUES ('${IDU_USER}', '${token}', '${nombre || 'Sin Nombre'}', '${htmlEscapado}', '${configEscapado}')`;
        }

        try {
            const res = await fetch('../librerias/AJAX/Execute.php', { 
                method: 'POST', 
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
                body: `sql=${encodeURIComponent(sql)}&db=${DB}` 
            }).then(r => r.json());

            if(res.status === 'success') {
                alert("✨ Guardado correctamente.");
                if (!id_actual && res.last_id) id_actual = res.last_id;
                await cargarLista();
                document.getElementById('sel_proyectos').value = id_actual;
                document.getElementById('btn_delete_trigger').style.display = 'block';
            } else { alert("Error: " + res.message); }
        } catch(e) { console.error(e); }
    }

    // --- ELIMINAR (DELETE) ---
    async function eliminarPagina() {
        if(!id_actual) return;
        if(!confirm("⚠️ ¿Estás seguro de que deseas eliminar permanentemente este proyecto?")) return;

        const sql = `DELETE FROM \`<?php echo $idu;?>-WebPaginas\` WHERE IDP = ${id_actual} AND IDU = '${IDU_USER}'`;
        try {
            const res = await fetch('../librerias/AJAX/Execute.php', { 
                method: 'POST', 
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
                body: `sql=${encodeURIComponent(sql)}&db=${DB}` 
            }).then(r => r.json());

            if(res.status === 'success') {
                alert("🗑️ Proyecto eliminado con éxito.");
                limpiarTodo();
                await cargarLista();
            } else { alert("Error al eliminar: " + res.message); }
        } catch(e) { console.error(e); }
    }

    cargarLista();
</script>
