<?php
session_start();
require_once(__DIR__ . '/../config/settings.php');
$masterAdmin = $db_settings['admin_user'] ?? 'Admin';

// 1. Verificar si hay sesión iniciada
if (!isset($_SESSION['logged_in']) || $_SESSION['user_id'] !== $masterAdmin) {
    header("Location: ../index.php");
    exit;
}

// 2. NUEVO: Verificar si superó el Blindaje 2FA
if (!isset($_SESSION['2fa_verified']) || $_SESSION['2fa_verified'] !== true) {
    header("Location: login_2fa.php");
    exit;
}

try {
    $dsn = "dblib:host={$db_settings['host']};dbname={$db_settings['name']};charset=UTF8";
    $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
    
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM Web_Settings");
    $db_conf = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    $stmtRank = $pdo->query("SELECT setting_key, setting_value FROM Web_Ranking_Config");
    $rank_conf = $stmtRank->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (Exception $e) {
    $db_conf = [];
    $rank_conf = [];
}

$webTitle = $db_conf['web_title'] ?? "MUMU ADMIN";
$webFavicon = (!empty($db_conf['web_favicon_url'])) ? $db_conf['web_favicon_url'] : "favicon.ico";
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($webTitle); ?> | PANEL MASTER CORE</title>
    <link rel="icon" type="image/x-icon" href="<?php echo $webFavicon; ?>?v=<?php echo time(); ?>">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Roboto:wght@300;400&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>
    <style>
        :root { --accent: #ff0000; }
        body { background-color: #030303; color: #e0e0e0; font-family: 'Roboto', sans-serif; overflow: hidden; }
        .font-title { font-family: 'Orbitron', sans-serif; }
        .submenu-container { max-height: 0; overflow: hidden; transition: max-height 0.4s ease; background: rgba(255,255,255,0.02); }
        .submenu-container.open { max-height: 600px; padding-bottom: 10px; }
        .nav-card { border-left: 3px solid transparent; transition: all 0.3s ease; cursor: pointer; }
        .nav-card:hover, .nav-card.active { background: linear-gradient(90deg, rgba(255,0,0,0.1) 0%, transparent 100%); border-left: 3px solid var(--accent); color: white; }
        .upload-box { position: relative; background: rgba(255,255,255,0.02); border: 1px dashed rgba(255,255,255,0.1); border-radius: 16px; padding: 20px; transition: all 0.3s; min-height: 200px; display: flex; flex-direction: column; align-items: center; justify-content: center; overflow: hidden; }
        .upload-box:hover { border-color: var(--accent); background: rgba(255,0,0,0.01); }
        .progress-overlay { position: absolute; bottom: 0; left: 0; width: 100%; height: 5px; background: #111; display: none; z-index: 60; }
        .progress-bar-fill { height: 100%; width: 0%; background: var(--accent); box-shadow: 0 0 10px var(--accent); transition: width 0.1s; }
        input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; z-index: 100; }
        .preview-img { max-width: 100%; max-height: 140px; object-fit: contain; border-radius: 8px; z-index: 10; position: relative; }
        .toast-container { position: fixed; top: 20px; right: -400px; background: linear-gradient(135deg, #ff0000 0%, #8b0000 100%); color: white; padding: 18px 28px; border-radius: 15px; z-index: 9999; transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55); border-left: 5px solid #fff; }
        .toast-container.active { right: 20px; }
        .ck-editor__editable { background: #0a0a0a !important; border: 1px solid #222 !important; color: white !important; min-height: 300px; }
        .ck.ck-toolbar { background: #151515 !important; border: 1px solid #222 !important; }
        
        /* Estilos para el Sistema de Guías - Fantasy Aesthetic */
.guide-card {
    background: linear-gradient(145deg, #0f0f0f, #050505);
    border: 1px solid rgba(220, 38, 38, 0.2);
    box-shadow: 0 10px 20px rgba(0,0,0,0.5), inset 0 0 15px rgba(220, 38, 38, 0.05);
}

.guide-card:hover {
    border-color: rgba(220, 38, 38, 0.6);
    box-shadow: 0 0 25px rgba(220, 38, 38, 0.2);
    transform: translateY(-3px);
}

.filter-badge {
    background: rgba(220, 38, 38, 0.1);
    border: 1px solid #dc2626;
    color: #fff;
    text-shadow: 0 0 5px #ff0000;
}

.btn-crystal-gold {
    background: linear-gradient(to bottom, #ca8a04, #854d0e);
    color: white;
    box-shadow: 0 4px 10px rgba(133, 77, 14, 0.3);
}
    </style>
</head>
<body class="flex h-screen">
    <aside class="w-72 bg-[#080808] border-r border-white/5 flex flex-col z-50">
        <div class="p-8 border-b border-white/5 text-center">
            <h2 class="font-title text-red-600 text-xl tracking-tighter italic uppercase">Master <span class="text-white">Core</span></h2>
        </div>
        <nav class="flex-1 overflow-y-auto py-4">
            <a href="javascript:void(0)" onclick="location.reload()" class="nav-card flex items-center px-6 py-4 text-gray-500">
                <i data-lucide="layout-dashboard" class="w-5 h-5 mr-4"></i>
                <span class="text-[11px] font-bold uppercase tracking-widest">Dashboard</span>
            </a>
            <a href="javascript:void(0)" onclick="loadModule('web_config')" class="nav-card flex items-center px-6 py-4 text-white">
                <i data-lucide="settings" class="w-5 h-5 mr-4 text-red-600"></i>
                <span class="text-[11px] font-bold uppercase tracking-widest">Configuración Web</span>
            </a>
            <div>
                <div onclick="toggleSubmenu('news-sub')" class="nav-card flex items-center px-6 py-4 text-white">
                    <i data-lucide="newspaper" class="w-5 h-5 mr-4 text-red-600"></i>
                    <span class="text-[11px] font-bold uppercase tracking-widest">Noticias</span>
                    <i data-lucide="chevron-down" class="w-4 h-4 ml-auto opacity-50"></i>
                </div>
                <div id="news-sub" class="submenu-container">
                    <a href="javascript:void(0)" onclick="loadModule('publish')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition">Publicar</a>
                    <a href="javascript:void(0)" onclick="loadModule('manage')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition">Gestionar</a>
                </div>
            </div>
            <div>
                <div onclick="toggleSubmenu('modules-sub')" class="nav-card flex items-center px-6 py-4 text-white">
                    <i data-lucide="layers" class="w-5 h-5 mr-4 text-red-600"></i>
                    <span class="text-[11px] font-bold uppercase tracking-widest">Módulos</span>
                    <i data-lucide="chevron-down" class="w-4 h-4 ml-auto opacity-50"></i>
                </div>
                <div id="modules-sub" class="submenu-container">
                    <a href="javascript:void(0)" onclick="loadModule('rankings')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition">Rankings Globales</a>
                    <a href="javascript:void(0)" onclick="loadModule('downloads')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition">Descargas</a>
                    <a href="javascript:void(0)" onclick="loadModule('register')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition">Registro y Zen</a>
                    <a href="javascript:void(0)" onclick="loadModule('coin_config')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition">Configuración Coin</a>
                    <a href="javascript:void(0)" onclick="loadModule('market_config')" class="flex items-center px-16 py-3 text-[10px] text-red-500 font-black uppercase tracking-widest transition">Mercado de Personajes</a>
                    <a href="javascript:void(0)" onclick="loadModule('paypal_config')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-blue-500 uppercase tracking-widest transition">
    <i data-lucide="badge-dollar-sign" class="w-3 h-3 mr-2"></i> Donaciones PayPal
</a>
                </div>
            </div>
            <div class="mb-2">
    <div onclick="toggleSubmenu('events-sub')" class="nav-card flex items-center px-6 py-4 text-white cursor-pointer hover:bg-white/5 transition group">
        <i data-lucide="calendar-clock" class="w-5 h-5 mr-4 text-red-600 transition-transform group-hover:scale-110"></i>
        <span class="text-[11px] font-bold uppercase tracking-widest text-gray-300 italic">Cronograma</span>
        <i data-lucide="chevron-down" class="w-4 h-4 ml-auto opacity-50 transition-transform duration-300"></i>
    </div>
    <div id="events-sub" class="submenu-container">
        <div class="py-2 space-y-1">
            <a href="javascript:void(0)" onclick="loadModule('edit_events')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition hover:bg-white/5 border-l-2 border-transparent hover:border-red-600">
                Eventos Diarios
            </a>
            <a href="javascript:void(0)" onclick="loadModule('edit_invasions')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition hover:bg-white/5 border-l-2 border-transparent hover:border-red-600">
                Invasiones
            </a>
        </div>
    </div>
</div>

<div class="mb-2">
    <div onclick="toggleSubmenu('templates-sub')" class="nav-card flex items-center px-6 py-4 text-white cursor-pointer hover:bg-white/5 transition group">
        <i data-lucide="layout-template" class="w-5 h-5 mr-4 text-red-600 transition-transform group-hover:scale-110"></i>
        <span class="text-[11px] font-bold uppercase tracking-widest text-gray-300 italic">Templates</span>
        <i data-lucide="chevron-down" class="w-4 h-4 ml-auto opacity-50 transition-transform duration-300"></i>
    </div>
    <div id="templates-sub" class="submenu-container">
        <div class="py-2 space-y-1">
            <a href="javascript:void(0)" onclick="loadModule('upload_template')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition hover:bg-white/5 border-l-2 border-transparent hover:border-red-600">
                <i data-lucide="upload" class="w-3 h-3 mr-2"></i> Gestión / Subir
            </a>
            <a href="javascript:void(0)" onclick="loadModule('my_templates')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition hover:bg-white/5 border-l-2 border-transparent hover:border-red-600">
                <i data-lucide="list" class="w-3 h-3 mr-2"></i> Mis Temas
            </a>
        </div>
    </div>
</div>

<div class="mb-2">
    <div onclick="toggleSubmenu('guides-sub')" class="nav-card flex items-center px-6 py-4 text-white cursor-pointer hover:bg-white/5 transition group">
        <i data-lucide="scroll" class="w-5 h-5 mr-4 text-red-600 drop-shadow-[0_0_8px_#ff0000]"></i>
        <span class="text-[11px] font-bold uppercase tracking-widest text-gray-300 italic font-title">Códice de Guías</span>
        <i data-lucide="chevron-down" class="w-4 h-4 ml-auto opacity-50 transition-transform"></i>
    </div>
    <div id="guides-sub" class="submenu-container">
        <div class="py-2 space-y-1">
            <a href="javascript:void(0)" onclick="loadModule('publish_guide')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition">
                <i data-lucide="feather" class="w-3 h-3 mr-2"></i> Publicar Guía
            </a>
            <a href="javascript:void(0)" onclick="loadModule('library_guides')" class="flex items-center px-16 py-3 text-[10px] text-gray-400 hover:text-red-500 uppercase tracking-widest transition">
                <i data-lucide="library" class="w-3 h-3 mr-2"></i> Biblioteca
            </a>
        </div>
    </div>
</div>

<a href="logout.php" class="nav-card flex items-center px-6 py-4 text-red-500 hover:bg-red-500/10 transition">
    <i data-lucide="log-out" class="w-5 h-5 mr-4"></i>
    <span class="text-[11px] font-bold uppercase tracking-widest">Cerrar Sesión Segura</span>
</a>
        </nav>
        <div class="p-6 bg-black/40 border-t border-white/5">
            <div class="flex items-center gap-3">
                <div class="w-8 h-8 rounded-full bg-red-600 flex items-center justify-center font-bold text-xs uppercase"><?php echo substr($masterAdmin, 0, 1); ?></div>
                <div class="text-[10px]">
                    <p class="text-white font-bold uppercase"><?php echo $masterAdmin; ?></p>
                    <p class="text-red-500 font-bold italic">Administrador</p>
                </div>
            </div>
        </div>
    </aside>

    <main id="content-area" class="flex-1 p-12 overflow-y-auto bg-[#050505]">
        <div class="flex flex-col items-center justify-center h-full opacity-10">
            <i data-lucide="box" class="w-24 h-24 mb-4"></i>
            <p class="font-title uppercase tracking-[0.5em]">Consola de Comando</p>
        </div>
    </main>
  <template id="tpl-web_config">
    <div class="max-w-4xl animate-in fade-in duration-500">
        <h1 class="font-title text-4xl text-white uppercase mb-10 italic drop-shadow-[0_0_10px_rgba(220,38,38,0.5)]">Identidad Visual</h1>
        
        <div class="bg-[#0d0d0d] border border-white/5 p-8 rounded-2xl space-y-10 shadow-2xl">
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="md:col-span-1">
                    <label class="text-[10px] text-red-600 uppercase font-bold block mb-3 tracking-widest italic">Título de la Web</label>
                    <input type="text" id="web_title" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition font-bold shadow-inner">
                </div>
                <div>
                    <label class="text-[10px] text-red-600 uppercase font-bold block mb-3 tracking-widest italic">Versión del Servidor</label>
                    <input type="text" id="server_version" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition font-bold shadow-inner">
                </div>
                <div>
                    <label class="text-[10px] text-red-600 uppercase font-bold block mb-3 tracking-widest italic">Experiencia</label>
                    <input type="text" id="server_exp" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition font-bold shadow-inner">
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 pt-4 border-t border-white/5">
                <div>
                    <label class="text-[10px] text-blue-500 uppercase font-bold block mb-3 tracking-widest italic">Facebook URL</label>
                    <input type="text" id="social_facebook" placeholder="https://facebook.com/..." class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-blue-500/50 transition text-xs shadow-inner">
                </div>
                <div>
                    <label class="text-[10px] text-indigo-500 uppercase font-bold block mb-3 tracking-widest italic">Discord URL</label>
                    <input type="text" id="social_discord" placeholder="https://discord.gg/..." class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-indigo-500/50 transition text-xs shadow-inner">
                </div>
                <div>
                    <label class="text-[10px] text-red-500 uppercase font-bold block mb-3 tracking-widest italic">YouTube URL</label>
                    <input type="text" id="social_youtube" placeholder="https://youtube.com/..." class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-500/50 transition text-xs shadow-inner">
                </div>
            </div>

            <div class="flex justify-end">
                <button onclick="saveWebInfo()" class="group bg-red-600 hover:bg-red-700 px-10 py-4 rounded-xl text-[10px] uppercase font-black tracking-[0.2em] flex items-center gap-2 transition-all shadow-[0_0_20px_rgba(220,38,38,0.3)]">
                    <i data-lucide="save" class="w-4 h-4"></i> Actualizar Núcleo
                </button>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-10 pt-4 border-t border-white/5">
                <div class="upload-box">
                    <label class="text-[10px] text-red-600 uppercase font-bold mb-4 tracking-widest block text-center">Logo Principal</label>
                    <div class="relative w-full h-32 flex items-center justify-center bg-black/20 rounded-xl overflow-hidden border border-white/5 group hover:border-red-600/30 transition-all">
                        <i data-lucide="shield-check" id="placeholder-logo" class="w-10 h-10 text-white/5"></i>
                        <img id="img-logo" class="preview-img hidden w-full h-full object-contain p-2">
                        <div class="progress-overlay" id="parent-logo"><div class="progress-bar-fill" id="fill-logo"></div></div>
                        <input type="file" id="input_logo" accept="image/*" class="absolute inset-0 opacity-0 cursor-pointer" onchange="processAutoUpload(this, 'web_logo_file')">
                    </div>
                </div>

                <div class="upload-box">
                    <label class="text-[10px] text-red-600 uppercase font-bold mb-4 tracking-widest block text-center">Favicon</label>
                    <div class="relative w-full h-32 flex items-center justify-center bg-black/20 rounded-xl overflow-hidden border border-white/5 group hover:border-red-600/30 transition-all">
                        <i data-lucide="image" id="placeholder-favicon" class="w-10 h-10 text-white/5"></i>
                        <img id="img-favicon" class="preview-img hidden w-full h-full object-contain p-2">
                        <div class="progress-overlay" id="parent-favicon"><div class="progress-bar-fill" id="fill-favicon"></div></div>
                        <input type="file" id="input_favicon" accept="image/x-icon,image/png" class="absolute inset-0 opacity-0 cursor-pointer" onchange="processAutoUpload(this, 'web_favicon_file')">
                    </div>
                </div>

                <div class="upload-box">
                    <label class="text-[10px] text-red-600 uppercase font-bold mb-4 tracking-widest block text-center">Banner Meta</label>
                    <div class="relative w-full h-32 flex items-center justify-center bg-black/20 rounded-xl overflow-hidden border border-white/5 group hover:border-red-600/30 transition-all">
                        <i data-lucide="layout" id="placeholder-meta" class="w-10 h-10 text-white/5"></i>
                        <img id="img-meta" class="preview-img hidden w-full h-full object-contain p-2">
                        <div class="progress-overlay" id="parent-meta"><div class="progress-bar-fill" id="fill-meta"></div></div>
                        <input type="file" id="input_meta" accept="image/*" class="absolute inset-0 opacity-0 cursor-pointer" onchange="processAutoUpload(this, 'web_meta_file')">
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

    <template id="tpl-publish">
        <div class="max-w-4xl animate-in fade-in duration-500">
            <h1 class="font-title text-4xl text-white uppercase mb-10 italic">Publicar <span class="text-red-600">Anuncio</span></h1>
            <form id="newsForm" class="space-y-6">
                <input type="hidden" id="editNewsId" value="">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <input type="text" id="newsTitle" placeholder="Título del Anuncio" class="w-full bg-[#0d0d0d] border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition font-bold uppercase text-xs">
                    <select id="newsCategory" class="bg-[#0d0d0d] border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition font-bold text-xs uppercase">
                        <option value="Actualización">⚙️ Actualización</option>
                        <option value="Evento Especial">⚔️ Evento Especial</option>
                        <option value="Noticias">📢 Noticias Generales</option>
                    </select>
                </div>
                <input type="text" id="newsImage" placeholder="URL de Imagen (Opcional)" class="w-full bg-[#0d0d0d] border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition text-xs">
                <div id="editor" class="rounded-xl overflow-hidden border border-white/10"></div>
                <div class="flex justify-end">
                    <button type="button" onclick="submitNews()" class="bg-red-600 text-white font-title text-[10px] px-12 py-5 rounded-xl uppercase tracking-[0.2em] hover:bg-red-700 transition shadow-lg shadow-red-600/20">Lanzar Publicación / Guardar Cambios</button>
                </div>
            </form>
        </div>
    </template>

    <template id="tpl-manage">
        <div class="max-w-6xl animate-in fade-in duration-500">
            <h1 class="font-title text-4xl text-white uppercase mb-10 italic">Archivo de <span class="text-red-600">Noticias</span></h1>
            <div class="bg-[#0d0d0d] border border-white/10 rounded-2xl overflow-hidden shadow-2xl">
                <table class="w-full text-left border-collapse">
                    <thead class="bg-white/5 border-b border-white/10 text-[10px] uppercase font-bold text-red-600">
                        <tr>
                            <th class="p-6 tracking-widest">Título del Anuncio</th>
                            <th class="p-6 tracking-widest">Categoría</th>
                            <th class="p-6 tracking-widest text-right">Acciones</th>
                        </tr>
                    </thead>
                    <tbody id="news-list-body" class="divide-y divide-white/5"></tbody>
                </table>
            </div>
        </div>
    </template>

    <template id="tpl-rankings">
        <div class="max-w-6xl animate-in fade-in duration-500">
            <h1 class="font-title text-4xl text-white uppercase mb-10 italic tracking-tighter">Módulos de <span class="text-red-600">Ranking</span></h1>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <div class="bg-[#0d0d0d] border border-white/5 p-8 rounded-2xl space-y-4">
                    <h3 class="text-red-600 font-bold uppercase text-[10px] mb-6 tracking-[0.3em] italic border-b border-red-600/20 pb-2">Estadísticas de Personajes</h3>
                    <?php 
                    $ranks = ['resets' => 'Resets Globales', 'mresets' => 'Master Resets', 'level' => 'Nivel Base', 'master' => 'Master Level', 'pk' => 'Asesinatos (PK)', 'gens' => 'Gens System'];
                    foreach($ranks as $id => $name): ?>
                    <label class="flex items-center justify-between p-4 bg-black/40 rounded-xl border border-white/5 hover:border-red-600/30 transition cursor-pointer group">
                        <span class="text-[10px] uppercase font-bold text-gray-400 group-hover:text-white transition tracking-widest"><?php echo $name; ?></span>
                        <input type="checkbox" id="check_<?php echo $id; ?>" class="w-5 h-5 rounded border-white/10 bg-black text-red-600 focus:ring-red-600 accent-red-600">
                    </label>
                    <?php endforeach; ?>
                </div>
                <div class="bg-[#0d0d0d] border border-white/5 p-8 rounded-2xl flex flex-col justify-between">
                    <div class="space-y-4">
                        <h3 class="text-red-600 font-bold uppercase text-[10px] mb-6 tracking-[0.3em] italic border-b border-red-600/20 pb-2">Eventos Especiales</h3>
                        <?php 
                        $evts = ['bc' => 'Blood Castle', 'ds' => 'Devil Square', 'cc' => 'Chaos Castle', 'it' => 'Illusion Temple', 'duels' => 'Duelos Totales'];
                        foreach($evts as $id => $name): ?>
                        <label class="flex items-center justify-between p-4 bg-black/40 rounded-xl border border-white/5 hover:border-red-600/30 transition cursor-pointer group">
                            <span class="text-[10px] uppercase font-bold text-gray-400 group-hover:text-white transition tracking-widest"><?php echo $name; ?></span>
                            <input type="checkbox" id="check_<?php echo $id; ?>" class="w-5 h-5 rounded border-white/10 bg-black text-red-600 focus:ring-red-600 accent-red-600">
                        </label>
                        <?php endforeach; ?>
                    </div>
                    <button onclick="saveRankingConfig()" class="mt-8 w-full bg-red-600 hover:bg-red-700 py-5 rounded-xl text-[10px] uppercase font-bold tracking-[0.3em] transition shadow-lg shadow-red-600/20 flex items-center justify-center gap-3">
                        <i data-lucide="save" class="w-4 h-4"></i> Guardar Filtros de Ranking
                    </button>
                </div>
            </div>
        </div>
    </template>
    
    <template id="tpl-publish_guide">
    <div class="max-w-5xl animate-in slide-in-from-bottom duration-500">
        <div class="mb-8">
            <h1 class="font-title text-4xl text-white uppercase italic">Forjar <span class="text-red-600">Conocimiento</span></h1>
            <p class="text-yellow-600 text-[10px] uppercase font-black tracking-[0.3em]">Editor de Guías Maestras</p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
            <div class="lg:col-span-3 space-y-6">
                <div class="bg-black/60 border border-red-900/30 p-6 rounded-2xl">
                    <label class="text-[9px] text-red-500 font-black uppercase mb-2 block italic">Título de la Guía</label>
                    <input type="text" id="guide_title" class="w-full bg-black border border-white/10 rounded-xl p-4 text-white uppercase text-xs focus:border-red-600 outline-none">
                </div>
                <div class="bg-black/60 border border-red-900/30 p-2 rounded-2xl overflow-hidden">
                    <div id="editor_container" class="min-h-[400px] text-black"></div>
                </div>
            </div>

            <div class="space-y-6">
                <div class="bg-black/60 border border-red-900/30 p-6 rounded-2xl">
                    <label class="text-[9px] text-yellow-600 font-black uppercase mb-4 block italic text-center">Imagen de Referencia</label>
                    <div class="relative group cursor-pointer border-2 border-dashed border-red-900/30 rounded-xl p-4 text-center hover:border-red-600 transition" onclick="document.getElementById('guide_img').click()">
                        <i data-lucide="image-plus" class="w-8 h-8 mx-auto text-red-900 group-hover:text-red-600"></i>
                        <input type="file" id="guide_img" class="hidden" accept="image/*">
                        <p class="text-[8px] text-gray-500 mt-2">SUBIR IMAGEN (PNG/JPG)</p>
                    </div>
                </div>

                <div class="bg-black/60 border border-red-900/30 p-6 rounded-2xl">
                    <label class="text-[9px] text-red-500 font-black uppercase mb-2 block italic">Categoría / Sección</label>
                    <select id="guide_category" class="w-full bg-black border border-white/10 rounded-lg p-3 text-white text-[10px] uppercase outline-none mb-3">
                        <option value="Web">Web</option>
                        <option value="Servidor">Servidor</option>
                        <option value="Eventos">Eventos</option>
                    </select>
                    <button onclick="addNewCategory()" class="w-full py-2 border border-yellow-600/30 text-yellow-600 text-[8px] font-black uppercase rounded hover:bg-yellow-600/10">+ Nueva Sección</button>
                </div>

                <button onclick="saveGuide()" class="w-full bg-red-600 hover:bg-red-700 text-white font-black py-4 rounded-xl text-[10px] uppercase tracking-widest shadow-lg shadow-red-600/30 transition">
                    Guardar Guía
                </button>
            </div>
        </div>
    </div>
</template>

<template id="tpl-library_guides">
    <div class="animate-in fade-in">
        <h1 class="font-title text-4xl text-white uppercase italic mb-8">Biblioteca de <span class="text-red-600">Poder</span></h1>
        
        <div id="category-filters" class="flex gap-3 mb-10 overflow-x-auto pb-4">
            <button onclick="filterGuides('all')" class="filter-badge px-6 py-2 rounded-full text-[9px] font-black uppercase">Todo</button>
            </div>

        <div id="guides-container" class="grid grid-cols-1 md:grid-cols-3 gap-8">
            </div>
    </div>
</template>

    <template id="tpl-market_config">
        <div class="max-w-5xl animate-in fade-in duration-500">
            <h1 class="font-title text-4xl text-white uppercase mb-10 italic tracking-tighter">Mercado <span class="text-red-600">Master</span></h1>
            
            <div class="bg-[#0d0d0d] border border-white/5 p-8 rounded-2xl space-y-8">
                <div class="flex items-center justify-between bg-black/40 p-6 rounded-xl border border-white/10">
                    <div>
                        <h4 class="text-white font-bold text-[11px] uppercase tracking-widest mb-1 italic">Estado del Módulo</h4>
                        <p class="text-[9px] text-gray-500 uppercase">Habilitar venta de personajes en la web</p>
                    </div>
                    <select id="market_active" class="bg-black border border-red-600/30 rounded-lg p-3 text-[10px] font-bold text-red-500 outline-none">
                        <option value="1">SISTEMA ACTIVO</option>
                        <option value="0">SISTEMA CERRADO</option>
                    </select>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div class="space-y-6">
                        <h3 class="text-red-600 font-bold uppercase text-[10px] tracking-widest italic border-b border-red-600/20 pb-2">Tasación por Poder</h3>
                        
                        <div>
                            <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic">Límite de Stats (32767 o 65000)</label>
                            <input type="number" id="market_max_stats" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-bold outline-none focus:border-red-600/50 transition">
                            <p class="text-[8px] text-gray-600 mt-2 uppercase tracking-tighter">Esto se usa para calcular el % de fuerza del personaje.</p>
                        </div>

                        <div>
                            <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic">Valor para PJ "Full Stats"</label>
                            <input type="number" id="market_full_val" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-bold outline-none focus:border-red-600/50 transition">
                            <p class="text-[8px] text-gray-600 mt-2 uppercase tracking-tighter">Monedas base si el PJ tiene todos los puntos al máximo.</p>
                        </div>
                        
                        <div>
                            <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic">Valor por cada Reset</label>
                            <input type="number" id="market_reset_val" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-bold outline-none focus:border-red-600/50 transition">
                            <p class="text-[8px] text-gray-600 mt-2 uppercase tracking-tighter">Suma esta cantidad por cada reset que tenga el PJ.</p>
                        </div>
                    </div>

                    <div class="space-y-6">
                        <h3 class="text-red-600 font-bold uppercase text-[10px] tracking-widest italic border-b border-red-600/20 pb-2">Restricciones Administrativas</h3>
                        
                        <div>
                            <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic text-red-500">Mínimo de Resets para Vender</label>
                            <input type="number" id="market_min_resets" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-bold outline-none focus:border-red-600/50 transition">
                            <p class="text-[8px] text-gray-600 mt-2 uppercase tracking-tighter">Evita que vendan personajes de nivel bajo.</p>
                        </div>

                        <div>
                            <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic">Comisión para la Web (%)</label>
                            <input type="number" id="market_tax" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-bold outline-none focus:border-red-600/50 transition">
                            <p class="text-[8px] text-gray-600 mt-2 uppercase tracking-tighter">Porcentaje que el servidor descuenta al vendedor.</p>
                        </div>
                    </div>
                </div>

                <div class="flex justify-end pt-4">
                    <button onclick="saveMarketConfig()" class="bg-red-600 px-12 py-5 rounded-xl text-[10px] uppercase font-bold tracking-[0.3em] flex items-center gap-3 shadow-lg shadow-red-600/20">
                        <i data-lucide="save" class="w-4 h-4"></i> Actualizar Módulo Mercado
                    </button>
                </div>
            </div>
        </div>
    </template>
    <template id="tpl-downloads">
        <div class="max-w-4xl animate-in fade-in duration-500">
            <h1 class="font-title text-4xl text-white uppercase mb-10 italic">Nodos de <span class="text-red-600">Descarga</span></h1>
            <div class="bg-[#0d0d0d] border border-white/5 p-8 rounded-2xl space-y-6 mb-10">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="text-[10px] text-red-600 uppercase font-bold block mb-2 tracking-widest italic">Etiqueta del Archivo</label>
                        <input type="text" id="dl_name" placeholder="Ej: Cliente Full Mu" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition font-bold text-xs">
                    </div>
                    <div>
                        <label class="text-[10px] text-red-600 uppercase font-bold block mb-2 tracking-widest italic">Enlace Externo (URL)</label>
                        <input type="text" id="dl_url" placeholder="https://mega.nz/..." class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition text-xs">
                    </div>
                </div>
                <button onclick="addDownload()" class="bg-red-600 px-12 py-4 rounded-xl text-[10px] uppercase font-bold tracking-widest">Registrar Nodo</button>
            </div>
            
            <div class="bg-[#0d0d0d] border border-white/10 rounded-2xl overflow-hidden shadow-2xl">
                <table class="w-full text-left">
                    <thead class="bg-white/5 text-[10px] uppercase font-bold text-gray-400">
                        <tr>
                            <th class="p-6">Nombre del Recurso</th>
                            <th class="p-6">Enlace Directo</th>
                            <th class="p-6 text-right">Acción</th>
                        </tr>
                    </thead>
                    <tbody id="downloads-list-body" class="divide-y divide-white/5"></tbody>
                </table>
            </div>
        </div>
    </template>

    <template id="tpl-register">
        <div class="max-w-4xl animate-in fade-in duration-500">
            <h1 class="font-title text-4xl text-white uppercase mb-10 italic">Bonos de <span class="text-red-600">Registro</span></h1>
            <div class="bg-[#0d0d0d] border border-white/5 p-8 rounded-2xl space-y-6">
                <div>
                    <label class="text-[10px] text-red-600 uppercase font-bold block mb-4 tracking-[0.2em] italic">Recompensa de Zen Inicial (Al crear personaje)</label>
                    <input type="number" id="welcome_zen" class="w-full bg-black/40 border border-white/10 rounded-xl p-5 text-white outline-none focus:border-red-600/50 transition font-bold text-lg">
                    <p class="text-[10px] text-gray-500 mt-4 uppercase italic">Nota: Este valor se entregará a cada personaje nuevo creado en la cuenta.</p>
                </div>
                <button onclick="saveRegisterConfig()" class="bg-red-600 px-12 py-5 rounded-xl text-[10px] uppercase font-bold tracking-widest shadow-lg shadow-red-600/20">Sincronizar Bono</button>
            </div>
        </div>
    </template>

    <template id="tpl-coin_config">
        <div class="max-w-5xl animate-in fade-in duration-500">
            <h1 class="font-title text-4xl text-white uppercase mb-10 italic">Motor de <span class="text-red-600">Economía</span></h1>
            <div class="bg-[#0d0d0d] border border-white/5 p-10 rounded-3xl space-y-10">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div class="md:col-span-2">
                        <label class="text-[11px] text-red-600 uppercase font-black block mb-4 tracking-[0.2em] italic border-b border-red-600/20 pb-2">Nombre Comercial de la Moneda</label>
                        <input type="text" id="coin_name" class="w-full bg-black/40 border border-white/10 rounded-2xl p-5 text-white outline-none focus:border-red-600/50 transition font-bold text-lg italic shadow-inner" placeholder="Ej: WCoins, Créditos, MuPoints">
                    </div>
                    <div>
                        <label class="text-[10px] text-gray-400 uppercase font-bold block mb-3 tracking-widest italic">Tabla en SQL Server</label>
                        <input type="text" id="coin_table" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition font-mono text-xs uppercase" placeholder="Ej: MEMB_INFO">
                    </div>
                    <div>
                        <label class="text-[10px] text-gray-400 uppercase font-bold block mb-3 tracking-widest italic">Columna de Saldo (Balance)</label>
                        <input type="text" id="coin_column" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition font-mono text-xs uppercase" placeholder="Ej: cspoints">
                    </div>
                    <div>
                        <label class="text-[10px] text-gray-400 uppercase font-bold block mb-3 tracking-widest italic">Columna Identificadora (Login ID)</label>
                        <input type="text" id="coin_id_column" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white outline-none focus:border-red-600/50 transition font-mono text-xs uppercase" placeholder="Ej: memb___id">
                    </div>
                    <div class="flex items-center gap-5 bg-red-600/5 border border-red-600/10 rounded-2xl p-6 hover:border-red-600/30 transition group">
                        <input type="checkbox" id="coin_check_online" class="w-6 h-6 accent-red-600 rounded cursor-pointer">
                        <div>
                            <span class="text-[11px] text-white uppercase font-black tracking-widest block italic group-hover:text-red-500 transition">Bloqueo Anti-Dupe (Online Check)</span>
                            <p class="text-[9px] text-gray-500 uppercase mt-1 tracking-tighter">Requiere que el usuario esté OFFLINE para procesar compras.</p>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end pt-6 border-t border-white/5">
                    <button onclick="saveCoinConfig()" class="bg-red-600 hover:bg-red-700 px-14 py-6 rounded-2xl text-[11px] uppercase font-black tracking-[0.3em] flex items-center gap-4 transition shadow-xl shadow-red-600/20 active:scale-95">
                        <i data-lucide="save" class="w-5 h-5"></i> Actualizar Sistema Monetario
                    </button>
                </div>
            </div>
        </div>
    </template>
    
    <template id="tpl-paypal_config">
    <div class="max-w-5xl animate-in fade-in duration-500">
        <h1 class="font-title text-4xl text-white uppercase mb-10 italic tracking-tighter">Pasarela <span class="text-blue-500">PayPal</span></h1>
        
        <div class="bg-[#0d0d0d] border border-white/5 p-8 rounded-2xl space-y-8">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="flex items-center justify-between bg-black/40 p-6 rounded-xl border border-white/10">
                    <div>
                        <h4 class="text-white font-bold text-[11px] uppercase tracking-widest mb-1 italic">Estado del Módulo</h4>
                        <p class="text-[9px] text-gray-500 uppercase">Habilitar donaciones en la web</p>
                    </div>
                    <select id="paypal_active" class="bg-black border border-blue-600/30 rounded-lg p-3 text-[10px] font-bold text-blue-500 outline-none">
                        <option value="1">SISTEMA ACTIVO</option>
                        <option value="0">SISTEMA CERRADO</option>
                    </select>
                </div>
                <div class="flex items-center justify-between bg-black/40 p-6 rounded-xl border border-white/10">
                    <div>
                        <h4 class="text-white font-bold text-[11px] uppercase tracking-widest mb-1 italic">Modo de Operación</h4>
                        <p class="text-[9px] text-gray-500 uppercase">Sandbox (Pruebas) / Live (Producción)</p>
                    </div>
                    <select id="paypal_mode" class="bg-black border border-yellow-600/30 rounded-lg p-3 text-[10px] font-bold text-yellow-500 outline-none">
                        <option value="sandbox">MODO PRUEBA (SANDBOX)</option>
                        <option value="live">MODO PRODUCCIÓN (LIVE)</option>
                    </select>
                </div>
            </div>

            <div class="space-y-6">
                <h3 class="text-blue-500 font-bold uppercase text-[10px] tracking-widest italic border-b border-blue-500/20 pb-2">Credenciales de API PayPal</h3>
                <div class="grid grid-cols-1 gap-4">
                    <div>
                        <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic">PayPal Client ID</label>
                        <input type="text" id="paypal_client_id" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-mono text-xs outline-none focus:border-blue-600/50 transition">
                    </div>
                    <div>
                        <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic">PayPal Secret Key</label>
                        <input type="password" id="paypal_secret" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-mono text-xs outline-none focus:border-blue-600/50 transition">
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                    <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic">Valor de 1 Moneda (USD)</label>
                    <input type="number" step="0.01" id="paypal_coin_rate" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-bold outline-none focus:border-blue-600/50 transition">
                    <p class="text-[8px] text-gray-600 mt-2 uppercase tracking-tighter">Ej: Si pones 5, cada moneda cuesta 5 USD.</p>
                </div>
                <div>
                    <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic">Mínimo de Compra (USD)</label>
                    <input type="number" id="paypal_min_purchase" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-bold outline-none focus:border-blue-600/50 transition">
                </div>
                <div>
                    <label class="text-[10px] text-gray-400 uppercase font-bold block mb-2 tracking-widest italic">Divisa</label>
                    <input type="text" id="paypal_currency" class="w-full bg-black/40 border border-white/10 rounded-xl p-4 text-white font-bold outline-none focus:border-blue-600/50 transition uppercase" value="USD">
                </div>
            </div>

            <div class="flex justify-end pt-4">
                <button onclick="savePaypalConfig()" class="bg-blue-600 px-12 py-5 rounded-xl text-[10px] uppercase font-bold tracking-[0.3em] flex items-center gap-3 shadow-lg shadow-blue-600/20 hover:bg-blue-700 transition">
                    <i data-lucide="save" class="w-4 h-4"></i> Guardar Configuración PayPal
                </button>
            </div>
        </div>
    </div>
</template>

<template id="tpl-edit_events">
    <div class="max-w-5xl animate-in slide-in-from-bottom-4 duration-500">
        <div class="flex justify-between items-center mb-10">
            <div>
                <h1 class="font-title text-4xl text-white uppercase italic">Gestión de <span id="module-title-dynamic" class="text-red-600">Horarios</span></h1>
                <p class="text-gray-500 text-[10px] uppercase tracking-[0.2em]">Administra tus cronogramas e imágenes</p>
            </div>
            <button onclick="openScheduleSlider()" class="bg-red-600 hover:bg-red-700 w-14 h-14 rounded-full flex items-center justify-center shadow-lg shadow-red-600/40 transition-transform hover:scale-110">
                <i data-lucide="plus" class="text-white w-8 h-8"></i>
            </button>
        </div>
        <div id="schedule-list" class="grid grid-cols-1 md:grid-cols-2 gap-4">
            </div>
    </div>
</template>

<template id="tpl-upload_template">
    <div class="max-w-5xl animate-in fade-in duration-500">
        <h1 class="font-title text-4xl text-white uppercase mb-10 italic text-left">Subir <span class="text-red-600">Nuevo Template</span></h1>
        
        <div class="bg-[#0d0d0d] border border-white/5 p-8 rounded-2xl mb-10 text-left">
            <label class="text-[10px] text-red-600 uppercase font-bold mb-4 tracking-widest block italic">Archivo comprimido (.zip)</label>
            <div class="relative border-dashed border-2 border-white/10 p-10 rounded-xl flex flex-col items-center justify-center hover:bg-white/5 transition">
                <i data-lucide="upload-cloud" class="w-12 h-12 text-white/10 mb-2"></i>
                <span class="text-xs text-gray-500 uppercase font-bold">Haz clic o arrastra tu archivo .zip aquí</span>
                <input type="file" id="zip_file" onchange="uploadTemplate()" class="absolute inset-0 opacity-0 cursor-pointer">
            </div>
            
            <div id="template-progress-container" class="hidden mt-4">
                <div class="h-1.5 w-full bg-white/5 rounded-full overflow-hidden">
                    <div id="template-progress-bar" class="h-full bg-red-600 w-0 transition-all duration-300"></div>
                </div>
                <p id="template-progress-text" class="text-[9px] text-gray-500 mt-2 uppercase text-center italic">Subiendo archivo...</p>
            </div>
        </div>
    </div>
</template>

<template id="tpl-my_templates">
    <div class="max-w-5xl animate-in fade-in duration-500">
        <h1 class="font-title text-4xl text-white uppercase mb-10 italic text-left">Mis <span class="text-red-600">Templates</span></h1>
        <div id="templates-grid" class="grid grid-cols-1 md:grid-cols-3 gap-6"></div>
    </div>
</template>

<div id="modal-install-confirm" class="fixed inset-0 bg-black/90 flex items-center justify-center z-[200] hidden">
    <div class="bg-[#0a0a0a] border border-white/10 p-8 rounded-3xl max-w-sm w-full text-center shadow-2xl">
        <div class="w-16 h-16 bg-red-600/10 rounded-full flex items-center justify-center mx-auto mb-4">
            <i data-lucide="archive" class="text-red-600 w-8 h-8"></i>
        </div>
        <h3 class="text-white font-bold uppercase mb-2 italic">Archivo Recibido</h3>
        <p class="text-gray-500 text-[10px] uppercase mb-6 leading-relaxed">
            Se ha cargado: <span id="uploaded-filename" class="text-white font-mono"></span><br>
            ¿Deseas descomprimir e instalar en la carpeta de templates?
        </p>
        <div class="flex gap-4">
            <button onclick="closeInstallModal()" class="flex-1 bg-white/5 hover:bg-white/10 py-3 rounded-xl text-[10px] text-gray-400 hover:text-white uppercase font-bold transition">Cancelar</button>
            <button onclick="installTemplate()" class="flex-1 bg-red-600 hover:bg-red-700 py-3 rounded-xl text-[10px] text-white uppercase font-bold shadow-lg shadow-red-600/20 transition">Sí, Instalar</button>
        </div>
    </div>
</div>

<div id="modal-install-confirm" class="fixed inset-0 bg-black/90 flex items-center justify-center z-[200] hidden p-6">
    <div class="bg-[#0a0a0a] border border-white/10 p-8 rounded-3xl max-w-md w-full text-center shadow-2xl">
        <div class="w-20 h-20 bg-red-600/10 rounded-full flex items-center justify-center mx-auto mb-6">
            <i data-lucide="archive" class="text-red-600 w-10 h-10"></i>
        </div>
        <h3 class="text-white font-title text-xl uppercase mb-2 italic">Archivo Recibido</h3>
        <p class="text-gray-500 text-xs mb-8 uppercase leading-relaxed">Se ha cargado <span id="uploaded-filename" class="text-red-500 font-bold"></span>.<br>¿Deseas proceder con la instalación en la carpeta de templates?</p>
        <div class="flex gap-4">
            <button onclick="closeInstallModal()" class="flex-1 bg-white/5 hover:bg-white/10 text-white py-4 rounded-xl text-[10px] uppercase font-bold tracking-widest transition">Cancelar</button>
            <button onclick="installTemplate()" class="flex-1 bg-red-600 hover:bg-red-700 text-white py-4 rounded-xl text-[10px] uppercase font-bold tracking-widest shadow-lg shadow-red-600/20 transition">Instalar Ahora</button>
        </div>
    </div>
</div>

<div id="modal-install-confirm" class="fixed inset-0 bg-black/80 backdrop-blur-sm z-[200] flex items-center justify-center hidden">
    <div class="bg-[#0d0d0d] border border-white/10 p-10 rounded-3xl max-w-sm w-full text-center shadow-2xl">
        <i data-lucide="package-check" class="w-16 h-16 text-green-500 mx-auto mb-6"></i>
        <h2 class="text-white font-title text-xl uppercase mb-2">¡Archivo Subido!</h2>
        <p class="text-gray-500 text-[10px] uppercase mb-8">El paquete <span id="uploaded-filename" class="text-white font-bold text-red-600">archivo.zip</span> se ha recibido. ¿Deseas extraerlo e instalarlo ahora?</p>
        <div class="grid grid-cols-2 gap-4">
            <button onclick="closeInstallModal()" class="border border-white/10 py-4 rounded-xl text-[9px] font-bold uppercase text-gray-400 hover:bg-white/5 transition">Cancelar</button>
            <button onclick="installTemplate()" class="bg-red-600 py-4 rounded-xl text-[9px] font-bold uppercase text-white hover:bg-red-700 shadow-[0_0_15px_rgba(255,0,0,0.3)] transition">Instalar Ahora</button>
        </div>
    </div>
</div>

<div id="modal-install-confirm" class="fixed inset-0 bg-black/80 backdrop-blur-sm z-[200] flex items-center justify-center hidden">
    <div class="bg-[#0d0d0d] border border-white/10 p-10 rounded-3xl max-w-sm w-full text-center shadow-2xl">
        <i data-lucide="package-check" class="w-16 h-16 text-green-500 mx-auto mb-6"></i>
        <h2 class="text-white font-title text-xl uppercase mb-2">Archivo Recibido</h2>
        <p class="text-gray-500 text-[10px] uppercase mb-8">¿Deseas proceder con la instalación de <span id="uploaded-filename" class="text-white font-bold text-red-600"></span>?</p>
        <div class="grid grid-cols-2 gap-4">
            <button onclick="closeInstallModal()" class="border border-white/10 py-4 rounded-xl text-[9px] font-bold uppercase text-gray-400 hover:bg-white/5 transition">Cancelar</button>
            <button onclick="installTemplate()" class="bg-green-600 py-4 rounded-xl text-[9px] font-bold uppercase text-white hover:bg-green-700 transition">Instalar Ahora</button>
        </div>
    </div>
</div>

<div id="schedule-slider" class="fixed inset-y-0 right-0 w-full max-w-md bg-[#0a0a0a] border-l border-white/10 translate-x-full shadow-2xl flex flex-col z-[100]">
    <div class="p-8 border-b border-white/5 flex justify-between items-center">
        <h2 class="text-xl font-title text-white uppercase italic">Configurar <span class="text-red-600">Nuevo</span></h2>
        <button onclick="closeScheduleSlider()" class="text-gray-500 hover:text-white"><i data-lucide="x"></i></button>
    </div>
    
    <div class="flex-1 overflow-y-auto p-8 space-y-6 text-left">
        <div>
            <label class="text-[9px] uppercase text-red-600 font-bold tracking-widest block mb-2 italic">Nombre</label>
            <input type="text" id="sch-name" class="w-full bg-white/5 border border-white/10 rounded-xl p-4 text-white focus:border-red-600 outline-none transition">
        </div>

        <div>
            <label class="text-[9px] uppercase text-red-600 font-bold tracking-widest block mb-2 italic">Descripción del Evento</label>
            <textarea id="sch-description" rows="2" class="w-full bg-white/5 border border-white/10 rounded-xl p-4 text-white focus:border-red-600 outline-none transition text-xs" placeholder="Escribe la descripción aquí..."></textarea>
        </div>

        <div>
            <label class="text-[9px] uppercase text-red-600 font-bold tracking-widest block mb-2 italic">Configurar Horarios</label>
            <div id="time-inputs-container" class="space-y-2">
                <div class="flex gap-2">
                    <input type="time" class="time-input w-full bg-white/5 border border-white/10 rounded-xl p-3 text-white focus:border-red-600 outline-none transition [color-scheme:dark]">
                    <button onclick="addTimeField()" class="bg-white/5 hover:bg-red-600/20 border border-white/10 w-12 rounded-xl flex items-center justify-center transition group">
                        <i data-lucide="plus" class="w-4 h-4 text-gray-400 group-hover:text-red-600"></i>
                    </button>
                </div>
            </div>
        </div>

        <div>
            <label class="text-[9px] uppercase text-red-600 font-bold tracking-widest block mb-2 italic">Zona Horaria (Server/País)</label>
            <div class="relative">
                <select id="sch-gmt" class="w-full bg-white/5 border border-white/10 rounded-xl p-4 text-white focus:border-red-600 outline-none transition appearance-none cursor-pointer">
                    <option value="UTC-12:00" class="bg-[#0a0a0a]">(UTC-12:00) International Date Line West</option>
                    <option value="UTC-11:00" class="bg-[#0a0a0a]">(UTC-11:00) Coordinated Universal Time-11</option>
                    <option value="UTC-10:00" class="bg-[#0a0a0a]">(UTC-10:00) Hawaii</option>
                    <option value="UTC-09:00" class="bg-[#0a0a0a]">(UTC-09:00) Alaska</option>
                    <option value="UTC-08:00" class="bg-[#0a0a0a]">(UTC-08:00) Pacific Time (US & Canada)</option>
                    <option value="UTC-07:00" class="bg-[#0a0a0a]">(UTC-07:00) Mountain Time (US & Canada)</option>
                    <option value="UTC-06:00" class="bg-[#0a0a0a]">(UTC-06:00) Central Time (US & Canada)</option>
                    <option value="UTC-05:00" class="bg-[#0a0a0a]">(UTC-05:00) Eastern Time (US & Canada), Bogota, Lima</option>
                    <option value="UTC-04:00" class="bg-[#0a0a0a]">(UTC-04:00) Atlantic Time (Canada), Caracas, La Paz</option>
                    <option value="UTC-03:00" class="bg-[#0a0a0a]">(UTC-03:00) Brasilia, Buenos Aires, Greenland</option>
                    <option value="UTC+00:00" class="bg-[#0a0a0a]" selected>(UTC+00:00) UTC, London, Lisbon</option>
                    <option value="UTC+01:00" class="bg-[#0a0a0a]">(UTC+01:00) Amsterdam, Berlin, Madrid, Paris</option>
                    <option value="UTC+02:00" class="bg-[#0a0a0a]">(UTC+02:00) Cairo, Johannesburg, Jerusalem</option>
                    <option value="UTC+03:00" class="bg-[#0a0a0a]">(UTC+03:00) Moscow, Istanbul, Riyadh</option>
                    <option value="UTC+08:00" class="bg-[#0a0a0a]">(UTC+08:00) Beijing, Hong Kong, Singapore</option>
                    <option value="UTC+09:00" class="bg-[#0a0a0a]">(UTC+09:00) Tokyo, Seoul</option>
                </select>
                <i data-lucide="chevron-down" class="w-4 h-4 absolute right-4 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none"></i>
            </div>
        </div>

        <div>
            <label class="text-[9px] uppercase text-red-600 font-bold tracking-widest block mb-2 italic">Imagen del Evento</label>
            <div class="image-upload-zone rounded-xl p-6 text-center relative border-2 border-dashed border-white/10 hover:border-red-600 transition">
                <input type="file" id="sch-img" accept="image/*" class="absolute inset-0 opacity-0 cursor-pointer">
                <i data-lucide="upload-cloud" class="mx-auto w-8 h-8 text-gray-600 mb-2"></i>
                <p class="text-[9px] text-gray-500 uppercase font-bold">Clic para subir imagen</p>
            </div>
        </div>

        <div>
            <label class="text-[9px] uppercase text-red-600 font-bold tracking-widest block mb-2 italic">Imágenes de los Drops (Múltiple)</label>
            <div class="image-upload-zone rounded-xl p-6 text-center relative border-2 border-dashed border-white/10 hover:border-red-600 transition bg-red-600/5">
                <input type="file" id="sch-drops-files" accept="image/*" multiple class="absolute inset-0 opacity-0 cursor-pointer">
                <i data-lucide="package-plus" class="mx-auto w-8 h-8 text-red-600/40 mb-2"></i>
                <p class="text-[9px] text-gray-500 uppercase font-bold">Subir imágenes de Items</p>
                <div id="drops-preview-text" class="text-[8px] text-red-500 mt-2 font-bold uppercase"></div>
            </div>
        </div>

        <div>
            <label class="text-[9px] uppercase text-red-600 font-bold tracking-widest block mb-2 italic">Rareza de los Drops (Resplandor)</label>
            <div class="relative">
                <select id="sch-rarity" class="w-full bg-white/5 border border-white/10 rounded-xl p-4 text-white focus:border-red-600 outline-none transition appearance-none cursor-pointer">
                    <option value="common" class="bg-[#0a0a0a]">COMÚN (SIN RESPLANDOR)</option>
                    <option value="excellent" class="bg-[#0a0a0a] text-green-500">EXCELENTE (RESPLANDOR VERDE)</option>
                    <option value="ancient" class="bg-[#0a0a0a] text-cyan-500">ANCIENT / ACC (RESPLANDOR CIAN)</option>
                    <option value="socket" class="bg-[#0a0a0a] text-purple-500">SOCKET / SEED (RESPLANDOR MORADO)</option>
                    <option value="boss" class="bg-[#0a0a0a] text-orange-500">BOSS / EPIC (RESPLANDOR NARANJA)</option>
                </select>
                <i data-lucide="sparkles" class="w-4 h-4 absolute right-4 top-1/2 -translate-y-1/2 text-red-600 pointer-events-none"></i>
            </div>
        </div>
    </div>
    
    <div class="p-8 border-t border-white/5 bg-black/40">
        <button onclick="addScheduleToList()" class="w-full bg-red-600 py-4 rounded-xl text-white uppercase text-xs font-bold shadow-lg shadow-red-600/20 hover:bg-red-700 transition">Guardar Registro</button>
    </div>
</div>

<script>
    lucide.createIcons();
    let myEditor;
    let currentType = 'event';

    function showToast(msg) {
        const t = document.createElement('div');
        t.className = 'toast-container';
        t.innerHTML = `<div class="flex items-center gap-3"><i data-lucide="check" class="w-5 h-5"></i><span class="text-xs uppercase font-bold tracking-widest">${msg}</span></div>`;
        document.body.appendChild(t);
        lucide.createIcons();
        setTimeout(() => t.classList.add('active'), 100);
        setTimeout(() => { t.classList.remove('active'); setTimeout(() => t.remove(), 600); }, 3000);
    }

    function toggleSubmenu(id) {
        document.getElementById(id).classList.toggle('open');
    }

    function loadModule(type) {
        const area = document.getElementById('content-area');
        let templateId = `tpl-${type}`;
        if(type === 'edit_invasions') {
            templateId = 'tpl-edit_events';
        }
        const tpl = document.getElementById(templateId);
        if(!tpl) return;
        area.innerHTML = '';
        area.appendChild(tpl.content.cloneNode(true));
        lucide.createIcons();
        if(type === 'publish') {
            ClassicEditor.create(document.querySelector('#editor')).then(e => myEditor = e);
        }
        if(type === 'web_config') refreshWebConfig();
        if(type === 'rankings') fetchRankingConfig();
        if(type === 'manage') fetchNewsList();
        if(type === 'downloads') fetchDownloads();
        if(type === 'register') fetchRegisterConfig();
        if(type === 'coin_config') fetchCoinConfig();
        if(type === 'market_config') fetchMarketConfig();
        if(type === 'paypal_config') fetchPaypalConfig();
        if(type === 'my_templates') fetchTemplatesList();
        if(type === 'edit_events' || type === 'edit_invasions') {
            currentType = (type === 'edit_events') ? 'event' : 'invasion';
            setTimeout(() => {
                const dynamicTitle = document.getElementById('module-title-dynamic');
                if(dynamicTitle) dynamicTitle.innerText = (currentType === 'event') ? 'Eventos' : 'Invasiones';
                fetchSchedules(); 
                const dropInput = document.getElementById('sch-drops-files');
                if(dropInput) {
                    dropInput.addEventListener('change', function() {
                        const count = this.files.length;
                        const textEl = document.getElementById('drops-preview-text');
                        if(textEl) textEl.innerText = count > 0 ? count + ' Archivos seleccionados' : '';
                    });
                }
            }, 50);
        }
    }

    function fetchNewsList() {
        fetch('get_news.php').then(r => r.json()).then(data => {
            const b = document.getElementById('news-list-body');
            if(!b) return;
            b.innerHTML = '';
            data.forEach(n => {
                b.innerHTML += `
                <tr class="border-b border-white/5 hover:bg-white/5 transition">
                    <td class="p-6 text-white font-bold text-xs uppercase">${n.title}</td>
                    <td class="p-6 text-red-500 font-bold text-[9px] uppercase tracking-tighter">${n.category}</td>
                    <td class="p-6 text-right flex justify-end gap-3">
                        <button onclick="editNews(${n.id})" class="text-gray-500 hover:text-blue-500 transition">
                            <i data-lucide="edit-3" class="w-4 h-4"></i>
                        </button>
                        <button onclick="deleteNews(${n.id})" class="text-gray-500 hover:text-red-500 transition">
                            <i data-lucide="trash-2" class="w-4 h-4"></i>
                        </button>
                    </td>
                </tr>`;
            });
            lucide.createIcons();
        });
    }

    function editNews(id) {
        fetch(`get_news_item.php?id=${id}`).then(r => r.json()).then(n => {
            loadModule('publish');
            setTimeout(() => {
                document.getElementById('newsTitle').value = n.title;
                document.getElementById('newsCategory').value = n.category;
                document.getElementById('newsImage').value = n.image_url;
                myEditor.setData(n.content);
                document.getElementById('editNewsId').value = n.id;
            }, 500);
        });
    }

    function deleteNews(id) {
        if(confirm('¿Seguro que deseas eliminar esta noticia?')) {
            fetch('delete_news.php?id='+id).then(r => r.json()).then(res => {
                if(res.status === 'success' || res) {
                    showToast("Noticia Eliminada");
                    fetchNewsList();
                }
            });
        }
    }

    function submitNews() {
        const fd = new FormData();
        const editId = document.getElementById('editNewsId').value;
        if(editId) fd.append('id', editId);
        fd.append('title', document.getElementById('newsTitle').value);
        fd.append('content', myEditor.getData());
        fd.append('category', document.getElementById('newsCategory').value);
        fd.append('image', document.getElementById('newsImage').value);
        fetch('save_news.php', { method: 'POST', body: fd }).then(() => {
            showToast(editId ? "Cambios Guardados" : "Anuncio Publicado");
            loadModule('manage');
        });
    }

    function addDownload() {
        const name = document.getElementById('dl_name').value;
        const url = document.getElementById('dl_url').value;
        if(!name || !url) return alert("Completa todos los campos");
        const fd = new FormData();
        fd.append('name', name); fd.append('url', url);
        fetch('save_download.php', { method: 'POST', body: fd })
        .then(r => r.json()).then(res => {
            if(res.status === 'success') {
                showToast("Descarga Registrada");
                fetchDownloads();
                document.getElementById('dl_name').value = '';
                document.getElementById('dl_url').value = '';
            }
        });
    }

    function fetchDownloads() {
        fetch('get_downloads.php').then(r => r.json()).then(data => {
            const b = document.getElementById('downloads-list-body');
            if(!b) return;
            b.innerHTML = '';
            data.forEach(d => {
                b.innerHTML += `
                <tr class="border-b border-white/5 hover:bg-white/5 transition">
                    <td class="p-6 text-white font-bold text-xs uppercase">${d.name}</td>
                    <td class="p-6 text-gray-500 text-[10px] italic">${d.url}</td>
                    <td class="p-6 text-right">
                        <button onclick="deleteDownload(${d.id})" class="text-gray-400 hover:text-red-500 transition">
                            <i data-lucide="x-circle" class="w-4 h-4"></i>
                        </button>
                    </td>
                </tr>`;
            });
            lucide.createIcons();
        });
    }

    function deleteDownload(id) {
        if(confirm('¿Remover este enlace?')) {
            fetch('delete_download.php?id='+id).then(() => {
                showToast("Enlace Removido");
                fetchDownloads();
            });
        }
    }

   function refreshWebConfig() {
        fetch('get_web_identity.php').then(r => r.json()).then(data => {
            if(document.getElementById('web_title')) document.getElementById('web_title').value = data.web_title || '';
            if(document.getElementById('server_version')) document.getElementById('server_version').value = data.server_version || '';
            if(document.getElementById('server_exp')) document.getElementById('server_exp').value = data.server_exp || '';
            if(document.getElementById('social_facebook')) document.getElementById('social_facebook').value = data.social_facebook || '';
            if(document.getElementById('social_discord')) document.getElementById('social_discord').value = data.social_discord || '';
            if(document.getElementById('social_youtube')) document.getElementById('social_youtube').value = data.social_youtube || '';
            
            if(data.web_logo_url) {
                const logoImg = document.getElementById('img-logo');
                if(logoImg) {
                    logoImg.src = data.web_logo_url + '?v=' + Date.now();
                    logoImg.classList.remove('hidden');
                    document.getElementById('placeholder-logo')?.classList.add('hidden');
                }
            }
            if(data.web_favicon_url) {
                const favImg = document.getElementById('img-favicon');
                if(favImg) {
                    favImg.src = data.web_favicon_url + '?v=' + Date.now();
                    favImg.classList.remove('hidden');
                    document.getElementById('placeholder-favicon')?.classList.add('hidden');
                }
            }
            if(data.web_meta_url) {
                const metaImg = document.getElementById('img-meta');
                if(metaImg) {
                    metaImg.src = data.web_meta_url + '?v=' + Date.now();
                    metaImg.classList.remove('hidden');
                    document.getElementById('placeholder-meta')?.classList.add('hidden');
                }
            }
        });
    }

    function saveWebInfo() {
        const btn = event.target.closest('button');
        const originalContent = btn.innerHTML;
        
        btn.innerHTML = '<i class="animate-spin" data-lucide="loader-2"></i> Procesando...';
        lucide.createIcons();

        const formData = new FormData();
        
        formData.append('web_title', document.getElementById('web_title').value);
        formData.append('server_version', document.getElementById('server_version').value);
        formData.append('server_exp', document.getElementById('server_exp').value);
        formData.append('social_facebook', document.getElementById('social_facebook').value);
        formData.append('social_discord', document.getElementById('social_discord').value);
        formData.append('social_youtube', document.getElementById('social_youtube').value);

        const logoInput = document.querySelector('input[name="web_logo_file"]');
        if (logoInput && logoInput.files[0]) {
            formData.append('web_logo_file', logoInput.files[0]);
        }

        fetch('save_web_identity.php', {
            method: 'POST',
            body: formData
        })
        .then(r => r.json())
        .then(data => {
            if (data.status === 'success') {
                showToast("Identidad Actualizada");
            } else {
                alert("❌ Error: " + data.message);
            }
        })
        .catch(error => console.error('Error:', error))
        .finally(() => {
            btn.innerHTML = originalContent;
            lucide.createIcons();
        });
    }

    function processAutoUpload(input, fieldName) {
        const file = input.files[0];
        if (!file) return;

        const suffix = fieldName.split('_')[1]; 
        const progressBar = document.getElementById('fill-' + suffix);
        const parentBar = document.getElementById('parent-' + suffix);
        const previewImg = document.getElementById('img-' + suffix);
        const placeholder = document.getElementById('placeholder-' + suffix);

        const formData = new FormData();
        formData.append(fieldName, file);

        if(parentBar) {
            parentBar.style.display = 'block';
            parentBar.style.opacity = '1';
        }
        if(progressBar) progressBar.style.width = '0%';

        fetch('save_web_identity.php', {
            method: 'POST',
            body: formData
        })
        .then(r => r.json())
        .then(data => {
            if (data.status === 'success') {
                if(progressBar) progressBar.style.width = '100%';
                
                const reader = new FileReader();
                reader.onload = (e) => {
                    if(previewImg) {
                        previewImg.src = e.target.result;
                        previewImg.classList.remove('hidden');
                    }
                    if(placeholder) placeholder.classList.add('hidden');
                };
                reader.readAsDataURL(file);
                showToast("Elemento Forjado");
            } else {
                alert("❌ Error: " + data.message);
            }
        })
        .finally(() => {
            setTimeout(() => {
                if(parentBar) parentBar.style.opacity = '0';
            }, 2000);
        });
    }

    function fetchRankingConfig() {
        fetch('get_ranking_config.php').then(r => r.json()).then(data => {
            const keys = ['resets','mresets','level','master','pk','gens','bc','ds','cc','it','duels'];
            keys.forEach(k => {
                if(document.getElementById('check_'+k)) document.getElementById('check_'+k).checked = data['show_'+k] == '1';
            });
        });
    }

    function saveRankingConfig() {
        const fd = new FormData();
        ['resets','mresets','level','master','pk','gens','bc','ds','cc','it','duels'].forEach(k => {
            const el = document.getElementById('check_'+k);
            if(el) fd.append('show_'+k, el.checked ? '1' : '0');
        });
        fetch('save_ranking_config.php', { method: 'POST', body: fd }).then(() => showToast("Rankings Actualizados"));
    }

    function fetchRegisterConfig() {
        fetch('get_web_identity.php').then(r => r.json()).then(data => {
            if(document.getElementById('welcome_zen')) document.getElementById('welcome_zen').value = data.welcome_zen || '0';
        });
    }

    function saveRegisterConfig() {
        const fd = new FormData();
        fd.append('welcome_zen', document.getElementById('welcome_zen').value);
        fetch('save_web_identity.php', { method: 'POST', body: fd }).then(() => showToast("Bono Sincronizado"));
    }

    function fetchCoinConfig() {
        fetch('get_coin_config.php').then(r => r.json()).then(data => {
            if(document.getElementById('coin_name')) document.getElementById('coin_name').value = data.coin_name || '';
            if(document.getElementById('coin_table')) document.getElementById('coin_table').value = data.coin_table || '';
            if(document.getElementById('coin_column')) document.getElementById('coin_column').value = data.coin_column || '';
            if(document.getElementById('coin_id_column')) document.getElementById('coin_id_column').value = data.coin_id_column || '';
            if(document.getElementById('coin_check_online')) document.getElementById('coin_check_online').checked = (data.coin_check_online === '1');
        });
    }

    function saveCoinConfig() {
        const fd = new FormData();
        fd.append('coin_name', document.getElementById('coin_name').value);
        fd.append('coin_table', document.getElementById('coin_table').value);
        fd.append('coin_column', document.getElementById('coin_column').value);
        fd.append('coin_id_column', document.getElementById('coin_id_column').value);
        fd.append('coin_check_online', document.getElementById('coin_check_online').checked ? '1' : '0');
        fetch('save_coin_config.php', { method: 'POST', body: fd })
        .then(r => r.json()).then(data => { if(data.status === 'success') showToast("Economía Actualizada"); });
    }

    function fetchMarketConfig() {
        fetch('get_market_config.php').then(r => r.json()).then(data => {
            if(document.getElementById('market_active')) document.getElementById('market_active').value = data.market_active || '0';
            if(document.getElementById('market_max_stats')) document.getElementById('market_max_stats').value = data.market_max_stats || '32767';
            if(document.getElementById('market_full_val')) document.getElementById('market_full_val').value = data.market_full_val || '1000';
            if(document.getElementById('market_reset_val')) document.getElementById('market_reset_val').value = data.market_reset_val || '10';
            if(document.getElementById('market_min_resets')) document.getElementById('market_min_resets').value = data.market_min_resets || '0';
            if(document.getElementById('market_tax')) document.getElementById('market_tax').value = data.market_tax || '0';
        });
    }

    function saveMarketConfig() {
        const fd = new FormData();
        fd.append('market_active', document.getElementById('market_active').value);
        fd.append('market_max_stats', document.getElementById('market_max_stats').value);
        fd.append('market_full_val', document.getElementById('market_full_val').value);
        fd.append('market_reset_val', document.getElementById('market_reset_val').value);
        fd.append('market_min_resets', document.getElementById('market_min_resets').value);
        fd.append('market_tax', document.getElementById('market_tax').value);
        fetch('save_market_config.php', { method: 'POST', body: fd })
        .then(r => r.json()).then(data => { if(data.status === 'success') showToast("Configuración Guardada"); });
    }
    
    function fetchPaypalConfig() {
        fetch('get_settings.php').then(r => r.json()).then(data => {
            if(document.getElementById('paypal_active')) document.getElementById('paypal_active').value = data.paypal_active || '0';
            if(document.getElementById('paypal_mode')) document.getElementById('paypal_mode').value = data.paypal_mode || 'sandbox';
            if(document.getElementById('paypal_client_id')) document.getElementById('paypal_client_id').value = data.paypal_client_id || '';
            if(document.getElementById('paypal_secret')) document.getElementById('paypal_secret').value = data.paypal_secret || '';
            if(document.getElementById('paypal_coin_rate')) document.getElementById('paypal_coin_rate').value = data.paypal_coin_rate || '10';
            if(document.getElementById('paypal_min_purchase')) document.getElementById('paypal_min_purchase').value = data.paypal_min_purchase || '1';
            if(document.getElementById('paypal_currency')) document.getElementById('paypal_currency').value = data.paypal_currency || 'USD';
        });
    }

    function savePaypalConfig() {
        const fd = new FormData();
        const fields = ['paypal_active', 'paypal_mode', 'paypal_client_id', 'paypal_secret', 'paypal_coin_rate', 'paypal_min_purchase', 'paypal_currency'];
        fields.forEach(f => {
            const el = document.getElementById(f);
            if(el) fd.append(f, el.value);
        });
        fetch('save_settings.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(data => { if(data.status === 'success') showToast("PayPal Configurado"); });
    }

    function openScheduleSlider() {
        document.getElementById('schedule-slider').classList.remove('translate-x-full');
    }

    function addTimeField() {
        const container = document.getElementById('time-inputs-container');
        const newDiv = document.createElement('div');
        newDiv.className = 'flex gap-2 animate-in slide-in-from-right-2';
        newDiv.innerHTML = `
            <input type="time" class="time-input w-full bg-white/5 border border-white/10 rounded-xl p-3 text-white focus:border-red-600 outline-none transition [color-scheme:dark]">
            <button onclick="this.parentElement.remove()" class="bg-white/5 hover:bg-red-600/20 border border-white/10 w-12 rounded-xl flex items-center justify-center transition group text-gray-500 hover:text-red-600">
                <i data-lucide="minus" class="w-4 h-4"></i>
            </button>
        `;
        container.appendChild(newDiv);
        lucide.createIcons();
    }

    function closeScheduleSlider() {
        document.getElementById('schedule-slider').classList.add('translate-x-full');
        document.getElementById('sch-name').value = '';
        document.getElementById('time-inputs-container').innerHTML = `
            <div class="flex gap-2">
                <input type="time" class="time-input w-full bg-white/5 border border-white/10 rounded-xl p-3 text-white focus:border-red-600 outline-none transition [color-scheme:dark]">
                <button onclick="addTimeField()" class="bg-white/5 hover:bg-red-600/20 border border-white/10 w-12 rounded-xl flex items-center justify-center transition group">
                    <i data-lucide="plus" class="w-4 h-4 text-gray-400 group-hover:text-red-600"></i>
                </button>
            </div>
        `;
        lucide.createIcons();
    }

    function addScheduleToList() {
        const name = document.getElementById('sch-name').value;
        const gmt = document.getElementById('sch-gmt').value;
        const imgFile = document.getElementById('sch-img').files[0];
        const description = document.getElementById('sch-description').value;
        const dropsFiles = document.getElementById('sch-drops-files').files;
        const rarity = document.getElementById('sch-rarity').value;
        const timeInputs = document.querySelectorAll('.time-input');
        let timesArray = [];
        timeInputs.forEach(input => { if(input.value) timesArray.push(input.value); });
        const timesString = timesArray.join(', ');
        if(!name || timesArray.length === 0) return showToast("Nombre y Horario obligatorios");
        const fd = new FormData();
        fd.append('type', currentType);
        fd.append('name', name);
        fd.append('times', timesString);
        fd.append('gmt', gmt);
        fd.append('description', description);
        if(imgFile) fd.append('sch_img', imgFile);
        if (dropsFiles.length > 0) {
            for (let i = 0; i < dropsFiles.length; i++) {
                fd.append('drops_images[]', dropsFiles[i]);
            }
        }
        fd.append('rarities[]', rarity); 
        fetch('save_schedules.php', { method: 'POST', body: fd })
        .then(r => r.json()).then(data => {
            if(data.status === 'success') {
                showToast("Registro Guardado");
                closeScheduleSlider();
                fetchSchedules();
            }
        });
    }

    function fetchSchedules() {
        const container = document.getElementById('schedule-list');
        if(!container) return;
        fetch('get_schedules.php?type=' + currentType).then(r => r.json()).then(data => {
            container.innerHTML = '';
            data.forEach(item => {
                const rarityClasses = { 'common': 'text-gray-500', 'excellent': 'text-green-500', 'ancient': 'text-cyan-400', 'socket': 'text-purple-500', 'boss': 'text-orange-500' };
                const firstRarity = item.drop_rarity ? item.drop_rarity.split(',')[0] : 'common';
                const colorClass = rarityClasses[firstRarity] || 'text-gray-500';
                const card = `
                <div class="bg-[#0d0d0d] border border-white/5 p-6 rounded-2xl flex items-center gap-4 hover:border-red-600/30 transition group shadow-xl">
                    <div class="w-12 h-12 bg-white/5 rounded-lg flex items-center justify-center border border-white/10 overflow-hidden">
                        ${item.image_url ? `<img src="../${item.image_url}" class="w-full h-full object-cover">` : `<i data-lucide="image" class="text-gray-700 w-5 h-5"></i>`}
                    </div>
                    <div class="flex-1">
                        <div class="flex items-center gap-2">
                            <h4 class="text-white font-bold uppercase text-[11px] tracking-widest">${item.name}</h4>
                            <span class="text-[7px] border border-current ${colorClass} px-1 rounded uppercase font-black italic">${firstRarity}</span>
                        </div>
                        <p class="text-red-500 font-mono text-[10px] mt-1">${item.times}</p>
                        <div class="text-[9px] text-gray-500 uppercase italic font-bold mt-1">${item.gmt}</div>
                    </div>
                    <button onclick="deleteSchedule(${item.id})" class="text-gray-800 hover:text-red-600 transition">
                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                    </button>
                </div>`;
                container.insertAdjacentHTML('beforeend', card);
            });
            lucide.createIcons();
        });
    }

    function deleteSchedule(id) {
        if(confirm('¿Eliminar este registro?')) {
            fetch('delete_schedule.php?id='+id).then(() => {
                showToast("Registro Eliminado");
                fetchSchedules();
            });
        }
    }

    function uploadTemplate() {
        const fileInput = document.getElementById('zip_file');
        if (!fileInput || !fileInput.files[0]) return;
        const file = fileInput.files[0];
        const fd = new FormData();
        fd.append('template_zip', file);
        const progressContainer = document.getElementById('template-progress-container');
        const progressBar = document.getElementById('template-progress-bar');
        const progressText = document.getElementById('template-progress-text');
        if(progressContainer) { 
            progressContainer.classList.remove('hidden'); 
            progressContainer.style.display = 'block'; 
        }
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'process_template.php?action=upload', true);
        xhr.upload.onprogress = function(e) {
            if (e.lengthComputable) {
                const percent = Math.round((e.loaded / e.total) * 100);
                if(progressBar) progressBar.style.width = percent + '%';
                if(progressText) progressText.innerText = percent + '% cargado...';
            }
        };
        xhr.onload = function() {
            if(progressContainer) progressContainer.style.display = 'none';
            if (xhr.status === 200) {
                const modal = document.getElementById('modal-install-confirm');
                if(modal) modal.classList.remove('hidden');
            } else {
                alert("Error al subir archivo.");
            }
        };
        xhr.send(fd);
    }

    function closeInstallModal() {
        const modal = document.getElementById('modal-install-confirm');
        if(modal) modal.classList.add('hidden');
    }

    function installTemplate() {
        closeInstallModal();
        showToast("Instalando plantilla...");
        const fd = new URLSearchParams();
        fd.append('filename', 'temp_package.zip');
        fetch('process_template.php?action=install', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: fd.toString()
        })
        .then(r => r.json())
        .then(data => {
            if (data.status === 'success') {
                showToast("Instalación Exitosa");
                setTimeout(() => loadModule('my_templates'), 1500);
            } else {
                alert("Error: " + data.message);
            }
        }).catch(() => {
            showToast("Finalizando proceso...");
            setTimeout(() => loadModule('my_templates'), 2000);
        });
    }
    
function initEditor() {
    if (document.querySelector('#editor_container')) {
        ClassicEditor.create(document.querySelector('#editor_container'))
            .then(editor => { myEditor = editor; })
            .catch(error => console.error(error));
    }
}

// Mantenemos tu lógica de loadModule
const originalLoadModule = loadModule;
loadModule = function(name) {
    originalLoadModule(name);
    if (name === 'publish_guide') {
        setTimeout(initEditor, 100);
    } else if (name === 'library_guides') {
        setTimeout(renderLibrary, 100);
    }
};

// Función para GUARDAR real en la DB
function saveGuide() {
    const title = document.getElementById('guide_title').value;
    const content = myEditor.getData();
    const category = document.getElementById('guide_category').value;
    const imgFile = document.getElementById('guide_img').files[0];

    if(!title || !content) return alert("El título y contenido son obligatorios.");

    const formData = new FormData();
    formData.append('title', title);
    formData.append('content', content);
    formData.append('category', category);
    if(imgFile) formData.append('image', imgFile);

    fetch('process_guides.php?action=save', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(data => {
            alert(data.message);
            if(data.status === 'success') loadModule('library_guides');
        });
}

// Tu función de RENDERIZADO ahora con datos reales
function renderLibrary() {
    fetch('process_guides.php?action=list')
    .then(r => r.json())
    .then(guides => {
        const container = document.getElementById('guides-container');
        const filters = document.getElementById('category-filters');
        
        // 1. Actualizar categorías únicas basadas en lo que hay en la DB
        const dbCategories = [...new Set(guides.map(g => g.category))];
        filters.innerHTML = `<button onclick="filterGuides('all')" class="filter-badge px-6 py-2 rounded-full text-[9px] font-black uppercase">Todo</button>`;
        dbCategories.forEach(cat => {
            filters.innerHTML += `<button onclick="filterGuides('${cat}')" class="filter-badge px-6 py-2 rounded-full text-[9px] font-black uppercase opacity-50 hover:opacity-100 transition">${cat}</button>`;
        });

        // 2. Renderizar las tarjetas con los datos de la DB
        container.innerHTML = ''; 
        guides.forEach(guide => {
            container.innerHTML += `
                <div class="guide-card rounded-2xl overflow-hidden group border border-red-900/20 bg-black/40">
                    <div class="h-40 relative overflow-hidden">
                        <img src="../${guide.image_path || 'assets/no-image.jpg'}" class="w-full h-full object-cover group-hover:scale-110 transition duration-700">
                        <div class="absolute inset-0 bg-gradient-to-t from-black/90 to-transparent"></div>
                        <span class="absolute top-2 left-2 bg-red-600 text-[8px] px-2 py-1 rounded font-black text-white shadow-[0_0_10px_#ff0000]">${guide.category.toUpperCase()}</span>
                    </div>
                    <div class="p-5">
                        <h3 class="text-white font-bold text-xs uppercase mb-4 tracking-wider">${guide.title}</h3>
                        <div class="flex gap-2">
                            <button onclick="editGuide(${guide.id})" class="flex-1 py-2 bg-white/5 hover:bg-white/10 text-white text-[9px] rounded uppercase font-bold transition">Editar</button>
                            <button onclick="deleteGuide(${guide.id})" class="flex-1 py-2 bg-red-900/20 hover:bg-red-600 text-white text-[9px] rounded uppercase font-bold transition">Borrar</button>
                        </div>
                    </div>
                </div>`;
        });
        lucide.createIcons();
    });
}

function deleteGuide(id) {
    if(confirm('¿Seguro que deseas eliminar este conocimiento del Códice?')) {
        fetch(`process_guides.php?action=delete&id=${id}`).then(() => renderLibrary());
    }
}
   function fetchTemplatesList() {
        fetch('process_template.php?action=list')
        .then(r => r.json()).then(data => {
            const container = document.getElementById('templates-grid');
            if(!container) return;
            container.innerHTML = '';
            data.forEach(tpl => {
                const previewUrl = `../templates/${tpl}/preview.jpg`;
                container.innerHTML += `
                <div class="bg-[#0d0d0d] border border-white/5 rounded-2xl overflow-hidden hover:border-red-600/50 transition group shadow-2xl">
                    <div class="relative h-[360px] bg-gray-900 overflow-hidden">
                        <img src="${previewUrl}" 
                             onerror="this.src='https://via.placeholder.com/400x600?text=Sin+Vista+Previa'" 
                             class="w-full h-full object-cover object-top group-hover:scale-105 transition duration-500">
                        
                        <div class="absolute inset-0 bg-gradient-to-t from-black/90 via-black/20 to-transparent"></div>
                        
                        <div class="absolute bottom-4 left-4">
                            <label class="text-[9px] text-red-600 uppercase font-black tracking-widest mb-1 block italic">Diseño Instalado</label>
                            <h3 class="text-white font-bold text-sm uppercase tracking-widest">${tpl}</h3>
                        </div>
                    </div>
                    <div class="p-4 bg-[#0d0d0d]">
                        <button onclick="activateTemplate('${tpl}')" class="w-full bg-red-600 hover:bg-red-700 text-white py-4 rounded-xl text-[10px] font-black uppercase tracking-tighter shadow-lg shadow-red-600/20 transition flex items-center justify-center gap-2">
                            <i data-lucide="check-circle" class="w-4 h-4"></i> Elegir Template
                        </button>
                    </div>
                </div>`;
            });
            lucide.createIcons();
        });
    }
    function activateTemplate(tpl) {
        fetch('process_template.php?action=activate&name=' + tpl)
        .then(r => r.json()).then(data => {
            if(data.status === 'success') showToast("Template Seleccionado");
        });
    }
    
    
</script>
</body>
</html>