<?php
session_start();

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: index.php');
    exit;
}

include('includes/header.php');

// Obtener estadísticas de la base de datos
try {
    $total_dns = $db->select('dns', 'COUNT(*) as count', '', '')[0]['count'];
    $total_users = $db->select('playlist', 'COUNT(*) as count', '', '')[0]['count'];
    $demo_users = $db->select('playlist', 'COUNT(*) as count', 'is_demo = 1', '')[0]['count'];
    $client_users = $db->select('playlist', 'COUNT(*) as count', 'is_demo = 0', '')[0]['count'];
    
    // Obtener usuarios recientes (últimos 10)
    $recent_users = $db->select('playlist', '*', '', '', [], 'ORDER BY last_used DESC LIMIT 10');
    
    // Obtener servidores DNS
    $dns_servers = $db->select('dns', '*', '', '');
    
    // Obtener configuración APK
    $apk_config = $db->select('apk_update', '*', '', '', [], 'ORDER BY id DESC LIMIT 1');
    $current_apk = !empty($apk_config) ? $apk_config[0] : null;
    
    // Obtener configuración TMDB
    $settings = $db->select('settings', '*', '', '');
    $tmdb_configured = !empty($settings) && !empty($settings[0]['tmdb_key']);
    
    // Crear array de títulos DNS para mapear IDs
    $dnsTitles = [];
    foreach($dns_servers as $dns) {
        $dnsTitles[$dns['id']] = $dns['title'];
    }
    
} catch (Exception $e) {
    $total_dns = 0;
    $total_users = 0;
    $demo_users = 0;
    $client_users = 0;
    $recent_users = [];
    $dns_servers = [];
    $current_apk = null;
    $tmdb_configured = false;
    $dnsTitles = [];
}

