<!DOCTYPE html>
<html lang="en" class="h-100">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>InsightTrail Analytics by Sentinel</title>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- Bootstrap JS (for Bootstrap 5) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <!-- DataTables -->
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <style>
        :root {
            --bg-color: #f8f9fa;
            --text-color: #212529;
            --card-bg: #ffffff;
            --border-color: #dee2e6;
            --hover-bg: #e9ecef;
            --navbar-bg: #ffffff;
            --footer-bg: #343a40;
            --metric-box-bg: #ffffff;
            --text-muted: #6c757d;
            --table-hover-bg: #f1f3f5;
            --modal-bg: #ffffff;
            --pre-bg: #e9ecef;
            --primary-color: #0d6efd;
            --primary-color-alpha: rgba(13, 110, 253, 0.1);
            --danger-color: #dc3545;
            --danger-color-alpha: rgba(220, 53, 69, 0.1);
            --success-color: #198754;
            --warning-color: #ffc107;
            --info-color: #0dcaf0;
            --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            --border-radius: 0.5rem;
        }

        [data-theme="dark"] {
            --bg-color: #121212;
            --text-color: #e0e0e0;
            --card-bg: #1e1e1e;
            --border-color: #333333;
            --hover-bg: #2a2a2a;
            --navbar-bg: #1e1e1e;
            --footer-bg: #1e1e1e;
            --metric-box-bg: #2a2a2a;
            --text-muted: #888888;
            --table-hover-bg: #2a2a2a;
            --modal-bg: #1e1e1e;
            --pre-bg: #2a2a2a;
            --primary-color: #3b82f6;
            --primary-color-alpha: rgba(59, 130, 246, 0.15);
            --danger-color: #ef4444;
            --danger-color-alpha: rgba(239, 68, 68, 0.15);
            --success-color: #22c55e;
            --warning-color: #f59e0b;
            --info-color: #38bdf8;
            --shadow: none;
            --bs-table-striped-bg: rgba(255, 255, 255, 0.04);
            --bs-table-hover-bg: rgba(255, 255, 255, 0.1);
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            transition: background-color 0.3s ease, color 0.3s ease;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            height: 100%;
        }

        .card {
            background-color: var(--card-bg);
            border: 1px solid var(--border-color);
            color: var(--text-color);
            transition: background-color 0.3s ease, border-color 0.3s ease;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            height: 100%;
        }

        .modal-content {
            background-color: var(--modal-bg);
            color: var(--text-color);
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius);
        }
        
        .modal-header, .modal-footer {
            border-bottom-color: var(--border-color);
            border-top-color: var(--border-color);
        }

        .table {
            color: var(--text-color);
        }
        
        .table td, .table th {
            border-color: var(--border-color);
            vertical-align: middle;
        }

        [data-theme="dark"] .table-striped > tbody > tr:nth-of-type(odd) > * {
            color: #bbb;
        }

        .text-muted {
            color: var(--text-muted) !important;
        }

        pre {
            background-color: var(--pre-bg);
            color: var(--text-color);
            border: 1px solid var(--border-color);
            border-radius: calc(var(--border-radius) / 2);
            padding: 1rem;
        }
        
        .metric-box {
            background-color: var(--metric-box-bg);
            color: var(--text-color);
            transition: background-color 0.3s ease;
            border: 1px solid var(--border-color);
            padding: 1rem;
            border-radius: var(--border-radius);
        }

        .metric-box .title {
            color: var(--text-muted);
            font-size: 0.9em;
        }

        .metric-box .value {
            color: var(--text-color);
            font-size: 1.5rem;
            font-weight: 600;
        }

        .nav-tabs .nav-link {
            color: var(--text-muted);
            background-color: transparent;
            border-color: transparent;
            border-bottom: 2px solid transparent;
            transition: color 0.2s, border-color 0.2s;
        }

        .nav-tabs .nav-link:hover {
            border-color: var(--hover-bg);
        }

        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            background-color: transparent;
            border-bottom-color: var(--primary-color);
        }
        
        .btn-close {
            filter: brightness(0) invert(1) var(--is-dark, 0);
        }

        [data-theme="dark"] .btn-close {
            filter: invert(1);
        }

        .dataTables_wrapper {
            color: var(--text-color);
        }

        .dataTables_wrapper .dataTables_length select,
        .dataTables_wrapper .dataTables_filter input {
            background-color: var(--bg-color);
            color: var(--text-color);
            border: 1px solid var(--border-color);
            border-radius: calc(var(--border-radius) / 2);
            padding: 0.375rem 0.75rem;
        }

        .dataTables_wrapper .paginate_button {
            color: var(--text-color) !important;
            border-color: var(--border-color) !important;
        }

        .dataTables_wrapper .paginate_button.current,
        .dataTables_wrapper .paginate_button:hover {
            background: var(--primary-color) !important;
            color: white !important;
            border-color: var(--primary-color) !important;
        }
        
        [data-theme="dark"] .dataTables_wrapper .paginate_button.disabled,
        [data-theme="dark"] .dataTables_wrapper .paginate_button.disabled:hover {
            color: var(--text-muted) !important;
            background: transparent !important;
            border-color: transparent !important;
        }
        
        .success-badge {
            background-color: var(--success-color);
            color: white;
            padding: 0.25em 0.6em;
            border-radius: 1em;
            font-size: 0.8em;
            font-weight: 600;
        }

        .error-badge {
            background-color: var(--danger-color);
            color: white;
            padding: 0.25em 0.6em;
            border-radius: 1em;
            font-size: 0.8em;
            font-weight: 600;
        }

        .navbar {
            background-color: var(--navbar-bg) !important;
            transition: background-color 0.3s ease;
            border-bottom: 1px solid var(--border-color);
            box-shadow: var(--shadow);
        }
        
        [data-theme="light"] .navbar {
            box-shadow: 0 2px 4px rgba(0,0,0,.04);
        }

        .footer {
            background-color: var(--footer-bg);
            transition: background-color 0.3s ease;
            color: var(--text-color);
            border-top: 1px solid var(--border-color);
            padding: 2rem 0;
        }
        
        .metric-card {
            text-align: center;
            padding: 1.5rem;
        }
        
        .metric-value {
            font-size: 2.25rem;
            font-weight: 700;
            color: var(--primary-color);
        }

        .metric-label {
            color: var(--text-muted);
            font-size: 1rem;
        }
        
        /* .error-list {
            max-height: 300px;
            overflow-y: auto;
        } */

        .error-item {
            padding: 0.75rem 1.25rem;
            border-bottom: 1px solid var(--border-color);
            transition: background-color 0.2s;
        }
        
        .error-item:last-child {
            border-bottom: none;
        }

        .error-item:hover {
            background-color: var(--hover-bg);
        }
        
        .social-links a {
            color: var(--text-muted);
            margin: 0 10px;
            font-size: 1.2rem;
            transition: color 0.3s;
        }
        
        .social-links a:hover {
            color: var(--primary-color);
        }

        .chart-container {
            position: relative;
            height: 250px;
        }
        
        .worker-list {
            max-height: 200px;
            overflow-y: auto;
        }
        
        .system-metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 1rem;
            margin-top: 10px;
        }
        
        .code-line.error-line {
            background-color: var(--danger-color-alpha);
            font-weight: bold;
        }
        
        .line-number {
            color: var(--text-muted);
            min-width: 3em;
            text-align: right;
            margin-right: 1em;
            user-select: none;
        }

        [data-theme="dark"] .bg-light {
            background-color: var(--metric-box-bg) !important;
        }
        
        /* Theme switcher */
        .theme-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 26px;
            margin: 0 10px;
        }

        .theme-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 26px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: var(--primary-color);
        }

        input:focus + .slider {
            box-shadow: 0 0 1px var(--primary-color);
        }

        input:checked + .slider:before {
            transform: translateX(24px);
        }
        
        .theme-icon {
            font-size: 1.2rem;
            color: var(--text-muted);
        }

        .navbar-brand {
            color: var(--text-color);
            font-size: 1.5rem;
            font-weight: 600;
        }

        .card-body-scrollable {
            flex: 1;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">InsightTrail</a>
            <div class="d-flex align-items-center">
                <div class="d-flex align-items-center me-3">
                    <i class="fas fa-sun theme-icon"></i>
                    <label class="theme-switch">
                        <input type="checkbox" id="themeSwitch">
                        <span class="slider round"></span>
                    </label>
                    <i class="fas fa-moon theme-icon"></i>
                </div>
                <button class="btn btn-outline-secondary me-2" onclick="refreshAllData()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
                <div class="d-flex">
                    <input type="text" class="form-control me-2" id="trace-id" placeholder="Enter Trace ID">
                    <button class="btn btn-primary" onclick="searchLogs()">Search</button>
                </div>
            </div>
        </div>
    </nav>

    <div class="content container-fluid px-4 py-4">
        <!-- Key Metrics Cards -->
        <div class="row g-4 mb-4">
            <div class="col-lg-3 col-md-6">
                <div class="card metric-card">
                    <div class="metric-value" id="totalRequests">0</div>
                    <div class="metric-label">Total Requests</div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6">
                <div class="card metric-card">
                    <div class="metric-value" id="errorRate">0%</div>
                    <div class="metric-label">Error Rate</div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6">
                <div class="card metric-card">
                    <div class="metric-value" id="avgResponseTime">0ms</div>
                    <div class="metric-label">Avg Response Time</div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6">
                <div class="card metric-card">
                    <div class="metric-value" id="cpuUsage">0%</div>
                    <div class="metric-label">CPU Usage</div>
                </div>
            </div>
        </div>

        <!-- Service Status Row -->
        <div class="row g-4 mb-4">
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header">
                        Service Status
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="metric-box mb-3">
                                    <div class="title">Service Uptime</div>
                                    <div class="value" id="serviceUptime">-</div>
                                </div>
                                <div class="metric-box">
                                    <div class="title">Process Uptime</div>
                                    <div class="value" id="processUptime">-</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="metric-box mb-3">
                                    <div class="title d-flex justify-content-between align-items-baseline">
                                        <span>Main Process</span>
                                        <span id="mainProcessName" class="small fw-normal text-muted">-</span>
                                    </div>
                                    <div class="value" id="mainPid">-</div>
                                </div>
                                <div class="metric-box">
                                    <div class="title">Active Workers</div>
                                    <div class="value" id="workerCount">0</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header">
                        System Resources
                    </div>
                    <div class="card-body">
                        <div class="system-metrics-grid">
                            <div class="metric-box">
                                <div class="title">CPU</div>
                                <div class="value" id="systemCpu">0%</div>
                            </div>
                            <div class="metric-box">
                                <div class="title">Memory</div>
                                <div class="value" id="systemMemory">0%</div>
                            </div>
                            <div class="metric-box">
                                <div class="title">Disk</div>
                                <div class="value" id="systemDisk">0%</div>
                            </div>
                            <div class="metric-box">
                                <div class="title">Cores</div>
                                <div class="value" id="cpuCores">0</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts Row -->
        <div class="row g-4 mb-4">
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header">
                        Response Time Distribution
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="responseTimeChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header">
                        Error Distribution
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="errorDistributionChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Full-width Row for Packages and Errors -->
        <div class="row g-4 mb-4">
            <div class="col-lg-8">
                <div class="card d-flex flex-column">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <span>Installed Packages</span>
                            <button class="btn btn-sm btn-outline-secondary" onclick="refreshPackages()">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                        </div>
                    </div>
                    <div class="card-body card-body-scrollable">
                        <div class="table-responsive">
                            <table class="table table-sm table-hover" id="packagesTable">
                                <thead>
                                    <tr>
                                        <th>Package</th>
                                        <th>Version</th>
                                        <th>Latest</th>
                                        <th>Status</th>
                                        <th>Description</th>
                                    </tr>
                                </thead>
                                <tbody id="packagesTableBody"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                 <div class="card d-flex flex-column">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        Recent Errors
                        <span class="badge rounded-pill" id="errorCount" style="background-color: var(--danger-color);">0</span>
                    </div>
                    <div class="card-body p-0 card-body-scrollable">
                        <div class="error-list" id="recentErrors">
                            <!-- Error items will be dynamically added here -->
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- System Metrics Chart -->
         <div class="row g-4 mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        System Resource Usage
                    </div>
                    <div class="card-body">
                        <div class="chart-container" style="height: 280px;">
                            <canvas id="systemMetricsChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Logs Table -->
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Request Logs</h5>
                    <div class="btn-group">
                        <button class="btn btn-outline-secondary btn-sm" onclick="refreshLogs()">
                            <i class="fas fa-sync-alt"></i> Refresh
                        </button>
                        <button class="btn btn-outline-secondary btn-sm" onclick="exportLogs()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="logTable" class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>Trace ID</th>
                                <th>Path</th>
                                <th>Method</th>
                                <th>Status</th>
                                <th>Duration</th>
                                <th>Client IP</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="logTableBody"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer mt-auto py-3">
        <div class="container text-center">
            <div class="social-links mb-2">
                <a href="https://github.com/your-repo" target="_blank"><i class="fab fa-github"></i></a>
                <a href="https://linkedin.com/your-profile" target="_blank"><i class="fab fa-linkedin"></i></a>
                <a href="mailto:support@insighttrail.com"><i class="fas fa-envelope"></i></a>
            </div>
            <span class="text-muted">© <span id="currentYear"></span> InsightTrail. All rights reserved.</span>
        </div>
    </footer>

    <!-- Log Details Modal -->
    <div class="modal fade" id="logDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Log Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <ul class="nav nav-tabs" id="logDetailTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="request-tab" data-bs-toggle="tab" data-bs-target="#request" type="button" role="tab">Request</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="runtime-tab" data-bs-toggle="tab" data-bs-target="#runtime" type="button" role="tab">Runtime</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="error-tab" data-bs-toggle="tab" data-bs-target="#error" type="button" role="tab">Error</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="trace-tab" data-bs-toggle="tab" data-bs-target="#trace" type="button" role="tab">Trace</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="system-tab" data-bs-toggle="tab" data-bs-target="#system" type="button" role="tab">System</button>
                        </li>
                    </ul>
                    <div class="tab-content p-3" id="logDetailTabsContent">
                        <div class="tab-pane fade show active" id="request" role="tabpanel"></div>
                        <div class="tab-pane fade" id="runtime" role="tabpanel"></div>
                        <div class="tab-pane fade" id="error" role="tabpanel"></div>
                        <div class="tab-pane fade" id="trace" role="tabpanel"></div>
                        <div class="tab-pane fade" id="system" role="tabpanel"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let logData = [];
        let charts = {};
        let logTable;

        function getComputedCssVar(varName) {
            return getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
        }

        function initializeTheme() {
            const theme = localStorage.getItem('theme') || 'light';
            document.documentElement.setAttribute('data-theme', theme);
            const isDarkMode = theme === 'dark';
            document.getElementById('themeSwitch').checked = isDarkMode;
            updateThemeIcons(isDarkMode);
        }

        function toggleTheme() {
            const isDarkMode = document.getElementById('themeSwitch').checked;
            const newTheme = isDarkMode ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            updateThemeIcons(isDarkMode);
            updateChartTheme();
        }
        
        function updateThemeIcons(isDarkMode) {
            $('.theme-icon.fa-sun').css('color', isDarkMode ? 'var(--text-muted)' : 'var(--primary-color)');
            $('.theme-icon.fa-moon').css('color', isDarkMode ? 'var(--primary-color)' : 'var(--text-muted)');
        }

        function getChartOptions() {
            const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark';
            const gridColor = isDarkMode ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)';
            const textColor = getComputedCssVar('--text-color');
            const mutedColor = getComputedCssVar('--text-muted');

            return {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        ticks: { color: mutedColor, padding: 10 },
                        grid: { color: gridColor, drawBorder: false }
                    },
                    y: {
                        ticks: { color: mutedColor, padding: 10 },
                        grid: { color: gridColor, drawBorder: false }
                    }
                },
                plugins: {
                    legend: {
                        labels: { 
                            color: textColor,
                            font: { size: 14 },
                            boxWidth: 20,
                            padding: 20
                        }
                    }
                },
                animation: {
                    duration: 400
                }
            };
        }

        function updateChartTheme() {
            const chartOptions = getChartOptions();
            Object.values(charts).forEach(chart => {
                if (chart.config.type === 'pie' || chart.config.type === 'doughnut') {
                    chart.options = { ...chartOptions, scales: {} };
                } else {
                    chart.options = chartOptions;
                }
                chart.data.datasets.forEach(dataset => {
                    if (dataset.borderColorName) dataset.borderColor = getComputedCssVar(dataset.borderColorName);
                    if (dataset.backgroundColorName) dataset.backgroundColor = getComputedCssVar(dataset.backgroundColorName);
                    if (dataset.pointBackgroundColorName) dataset.pointBackgroundColor = getComputedCssVar(dataset.pointBackgroundColorName);
                });
                chart.update();
            });
        }


        function initializeCharts() {
            // Response Time Distribution Chart
            charts.responseTime = new Chart(document.getElementById('responseTimeChart'), {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Response Time (ms)',
                        data: [],
                        borderColorName: '--primary-color',
                        backgroundColorName: '--primary-color-alpha',
                        tension: 0.4,
                        fill: true,
                        pointRadius: 0,
                        pointHoverRadius: 6,
                        pointBackgroundColorName: '--primary-color'
                    }]
                },
                options: getChartOptions()
            });

            // Error Distribution Chart
            charts.errorDist = new Chart(document.getElementById('errorDistributionChart'), {
                type: 'pie',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: [],
                        borderWidth: 0
                    }]
                },
                options: { ...getChartOptions(), scales: {} }
            });

            // System Metrics Chart
            charts.systemMetrics = new Chart(document.getElementById('systemMetricsChart'), {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'CPU Usage (%)',
                        data: [],
                        borderColorName: '--primary-color',
                        backgroundColorName: '--primary-color-alpha',
                        fill: true,
                        tension: 0.4
                    }, {
                        label: 'Memory Usage (%)',
                        data: [],
                        borderColorName: '--danger-color',
                        backgroundColorName: '--danger-color-alpha',
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: getChartOptions()
            });
        }

        function initializeDataTable() {
            logTable = $('#logTable').DataTable({
                pageLength: 10,
                order: [[0, 'desc']],
                responsive: true,
                language: {
                    search: "",
                    searchPlaceholder: "Filter logs...",
                    paginate: {
                        first: '<i class="fas fa-angle-double-left"></i>',
                        previous: '<i class="fas fa-angle-left"></i>',
                        next: '<i class="fas fa-angle-right"></i>',
                        last: '<i class="fas fa-angle-double-right"></i>'
                    }
                },
                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rtip',
            });
        }

        function updateMetrics(data) {
            try {
                const totalRequests = data.length;
                const errors = data.filter(log => log.error || (log.request?.status >= 400));
                const errorRate = totalRequests > 0 ? ((errors.length / totalRequests) * 100).toFixed(1) : 0;
                const avgResponse = data.length > 0 ? 
                    (data.reduce((acc, log) => acc + (log.request?.duration_ms || 0), 0) / totalRequests).toFixed(2) : 
                    0;
                const latestCpuUsage = data[0]?.system?.cpu?.percent || 0;

                $('#totalRequests').text(totalRequests);
                $('#errorRate').text(errorRate + '%');
                $('#avgResponseTime').text(avgResponse + 'ms');
                $('#cpuUsage').text(latestCpuUsage.toFixed(1) + '%');
                $('#errorCount').text(errors.length);

                if (errors.length > 0) {
                    const recentErrorsHtml = errors.slice(0, 5).map(error => {
                        const timestamp = error.timestamp ? new Date(error.timestamp) : null;
                        const message = error.error?.message || `Status ${error.request?.status || 'Unknown'}`;
                        return `
                            <div class="error-item" onclick="showDetails('${encodeURIComponent(JSON.stringify(error))}')" style="cursor: pointer;">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong style="color: var(--danger-color);">${error.request?.method || ''} ${error.request?.path || 'Unknown Path'}</strong>
                                        <div class="text-muted small">${message.substring(0, 50)}${message.length > 50 ? '...' : ''}</div>
                                    </div>
                                    <div class="text-end text-muted small">
                                        ${timestamp ? `<div>${timestamp.toLocaleTimeString()}</div>` : ''}
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('');
                    $('#recentErrors').html(recentErrorsHtml);
                } else {
                    $('#recentErrors').html(`
                        <div class="d-flex align-items-center justify-content-center h-100 p-4">
                            <div class="text-center text-muted">
                                <i class="fas fa-check-circle fa-2x mb-2 text-success"></i>
                                <div>No errors to display</div>
                            </div>
                        </div>
                    `);
                }
            } catch (error) {
                console.error('Error updating metrics:', error);
                $('#recentErrors').html(`<div class="text-center p-4 text-danger">Error updating metrics</div>`);
            }
        }

        function updateCharts(data) {
            const timeLabels = data.slice(0, 20).map(log => new Date(log.timestamp).toLocaleTimeString()).reverse();
            
            charts.responseTime.data.labels = timeLabels;
            charts.responseTime.data.datasets[0].data = data.slice(0, 20).map(log => log.request.duration_ms || 0).reverse();
            charts.responseTime.update();

            const errorTypes = {};
            data.forEach(log => {
                if (log.error || (log.request?.status >= 400)) {
                    const errorType = log.error?.type || `HTTP ${log.request.status}`;
                    errorTypes[errorType] = (errorTypes[errorType] || 0) + 1;
                }
            });
            
            const colorNames = ['--danger-color', '--warning-color', '--info-color', '--primary-color', '--success-color'];
            charts.errorDist.data.labels = Object.keys(errorTypes);
            charts.errorDist.data.datasets[0].data = Object.values(errorTypes);
            charts.errorDist.data.datasets[0].backgroundColor = Object.keys(errorTypes).map((_, i) => 
                getComputedCssVar(colorNames[i % colorNames.length])
            );
            charts.errorDist.update();

            charts.systemMetrics.data.labels = timeLabels;
            charts.systemMetrics.data.datasets[0].data = data.slice(0, 20).map(log => log.system?.cpu?.percent || 0).reverse();
            charts.systemMetrics.data.datasets[1].data = data.slice(0, 20).map(log => log.system?.memory?.percent || 0).reverse();
            charts.systemMetrics.update();
        }

        function showDetails(logDataStr) {
            try {
                const log = JSON.parse(decodeURIComponent(logDataStr));
                
                const requestHtml = `
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <tbody>
                                <tr><th>Path</th><td>${log.request?.path || 'N/A'}</td></tr>
                                <tr><th>Method</th><td>${log.request?.method || 'N/A'}</td></tr>
                                <tr><th>Status</th><td>${log.request?.status || 'N/A'}</td></tr>
                                <tr><th>Duration</th><td>${log.request?.duration_ms ? log.request.duration_ms.toFixed(2) + 'ms' : 'N/A'}</td></tr>
                                <tr><th>Client IP</th><td>${log.request?.client || 'N/A'}</td></tr>
                                <tr><th>User Agent</th><td><pre>${log.request?.user_agent || 'N/A'}</pre></td></tr>
                                <tr><th>Query Params</th><td><pre>${JSON.stringify(log.request?.query_params || {}, null, 2)}</pre></td></tr>
                            </tbody>
                        </table>
                    </div>
                `;
                $('#request').html(requestHtml);

                const runtimeHtml = `
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <tbody>
                                <tr><th>Python Version</th><td>${log.runtime?.python?.version || 'N/A'}</td></tr>
                                <tr><th>Implementation</th><td>${log.runtime?.python?.implementation || 'N/A'}</td></tr>
                                <tr><th>Process ID</th><td>${log.runtime?.process?.pid || 'N/A'}</td></tr>
                                <tr><th>Threads</th><td>${log.runtime?.python?.thread_count || 'N/A'}</td></tr>
                                <tr><th>Memory (MB)</th><td>${log.runtime?.process?.memory_mb?.toFixed(2) || 'N/A'}</td></tr>
                            </tbody>
                        </table>
                        <h6>Environment Variables (non-sensitive)</h6>
                        <pre style="max-height: 200px; overflow-y: auto;">${JSON.stringify(log.runtime?.env_vars || {}, null, 2)}</pre>
                    </div>
                `;
                $('#runtime').html(runtimeHtml);

                let errorHtml = '';
                if (log.error) {
                    errorHtml = `
                        <div class="error-details">
                            <h6 style="color: var(--danger-color);"><i class="fas fa-exclamation-triangle me-2"></i>${log.error.type || 'Unknown Error'}</h6>
                            <p>${log.error.message || 'No error message available'}</p>
                            ${log.error.context ? `<h6>Error Context:</h6><pre>${JSON.stringify(log.error.context, null, 2)}</pre>` : ''}
                        </div>
                    `;
                } else {
                    errorHtml = `<div class="text-center text-muted p-4"><i class="fas fa-check-circle fa-2x mb-3"></i><p>No errors recorded</p></div>`;
                }
                $('#error').html(errorHtml);

                let traceHtml = '';
                if (log.error?.traceback) {
                    traceHtml = `<pre style="color: var(--danger-color); max-height: 400px; overflow-y: auto;">${log.error.traceback}</pre>`;
                } else {
                    traceHtml = `<div class="text-center text-muted p-4"><i class="fas fa-code fa-2x mb-3"></i><p>No traceback available</p></div>`;
                }
                $('#trace').html(traceHtml);

                const systemHtml = `
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <tbody>
                                <tr>
                                    <th>CPU Usage</th>
                                    <td>${log.system?.cpu?.percent ? log.system.cpu.percent.toFixed(1) + '%' : 'N/A'}</td>
                                </tr>
                                <tr>
                                    <th>Memory Usage</th>
                                    <td>${log.system?.memory?.percent ? log.system.memory.percent.toFixed(1) + '%' : 'N/A'} (${log.system?.memory?.available_gb ? log.system.memory.available_gb.toFixed(2) + ' GB free' : ''})</td>
                                </tr>
                                <tr>
                                    <th>Disk Usage</th>
                                    <td>${log.system?.disk?.percent ? log.system.disk.percent.toFixed(1) + '%' : 'N/A'} (${log.system?.disk?.free_gb ? log.system.disk.free_gb.toFixed(2) + ' GB free' : ''})</td>
                                </tr>
                                <tr>
                                    <th>CPU Cores</th>
                                    <td>${log.system?.cpu?.count || 'N/A'}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                `;
                $('#system').html(systemHtml);

                const errorTab = document.querySelector('#error-tab');
                const traceTab = document.querySelector('#trace-tab');
                if (log.error) {
                    errorTab.parentElement.style.display = 'block';
                    traceTab.parentElement.style.display = log.error.traceback ? 'block' : 'none';
                } else {
                    errorTab.parentElement.style.display = 'none';
                    traceTab.parentElement.style.display = 'none';
                }

                const modal = new bootstrap.Modal(document.getElementById('logDetailsModal'));
                modal.show();
            } catch (error) {
                console.error('Error showing log details:', error);
            }
        }

        function refreshLogs() {
            fetchLogs();
        }

        function exportLogs() {
            const csv = [
                ['Time', 'Trace ID', 'Path', 'Method', 'Status', 'Duration', 'Client IP', 'Error'],
                ...logData.map(log => [
                    log.timestamp,
                    log.trace_id,
                    log.request.path,
                    log.request.method,
                    log.request.status,
                    log.request.duration_ms,
                    log.request.client,
                    log.error ? log.error.message.replace(/,/g, '') : ''
                ])
            ].map(row => row.join(',')).join('\n');

            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.setAttribute('href', url);
            a.setAttribute('download', 'insighttrail_logs.csv');
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }

        function searchLogs() {
            const traceId = $('#trace-id').val();
            if (traceId) {
                $.getJSON(`/insight/api/analytics/search?trace_id=${traceId}`, function(response) {
                    logData = response.logs;
                    updateTable();
                    updateMetrics(logData);
                    updateCharts(logData);
                    updateServiceMetrics(response.metrics);
                }).fail(function() {
                    alert('Failed to search logs.');
                });
            } else {
                refreshAllData();
            }
        }

        function updateTable() {
            if (!logTable) return;
            try {
                logTable.clear();
                logData.forEach(log => {
                    const status = log.request?.status ? `<span class="${log.request.status < 400 ? 'success-badge' : 'error-badge'}">${log.request.status}</span>` : 'N/A';
                    logTable.row.add([
                        log.timestamp ? new Date(log.timestamp).toLocaleString() : 'N/A',
                        log.trace_id || 'N/A',
                        log.request?.path || 'N/A',
                        log.request?.method || 'N/A',
                        status,
                        log.request?.duration_ms ? `${log.request.duration_ms.toFixed(2)}ms` : 'N/A',
                        log.request?.client || 'N/A',
                        `<button class="btn btn-sm btn-outline-primary" onclick="showDetails('${encodeURIComponent(JSON.stringify(log))}')"><i class="fas fa-eye"></i></button>`
                    ]);
                });
                logTable.draw();
            } catch (error) {
                console.error('Error updating table:', error);
            }
        }

        function formatUptime(seconds) {
            if (seconds === null || isNaN(seconds)) return '-';
            const d = Math.floor(seconds / (3600*24));
            const h = Math.floor(seconds % (3600*24) / 3600);
            const m = Math.floor(seconds % 3600 / 60);
            return `${d}d ${h}h ${m}m`;
        }

        function updateServiceMetrics(metrics) {
            if (!metrics) return;
            $('#serviceUptime').text(formatUptime(metrics.uptime_seconds));
            $('#processUptime').text(formatUptime(metrics.process_uptime_seconds));
            
            const processInfo = metrics.process_info;
            if (processInfo) {
                $('#mainPid').text(processInfo.main_pid);
                $('#mainProcessName').text(processInfo.main_name);
                $('#workerCount').text(processInfo.worker_count);
                $('#cpuCores').text(processInfo.cpu_cores);
            }
            
            const systemMetrics = metrics.system_metrics;
            if (systemMetrics) {
                $('#systemCpu').text((systemMetrics.cpu_percent || 0).toFixed(1) + '%');
                $('#systemMemory').text((systemMetrics.memory_percent || 0).toFixed(1) + '%');
                $('#systemDisk').text((systemMetrics.disk_usage || 0).toFixed(1) + '%');
            }
        }

        function fetchLogs() {
            return $.getJSON('/insight/api/analytics/logs');
        }

        function refreshAllData() {
            const refreshBtn = $('button[onclick="refreshAllData()"]');
            const originalContent = refreshBtn.html();
            refreshBtn.html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true);

            $('#logTableBody').html('<tr><td colspan="8" class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>');
            $('#recentErrors').html('<div class="text-center p-4 text-muted"><i class="fas fa-spinner fa-spin"></i> Loading...</div>');

            fetchLogs()
                .done(response => {
                    if (!response || !response.logs) throw new Error('Invalid response');
                    logData = response.logs;
                    updateTable();
                    updateMetrics(logData);
                    updateCharts(logData);
                    updateServiceMetrics(response.metrics);
                })
                .fail(error => {
                    console.error('Failed to refresh data:', error);
                    const errorMsg = 'Failed to load data';
                    $('#logTableBody').html(`<tr><td colspan="8" class="text-center text-danger"><i class="fas fa-exclamation-circle"></i> ${errorMsg}</td></tr>`);
                    $('#recentErrors').html(`<div class="text-center p-4 text-danger"><i class="fas fa-exclamation-circle"></i> ${errorMsg}</div>`);
                })
                .always(() => {
                    refreshBtn.html(originalContent).prop('disabled', false);
                });
        }

        function refreshPackages() {
            const packagesTableBody = $('#packagesTableBody');
            packagesTableBody.html(`<tr><td colspan="5" class="text-center"><i class="fas fa-spinner fa-spin"></i></td></tr>`);

            $.getJSON('/insight/api/packages', function(packages) {
                packagesTableBody.empty();
                packages.forEach(pkg => {
                    const isUpToDate = pkg.current_version === pkg.latest_version;
                    const statusBadge = isUpToDate ? 
                        '<span class="badge" style="background-color: var(--success-color);">Up to date</span>' : 
                        `<span class="badge" style="background-color: var(--warning-color); color: #000">Update available</span>`;
                    
                    packagesTableBody.append(`
                        <tr>
                            <td><strong>${pkg.name}</strong>${pkg.required ? ' <span class="badge" style="background-color: var(--info-color); color: #000">Required</span>' : ''}</td>
                            <td>${pkg.current_version}</td>
                            <td>${pkg.latest_version}</td>
                            <td>${statusBadge}</td>
                            <td><small class="text-muted">${pkg.description || 'N/A'}</small></td>
                        </tr>
                    `);
                });
            }).fail(function() {
                packagesTableBody.html(`<tr><td colspan="5" class="text-center text-danger"><i class="fas fa-exclamation-circle"></i> Failed to load packages.</td></tr>`);
            });
        }

        document.getElementById('themeSwitch').addEventListener('change', toggleTheme);

        $(document).ready(function() {
            initializeTheme();
            initializeCharts();
            initializeDataTable();
            refreshAllData();
            refreshPackages();
            
            $('#currentYear').text(new Date().getFullYear());
        });
    </script>
</body>
</html>