@page
@model IndexModel
@{
    ViewData["Title"] = "EonaCat LogCentral";
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EonaCat LogCentral</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg: #f8fafc;
            --card: #ffffff;
            --border: #e5e7eb;
            --text: #0f172a;
            --muted: #64748b;
            --primary: #2563eb;
            --primary-soft: #dbeafe;
            --danger: #ef4444;
            --warning: #f59e0b;
            --success: #10b981;
            --radius: 1rem;
            --shadow-soft: 0 10px 25px -10px rgba(0,0,0,.15);
            --shadow-hover: 0 20px 35px -15px rgba(0,0,0,.25);
        }

        * {
            font-family: 'Inter', sans-serif;
        }

        .log-trace {
            background: linear-gradient(to right, #f3f4f6 0%, #f9fafb 100%);
            border-left: 4px solid #9ca3af;
        }

        .log-debug {
            background: linear-gradient(to right, #dbeafe 0%, #eff6ff 100%);
            border-left: 4px solid #3b82f6;
        }

        .log-info {
            background: linear-gradient(to right, #d1fae5 0%, #ecfdf5 100%);
            border-left: 4px solid #10b981;
        }

        .log-warning {
            background: linear-gradient(to right, #fef3c7 0%, #fffbeb 100%);
            border-left: 4px solid #f59e0b;
        }

        .log-error {
            background: linear-gradient(to right, #fee2e2 0%, #fef2f2 100%);
            border-left: 4px solid #ef4444;
        }

        .log-critical {
            background: linear-gradient(to right, #fae8ff 0%, #fdf4ff 100%);
            border-left: 4px solid #a855f7;
        }

        .log-security {
            background: linear-gradient(to right, #fed7aa 0%, #ffedd5 100%);
            border-left: 4px solid #f97316;
        }

        .log-analytics {
            background: linear-gradient(to right, #ccfbf1 0%, #f0fdfa 100%);
            border-left: 4px solid #14b8a6;
        }

        .stat-card {
            transition: all 0.3s ease;
        }

            .stat-card:hover {
                transform: translateY(-4px);
                box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1);
            }

        .tab-btn {
            padding: .5rem 1rem;
            border-radius: .75rem;
            font-weight: 600;
            color: #475569;
            transition: all .2s ease;
        }

            .tab-btn:hover {
                background: white;
            }

            .tab-btn.active {
                background: white;
                color: var(--primary);
                box-shadow: var(--shadow-soft);
            }

        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        @@keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .pulse-dot {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        @@keyframes pulse {
            0%, 100% {
                opacity: 1;
            }

            50% {
                opacity: 0.5;
            }
        }

        .log-entry {
            transition: all 0.2s;
            cursor: pointer;
        }

            .log-entry:hover {
                transform: translateX(4px);
                box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
            }

        .badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .search-highlight {
            background-color: #fef08a;
            padding: 2px 4px;
            border-radius: 2px;
        }

        .tooltip {
            position: relative;
        }

            .tooltip:hover::after {
                content: attr(data-tooltip);
                position: absolute;
                bottom: 100%;
                left: 50%;
                transform: translateX(-50%);
                background: #1f2937;
                color: white;
                padding: 0.5rem;
                border-radius: 0.375rem;
                font-size: 0.75rem;
                white-space: nowrap;
                z-index: 50;
            }

        .filter-chip {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.25rem 0.75rem;
            background: #3b82f6;
            color: white;
            border-radius: 9999px;
            font-size: 0.875rem;
        }

        .spinner {
            border: 3px solid #f3f4f6;
            border-top: 3px solid #3b82f6;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        @@keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .log-entry {
            background: white;
            border-radius: var(--radius);
            padding: 1rem;
            border: 1px solid var(--border);
            transition: all .2s ease;
        }

            .log-entry:hover {
                transform: translateY(-2px);
                box-shadow: var(--shadow-soft);
            }
    </style>
</head>
<body class="bg-[var(--bg)] text-[var(--text)]">
    <div class="min-h-screen">
        <!-- Enhanced Header -->
        <header class="sticky top-0 z-40 backdrop-blur-xl bg-white/70 border-b border-gray-200">
            <div class="container mx-auto px-6 py-4 flex items-center justify-between">
                <div class="flex items-center gap-4">
                    <div class="w-11 h-11 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-600 flex items-center justify-center shadow-lg">
                        <i class="fas fa-database text-white text-lg"></i>
                    </div>
                    <div>
                        <h1 class="text-xl font-bold tracking-tight">EonaCat LogCentral</h1>
                        <p class="text-xs text-gray-500">Logging all the things!</p>
                    </div>
                </div>

                <nav class="flex gap-1 bg-gray-100 p-1 rounded-xl">
                    <button class="tab-btn active" onclick="showTab('dashboard')">Dashboard</button>
                    <button class="tab-btn" onclick="showTab('logs')">Logs</button>
                    <button class="tab-btn" onclick="showTab('analytics')">Analytics</button>
                    <button class="tab-btn" onclick="showTab('search')">Search</button>
                </nav>
            </div>
        </header>

        <div class="container mx-auto px-6 py-8">
            <!-- Dashboard Tab -->
            <div id="dashboard-tab" class="tab-content fade-in">
                <!-- Enhanced Stats Cards -->
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                    <div class="stat-card bg-white rounded-xl shadow-lg p-6 border-l-4 border-blue-500">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-gray-500 text-sm font-semibold uppercase tracking-wide">Total Logs</p>
                                <p id="stat-total" class="text-4xl font-bold text-gray-800 mt-2">0</p>
                            </div>
                            <div class="bg-gradient-to-br from-blue-400 to-blue-600 rounded-2xl p-4 shadow-lg">
                                <i class="fas fa-database text-white text-2xl"></i>
                            </div>
                        </div>
                        <div class="flex items-center justify-between text-sm">
                            <span class="text-green-600 font-semibold">
                                <i class="fas fa-arrow-up mr-1"></i><span id="stat-last24h">0</span> today
                            </span>
                            <span class="text-gray-500"><span id="stat-lasthour">0</span> last hour</span>
                        </div>
                    </div>

                    <div class="stat-card bg-white rounded-xl shadow-lg p-6 border-l-4 border-red-500">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-gray-500 text-sm font-semibold uppercase tracking-wide">Errors</p>
                                <p id="stat-errors" class="text-4xl font-bold text-red-600 mt-2">0</p>
                            </div>
                            <div class="bg-gradient-to-br from-red-400 to-red-600 rounded-2xl p-4 shadow-lg">
                                <i class="fas fa-exclamation-triangle text-white text-2xl"></i>
                            </div>
                        </div>
                        <div class="flex items-center justify-between text-sm">
                            <span class="text-red-600 font-semibold">
                                <i class="fas fa-times-circle mr-1"></i><span id="stat-critical">0</span> critical
                            </span>
                            <span class="text-orange-600"><span id="stat-security">0</span> security</span>
                        </div>
                    </div>

                    <div class="stat-card bg-white rounded-xl shadow-lg p-6 border-l-4 border-yellow-500">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-gray-500 text-sm font-semibold uppercase tracking-wide">Warnings</p>
                                <p id="stat-warnings" class="text-4xl font-bold text-yellow-600 mt-2">0</p>
                            </div>
                            <div class="bg-gradient-to-br from-yellow-400 to-yellow-600 rounded-2xl p-4 shadow-lg">
                                <i class="fas fa-exclamation-circle text-white text-2xl"></i>
                            </div>
                        </div>
                        <p class="text-gray-500 text-sm">Requires attention</p>
                    </div>

                    <div class="stat-card bg-white rounded-xl shadow-lg p-6 border-l-4 border-purple-500">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-gray-500 text-sm font-semibold uppercase tracking-wide">Applications</p>
                                <p id="stat-apps" class="text-4xl font-bold text-purple-600 mt-2">0</p>
                            </div>
                            <div class="bg-gradient-to-br from-purple-400 to-purple-600 rounded-2xl p-4 shadow-lg">
                                <i class="fas fa-server text-white text-2xl"></i>
                            </div>
                        </div>
                        <p class="text-gray-500 text-sm">Active services</p>
                    </div>
                </div>

                <!-- Charts Row -->
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
                    <div class="lg:col-span-2 bg-white rounded-xl shadow-lg p-6">
                        <div class="flex items-center justify-between mb-6">
                            <h3 class="text-xl font-bold text-gray-800">
                                <i class="fas fa-chart-area text-blue-600 mr-2"></i>Log Trends (24 Hours)
                            </h3>
                            <select id="trend-period" onchange="changeTrendPeriod()" class="px-3 py-1 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500">
                                <option value="6">Last 6 Hours</option>
                                <option value="24" selected>Last 24 Hours</option>
                                <option value="72">Last 3 Days</option>
                                <option value="168">Last Week</option>
                            </select>
                        </div>
                        <div class="lg:col-span-2 bg-white rounded-xl shadow-lg p-6">
                            <div class="relative h-[320px]">
                                <canvas id="trendChart"></canvas>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-xl shadow-lg p-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-6">
                            <i class="fas fa-layer-group text-green-600 mr-2"></i>By Level
                        </h3>
                        <canvas id="levelChart"></canvas>
                    </div>
                </div>

                <!-- Top Applications & Recent Critical Events -->
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="bg-white rounded-xl shadow-lg p-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-6">
                            <i class="fas fa-fire text-orange-600 mr-2"></i>Top Applications (24h)
                        </h3>
                        <div id="top-apps" class="space-y-3"></div>
                    </div>

                    <div class="bg-white rounded-xl shadow-lg p-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-6">
                            <i class="fas fa-bolt text-red-600 mr-2"></i>Recent Critical Events
                        </h3>
                        <div id="recent-errors" class="space-y-3 max-h-96 overflow-y-auto"></div>
                    </div>
                </div>
            </div>

            <!-- Logs Tab -->
            <div id="logs-tab" class="tab-content hidden">
                <!-- Advanced Filters -->
                <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-filter text-blue-600 mr-2"></i>Filters
                        </h3>
                        <button onclick="clearFilters()" class="text-sm text-gray-600 hover:text-gray-800">
                            <i class="fas fa-times-circle mr-1"></i>Clear All
                        </button>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                        <div class="relative">
                            <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                            <input type="text" id="filter-search" placeholder="Search logs..."
                                   class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        </div>

                        <select id="filter-app" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            <option value="">All Applications</option>
                        </select>

                        <select id="filter-env" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            <option value="">All Environments</option>
                        </select>

                        <select id="filter-level" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            <option value="">All Levels</option>
                            <option value="0">🔍 Trace</option>
                            <option value="1">🐛 Debug</option>
                            <option value="2">ℹ️ Info</option>
                            <option value="3">⚠️ Warning</option>
                            <option value="4">❌ Error</option>
                            <option value="5">🔴 Critical</option>
                            <option value="6">🔒 Security</option>
                            <option value="7">📊 Analytics</option>
                        </select>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <input type="datetime-local" id="filter-start"
                               class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">

                        <input type="datetime-local" id="filter-end"
                               class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">

                        <button onclick="applyFilters()"
                                class="bg-gradient-to-r from-blue-600 to-blue-700 text-white px-6 py-2 rounded-lg hover:from-blue-700 hover:to-blue-800 transition shadow-lg font-semibold">
                            <i class="fas fa-check mr-2"></i>Apply Filters
                        </button>
                    </div>

                    <div id="active-filters" class="mt-4 flex flex-wrap gap-2"></div>
                </div>

                <!-- Log List -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-list-ul text-green-600 mr-2"></i>Log Entries
                        </h3>
                        <div class="flex items-center gap-3">
                            <span class="text-sm text-gray-600">
                                <span id="log-count">0</span> logs
                            </span>
                            <button onclick="exportLogs()" class="text-sm text-blue-600 hover:text-blue-800 font-semibold">
                                <i class="fas fa-download mr-1"></i>Export
                            </button>
                        </div>
                    </div>

                    <div id="logs-container" class="space-y-3"></div>

                    <div class="mt-6 flex justify-between items-center">
                        <button onclick="previousPage()" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition">
                            <i class="fas fa-chevron-left mr-2"></i>Previous
                        </button>
                        <span id="page-info" class="text-gray-600 font-medium">Page 1 of 1</span>
                        <button onclick="nextPage()" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition">
                            Next<i class="fas fa-chevron-right ml-2"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Analytics Tab -->
            <div id="analytics-tab" class="tab-content hidden">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                    <div class="bg-white rounded-xl shadow-lg p-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-4">
                            <i class="fas fa-calendar text-purple-600 mr-2"></i>Date Range
                        </h3>
                        <div class="grid grid-cols-2 gap-4">
                            <input type="date" id="analytics-start" class="px-4 py-2 border border-gray-300 rounded-lg">
                            <input type="date" id="analytics-end" class="px-4 py-2 border border-gray-300 rounded-lg">
                        </div>
                        <button onclick="loadAnalytics()" class="mt-4 w-full bg-gradient-to-r from-purple-600 to-purple-700 text-white px-6 py-2 rounded-lg hover:from-purple-700 hover:to-purple-800 transition shadow-lg font-semibold">
                            <i class="fas fa-sync-alt mr-2"></i>Refresh Analytics
                        </button>
                    </div>

                    <div class="bg-white rounded-xl shadow-lg p-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-4">
                            <i class="fas fa-chart-bar text-teal-600 mr-2"></i>Event Summary
                        </h3>
                        <div id="analytics-summary" class="space-y-3"></div>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="bg-white rounded-xl shadow-lg p-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-6">
                            <i class="fas fa-trophy text-yellow-600 mr-2"></i>Top Events
                        </h3>
                        <div id="analytics-events" class="space-y-3"></div>
                    </div>

                    <div class="bg-white rounded-xl shadow-lg p-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-6">
                            <i class="fas fa-users text-blue-600 mr-2"></i>Top Users
                        </h3>
                        <div id="analytics-users" class="space-y-3"></div>
                    </div>
                </div>
            </div>

            <!-- Search Tab -->
            <div id="search-tab" class="tab-content hidden">
                <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                    <h3 class="text-xl font-bold text-gray-800 mb-4">
                        <i class="fas fa-search-plus text-indigo-600 mr-2"></i>Advanced Search
                    </h3>

                    <div class="flex gap-4 mb-6">
                        <div class="relative flex-1">
                            <i class="fas fa-search absolute left-4 top-4 text-gray-400"></i>
                            <input type="text" id="search-query" placeholder="Search across all fields (message, exception, user, correlation ID...)"
                                   class="w-full pl-12 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-lg">
                        </div>
                        <button onclick="performSearch()"
                                class="bg-gradient-to-r from-indigo-600 to-indigo-700 text-white px-8 py-3 rounded-lg hover:from-indigo-700 hover:to-indigo-800 transition shadow-lg font-semibold">
                            <i class="fas fa-search mr-2"></i>Search
                        </button>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <select id="search-apps" multiple class="px-4 py-2 border border-gray-300 rounded-lg h-32">
                            <option value="">All Applications</option>
                        </select>
                        <select id="search-envs" multiple class="px-4 py-2 border border-gray-300 rounded-lg h-32">
                            <option value="">All Environments</option>
                        </select>
                        <select id="search-levels" multiple class="px-4 py-2 border border-gray-300 rounded-lg h-32">
                            <option value="0">Trace</option>
                            <option value="1">Debug</option>
                            <option value="2">Info</option>
                            <option value="3">Warning</option>
                            <option value="4">Error</option>
                            <option value="5">Critical</option>
                            <option value="6">Security</option>
                            <option value="7">Analytics</option>
                        </select>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-lg p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-list text-green-600 mr-2"></i>Search Results
                        </h3>
                        <span id="search-count" class="text-sm text-gray-600">0 results</span>
                    </div>
                    <div id="search-results" class="space-y-3"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Loading Overlay -->
    <div id="loading" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl p-8 shadow-2xl">
            <div class="spinner mx-auto mb-4"></div>
            <p class="text-gray-700 font-semibold">Loading...</p>
        </div>
    </div>

    <!-- Log Detail Modal -->
    <div id="log-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden" onclick="closeModal(event)">
        <div class="bg-white rounded-xl shadow-2xl max-w-4xl w-full mx-4 max-h-[90vh] overflow-y-auto" onclick="event.stopPropagation()">
            <div class="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
                <h3 class="text-xl font-bold text-gray-800">Log Details</h3>
                <button onclick="closeModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div id="log-modal-content" class="p-6"></div>
        </div>
    </div>

    <script>
        let currentPage = 1;
        let totalPages = 1;
        let levelChart, trendChart;
        let currentFilters = {};

        const levelNames = ['TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL', 'SECURITY', 'ANALYTICS'];
        const levelIcons = ['🔍', '🐛', 'ℹ️', '⚠️', '❌', '🔴', '🔒', '📊'];
        const levelClasses = ['trace', 'debug', 'info', 'warning', 'error', 'critical', 'security', 'analytics'];
        const levelColors = ['#9ca3af', '#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#a855f7', '#f97316', '#14b8a6'];

        async function loadStats() {
            try {
                const response = await fetch('/api/logs/stats');
                const stats = await response.json();

                document.getElementById('stat-total').textContent = stats.totalLogs.toLocaleString();
                document.getElementById('stat-last24h').textContent = stats.last24Hours.toLocaleString();
                document.getElementById('stat-lasthour').textContent = stats.lastHour.toLocaleString();
                document.getElementById('stat-errors').textContent = stats.errorCount.toLocaleString();
                document.getElementById('stat-warnings').textContent = stats.warningCount.toLocaleString();
                document.getElementById('stat-critical').textContent = stats.criticalCount.toLocaleString();
                document.getElementById('stat-security').textContent = stats.securityCount.toLocaleString();
                document.getElementById('stat-apps').textContent = stats.applications.toLocaleString();

                updateLevelChart(stats.byLevel);
                displayTopApplications(stats.topApplications);
                displayRecentErrors(stats.topErrors);
            } catch (error) {
                console.error('Error loading stats:', error);
            }
        }

        function updateLevelChart(byLevel) {
            const ctx = document.getElementById('levelChart').getContext('2d');
            const data = Array(8).fill(0);
            byLevel.forEach(item => data[item.level] = item.count);

            if (levelChart) levelChart.destroy();
            levelChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: levelNames,
                    datasets: [{
                        data: data,
                        backgroundColor: levelColors,
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { position: 'bottom' },
                        tooltip: {
                            callbacks: {
                                label: (context) => `${context.label}: ${context.parsed.toLocaleString()}`
                            }
                        }
                    }
                }
            });
        }

        function updateTrendChart(trend) {
            const ctx = document.getElementById('trendChart').getContext('2d');
            const labels = trend.map(t => new Date(t.timestamp).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}));

            const datasets = [
                { label: 'Total', data: trend.map(t => t.count), borderColor: '#3b82f6', backgroundColor: '#3b82f620', fill: true }
            ];

            if (trendChart) trendChart.destroy();
            trendChart = new Chart(ctx, {
                type: 'line',
                data: { labels, datasets },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    },
                    scales: {
                        y: { beginAtZero: true }
                    }
                }
            });
        }

        function displayTopApplications(apps) {
            const container = document.getElementById('top-apps');
            if (!apps || apps.length === 0) {
                container.innerHTML = '<p class="text-gray-500 text-center py-8">No data available</p>';
                return;
            }

            const maxCount = Math.max(...apps.map(a => a.count));
            container.innerHTML = apps.map(app => `
                <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition">
                    <div class="flex items-center gap-3 flex-1">
                        <div class="bg-blue-100 rounded-lg p-2">
                            <i class="fas fa-cube text-blue-600"></i>
                        </div>
                        <div class="flex-1">
                            <p class="font-semibold text-gray-800">${app.application}</p>
                            <div class="w-full bg-gray-200 rounded-full h-2 mt-1">
                                <div class="bg-blue-600 h-2 rounded-full transition-all" style="width: ${(app.count / maxCount) * 100}%"></div>
                            </div>
                        </div>
                    </div>
                    <span class="badge bg-blue-100 text-blue-800">${app.count.toLocaleString()}</span>
                </div>
            `).join('');
        }

        function displayRecentErrors(errors) {
            const container = document.getElementById('recent-errors');
            if (!errors || errors.length === 0) {
                container.innerHTML = '<p class="text-gray-500 text-center py-8">No critical events</p>';
                return;
            }

            container.innerHTML = errors.map(err => `
                <div class="p-3 bg-red-50 border-l-4 border-red-500 rounded-lg">
                    <div class="flex items-center justify-between mb-1">
                        <span class="font-semibold text-red-800 text-sm">${escapeHtml(err.message.substring(0, 80))}</span>
                        <span class="badge bg-red-100 text-red-800">${err.count}×</span>
                    </div>
                </div>
            `).join('');
        }

        async function loadLogs() {
            showLoading();
            try {
                const params = new URLSearchParams({
                    page: currentPage,
                    pageSize: 20,
                    ...currentFilters
                });

                const response = await fetch(`/api/logs?${params}`);
                const result = await response.json();

                totalPages = result.totalPages;
                displayLogs(result.items);
                document.getElementById('page-info').textContent = `Page ${result.page} of ${result.totalPages}`;
                document.getElementById('log-count').textContent = result.totalCount.toLocaleString();
            } catch (error) {
                console.error('Error loading logs:', error);
            } finally {
                hideLoading();
            }
        }

        function displayLogs(logs) {
            const container = document.getElementById('logs-container');
            if (logs.length === 0) {
                container.innerHTML = '<p class="text-gray-500 text-center py-12">No logs found</p>';
                return;
            }

            container.innerHTML = logs.map(log => {
                const level = log.level;
                return `
                    <div class="log-entry log-${levelClasses[level]} p-4 rounded-lg" onclick="showLogDetail('${log.id}')">
                        <div class="flex justify-between items-start mb-2">
                            <div class="flex items-center space-x-3 flex-wrap gap-2">
                                <span class="badge bg-white shadow-sm">${levelIcons[level]} ${levelNames[level]}</span>
                                <span class="text-sm font-semibold text-gray-700">${escapeHtml(log.applicationName)}</span>
                                <span class="text-xs px-2 py-1 bg-white rounded-full text-gray-600">${escapeHtml(log.category)}</span>
                                <span class="text-xs px-2 py-1 bg-white rounded-full text-gray-600">${escapeHtml(log.environment)}</span>
                            </div>
                            <span class="text-xs text-gray-600 whitespace-nowrap">${new Date(log.timestamp).toLocaleString()}</span>
                        </div>
                        <p class="text-gray-900 font-medium mb-2">${escapeHtml(log.message)}</p>
                        ${log.exception ? `<div class="text-xs text-red-700 bg-red-100 p-2 rounded mt-2 font-mono">${escapeHtml(log.exception.substring(0, 150))}...</div>` : ''}
                        <div class="flex gap-3 mt-3 text-xs text-gray-600">
                            <span><i class="fas fa-server mr-1"></i>${escapeHtml(log.machineName)}</span>
                            ${log.userId ? `<span><i class="fas fa-user mr-1"></i>${escapeHtml(log.userId)}</span>` : ''}
                            ${log.correlationId ? `<span><i class="fas fa-link mr-1"></i>${escapeHtml(log.correlationId.substring(0, 8))}</span>` : ''}
                        </div>
                    </div>
                `;
            }).join('');
        }

        async function showLogDetail(id) {
            try {
                const response = await fetch(`/api/logs/${id}`);
                const log = await response.json();

                const modal = document.getElementById('log-modal');
                const content = document.getElementById('log-modal-content');

                const properties = log.properties ? JSON.parse(log.properties) : {};

                content.innerHTML = `
                    <div class="space-y-4">
                        <div class="flex items-center gap-3 pb-4 border-b">
                            <span class="badge bg-${levelClasses[log.level]}-100">${levelIcons[log.level]} ${levelNames[log.level]}</span>
                            <span class="text-sm text-gray-600">${new Date(log.timestamp).toLocaleString()}</span>
                        </div>

                        <div>
                            <label class="text-sm font-semibold text-gray-700">Message</label>
                            <p class="mt-1 p-3 bg-gray-50 rounded-lg">${escapeHtml(log.message)}</p>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="text-sm font-semibold text-gray-700">Application</label>
                                <p class="mt-1 p-3 bg-gray-50 rounded-lg">${escapeHtml(log.applicationName)} v${escapeHtml(log.applicationVersion)}</p>
                            </div>
                            <div>
                                <label class="text-sm font-semibold text-gray-700">Environment</label>
                                <p class="mt-1 p-3 bg-gray-50 rounded-lg">${escapeHtml(log.environment)}</p>
                            </div>
                            <div>
                                <label class="text-sm font-semibold text-gray-700">Machine</label>
                                <p class="mt-1 p-3 bg-gray-50 rounded-lg">${escapeHtml(log.machineName)}</p>
                            </div>
                            <div>
                                <label class="text-sm font-semibold text-gray-700">Category</label>
                                <p class="mt-1 p-3 bg-gray-50 rounded-lg">${escapeHtml(log.category)}</p>
                            </div>
                        </div>

                        ${log.exception ? `
                            <div>
                                <label class="text-sm font-semibold text-gray-700">Exception</label>
                                <pre class="mt-1 p-3 bg-red-50 rounded-lg text-xs overflow-x-auto">${escapeHtml(log.exception)}</pre>
                            </div>
                        ` : ''}

                        ${log.stackTrace ? `
                            <div>
                                <label class="text-sm font-semibold text-gray-700">Stack Trace</label>
                                <pre class="mt-1 p-3 bg-gray-50 rounded-lg text-xs overflow-x-auto">${escapeHtml(log.stackTrace)}</pre>
                            </div>
                        ` : ''}

                        ${Object.keys(properties).length > 0 ? `
                            <div>
                                <label class="text-sm font-semibold text-gray-700">Properties</label>
                                <pre class="mt-1 p-3 bg-gray-50 rounded-lg text-xs overflow-x-auto">${JSON.stringify(properties, null, 2)}</pre>
                            </div>
                        ` : ''}

                        <div class="grid grid-cols-3 gap-4 pt-4 border-t">
                            ${log.userId ? `<div><label class="text-xs text-gray-600">User ID</label><p class="font-mono text-sm">${escapeHtml(log.userId)}</p></div>` : ''}
                            ${log.sessionId ? `<div><label class="text-xs text-gray-600">Session ID</label><p class="font-mono text-sm">${escapeHtml(log.sessionId)}</p></div>` : ''}
                            ${log.requestId ? `<div><label class="text-xs text-gray-600">Request ID</label><p class="font-mono text-sm">${escapeHtml(log.requestId)}</p></div>` : ''}
                            ${log.correlationId ? `<div><label class="text-xs text-gray-600">Correlation ID</label><p class="font-mono text-sm">${escapeHtml(log.correlationId)}</p></div>` : ''}
                        </div>
                    </div>
                `;

                modal.classList.remove('hidden');
            } catch (error) {
                console.error('Error loading log detail:', error);
            }
        }

        function closeModal(event) {
            if (!event || event.target.id === 'log-modal') {
                document.getElementById('log-modal').classList.add('hidden');
            }
        }

        async function loadDropdowns() {
            try {
                const [apps, envs] = await Promise.all([
                    fetch('/api/logs/applications').then(r => r.json()),
                    fetch('/api/logs/environments').then(r => r.json())
                ]);

                const appSelects = [document.getElementById('filter-app'), document.getElementById('search-apps')];
                const envSelects = [document.getElementById('filter-env'), document.getElementById('search-envs')];

                appSelects.forEach(select => {
                    select.innerHTML = '<option value="">All Applications</option>' +
                        apps.map(app => `<option value="${app}">${app}</option>`).join('');
                });

                envSelects.forEach(select => {
                    select.innerHTML = '<option value="">All Environments</option>' +
                        envs.map(env => `<option value="${env}">${env}</option>`).join('');
                });
            } catch (error) {
                console.error('Error loading dropdowns:', error);
            }
        }

        function applyFilters() {
            currentPage = 1;
            currentFilters = {
                search: document.getElementById('filter-search').value,
                application: document.getElementById('filter-app').value,
                environment: document.getElementById('filter-env').value,
                level: document.getElementById('filter-level').value,
                startDate: document.getElementById('filter-start').value,
                endDate: document.getElementById('filter-end').value
            };

            Object.keys(currentFilters).forEach(key => {
                if (!currentFilters[key]) delete currentFilters[key];
            });

            updateActiveFilters();
            loadLogs();
        }

        function updateActiveFilters() {
            const container = document.getElementById('active-filters');
            const filters = [];

            if (currentFilters.search) filters.push({label: 'Search', value: currentFilters.search});
            if (currentFilters.application) filters.push({label: 'App', value: currentFilters.application});
            if (currentFilters.environment) filters.push({label: 'Env', value: currentFilters.environment});
            if (currentFilters.level) filters.push({label: 'Level', value: levelNames[currentFilters.level]});

            container.innerHTML = filters.map(f => `
                <span class="filter-chip">
                    <span>${f.label}: ${f.value}</span>
                    <button onclick="removeFilter('${Object.keys(currentFilters).find(k => currentFilters[k] === f.value)}')" class="hover:text-red-200">
                        <i class="fas fa-times"></i>
                    </button>
                </span>
            `).join('');
        }

        function removeFilter(key) {
            delete currentFilters[key];
            updateActiveFilters();
            loadLogs();
        }

        function clearFilters() {
            currentFilters = {};
            document.getElementById('filter-search').value = '';
            document.getElementById('filter-app').value = '';
            document.getElementById('filter-env').value = '';
            document.getElementById('filter-level').value = '';
            document.getElementById('filter-start').value = '';
            document.getElementById('filter-end').value = '';
            updateActiveFilters();
            loadLogs();
        }

        async function performSearch() {
            showLoading();
            try {
                const request = {
                    query: document.getElementById('search-query').value,
                    applications: Array.from(document.getElementById('search-apps').selectedOptions).map(o => o.value).filter(v => v),
                    environments: Array.from(document.getElementById('search-envs').selectedOptions).map(o => o.value).filter(v => v),
                    levels: Array.from(document.getElementById('search-levels').selectedOptions).map(o => parseInt(o.value)),
                    limit: 100
                };

                const response = await fetch('/api/logs/search', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(request)
                });

                const result = await response.json();
                displaySearchResults(result);
            } catch (error) {
                console.error('Error searching:', error);
            } finally {
                hideLoading();
            }
        }

        function displaySearchResults(result) {
            const container = document.getElementById('search-results');
            document.getElementById('search-count').textContent = `${result.totalCount.toLocaleString()} results`;

            if (result.results.length === 0) {
                container.innerHTML = '<p class="text-gray-500 text-center py-12">No results found</p>';
                return;
            }

            container.innerHTML = result.results.map(log => {
                const level = log.level;
                return `
                    <div class="log-entry log-${levelClasses[level]} p-4 rounded-lg" onclick="showLogDetail('${log.id}')">
                        <div class="flex justify-between items-start mb-2">
                            <div class="flex items-center space-x-3">
                                <span class="badge bg-white shadow-sm">${levelIcons[level]} ${levelNames[level]}</span>
                                <span class="text-sm font-semibold">${escapeHtml(log.applicationName)}</span>
                            </div>
                            <span class="text-xs text-gray-600">${new Date(log.timestamp).toLocaleString()}</span>
                        </div>
                        <p class="text-gray-900 font-medium">${escapeHtml(log.message)}</p>
                    </div>
                `;
            }).join('');
        }

        async function loadAnalytics() {
            showLoading();
            try {
                const start = document.getElementById('analytics-start').value;
                const end = document.getElementById('analytics-end').value;
                const params = new URLSearchParams();
                if (start) params.append('start', start);
                if (end) params.append('end', end);

                const response = await fetch(`/api/logs/analytics?${params}`);
                const analytics = await response.json();

                displayAnalytics(analytics);
            } catch (error) {
                console.error('Error loading analytics:', error);
            } finally {
                hideLoading();
            }
        }

        function displayAnalytics(analytics) {
            document.getElementById('analytics-summary').innerHTML = `
                <div class="p-4 bg-teal-50 rounded-lg">
                    <p class="text-3xl font-bold text-teal-700">${analytics.totalEvents.toLocaleString()}</p>
                    <p class="text-sm text-gray-600 mt-1">Total Analytics Events</p>
                </div>
            `;

            const eventsContainer = document.getElementById('analytics-events');
            eventsContainer.innerHTML = analytics.topEvents.map((evt, idx) => `
                <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div class="flex items-center gap-3">
                        <span class="flex items-center justify-center w-8 h-8 bg-teal-600 text-white rounded-full font-bold text-sm">${idx + 1}</span>
                        <div>
                            <p class="font-semibold text-gray-800">${escapeHtml(evt.event)}</p>
                            <p class="text-xs text-gray-500">Last seen: ${evt.lastSeen}</p>
                        </div>
                    </div>
                    <span class="badge bg-teal-100 text-teal-800">${evt.count.toLocaleString()}</span>
                </div>
            `).join('');

            const usersContainer = document.getElementById('analytics-users');
            usersContainer.innerHTML = analytics.topUsers.map((user, idx) => `
                <div class="p-3 bg-blue-50 rounded-lg">
                    <div class="flex items-center justify-between mb-2">
                        <div class="flex items-center gap-2">
                            <i class="fas fa-user-circle text-blue-600 text-xl"></i>
                            <span class="font-semibold text-gray-800">${escapeHtml(user.userId)}</span>
                        </div>
                        <span class="badge bg-blue-100 text-blue-800">${user.eventCount}</span>
                    </div>
                    <div class="flex flex-wrap gap-1">
                        ${user.topEvents.map(e => `<span class="text-xs px-2 py-1 bg-white rounded-full">${escapeHtml(e)}</span>`).join('')}
                    </div>
                </div>
            `).join('');
        }

        function showTab(tab) {
            document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
            document.getElementById(`${tab}-tab`).classList.remove('hidden');

            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            event.target.closest('.tab-btn').classList.add('active');

            if (tab === 'dashboard') {
                loadStats();
                loadTrend();
            }
            if (tab === 'logs') {
                loadLogs();
                loadDropdowns();
            }
            if (tab === 'analytics') {
                const today = new Date().toISOString().split('T')[0];
                const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
                document.getElementById('analytics-start').value = weekAgo;
                document.getElementById('analytics-end').value = today;
                loadAnalytics();
            }
            if (tab === 'search') {
                loadDropdowns();
            }
        }

        function previousPage() {
            if (currentPage > 1) {
                currentPage--;
                loadLogs();
            }
        }

        function nextPage() {
            if (currentPage < totalPages) {
                currentPage++;
                loadLogs();
            }
        }

        function changeTrendPeriod() {
            loadTrend();
        }

        function showLoading() {
            document.getElementById('loading').classList.remove('hidden');
        }

        function hideLoading() {
            document.getElementById('loading').classList.add('hidden');
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function exportLogs() {
            alert('Export functionality coming soon!');
        }

        async function loadTrend()
        {
            try
            {
                const hours = document.getElementById('trend-period').value;
                const response = await fetch(`/api/logs/trend?hours=${hours}`);
                const trend = await response.json();
                updateTrendChart(trend);
            }
            catch (error)
            {
                console.error('Error loading trend data:', error);
            }
        }

        loadStats();
        loadTrend();
        setInterval(() => {
            if (!document.getElementById('dashboard-tab').classList.contains('hidden')) {
                loadStats();
                loadTrend();
            }
        }, 30000);
    </script>
</body>
</html>