// Calcular porcentajes para gráficos
$demo_percentage = $total_users > 0 ? round(($demo_users / $total_users) * 100, 1) : 0;
$client_percentage = $total_users > 0 ? round(($client_users / $total_users) * 100, 1) : 0;
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <base target="_self">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Dashboard - Rgvip 4K Plus Panel</title>
    <meta name="description" content="Panel de control principal para gestión de usuarios y servidores DNS">
    
    <!-- CSS optimizado para móviles -->
    <style>
        /* Variables CSS mejoradas */
        :root {
            --neon-purple: #bc13fe;
            --neon-blue: #00fff0;
            --neon-pink: #ff44cc;
            --neon-green: #00ff41;
            --dark-bg: #0a0a1a;
            --darker-bg: #050510;
            --card-bg: rgba(15, 5, 30, 0.95);
            --border-color: rgba(188, 19, 254, 0.3);
            --text-primary: #ffffff;
            --text-secondary: #e0e0e0;
            --text-muted: #a0a0a0;
        }
        
        /* Reset y base móvil */
        * {
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            font-size: 14px;
            line-height: 1.4;
            overflow-x: hidden;
        }
        
        /* Contenedor principal móvil */
        .container-fluid {
            padding: 0.75rem;
            max-width: 100vw;
        }
        
        /* Título responsivo */
        .dashboard-title {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
            text-align: center;
        }
        
        .dashboard-subtitle {
            font-size: 0.8rem;
            text-align: center;
            margin-bottom: 1rem;
            color: var(--text-muted);
        }
        
        /* Tarjetas de estadísticas móviles */
        .dashboard-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(188, 19, 254, 0.15);
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            margin-bottom: 1rem;
            overflow: hidden;
        }
        
        .dashboard-card:active {
            transform: scale(0.98);
            box-shadow: 0 2px 10px rgba(188, 19, 254, 0.3);
        }
        
        /* Estadísticas compactas para móvil */
        .stat-card-mobile {
            padding: 1rem;
            text-align: center;
            position: relative;
        }
        
        .stat-icon-mobile {
            font-size: 1.8rem;
            margin-bottom: 0.5rem;
            display: block;
        }
        
        .stat-number-mobile {
            font-size: 1.8rem;
            font-weight: bold;
            color: var(--neon-purple);
            text-shadow: 0 0 8px rgba(188, 19, 254, 0.6);
            display: block;
            margin-bottom: 0.25rem;
        }
        
        .stat-label-mobile {
            color: var(--text-secondary);
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-weight: 500;
        }
        
        /* Grid responsivo para estadísticas */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 0.75rem;
            margin-bottom: 1.5rem;
        }
        
        @media (min-width: 576px) {
            .stats-grid {
                grid-template-columns: repeat(4, 1fr);
            }
        }
        
        /* Sección colapsible móvil */
        .collapsible-section {
            margin-bottom: 1rem;
        }
        
        .section-header {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 0.75rem 1rem;
            cursor: pointer;
            display: flex;
            justify-content: between;
            align-items: center;
            transition: all 0.3s ease;
            user-select: none;
        }
        
        .section-header:active {
            background: rgba(188, 19, 254, 0.1);
        }
        
        .section-header h6 {
            margin: 0;
            color: var(--neon-blue);
            font-size: 0.9rem;
            font-weight: 600;
            flex: 1;
        }
        
        .section-toggle {
            color: var(--neon-purple);
            font-size: 1rem;
            transition: transform 0.3s ease;
        }
        
        .section-toggle.rotated {
            transform: rotate(180deg);
        }
        
        .section-content {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-top: none;
            border-radius: 0 0 8px 8px;
        }
        
        .section-content.expanded {
            max-height: 1000px;
            padding: 1rem;
        }
        
        /* Progreso móvil */
        .progress-mobile {
            background-color: rgba(0, 0, 0, 0.4);
            border-radius: 10px;
            height: 8px;
            margin-bottom: 1rem;
            overflow: hidden;
        }
        
        .progress-bar-mobile {
            height: 100%;
            border-radius: 10px;
            transition: width 0.5s ease;
            position: relative;
        }
        
        .progress-demo {
            background: linear-gradient(90deg, #ff6b35, #f7931e);
            box-shadow: 0 0 8px rgba(255, 107, 53, 0.5);
        }
        
        .progress-client {
            background: linear-gradient(90deg, var(--neon-green), #00d4aa);
            box-shadow: 0 0 8px rgba(0, 255, 65, 0.5);
        }
        
        /* Acciones rápidas móviles */
        .quick-actions-mobile {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 0.5rem;
            margin-bottom: 1.5rem;
        }
        
        .quick-action-mobile {
            background: rgba(188, 19, 254, 0.1);
            border: 1px solid rgba(188, 19, 254, 0.4);
            color: var(--neon-purple);
            text-decoration: none;
            padding: 0.75rem 0.5rem;
            border-radius: 8px;
            text-align: center;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            min-height: 70px;
            justify-content: center;
        }
        
        .quick-action-mobile:hover,
        .quick-action-mobile:active {
            background: rgba(188, 19, 254, 0.2);
            color: white;
            text-decoration: none;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(188, 19, 254, 0.4);
        }
        
        .quick-action-mobile i {
            font-size: 1.2rem;
            margin-bottom: 0.25rem;
            color: var(--neon-blue);
        }
        
        .quick-action-mobile small {
            font-size: 0.7rem;
            line-height: 1.2;
            font-weight: 500;
        }
        
        /* Tabla móvil responsiva */
        .table-mobile {
            width: 100%;
            font-size: 0.75rem;
            background: transparent;
        }
        
        .table-mobile th,
        .table-mobile td {
            padding: 0.5rem 0.25rem;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }
        
        .table-mobile th {
            background: linear-gradient(90deg, rgba(188, 19, 254, 0.2), rgba(0, 255, 252, 0.2));
            color: var(--neon-blue);
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .table-mobile td {
            color: var(--text-secondary);
        }
        
        /* Ocultar columnas en móvil */
        @media (max-width: 767px) {
            .hide-mobile {
                display: none;
            }
            
            .table-mobile td:first-child,
            .table-mobile th:first-child {
                padding-left: 0.5rem;
            }
            
            .table-mobile td:last-child,
            .table-mobile th:last-child {
                padding-right: 0.5rem;
            }
        }
        
        /* Badges móviles */
        .badge-mobile {
            font-size: 0.65rem;
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .badge-demo-mobile {
            background: linear-gradient(45deg, #ff6b35, #f7931e);
            color: white;
            box-shadow: 0 0 6px rgba(255, 107, 53, 0.4);
        }
        
        .badge-client-mobile {
            background: linear-gradient(45deg, #00ff41, #00d4aa);
            color: #000;
            box-shadow: 0 0 6px rgba(0, 255, 65, 0.4);
        }
        
        /* Estado del sistema móvil */
        .status-item-mobile {
            display: flex;
            align-items: center;
            padding: 0.5rem 0;
            border-bottom: 1px solid rgba(188, 19, 254, 0.1);
        }
        
        .status-item-mobile:last-child {
            border-bottom: none;
        }
        
        .status-indicator-mobile {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 0.75rem;
            flex-shrink: 0;
        }
        
        .status-online-mobile {
            background: var(--neon-green);
            box-shadow: 0 0 6px var(--neon-green);
        }
        
        .status-offline-mobile {
            background: #ff4444;
            box-shadow: 0 0 6px #ff4444;
        }
        
        .status-text-mobile {
            flex: 1;
            font-size: 0.8rem;
        }
        
        .status-label-mobile {
            font-weight: 600;
            color: var(--text-primary);
        }
        
        .status-value-mobile {
            color: var(--text-muted);
            margin-left: 0.5rem;
        }
        
        /* DNS servers móvil */
        .dns-item-mobile {
            background: rgba(188, 19, 254, 0.08);
            border-radius: 6px;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
            border-left: 3px solid var(--neon-purple);
        }
        
        .dns-title-mobile {
            font-weight: 600;
            color: var(--text-primary);
            font-size: 0.8rem;
            margin-bottom: 0.25rem;
        }
        
        .dns-url-mobile {
            font-size: 0.7rem;
            color: var(--text-muted);
            word-break: break-all;
        }
        
        /* Información del sistema móvil */
        .system-info-mobile {
            display: grid;
            grid-template-columns: 1fr;
            gap: 0.75rem;
        }
        
        @media (min-width: 576px) {
            .system-info-mobile {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        .info-item-mobile {
            text-align: center;
            padding: 0.75rem;
            background: rgba(188, 19, 254, 0.05);
            border-radius: 6px;
            border: 1px solid rgba(188, 19, 254, 0.2);
        }
        
        .info-label-mobile {
            font-size: 0.7rem;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 0.25rem;
        }
        
        .info-value-mobile {
            font-size: 0.8rem;
            color: var(--text-primary);
            font-weight: 600;
        }
        
        /* Animaciones móviles optimizadas */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .animate-in {
            animation: fadeInUp 0.5s ease forwards;
        }
        
        /* Mejoras de rendimiento móvil */
        .dashboard-card,
        .quick-action-mobile,
        .section-header {
            will-change: transform;
        }
        
        /* Scroll suave */
        html {
            scroll-behavior: smooth;
        }
        
        /* Mejoras de accesibilidad táctil */
        .quick-action-mobile,
        .section-header {
            min-height: 44px;
            touch-action: manipulation;
        }
        
        /* Responsive breakpoints adicionales */
        @media (min-width: 768px) {
            .container-fluid {
                padding: 1.5rem;
            }
            
            .dashboard-title {
                font-size: 2rem;
            }
            
            .stats-grid {
                gap: 1rem;
            }
            
            .quick-actions-mobile {
                grid-template-columns: repeat(6, 1fr);
            }
        }
        
        @media (min-width: 992px) {
            .quick-actions-mobile {
                grid-template-columns: repeat(6, 1fr);
                gap: 1rem;
            }
            
            .quick-action-mobile {
                min-height: 80px;
                padding: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <!-- Título del Dashboard -->
        <div class="dashboard-title neon-purple">
            <i class="fa fa-tachometer"></i> Dashboard
        </div>
        <div class="dashboard-subtitle">
            Panel de control y estadísticas del sistema
        </div>

        <!-- Tarjetas de Estadísticas -->
        <div class="stats-grid">
            <div class="dashboard-card stat-card-mobile animate-in">
                <i class="fa fa-server stat-icon-mobile" style="color: var(--neon-blue);"></i>
                <div class="stat-number-mobile"><?= $total_dns ?></div>
                <div class="stat-label-mobile">DNS</div>
            </div>
            
            <div class="dashboard-card stat-card-mobile animate-in" style="animation-delay: 0.1s;">
                <i class="fa fa-users stat-icon-mobile" style="color: var(--neon-green);"></i>
                <div class="stat-number-mobile"><?= $total_users ?></div>
                <div class="stat-label-mobile">Usuarios</div>
            </div>
            
            <div class="dashboard-card stat-card-mobile animate-in" style="animation-delay: 0.2s;">
                <i class="fa fa-bolt stat-icon-mobile" style="color: #ff6b35;"></i>
                <div class="stat-number-mobile"><?= $demo_users ?></div>
                <div class="stat-label-mobile">Demos</div>
            </div>
            
            <div class="dashboard-card stat-card-mobile animate-in" style="animation-delay: 0.3s;">
                <i class="fa fa-check-circle stat-icon-mobile" style="color: var(--neon-green);"></i>
                <div class="stat-number-mobile"><?= $client_users ?></div>
                <div class="stat-label-mobile">Clientes</div>
            </div>
        </div>

        <!-- Acciones Rápidas -->
        <div class="quick-actions-mobile">
            <a href="actusers.php" class="quick-action-mobile">
                <i class="fa fa-user-plus"></i>
                <small>Agregar Usuario</small>
            </a>
            <a href="dns.php" class="quick-action-mobile">
                <i class="fa fa-server"></i>
                <small>DNS</small>
            </a>
            <a href="demo_rgvip.php" class="quick-action-mobile">
                <i class="fa fa-bolt"></i>
                <small>Demo</small>
            </a>
            <a href="generar_codes.php" class="quick-action-mobile">
                <i class="fa fa-key"></i>
                <small>Códigos</small>
            </a>
            <a href="apk_manage.php" class="quick-action-mobile">
                <i class="fa fa-android"></i>
                <small>APK</small>
            </a>
            <a href="user.php" class="quick-action-mobile">
                <i class="fa fa-user"></i>
                <small>Perfil</small>
            </a>
        </div>

        <!-- Distribución de Usuarios (Colapsible) -->
        <div class="collapsible-section">
            <div class="section-header" onclick="toggleSection('distribution')">
                <h6><i class="fa fa-pie-chart"></i> Distribución de Usuarios</h6>
                <i class="fa fa-chevron-down section-toggle" id="distribution-toggle"></i>
            </div>
            <div class="section-content" id="distribution-content">
                <div style="margin-bottom: 1rem;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem; font-size: 0.8rem;">
                        <span>Usuarios Demo</span>
                        <span><?= $demo_percentage ?>%</span>
                    </div>
                    <div class="progress-mobile">
                        <div class="progress-bar-mobile progress-demo" style="width: <?= $demo_percentage ?>%;"></div>
                    </div>
                </div>
                
                <div>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem; font-size: 0.8rem;">
                        <span>Clientes Finales</span>
                        <span><?= $client_percentage ?>%</span>
                    </div>
                    <div class="progress-mobile">
                        <div class="progress-bar-mobile progress-client" style="width: <?= $client_percentage ?>%;"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Estado del Sistema (Colapsible) -->
        <div class="collapsible-section">
            <div class="section-header" onclick="toggleSection('system')">
                <h6><i class="fa fa-cogs"></i> Estado del Sistema</h6>
                <i class="fa fa-chevron-down section-toggle" id="system-toggle"></i>
            </div>
            <div class="section-content" id="system-content">
                <div class="status-item-mobile">
                    <div class="status-indicator-mobile status-online-mobile"></div>
                    <div class="status-text-mobile">
                        <span class="status-label-mobile">Base de Datos:</span>
                        <span class="status-value-mobile">Conectada</span>
                    </div>
                </div>
                <div class="status-item-mobile">
                    <div class="status-indicator-mobile <?= $tmdb_configured ? 'status-online-mobile' : 'status-offline-mobile' ?>"></div>
                    <div class="status-text-mobile">
                        <span class="status-label-mobile">TMDB API:</span>
                        <span class="status-value-mobile"><?= $tmdb_configured ? 'Configurada' : 'No configurada' ?></span>
                    </div>
                </div>
                <div class="status-item-mobile">
                    <div class="status-indicator-mobile <?= $current_apk ? 'status-online-mobile' : 'status-offline-mobile' ?>"></div>
                    <div class="status-text-mobile">
                        <span class="status-label-mobile">APK Update:</span>
                        <span class="status-value-mobile"><?= $current_apk ? 'v' . $current_apk['version'] : 'No configurada' ?></span>
                    </div>
                </div>
                <div class="status-item-mobile">
                    <div class="status-indicator-mobile status-online-mobile"></div>
                    <div class="status-text-mobile">
                        <span class="status-label-mobile">Servidores DNS:</span>
                        <span class="status-value-mobile"><?= $total_dns ?> activos</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Usuarios Recientes (Colapsible) -->
        <div class="collapsible-section">
            <div class="section-header" onclick="toggleSection('users')">
                <h6><i class="fa fa-clock-o"></i> Usuarios Recientes</h6>
                <i class="fa fa-chevron-down section-toggle" id="users-toggle"></i>
            </div>
            <div class="section-content" id="users-content">
                <div style="overflow-x: auto;">
                    <table class="table-mobile">
                        <thead>
                            <tr>
                                <th>DNS</th>
                                <th class="hide-mobile">MAC</th>
                                <th>Usuario</th>
                                <th>Tipo</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($recent_users)): ?>
                                <?php foreach (array_slice($recent_users, 0, 5) as $user): ?>
                                    <tr>
                                        <td style="font-size: 0.7rem;"><?= substr($dnsTitles[$user['dns_id']] ?? 'Unknown', 0, 10) ?></td>
                                        <td class="hide-mobile" style="font-family: monospace; font-size: 0.65rem;"><?= substr($user['mac_address'], -8) ?></td>
                                        <td style="font-size: 0.7rem;"><?= substr(htmlspecialchars($user['username']), 0, 12) ?></td>
                                        <td>
                                            <?php if ($user['is_demo']): ?>
                                                <span class="badge-mobile badge-demo-mobile">Demo</span>
                                            <?php else: ?>
                                                <span class="badge-mobile badge-client-mobile">Cliente</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" style="text-align: center; color: var(--text-muted); font-size: 0.8rem;">No hay usuarios</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <div style="text-align: center; margin-top: 1rem;">
                    <a href="actusers.php" class="quick-action-mobile" style="display: inline-flex; width: auto; padding: 0.5rem 1rem;">
                        Ver todos <i class="fa fa-arrow-right" style="margin-left: 0.5rem;"></i>
                    </a>
                </div>
            </div>
        </div>

        <!-- Servidores DNS (Colapsible) -->
        <div class="collapsible-section">
            <div class="section-header" onclick="toggleSection('dns')">
                <h6><i class="fa fa-server"></i> Servidores DNS</h6>
                <i class="fa fa-chevron-down section-toggle" id="dns-toggle"></i>
            </div>
            <div class="section-content" id="dns-content">
                <?php if (!empty($dns_servers)): ?>
                    <?php foreach ($dns_servers as $dns): ?>
                        <div class="dns-item-mobile">
                            <div class="dns-title-mobile"><?= htmlspecialchars($dns['title']) ?></div>
                            <div class="dns-url-mobile"><?= htmlspecialchars($dns['url']) ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p style="text-align: center; color: var(--text-muted); font-size: 0.8rem;">No hay servidores DNS configurados</p>
                <?php endif; ?>
                
                <div style="text-align: center; margin-top: 1rem;">
                    <a href="dns.php" class="quick-action-mobile" style="display: inline-flex; width: auto; padding: 0.5rem 1rem;">
                        Gestionar DNS <i class="fa fa-cog" style="margin-left: 0.5rem;"></i>
                    </a>
                </div>
            </div>
        </div>

        <!-- Información del Sistema -->
        <div class="collapsible-section">
            <div class="section-header" onclick="toggleSection('info')">
                <h6><i class="fa fa-info-circle"></i> Información del Sistema</h6>
                <i class="fa fa-chevron-down section-toggle" id="info-toggle"></i>
            </div>
            <div class="section-content" id="info-content">
                <div class="system-info-mobile">
                    <div class="info-item-mobile">
                        <div class="info-label-mobile">Versión</div>
                        <div class="info-value-mobile">Rgvip 4K Plus v2.0</div>
                    </div>
                    <div class="info-item-mobile">
                        <div class="info-label-mobile">Base de Datos</div>
                        <div class="info-value-mobile">SQLite</div>
                    </div>
                    <div class="info-item-mobile">
                        <div class="info-label-mobile">Actualización</div>
                        <div class="info-value-mobile"><?= date('d/m/Y') ?></div>
                    </div>
                    <div class="info-item-mobile">
                        <div class="info-label-mobile">Usuario</div>
                        <div class="info-value-mobile"><?= htmlspecialchars($loggedinuser ?? 'Admin') ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts optimizados para móvil -->
    <script>
        // Variables globales
        let expandedSections = new Set();
        
        // Función para alternar secciones
        function toggleSection(sectionId) {
            const content = document.getElementById(sectionId + '-content');
            const toggle = document.getElementById(sectionId + '-toggle');
            
            if (expandedSections.has(sectionId)) {
                // Colapsar
                content.classList.remove('expanded');
                toggle.classList.remove('rotated');
                expandedSections.delete(sectionId);
                
                // Guardar estado en localStorage
                localStorage.setItem('expandedSections', JSON.stringify([...expandedSections]));
            } else {
                // Expandir
                content.classList.add('expanded');
                toggle.classList.add('rotated');
                expandedSections.add(sectionId);
                
                // Guardar estado en localStorage
                localStorage.setItem('expandedSections', JSON.stringify([...expandedSections]));
            }
        }
        
        // Restaurar estado de secciones al cargar
        document.addEventListener('DOMContentLoaded', function() {
            // Restaurar secciones expandidas
            const saved = localStorage.getItem('expandedSections');
            if (saved) {
                try {
                    const savedSections = JSON.parse(saved);
                    savedSections.forEach(sectionId => {
                        const content = document.getElementById(sectionId + '-content');
                        const toggle = document.getElementById(sectionId + '-toggle');
                        if (content && toggle) {
                            content.classList.add('expanded');
                            toggle.classList.add('rotated');
                            expandedSections.add(sectionId);
                        }
                    });
                } catch (e) {
                    console.log('Error restaurando estado de secciones');
                }
            }
            
            // Animación de números
            animateNumbers();
            
            // Animación de barras de progreso
            animateProgressBars();
            
            // Configurar actualización automática (solo en WiFi para ahorrar datos)
            if (navigator.connection && navigator.connection.type === 'wifi') {
                setInterval(updateStats, 60000); // Cada minuto en WiFi
            }
            
            // Optimización de rendimiento: lazy loading para elementos no visibles
            if ('IntersectionObserver' in window) {
                setupLazyLoading();
            }
        });
        
        // Animación de números optimizada
        function animateNumbers() {
            const numbers = document.querySelectorAll('.stat-number-mobile');
            numbers.forEach((number, index) => {
                const finalValue = parseInt(number.textContent);
                if (finalValue === 0) return;
                
                let currentValue = 0;
                const increment = Math.max(1, Math.ceil(finalValue / 20));
                
                const timer = setInterval(() => {
                    currentValue += increment;
                    if (currentValue >= finalValue) {
                        number.textContent = finalValue;
                        clearInterval(timer);
                    } else {
                        number.textContent = currentValue;
                    }
                }, 50 + (index * 10)); // Escalonar animaciones
            });
        }
        
        // Animación de barras de progreso
        function animateProgressBars() {
            const progressBars = document.querySelectorAll('.progress-bar-mobile');
            progressBars.forEach((bar, index) => {
                const width = bar.style.width;
                bar.style.width = '0%';
                
                setTimeout(() => {
                    bar.style.width = width;
                }, 500 + (index * 200));
            });
        }
        
        // Actualización de estadísticas (solo elementos críticos)
        function updateStats() {
            // Implementar actualización AJAX ligera aquí si es necesario
            console.log('Actualizando estadísticas...');
        }
        
        // Lazy loading para optimizar rendimiento
        function setupLazyLoading() {
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('animate-in');
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.1,
                rootMargin: '50px'
            });
            
            document.querySelectorAll('.dashboard-card').forEach(card => {
                observer.observe(card);
            });
        }
        
        // Optimización táctil: prevenir zoom accidental
        let lastTouchEnd = 0;
        document.addEventListener('touchend', function (event) {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);
        
        // Gestión de orientación de pantalla
        window.addEventListener('orientationchange', function() {
            setTimeout(() => {
                // Recalcular layouts si es necesario
                window.scrollTo(0, 0);
            }, 100);
        });
        
        // Optimización de memoria: limpiar timers al salir
        window.addEventListener('beforeunload', function() {
            // Limpiar cualquier timer activo
        });
    </script>
</body>
</html>

<?php include('includes/footer.php'); ?>