<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GraphQL System Health Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .dashboard {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            font-size: 2.5rem;
            font-weight: 700;
            background: linear-gradient(135deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 10px;
        }

        .header .subtitle {
            color: #666;
            font-size: 1.1rem;
        }

        .status-overview {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .status-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .status-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
        }

        .status-card h3 {
            font-size: 1.2rem;
            margin-bottom: 15px;
            color: #333;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }

        .status-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            animation: pulse 2s infinite;
        }

        .status-dot.healthy {
            background: #10b981;
        }

        .status-dot.degraded {
            background: #f59e0b;
        }

        .status-dot.unhealthy {
            background: #ef4444;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .metric-value {
            font-size: 2rem;
            font-weight: 700;
            color: #333;
        }

        .metric-label {
            color: #666;
            font-size: 0.9rem;
            margin-top: 5px;
        }

        .charts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 30px;
            margin-bottom: 30px;
        }

        .chart-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }

        .chart-container h3 {
            margin-bottom: 20px;
            color: #333;
            font-size: 1.3rem;
        }

        .chart-canvas {
            max-height: 300px;
        }

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

        .component-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }

        .component-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .component-name {
            font-weight: 600;
            color: #333;
        }

        .component-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .component-status.healthy {
            background: #dcfce7;
            color: #166534;
        }

        .component-status.degraded {
            background: #fef3c7;
            color: #92400e;
        }

        .component-status.unhealthy {
            background: #fee2e2;
            color: #991b1b;
        }

        .component-details {
            color: #666;
            font-size: 0.9rem;
            line-height: 1.5;
        }

        .response-time {
            margin-top: 10px;
            font-size: 0.8rem;
            color: #888;
        }

        .alerts-section {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }

        .alerts-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .alert-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 10px;
            border-left: 4px solid;
        }

        .alert-item.critical {
            background: #fef2f2;
            border-left-color: #ef4444;
        }

        .alert-item.warning {
            background: #fffbeb;
            border-left-color: #f59e0b;
        }

        .alert-item.info {
            background: #eff6ff;
            border-left-color: #3b82f6;
        }

        .alert-icon {
            width: 20px;
            height: 20px;
            border-radius: 50%;
        }

        .alert-icon.critical {
            background: #ef4444;
        }

        .alert-icon.warning {
            background: #f59e0b;
        }

        .alert-icon.info {
            background: #3b82f6;
        }

        .alert-content {
            flex: 1;
        }

        .alert-message {
            font-weight: 600;
            margin-bottom: 5px;
        }

        .alert-time {
            font-size: 0.8rem;
            color: #666;
        }

        .refresh-controls {
            display: flex;
            gap: 15px;
            align-items: center;
            margin-bottom: 20px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: #f3f4f6;
            color: #374151;
        }

        .btn-secondary:hover {
            background: #e5e7eb;
        }

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

        .switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }

        .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: 24px;
        }

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

        input:checked + .slider {
            background: linear-gradient(135deg, #667eea, #764ba2);
        }

        input:checked + .slider:before {
            transform: translateX(26px);
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
            color: #666;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .last-updated {
            text-align: center;
            color: #666;
            font-size: 0.9rem;
            margin-top: 20px;
        }

        /* Advanced Performance Monitoring Styles */
        .performance-section {
            margin-top: 40px;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }

        .performance-section h2 {
            color: #1f2937;
            margin-bottom: 25px;
            font-size: 1.8rem;
            font-weight: 700;
        }

        .performance-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 25px;
        }

        .performance-card {
            background: #ffffff;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
            border: 1px solid #e5e7eb;
        }

        .performance-card h3 {
            color: #374151;
            margin-bottom: 15px;
            font-size: 1.2rem;
            font-weight: 600;
            border-bottom: 2px solid #f3f4f6;
            padding-bottom: 10px;
        }

        .queries-table {
            max-height: 300px;
            overflow-y: auto;
        }

        .queries-table table {
            width: 100%;
            border-collapse: collapse;
        }

        .queries-table th,
        .queries-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #f3f4f6;
        }

        .queries-table th {
            background-color: #f8fafc;
            font-weight: 600;
            color: #374151;
            position: sticky;
            top: 0;
        }

        .queries-table tbody tr:hover {
            background-color: #f9fafb;
        }

        .query-item {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 12px;
            border-bottom: 1px solid #f3f4f6;
            transition: background-color 0.2s ease;
        }

        .query-item:hover {
            background-color: #f9fafb;
        }

        .query-info {
            flex: 1;
            margin-right: 15px;
        }

        .query-name {
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 4px;
        }

        .query-text {
            font-size: 0.8rem;
            color: #6b7280;
            font-family: 'Courier New', monospace;
            background: #f3f4f6;
            padding: 4px 8px;
            border-radius: 4px;
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .query-stats {
            text-align: right;
            min-width: 120px;
        }

        .stat-value {
            font-weight: 600;
            color: #1f2937;
        }

        .stat-label {
            font-size: 0.8rem;
            color: #6b7280;
        }

        .alerts-list {
            max-height: 300px;
            overflow-y: auto;
        }

        .slow-query-alert {
            padding: 12px;
            border-left: 4px solid #ef4444;
            background: #fef2f2;
            margin-bottom: 10px;
            border-radius: 0 8px 8px 0;
        }

        .alert-query-name {
            font-weight: 600;
            color: #dc2626;
            margin-bottom: 4px;
        }

        .alert-details {
            font-size: 0.85rem;
            color: #7f1d1d;
        }

        .alert-timestamp {
            font-size: 0.75rem;
            color: #991b1b;
            margin-top: 4px;
        }

        .percentiles-display {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 15px;
        }

        .percentile-item {
            text-align: center;
            padding: 15px;
            background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
            border-radius: 10px;
        }

        .percentile-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 5px;
        }

        .percentile-label {
            font-size: 0.8rem;
            color: #6b7280;
            font-weight: 500;
        }

        .complexity-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .complexity-item {
            text-align: center;
            padding: 12px;
            background: #f8fafc;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }

        .complexity-value {
            font-size: 1.3rem;
            font-weight: 600;
            color: #2563eb;
            margin-bottom: 4px;
        }

        .complexity-label {
            font-size: 0.75rem;
            color: #64748b;
        }

        .no-alerts,
        .no-data {
            text-align: center;
            color: #6b7280;
            font-style: italic;
            padding: 20px;
        }

        @media (max-width: 768px) {
            .dashboard {
                padding: 10px;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .charts-grid {
                grid-template-columns: 1fr;
            }
            
            .status-overview {
                grid-template-columns: 1fr;
            }

            .performance-grid {
                grid-template-columns: 1fr;
            }

            .percentiles-display {
                grid-template-columns: repeat(2, 1fr);
            }

            .complexity-stats {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body>
    <div class="dashboard">
        <div class="header">
            <h1>GraphQL System Health Dashboard</h1>
            <p class="subtitle">Real-time monitoring and diagnostics for your GraphQL infrastructure</p>
        </div>

        <div class="refresh-controls">
            <button class="btn btn-primary" onclick="refreshData()">Refresh Now</button>
            <div class="auto-refresh">
                <label class="switch">
                    <input type="checkbox" id="autoRefresh" onchange="toggleAutoRefresh()">
                    <span class="slider"></span>
                </label>
                <span>Auto-refresh (30s)</span>
            </div>
        </div>

        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>Loading health data...</p>
        </div>

        <div class="status-overview" id="statusOverview">
            <!-- Status cards will be populated by JavaScript -->
        </div>

        <div class="charts-grid">
            <div class="chart-container">
                <h3>System Performance</h3>
                <canvas id="performanceChart" class="chart-canvas"></canvas>
            </div>
            <div class="chart-container">
                <h3>Response Times</h3>
                <canvas id="responseTimeChart" class="chart-canvas"></canvas>
            </div>
            <div class="chart-container">
                <h3>Query Execution Distribution</h3>
                <canvas id="executionDistributionChart" class="chart-canvas"></canvas>
            </div>
            <div class="chart-container">
                <h3>Query Complexity Analysis</h3>
                <canvas id="complexityChart" class="chart-canvas"></canvas>
            </div>
        </div>

        <!-- Advanced Performance Monitoring Section -->
        <div class="performance-section">
            <h2>Advanced Performance Monitoring</h2>
            
            <div class="performance-grid">
                <div class="performance-card">
                    <h3>Most Frequent Queries</h3>
                    <div id="frequentQueriesTable" class="queries-table">
                        <table>
                            <thead>
                                <tr>
                                    <th>Query Name</th>
                                    <th>Call Count</th>
                                    <th>Avg Time</th>
                                    <th>Success Rate</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Will be populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div class="performance-card">
                    <h3>Slowest Queries</h3>
                    <div id="slowestQueriesTable" class="queries-table">
                        <table>
                            <thead>
                                <tr>
                                    <th>Query Name</th>
                                    <th>Call Count</th>
                                    <th>Avg Time</th>
                                    <th>Success Rate</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Will be populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div class="performance-card">
                    <h3>Recent Slow Query Alerts</h3>
                    <div id="slowQueryAlerts" class="alerts-list">
                        <!-- Will be populated by JavaScript -->
                    </div>
                </div>
                
                <div class="performance-card">
                    <h3>Performance Percentiles</h3>
                    <div id="performancePercentiles" class="percentiles-display">
                        <!-- Will be populated by JavaScript -->
                    </div>
                </div>
            </div>
        </div>
            <div class="chart-container">
                <h3>Component Health Over Time</h3>
                <canvas id="healthTrendChart" class="chart-canvas"></canvas>
            </div>
            <div class="chart-container">
                <h3>Resource Usage</h3>
                <canvas id="resourceChart" class="chart-canvas"></canvas>
            </div>
        </div>

        <div class="components-grid" id="componentsGrid">
            <!-- Component cards will be populated by JavaScript -->
        </div>

        <div class="alerts-section">
            <div class="alerts-header">
                <h3>Recent Alerts & Recommendations</h3>
                <span id="alertCount" class="metric-value">0</span>
            </div>
            <div id="alertsList">
                <!-- Alerts will be populated by JavaScript -->
            </div>
        </div>

        <div class="last-updated" id="lastUpdated">
            Last updated: Never
        </div>
    </div>

    <script>
        // Global variables
        let autoRefreshInterval = null;
        let charts = {};
        let healthHistory = [];

        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            initializeCharts();
            refreshData();
        });

        // Initialize Chart.js charts
        function initializeCharts() {
            const chartOptions = {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            };

            // Performance Chart
            charts.performance = new Chart(document.getElementById('performanceChart'), {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'CPU Usage (%)',
                        data: [],
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'Memory Usage (%)',
                        data: [],
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        tension: 0.4
                    }]
                },
                options: chartOptions
            });

            // Response Time Chart
            charts.responseTime = new Chart(document.getElementById('responseTimeChart'), {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Response Time (ms)',
                        data: [],
                        backgroundColor: [
                            '#10b981',
                            '#3b82f6',
                            '#8b5cf6',
                            '#f59e0b',
                            '#ef4444'
                        ]
                    }]
                },
                options: chartOptions
            });

            // Health Trend Chart
            charts.healthTrend = new Chart(document.getElementById('healthTrendChart'), {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Healthy Components',
                        data: [],
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'Degraded Components',
                        data: [],
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'Unhealthy Components',
                        data: [],
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        tension: 0.4
                    }]
                },
                options: chartOptions
            });

            // Resource Chart (Doughnut)
            charts.resource = new Chart(document.getElementById('resourceChart'), {
                type: 'doughnut',
                data: {
                    labels: ['Used Memory', 'Available Memory'],
                    datasets: [{
                        data: [0, 100],
                        backgroundColor: ['#ef4444', '#10b981']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });

            // Execution Distribution Chart
            charts.executionDistribution = new Chart(document.getElementById('executionDistributionChart'), {
                type: 'bar',
                data: {
                    labels: ['P50', 'P75', 'P90', 'P95', 'P99'],
                    datasets: [{
                        label: 'Execution Time (ms)',
                        data: [0, 0, 0, 0, 0],
                        backgroundColor: [
                            '#10b981',
                            '#3b82f6',
                            '#8b5cf6',
                            '#f59e0b',
                            '#ef4444'
                        ]
                    }]
                },
                options: {
                    ...chartOptions,
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Time (ms)'
                            }
                        }
                    }
                }
            });

            // Complexity Chart
            charts.complexity = new Chart(document.getElementById('complexityChart'), {
                type: 'radar',
                data: {
                    labels: ['Avg Complexity', 'Max Complexity', 'Avg Depth', 'Max Depth', 'Complex Queries', 'Deep Queries'],
                    datasets: [{
                        label: 'Query Complexity Metrics',
                        data: [0, 0, 0, 0, 0, 0],
                        borderColor: '#8b5cf6',
                        backgroundColor: 'rgba(139, 92, 246, 0.1)',
                        pointBackgroundColor: '#8b5cf6'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    },
                    scales: {
                        r: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // Get CSRF token from cookie
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // Refresh health data
        async function refreshData() {
            console.log("Starting data refresh...")
            showLoading(true);
            try {
                const csrftoken = getCookie('csrftoken');
                const response = await fetch('/graphql/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrftoken,
                    },
                    body: JSON.stringify({
                        query: `
                            query {
                    health_status {
                        overall_status
                        timestamp
                        report_generation_time_ms
                        healthy_components
                        degraded_components
                        unhealthy_components
                        recommendations
                    }
                    system_metrics {
                        cpu_usage_percent
                        memory_usage_percent
                        memory_used_mb
                        memory_available_mb
                        disk_usage_percent
                        active_connections
                        cache_hit_rate
                        uptime_seconds
                    }
                    schema_health {
                        component
                        status
                        message
                        response_time_ms
                        timestamp
                    }
                    performance {
                        execution_time_distribution(time_window_minutes: 60) {
                            p50
                            p75
                            p90
                            p95
                            p99
                            min_time
                            max_time
                            avg_time
                            total_requests
                        }
                        most_frequent_queries(limit: 10) {
                            query_hash
                            query_name
                            query_text
                            call_count
                            avg_execution_time
                            success_rate
                        }
                        slowest_queries(limit: 10) {
                            query_hash
                            query_name
                            query_text
                            call_count
                            avg_execution_time
                            success_rate
                        }
                        recent_slow_queries(limit: 20) {
                            query_hash
                            query_name
                            execution_time
                            threshold
                            timestamp
                            query_complexity
                        }
                        complexity_stats {
                            avg_complexity
                            max_complexity
                            avg_depth
                            max_depth
                            complex_queries_count
                            deep_queries_count
                        }
                    }
                }
                        `
                    })
                });
                console.log(response)
                if (!response.ok) {
                    throw new Error('Failed to fetch health data');
                }

                const data = await response.json();
                
                if (data.errors) {
                    throw new Error(data.errors[0].message);
                }

                updateDashboard(data.data);
                
            } catch (error) {
                console.error('Error fetching health data:', error);
                showError('Failed to fetch health data: ' + error.message);
            } finally {
                showLoading(false);
                updateLastUpdated();
            }
        }

        // Update dashboard with new data
        function updateDashboard(data) {
            updateStatusOverview(data);
            updateCharts(data);
            updateComponents(data);
            updateAlerts(data);
            updatePerformanceData(data);
            
            // Store in history for trending
            healthHistory.push({
                timestamp: new Date(),
                ...data
            });
            
            // Keep only last 20 entries
            if (healthHistory.length > 20) {
                healthHistory = healthHistory.slice(-20);
            }
        }

        // Update status overview cards
        function updateStatusOverview(data) {
            const container = document.getElementById('statusOverview');
            const healthStatus = data.health_status || {};
                const systemMetrics = data.system_metrics || {};
            
            container.innerHTML = `
                <div class="status-card">
                    <h3>Overall Status</h3>
                    <div class="status-indicator">
                        <div class="status-dot ${healthStatus.overall_status || 'unhealthy'}"></div>
                <span class="metric-value">${(healthStatus.overall_status || 'Unknown').toUpperCase()}</span>
                    </div>
                    <div class="metric-label">System Health</div>
                </div>
                
                <div class="status-card">
                    <h3>CPU Usage</h3>
                    <div class="metric-value">${(systemMetrics.cpu_usage_percent || 0).toFixed(1)}%</div>
                    <div class="metric-label">Current CPU Load</div>
                </div>
                
                <div class="status-card">
                    <h3>Memory Usage</h3>
                    <div class="metric-value">${(systemMetrics.memory_usage_percent || 0).toFixed(1)}%</div>
                <div class="metric-label">${(systemMetrics.memory_used_mb || 0).toFixed(0)} MB Used</div>
                </div>
                
                <div class="status-card">
                    <h3>Cache Performance</h3>
                    <div class="metric-value">${(systemMetrics.cache_hit_rate || 0).toFixed(1)}%</div>
                    <div class="metric-label">Hit Rate</div>
                </div>
                
                <div class="status-card">
                    <h3>Active Connections</h3>
                    <div class="metric-value">${systemMetrics.active_connections || 0}</div>
                    <div class="metric-label">Database Connections</div>
                </div>
                
                <div class="status-card">
                    <h3>Uptime</h3>
                    <div class="metric-value">${formatUptime(systemMetrics.uptime_seconds || 0)}</div>
                    <div class="metric-label">System Uptime</div>
                </div>
            `;
        }

        // Update charts with new data
        function updateCharts(data) {
            const systemMetrics = data.system_metrics || {};
            const timestamp = new Date().toLocaleTimeString();
            
            // Update performance chart
            if (charts.performance) {
                charts.performance.data.labels.push(timestamp);
                charts.performance.data.datasets[0].data.push(systemMetrics.cpu_usage_percent || 0);
            charts.performance.data.datasets[1].data.push(systemMetrics.memory_usage_percent || 0);
                
                // Keep only last 10 data points
                if (charts.performance.data.labels.length > 10) {
                    charts.performance.data.labels.shift();
                    charts.performance.data.datasets[0].data.shift();
                    charts.performance.data.datasets[1].data.shift();
                }
                
                charts.performance.update();
            }
            
            // Update resource chart
            if (charts.resource && systemMetrics.memory_usage_percent) {
                charts.resource.data.datasets[0].data = [
                    systemMetrics.memory_usage_percent,
                    100 - systemMetrics.memory_usage_percent
                ];
                charts.resource.update();
            }
            
            // Update health trend chart
            if (charts.healthTrend && data.health_status) {
                charts.healthTrend.data.labels.push(timestamp);
                charts.healthTrend.data.datasets[0].data.push(data.health_status.healthy_components || 0);
                charts.healthTrend.data.datasets[1].data.push(data.health_status.degraded_components || 0);
                charts.healthTrend.data.datasets[2].data.push(data.health_status.unhealthy_components || 0);
                
                // Keep only last 10 data points
                if (charts.healthTrend.data.labels.length > 10) {
                    charts.healthTrend.data.labels.shift();
                    charts.healthTrend.data.datasets[0].data.shift();
                    charts.healthTrend.data.datasets[1].data.shift();
                    charts.healthTrend.data.datasets[2].data.shift();
                }
                
                charts.healthTrend.update();
            }
        }

        // Update component status
        function updateComponents(data) {
            const container = document.getElementById('componentsGrid');
            const schemaHealth = data.schema_health || {};
            
            // Mock component data - in real implementation, this would come from the API
            const components = [
                {
                    name: 'GraphQL Schema',
                    status: schemaHealth.status || 'unknown',
                    message: schemaHealth.message || 'No data available',
                    responseTime: schemaHealth.responseTimeMs || 0
                },
                {
                    name: 'Primary Database',
                    status: 'healthy',
                    message: 'Connection successful',
                    responseTime: 45
                },
                {
                    name: 'Redis Cache',
                    status: 'healthy',
                    message: 'Operations successful',
                    responseTime: 12
                },
                {
                    name: 'File Storage',
                    status: 'healthy',
                    message: 'All operations normal',
                    responseTime: 78
                }
            ];
            
            container.innerHTML = components.map(component => `
                <div class="component-card">
                    <div class="component-header">
                        <span class="component-name">${component.name}</span>
                        <span class="component-status ${component.status}">${component.status}</span>
                    </div>
                    <div class="component-details">${component.message}</div>
                    <div class="response-time">Response time: ${component.responseTime}ms</div>
                </div>
            `).join('');
        }

        // Update alerts section
        function updateAlerts(data) {
            const container = document.getElementById('alertsList');
            const countElement = document.getElementById('alertCount');
            const recommendations = data.health_status?.recommendations || [];
            
            countElement.textContent = recommendations.length;
            
            if (recommendations.length === 0) {
                container.innerHTML = '<p style="color: #666; text-align: center; padding: 20px;">No alerts or recommendations at this time.</p>';
                return;
            }
            
            container.innerHTML = recommendations.map((rec, index) => {
                const level = rec.toLowerCase().includes('critical') ? 'critical' : 
                             rec.toLowerCase().includes('warning') || rec.toLowerCase().includes('high') ? 'warning' : 'info';
                
                return `
                    <div class="alert-item ${level}">
                        <div class="alert-icon ${level}"></div>
                        <div class="alert-content">
                            <div class="alert-message">${rec}</div>
                            <div class="alert-time">Just now</div>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // Toggle auto-refresh
        function toggleAutoRefresh() {
            const checkbox = document.getElementById('autoRefresh');
            
            if (checkbox.checked) {
                autoRefreshInterval = setInterval(refreshData, 30000); // 30 seconds
            } else {
                if (autoRefreshInterval) {
                    clearInterval(autoRefreshInterval);
                    autoRefreshInterval = null;
                }
            }
        }

        // Show/hide loading indicator
        function showLoading(show) {
            const loading = document.getElementById('loading');
            loading.style.display = show ? 'block' : 'none';
        }

        // Show error message
        function showError(message) {
            const container = document.getElementById('statusOverview');
            container.innerHTML = `
                <div class="status-card" style="grid-column: 1 / -1; background: #fee2e2; border-left: 4px solid #ef4444;">
                    <h3 style="color: #991b1b;">Error</h3>
                    <p style="color: #991b1b;">${message}</p>
                </div>
            `;
        }

        // Update last updated timestamp
        function updateLastUpdated() {
            const element = document.getElementById('lastUpdated');
            element.textContent = `Last updated: ${new Date().toLocaleString()}`;
        }

        // Update performance data and visualizations
        function updatePerformanceData(data) {
            const performance = data.performance || {};
            
            // Update execution distribution chart
            if (charts.executionDistribution && performance.execution_time_distribution) {
                const dist = performance.execution_time_distribution;
                charts.executionDistribution.data.datasets[0].data = [
                    dist.p50 || 0,
                    dist.p75 || 0,
                    dist.p90 || 0,
                    dist.p95 || 0,
                    dist.p99 || 0
                ];
                charts.executionDistribution.update();
            }
            
            // Update complexity chart
            if (charts.complexity && performance.complexity_stats) {
                const stats = performance.complexity_stats;
                charts.complexity.data.datasets[0].data = [
                    stats.avg_complexity || 0,
                    stats.max_complexity || 0,
                    stats.avg_depth || 0,
                    stats.max_depth || 0,
                    stats.complex_queries_count || 0,
                    stats.deep_queries_count || 0
                ];
                charts.complexity.update();
            }
            
            // Update performance percentiles
            updatePerformancePercentiles(performance.execution_time_distribution);
            
            // Update query tables
            updateQueryTables(performance);
            
            // Update slow query alerts
            updateSlowQueryAlerts(performance.recent_slow_queries);
        }
        
        // Update performance percentiles display
        function updatePerformancePercentiles(distribution) {
            const container = document.getElementById('performancePercentiles');
            if (!container) return;
            
            if (!distribution) {
                container.innerHTML = '<p class="no-data">No performance data available</p>';
                return;
            }
            
            container.innerHTML = `
                <div class="percentile-item">
                    <span class="percentile-label">P50</span>
                    <span class="percentile-value">${(distribution.p50 || 0).toFixed(2)}ms</span>
                </div>
                <div class="percentile-item">
                    <span class="percentile-label">P95</span>
                    <span class="percentile-value">${(distribution.p95 || 0).toFixed(2)}ms</span>
                </div>
                <div class="percentile-item">
                    <span class="percentile-label">P99</span>
                    <span class="percentile-value">${(distribution.p99 || 0).toFixed(2)}ms</span>
                </div>
                <div class="percentile-item">
                    <span class="percentile-label">Avg</span>
                    <span class="percentile-value">${(distribution.avg_time || 0).toFixed(2)}ms</span>
                </div>
                <div class="percentile-item">
                    <span class="percentile-label">Total</span>
                    <span class="percentile-value">${distribution.total_requests || 0}</span>
                </div>
            `;
        }
        
        // Update query tables
        function updateQueryTables(performance) {
            // Update most frequent queries
            const frequentContainer = document.getElementById('frequentQueriesTable');
            if (frequentContainer && performance.most_frequent_queries) {
                const tbody = frequentContainer.querySelector('tbody');
                if (tbody) {
                    tbody.innerHTML = performance.most_frequent_queries.map(query => `
                        <tr>
                            <td title="${query.query_text || 'N/A'}">${query.query_name || query.query_hash || 'Unknown'}</td>
                            <td>${query.call_count || 0}</td>
                            <td>${(query.avg_execution_time || 0).toFixed(2)}ms</td>
                            <td>${((query.success_rate || 0) * 100).toFixed(1)}%</td>
                        </tr>
                    `).join('');
                }
            }
            
            // Update slowest queries
            const slowestContainer = document.getElementById('slowestQueriesTable');
            if (slowestContainer && performance.slowest_queries) {
                const tbody = slowestContainer.querySelector('tbody');
                if (tbody) {
                    tbody.innerHTML = performance.slowest_queries.map(query => `
                        <tr>
                            <td title="${query.query_text || 'N/A'}">${query.query_name || query.query_hash || 'Unknown'}</td>
                            <td>${query.call_count || 0}</td>
                            <td>${(query.avg_execution_time || 0).toFixed(2)}ms</td>
                            <td>${((query.success_rate || 0) * 100).toFixed(1)}%</td>
                        </tr>
                    `).join('');
                }
            }
        }
        
        // Update slow query alerts
        function updateSlowQueryAlerts(slowQueries) {
            const container = document.getElementById('slowQueryAlerts');
            if (!container) return;
            
            if (!slowQueries || slowQueries.length === 0) {
                container.innerHTML = '<p class="no-alerts">No recent slow queries detected</p>';
                return;
            }
            
            container.innerHTML = slowQueries.map(alert => `
                <div class="slow-query-alert">
                    <div class="alert-header">
                        <span class="query-name">${alert.query_name || alert.query_hash || 'Unknown Query'}</span>
                        <span class="alert-time">${new Date(alert.timestamp).toLocaleTimeString()}</span>
                    </div>
                    <div class="alert-details">
                        <span>Execution: ${(alert.execution_time || 0).toFixed(2)}ms</span>
                        <span>Threshold: ${(alert.threshold || 0).toFixed(2)}ms</span>
                        <span>Complexity: ${alert.query_complexity || 'N/A'}</span>
                    </div>
                </div>
            `).join('');
        }

        // Format uptime seconds to human readable
        function formatUptime(seconds) {
            const days = Math.floor(seconds / 86400);
            const hours = Math.floor((seconds % 86400) / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            
            if (days > 0) {
                return `${days}d ${hours}h`;
            } else if (hours > 0) {
                return `${hours}h ${minutes}m`;
            } else {
                return `${minutes}m`;
            }
        }
    </script>
</body>
</html>