<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Consola de Debug - Sistema de Errores</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Courier New', monospace;
            background: #0d1117;
            color: #c9d1d9;
            height: 100vh;
            overflow: hidden;
        }

        .header {
            background: #161b22;
            padding: 15px 20px;
            border-bottom: 1px solid #30363d;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            color: #f0f6fc;
            font-size: 18px;
        }

        .controls {
            display: flex;
            gap: 10px;
        }

        .btn {
            background: #238636;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            transition: background 0.2s;
        }

        .btn:hover {
            background: #2ea043;
        }

        .btn.danger {
            background: #da3633;
        }

        .btn.danger:hover {
            background: #f85149;
        }

        .btn.secondary {
            background: #21262d;
            border: 1px solid #30363d;
        }

        .btn.secondary:hover {
            background: #30363d;
        }

        .main-content {
            display: flex;
            height: calc(100vh - 70px);
        }

        .sidebar {
            width: 300px;
            background: #161b22;
            border-right: 1px solid #30363d;
            padding: 20px;
            overflow-y: auto;
        }

        .sidebar h3 {
            color: #f0f6fc;
            margin-bottom: 15px;
            font-size: 14px;
        }

        .log-files {
            list-style: none;
        }

        .log-files li {
            padding: 8px 12px;
            margin-bottom: 5px;
            background: #21262d;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            transition: background 0.2s;
        }

        .log-files li:hover {
            background: #30363d;
        }

        .log-files li.active {
            background: #1f6feb;
        }

        .content-area {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .tabs {
            background: #161b22;
            border-bottom: 1px solid #30363d;
            display: flex;
        }

        .tab {
            padding: 12px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            font-size: 12px;
            transition: all 0.2s;
        }

        .tab:hover {
            background: #21262d;
        }

        .tab.active {
            border-bottom-color: #1f6feb;
            color: #58a6ff;
        }

        .log-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            font-size: 12px;
            line-height: 1.5;
        }

        .log-entry {
            margin-bottom: 15px;
            padding: 12px;
            background: #0d1117;
            border: 1px solid #30363d;
            border-radius: 6px;
            border-left: 4px solid #238636;
        }

        .log-entry.error {
            border-left-color: #f85149;
        }

        .log-entry.warning {
            border-left-color: #d29922;
        }

        .log-entry.critical {
            border-left-color: #da3633;
            background: #1a0f0f;
        }

        .log-timestamp {
            color: #7d8590;
            font-size: 11px;
            margin-bottom: 5px;
        }

        .log-message {
            color: #f0f6fc;
            margin-bottom: 8px;
        }

        .log-details {
            background: #161b22;
            padding: 10px;
            border-radius: 4px;
            margin-top: 8px;
            font-size: 11px;
        }

        .log-details pre {
            white-space: pre-wrap;
            word-break: break-all;
        }

        .status-bar {
            background: #161b22;
            padding: 8px 20px;
            border-top: 1px solid #30363d;
            font-size: 11px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #238636;
        }

        .status-dot.error {
            background: #f85149;
        }

        .auto-refresh {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .filter-section {
            margin-bottom: 20px;
        }

        .filter-input {
            width: 100%;
            padding: 8px 12px;
            background: #0d1117;
            border: 1px solid #30363d;
            border-radius: 6px;
            color: #c9d1d9;
            font-size: 12px;
        }

        .filter-input:focus {
            outline: none;
            border-color: #1f6feb;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 10px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: #161b22;
            padding: 12px;
            border-radius: 6px;
            text-align: center;
            border: 1px solid #30363d;
        }

        .stat-number {
            font-size: 18px;
            font-weight: bold;
            color: #f0f6fc;
        }

        .stat-label {
            font-size: 10px;
            color: #7d8590;
            margin-top: 4px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #7d8590;
        }

        .no-logs {
            text-align: center;
            padding: 40px;
            color: #7d8590;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🚨 Consola de Debug - Sistema de Errores</h1>
        <div class="controls">
            <button class="btn" onclick="refreshLogs()">
                <i class="fas fa-sync-alt"></i> Actualizar
            </button>
            <button class="btn secondary" onclick="exportLogs()">
                <i class="fas fa-download"></i> Exportar
            </button>
            <button class="btn danger" onclick="clearLogs()">
                <i class="fas fa-trash"></i> Limpiar
            </button>
        </div>
    </div>

    <div class="main-content">
        <div class="sidebar">
            <div class="filter-section">
                <h3>Filtros</h3>
                <input type="text" class="filter-input" id="filterInput" placeholder="Filtrar logs..." onkeyup="filterLogs()">
            </div>

            <div class="stats">
                <div class="stat-card">
                    <div class="stat-number" id="totalErrors">0</div>
                    <div class="stat-label">Total Errores</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="criticalErrors">0</div>
                    <div class="stat-label">Críticos</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="recentErrors">0</div>
                    <div class="stat-label">Últimos 5min</div>
                </div>
            </div>

            <h3>Archivos de Log</h3>
            <ul class="log-files" id="logFilesList">
                <li class="loading">Cargando archivos...</li>
            </ul>
        </div>

        <div class="content-area">
            <div class="tabs">
                <div class="tab active" onclick="switchTab('live')">En Vivo</div>
                <div class="tab" onclick="switchTab('frontend')">Frontend</div>
                <div class="tab" onclick="switchTab('backend')">Backend</div>
                <div class="tab" onclick="switchTab('critical')">Críticos</div>
            </div>

            <div class="log-content" id="logContent">
                <div class="loading">Cargando logs...</div>
            </div>
        </div>
    </div>

    <div class="status-bar">
        <div class="status-indicator">
            <div class="status-dot" id="statusDot"></div>
            <span id="statusText">Conectado</span>
        </div>
        <div class="auto-refresh">
            <label>
                <input type="checkbox" id="autoRefresh" checked> Auto-actualizar
            </label>
            <span id="lastUpdate">Nunca</span>
        </div>
    </div>

    <script>
        let currentTab = 'live';
        let currentLogFile = null;
        let refreshInterval = null;
        let logs = [];

        // Inicializar
        document.addEventListener('DOMContentLoaded', function() {
            loadLogFiles();
            startAutoRefresh();
        });

        function switchTab(tab) {
            currentTab = tab;
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.querySelector(`.tab:nth-child(${getTabIndex(tab)})`).classList.add('active');
            loadLogs();
        }

        function getTabIndex(tab) {
            const tabs = ['live', 'frontend', 'backend', 'critical'];
            return tabs.indexOf(tab) + 1;
        }

        async function loadLogFiles() {
            try {
                const response = await fetch('get_log_files.php');
                const files = await response.json();
                
                const filesList = document.getElementById('logFilesList');
                filesList.innerHTML = '';
                
                if (files.length === 0) {
                    filesList.innerHTML = '<li class="no-logs">No hay archivos de log</li>';
                    return;
                }
                
                files.forEach(file => {
                    const li = document.createElement('li');
                    li.textContent = file.name;
                    li.onclick = () => selectLogFile(file.name, li);
                    filesList.appendChild(li);
                });
                
                // Seleccionar el primer archivo por defecto
                if (files.length > 0) {
                    selectLogFile(files[0].name, filesList.firstChild);
                }
                
            } catch (error) {
                console.error('Error cargando archivos de log:', error);
                document.getElementById('logFilesList').innerHTML = '<li class="error">Error cargando archivos</li>';
            }
        }

        function selectLogFile(filename, element) {
            currentLogFile = filename;
            document.querySelectorAll('.log-files li').forEach(li => li.classList.remove('active'));
            element.classList.add('active');
            loadLogs();
        }

        async function loadLogs() {
            const content = document.getElementById('logContent');
            content.innerHTML = '<div class="loading">Cargando logs...</div>';
            
            try {
                const params = new URLSearchParams({
                    tab: currentTab,
                    file: currentLogFile || ''
                });
                
                const response = await fetch(`get_logs.php?${params}`);
                const data = await response.json();
                
                logs = data.logs || [];
                displayLogs(logs);
                updateStats(data.stats || {});
                updateStatus('Conectado', false);
                
            } catch (error) {
                console.error('Error cargando logs:', error);
                content.innerHTML = '<div class="no-logs">Error cargando logs</div>';
                updateStatus('Error de conexión', true);
            }
        }

        function displayLogs(logsToShow) {
            const content = document.getElementById('logContent');
            
            if (logsToShow.length === 0) {
                content.innerHTML = '<div class="no-logs">No hay logs para mostrar</div>';
                return;
            }
            
            content.innerHTML = logsToShow.map(log => {
                const logClass = getLogClass(log);
                return `
                    <div class="log-entry ${logClass}">
                        <div class="log-timestamp">${log.timestamp}</div>
                        <div class="log-message">${escapeHtml(log.message)}</div>
                        ${log.context ? `
                            <div class="log-details">
                                <strong>Contexto:</strong>
                                <pre>${escapeHtml(JSON.stringify(log.context, null, 2))}</pre>
                            </div>
                        ` : ''}
                        ${log.stack_trace ? `
                            <div class="log-details">
                                <strong>Stack Trace:</strong>
                                <pre>${escapeHtml(log.stack_trace)}</pre>
                            </div>
                        ` : ''}
                    </div>
                `;
            }).join('');
        }

        function getLogClass(log) {
            if (log.type && log.type.toLowerCase().includes('critical')) return 'critical';
            if (log.type && log.type.toLowerCase().includes('error')) return 'error';
            if (log.type && log.type.toLowerCase().includes('warning')) return 'warning';
            return '';
        }

        function updateStats(stats) {
            document.getElementById('totalErrors').textContent = stats.total || 0;
            document.getElementById('criticalErrors').textContent = stats.critical || 0;
            document.getElementById('recentErrors').textContent = stats.recent || 0;
        }

        function updateStatus(text, isError) {
            document.getElementById('statusText').textContent = text;
            document.getElementById('statusDot').className = `status-dot ${isError ? 'error' : ''}`;
            document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString();
        }

        function filterLogs() {
            const filter = document.getElementById('filterInput').value.toLowerCase();
            const filteredLogs = logs.filter(log => 
                log.message.toLowerCase().includes(filter) ||
                (log.context && JSON.stringify(log.context).toLowerCase().includes(filter))
            );
            displayLogs(filteredLogs);
        }

        function refreshLogs() {
            loadLogs();
        }

        function startAutoRefresh() {
            const checkbox = document.getElementById('autoRefresh');
            
            function updateRefresh() {
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                    refreshInterval = null;
                }
                
                if (checkbox.checked) {
                    refreshInterval = setInterval(loadLogs, 5000); // Cada 5 segundos
                }
            }
            
            checkbox.addEventListener('change', updateRefresh);
            updateRefresh();
        }

        function exportLogs() {
            const dataStr = JSON.stringify(logs, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            const url = URL.createObjectURL(dataBlob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `debug_logs_${new Date().toISOString().slice(0,19).replace(/:/g, '-')}.json`;
            link.click();
        }

        async function clearLogs() {
            if (!confirm('¿Estás seguro de que quieres limpiar todos los logs?')) {
                return;
            }
            
            try {
                const response = await fetch('clear_logs.php', { method: 'POST' });
                const result = await response.json();
                
                if (result.success) {
                    loadLogs();
                    loadLogFiles();
                } else {
                    alert('Error limpiando logs: ' + result.message);
                }
            } catch (error) {
                alert('Error limpiando logs: ' + error.message);
            }
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>