<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Judge LLM - Monitor</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #fafafa;
            color: #1a1a1a;
            overflow: hidden;
        }

        .app {
            display: flex;
            height: 100vh;
        }

        /* Left Sidebar */
        .sidebar {
            width: 220px;
            background: white;
            border-right: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            padding: 16px 20px;
            border-bottom: 1px solid #e0e0e0;
        }

        .project-name {
            font-size: 13px;
            font-weight: 600;
            color: #666;
            margin-bottom: 4px;
        }

        .project-title {
            font-size: 15px;
            font-weight: 600;
            color: #1a1a1a;
        }

        .sidebar-nav {
            flex: 1;
            overflow-y: auto;
            padding: 8px 0;
        }

        .nav-item {
            display: flex;
            align-items: center;
            padding: 8px 20px;
            color: #666;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.15s;
            border-left: 2px solid transparent;
        }

        .nav-item:hover {
            background: #f5f5f5;
            color: #1a1a1a;
        }

        .nav-item.active {
            background: #f0f0f0;
            color: #1a1a1a;
            border-left-color: #4a90e2;
        }

        .nav-item-icon {
            margin-right: 10px;
            font-size: 14px;
        }

        .nav-separator {
            height: 1px;
            background: #e0e0e0;
            margin: 8px 20px;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        /* Top Bar */
        .topbar {
            background: white;
            border-bottom: 1px solid #e0e0e0;
            padding: 12px 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .page-title {
            font-size: 15px;
            font-weight: 600;
            color: #1a1a1a;
        }

        .topbar-actions {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .btn-upload {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            background: white;
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            font-size: 12px;
            color: #1a1a1a;
            cursor: pointer;
            transition: all 0.15s;
        }

        .btn-upload:hover {
            border-color: #4a90e2;
            background: #f9fafb;
        }

        .time-filter {
            display: flex;
            gap: 4px;
            padding: 2px;
            background: #f5f5f5;
            border-radius: 4px;
        }

        .time-btn {
            padding: 4px 12px;
            font-size: 11px;
            border: none;
            background: transparent;
            color: #666;
            cursor: pointer;
            border-radius: 3px;
            transition: all 0.15s;
        }

        .time-btn.active {
            background: white;
            color: #1a1a1a;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
        }

        /* Content Area */
        .content {
            flex: 1;
            overflow-y: auto;
            padding: 24px;
            padding-bottom: 50px; /* Space for footer */
        }

        .upload-prompt {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #999;
        }

        .upload-prompt-icon {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.3;
        }

        .upload-prompt-text {
            font-size: 14px;
            margin-bottom: 20px;
        }

        /* Metrics Grid */
        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .metric-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 16px;
        }

        .metric-label {
            font-size: 11px;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 8px;
        }

        .metric-value {
            font-size: 24px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 4px;
        }

        .metric-subtitle {
            font-size: 12px;
            color: #999;
        }

        /* Charts Section */
        .charts-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .chart-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 20px;
        }

        .chart-card.wide {
            grid-column: 1 / -1;
        }

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

        .chart-title {
            font-size: 13px;
            font-weight: 600;
            color: #1a1a1a;
        }

        .chart-info {
            font-size: 11px;
            color: #999;
        }

        .chart-container {
            height: 200px;
        }

        .chart-container.tall {
            height: 300px;
        }

        .no-data {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 200px;
            color: #ccc;
            font-size: 12px;
        }

        /* Table */
        .table-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            overflow: hidden;
        }

        .table-header {
            padding: 16px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .table-title {
            font-size: 13px;
            font-weight: 600;
            color: #1a1a1a;
        }

        .table-search {
            padding: 4px 10px;
            font-size: 12px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            outline: none;
            width: 200px;
        }

        .table-search:focus {
            border-color: #4a90e2;
        }

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

        thead {
            background: #fafafa;
            border-bottom: 1px solid #e0e0e0;
        }

        th {
            padding: 10px 20px;
            text-align: left;
            font-size: 11px;
            font-weight: 600;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        td {
            padding: 12px 20px;
            font-size: 13px;
            color: #1a1a1a;
            border-bottom: 1px solid #f0f0f0;
        }

        tr:hover {
            background: #fafafa;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: 500;
        }

        .status-success {
            background: #e6f7ed;
            color: #1e7e34;
        }

        .status-error {
            background: #fee;
            color: #c41e3a;
        }

        .execution-row {
            cursor: pointer;
        }

        .execution-details {
            padding: 16px 20px;
            background: #f9f9f9;
            border-top: 1px solid #e0e0e0;
        }

        .execution-row.expanded {
            background: #f0f0f0;
        }

        .detail-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 16px;
        }

        .detail-section {
            margin-bottom: 16px;
        }

        .detail-label {
            font-size: 11px;
            color: #666;
            text-transform: uppercase;
            margin-bottom: 6px;
            letter-spacing: 0.5px;
        }

        .detail-value {
            font-size: 13px;
            color: #1a1a1a;
        }

        .detail-value code {
            font-family: 'Monaco', 'Courier New', monospace;
            font-size: 12px;
            color: #666;
        }

        .conversation-comparison {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .conv-panel {
            padding: 12px;
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
        }

        .conv-header {
            font-size: 11px;
            color: #666;
            margin-bottom: 8px;
            text-transform: uppercase;
        }

        .conv-content {
            font-size: 13px;
            line-height: 1.6;
            color: #1a1a1a;
        }

        code {
            font-family: 'Monaco', 'Courier New', monospace;
            font-size: 12px;
            color: #666;
        }

        #fileInput {
            display: none;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }

        /* Loading state */
        .loading {
            display: inline-block;
            width: 14px;
            height: 14px;
            border: 2px solid #f0f0f0;
            border-top-color: #666;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* Agent Performance Grid */
        .agent-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .agent-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 16px;
            cursor: pointer;
            transition: all 0.15s;
        }

        .agent-card:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .agent-name {
            font-size: 14px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 8px;
        }

        .agent-stats {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            font-size: 12px;
            color: #666;
        }

        .agent-stat {
            display: flex;
            justify-content: space-between;
        }

        .agent-stat-value {
            font-weight: 600;
            color: #1a1a1a;
        }
    </style>
</head>
<body>
    <div class="app">
        <!-- Left Sidebar -->
        <div class="sidebar">
            <div class="sidebar-header">
                <div class="project-title">Judge LLM</div>
            </div>

            <nav class="sidebar-nav">
                <div style="padding: 8px 20px; margin-bottom: 8px;">
                    <a href="https://github.com/HiHelloAI/judge-llm" target="_blank" rel="noopener noreferrer" style="color: #666; text-decoration: none; font-size: 11px; display: flex; align-items: center; gap: 6px;">
                        <span>⭐</span>
                        <span>Star on GitHub</span>
                    </a>
                </div>
                <div class="nav-item active" data-view="monitor">
                    <span class="nav-item-icon">📊</span>
                    Monitor
                </div>
                <div class="nav-item" data-view="agents">
                    <span class="nav-item-icon">🤖</span>
                    Agents
                </div>
                <div class="nav-item" data-view="executions">
                    <span class="nav-item-icon">🚀</span>
                    Executions
                </div>
                <div class="nav-item" data-view="providers">
                    <span class="nav-item-icon">🔌</span>
                    Providers
                </div>
                <div class="nav-item" data-view="testcases">
                    <span class="nav-item-icon">🧪</span>
                    Test Cases
                </div>
                <div class="nav-item" data-view="evaluators">
                    <span class="nav-item-icon">🎯</span>
                    Evaluators
                </div>
                <div class="nav-separator"></div>
                <div class="nav-item" data-view="datasets">
                    <span class="nav-item-icon">📁</span>
                    Datasets
                </div>
                <div class="nav-item" data-view="reports">
                    <span class="nav-item-icon">📄</span>
                    Reports
                </div>
            </nav>
        </div>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Top Bar -->
            <div class="topbar">
                <div class="topbar-left">
                    <div class="page-title" id="pageTitle">Monitor</div>
                </div>

                <div class="topbar-actions">
                    <div class="time-filter">
                        <button class="time-btn" data-days="1">1d</button>
                        <button class="time-btn active" data-days="3">3d</button>
                        <button class="time-btn" data-days="7">7d</button>
                        <button class="time-btn" data-days="30">30d</button>
                        <button class="time-btn" data-days="all">All</button>
                    </div>

                    <button class="btn-upload" id="uploadBtn">
                        <span>📁</span>
                        <span>Load Database</span>
                    </button>
                    <input type="file" id="fileInput" accept=".db">
                </div>
            </div>

            <!-- Content -->
            <div class="content" id="content">
                <div class="upload-prompt">
                    <div class="upload-prompt-icon">📊</div>
                    <div class="upload-prompt-text">Load a database file to view evaluation results</div>
                    <button class="btn-upload" onclick="document.getElementById('fileInput').click()">
                        <span>📁</span>
                        <span>Choose Database File</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer style="position: fixed; bottom: 0; left: 0; right: 0; background: #f5f5f5; border-top: 1px solid #e0e0e0; padding: 8px 20px; font-size: 11px; color: #666; text-align: center; z-index: 1000;">
        <div style="display: flex; justify-content: center; align-items: center; gap: 20px; flex-wrap: wrap;">
            <span>© 2025 <a href="https://github.com/HiHelloAI/judge-llm" target="_blank" rel="noopener noreferrer" style="color: #4a90e2; text-decoration: none;">Judge LLM</a></span>
            <span style="color: #ccc;">|</span>
            <span>Powered by <a href="https://github.com/sql-js/sql.js" target="_blank" rel="noopener noreferrer" style="color: #4a90e2; text-decoration: none;">sql.js</a> (SQLite compiled to WebAssembly)</span>
            <span style="color: #ccc;">|</span>
            <span>Charts by <a href="https://www.chartjs.org/" target="_blank" rel="noopener noreferrer" style="color: #4a90e2; text-decoration: none;">Chart.js</a></span>
        </div>
    </footer>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

    <script>
        let db = null;
        let currentView = 'monitor';
        let currentDays = 3;
        let currentAgent = null;

        // File upload
        const fileInput = document.getElementById('fileInput');
        const uploadBtn = document.getElementById('uploadBtn');

        uploadBtn.addEventListener('click', () => fileInput.click());
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) loadDatabase(file);
        });

        async function loadDatabase(file) {
            try {
                const content = document.getElementById('content');
                content.innerHTML = '<div class="upload-prompt"><div class="loading"></div><div class="upload-prompt-text" style="margin-top:16px">Loading database...</div></div>';

                const arrayBuffer = await file.arrayBuffer();
                const SQL = await initSqlJs({
                    locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${file}`
                });

                db = new SQL.Database(new Uint8Array(arrayBuffer));
                loadView(currentView);
            } catch (error) {
                console.error('Error loading database:', error);
                alert('Error loading database: ' + error.message);
            }
        }

        async function loadDatabaseFromBytes(uint8Array) {
            try {
                const content = document.getElementById('content');
                content.innerHTML = '<div class="upload-prompt"><div class="loading"></div><div class="upload-prompt-text" style="margin-top:16px">Loading embedded database...</div></div>';

                const SQL = await initSqlJs({
                    locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${file}`
                });

                db = new SQL.Database(uint8Array);
                loadView(currentView);
            } catch (error) {
                console.error('Error loading embedded database:', error);
                alert('Error loading embedded database: ' + error.message);
            }
        }

        // Auto-load embedded database if present (injected by CLI --db flag)
        window.addEventListener('DOMContentLoaded', function() {
            if (typeof EMBEDDED_DB_BASE64 !== 'undefined' && EMBEDDED_DB_BASE64) {
                const binaryString = atob(EMBEDDED_DB_BASE64);
                const bytes = new Uint8Array(binaryString.length);
                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }
                loadDatabaseFromBytes(bytes);
            }
        });

        // Navigation
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', function() {
                if (!db) {
                    alert('Please load a database first');
                    return;
                }

                document.querySelectorAll('.nav-item').forEach(i => i.classList.remove('active'));
                this.classList.add('active');

                currentView = this.getAttribute('data-view');
                currentAgent = null; // Reset agent selection
                document.getElementById('pageTitle').textContent = this.textContent.trim();
                loadView(currentView);
            });
        });

        // Time filter
        document.querySelectorAll('.time-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.time-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                currentDays = this.getAttribute('data-days');
                if (db) loadView(currentView);
            });
        });

        function loadView(view) {
            switch(view) {
                case 'monitor': loadMonitorView(); break;
                case 'agents': loadAgentsView(); break;
                case 'executions': loadExecutionsView(); break;
                case 'providers': loadProvidersView(); break;
                case 'testcases': loadTestCasesView(); break;
                case 'evaluators': loadEvaluatorsView(); break;
                case 'datasets': loadDatasetsView(); break;
                case 'reports': loadReportsView(); break;
            }
        }

        function getDateFilter() {
            if (currentDays === 'all') return '';
            return `WHERE datetime(timestamp) >= datetime('now', '-${currentDays} days')`;
        }

        function loadMonitorView() {
            const filter = getDateFilter();

            // Get metrics
            const totalExec = db.exec(`SELECT COUNT(*) as count FROM execution_runs ${filter}`)[0];
            const successRate = db.exec(`SELECT SUM(CASE WHEN overall_success = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as rate FROM execution_runs ${filter}`)[0];
            const totalCost = db.exec(`SELECT SUM(cost) as total FROM execution_runs ${filter}`)[0];
            const avgLatency = db.exec(`SELECT AVG(time_taken) as avg FROM execution_runs ${filter}`)[0];

            const metrics = {
                executions: totalExec?.values[0][0] || 0,
                successRate: successRate?.values[0][0] || 0,
                totalCost: totalCost?.values[0][0] || 0,
                avgLatency: avgLatency?.values[0][0] || 0
            };

            // Get trends
            const trends = db.exec(`
                SELECT
                    DATE(timestamp) as date,
                    COUNT(*) as executions,
                    SUM(CASE WHEN overall_success = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as success_rate,
                    SUM(cost) as cost,
                    AVG(time_taken) as latency
                FROM execution_runs
                ${filter}
                GROUP BY DATE(timestamp)
                ORDER BY date
            `)[0];

            // Get individual execution costs for bar graph
            const execCosts = db.exec(`
                SELECT
                    execution_id,
                    eval_case_id,
                    cost,
                    timestamp
                FROM execution_runs
                ${filter}
                ORDER BY timestamp DESC
                LIMIT 50
            `)[0];

            let html = `
                <div class="metrics-grid">
                    <div class="metric-card">
                        <div class="metric-label">Total Executions</div>
                        <div class="metric-value">${metrics.executions}</div>
                        <div class="metric-subtitle">Test runs completed</div>
                    </div>
                    <div class="metric-card">
                        <div class="metric-label">Success Rate</div>
                        <div class="metric-value">${metrics.successRate.toFixed(1)}%</div>
                        <div class="metric-subtitle">Tests passed</div>
                    </div>
                    <div class="metric-card">
                        <div class="metric-label">Total Cost</div>
                        <div class="metric-value">$${metrics.totalCost.toFixed(4)}</div>
                        <div class="metric-subtitle">Across all runs</div>
                    </div>
                    <div class="metric-card">
                        <div class="metric-label">Avg Latency</div>
                        <div class="metric-value">${metrics.avgLatency.toFixed(2)}s</div>
                        <div class="metric-subtitle">Average response time</div>
                    </div>
                </div>

                <div class="charts-section">
                    <div class="chart-card wide">
                        <div class="chart-header">
                            <div class="chart-title">Individual Execution Costs</div>
                            <div class="chart-info">Last 50 executions</div>
                        </div>
                        <div class="chart-container tall">
                            ${execCosts && execCosts.values.length > 0 ? '<canvas id="execCostChart"></canvas>' : '<div class="no-data">No data</div>'}
                        </div>
                    </div>

                    <div class="chart-card">
                        <div class="chart-header">
                            <div class="chart-title">Success Rate</div>
                            <div class="chart-info">Past ${currentDays === 'all' ? 'all time' : currentDays + ' days'}</div>
                        </div>
                        <div class="chart-container">
                            ${trends && trends.values.length > 0 ? '<canvas id="successChart"></canvas>' : '<div class="no-data">No data</div>'}
                        </div>
                    </div>

                    <div class="chart-card">
                        <div class="chart-header">
                            <div class="chart-title">Total Cost</div>
                            <div class="chart-info">Daily spending</div>
                        </div>
                        <div class="chart-container">
                            ${trends && trends.values.length > 0 ? '<canvas id="costChart"></canvas>' : '<div class="no-data">No data</div>'}
                        </div>
                    </div>

                    <div class="chart-card">
                        <div class="chart-header">
                            <div class="chart-title">Executions</div>
                            <div class="chart-info">Daily test runs</div>
                        </div>
                        <div class="chart-container">
                            ${trends && trends.values.length > 0 ? '<canvas id="execChart"></canvas>' : '<div class="no-data">No data</div>'}
                        </div>
                    </div>

                    <div class="chart-card">
                        <div class="chart-header">
                            <div class="chart-title">Latency (p50)</div>
                            <div class="chart-info">Response time</div>
                        </div>
                        <div class="chart-container">
                            ${trends && trends.values.length > 0 ? '<canvas id="latencyChart"></canvas>' : '<div class="no-data">No data</div>'}
                        </div>
                    </div>
                </div>
            `;

            document.getElementById('content').innerHTML = html;

            if (trends && trends.values.length > 0) {
                const dates = trends.values.map(r => r[0]);
                const successRates = trends.values.map(r => r[2]);
                const costs = trends.values.map(r => r[3]);
                const executions = trends.values.map(r => r[1]);
                const latencies = trends.values.map(r => r[4]);

                createLineChart('successChart', dates, successRates, 'Success Rate (%)', '#4a90e2');
                createBarChart('costChart', dates, costs, 'Cost ($)', '#f5a623');
                createBarChart('execChart', dates, executions, 'Executions', '#7ed321');
                createLineChart('latencyChart', dates, latencies, 'Latency (s)', '#9013fe');
            }

            // Create individual execution costs chart
            if (execCosts && execCosts.values.length > 0) {
                const labels = execCosts.values.map(r => r[1].substring(0, 15)); // Shortened execution IDs
                const costs = execCosts.values.map(r => r[2]);

                new Chart(document.getElementById('execCostChart'), {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Cost ($)',
                            data: costs,
                            backgroundColor: costs.map(c => c > 0.01 ? '#f5a623cc' : '#4a90e2cc'),
                            borderColor: costs.map(c => c > 0.01 ? '#f5a623' : '#4a90e2'),
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: false },
                            tooltip: {
                                callbacks: {
                                    title: function(context) {
                                        const idx = context[0].dataIndex;
                                        return execCosts.values[idx][0]; // Full execution ID
                                    },
                                    label: function(context) {
                                        return 'Cost: $' + context.parsed.y.toFixed(4);
                                    }
                                }
                            }
                        },
                        scales: {
                            y: { beginAtZero: true, title: { display: true, text: 'Cost ($)' } },
                            x: { display: false }
                        }
                    }
                });
            }
        }

        function loadAgentsView() {
            const filter = getDateFilter();

            // If specific agent selected, show detailed view
            if (currentAgent) {
                loadAgentDetailView(currentAgent);
                return;
            }

            // Get all agents (using app_name from eval_cases)
            const agents = db.exec(`
                SELECT
                    ec.app_name,
                    COUNT(DISTINCT er.execution_id) as total_executions,
                    SUM(CASE WHEN er.overall_success = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(er.execution_id) as success_rate,
                    SUM(er.cost) as total_cost,
                    AVG(er.time_taken) as avg_latency,
                    COUNT(DISTINCT ec.eval_case_id) as test_cases,
                    COUNT(DISTINCT er.provider_type) as providers
                FROM eval_cases ec
                JOIN execution_runs er ON ec.eval_case_id = er.eval_case_id
                ${filter ? 'WHERE ' + filter.split('WHERE ')[1] : ''}
                GROUP BY ec.app_name
                ORDER BY total_executions DESC
            `)[0];

            let html = `
                <div class="chart-card" style="margin-bottom: 20px;">
                    <div class="chart-header">
                        <div class="chart-title">Agents</div>
                        <div class="chart-info">Click on an agent to see detailed performance</div>
                    </div>
                </div>
                <div class="agent-grid">
            `;

            if (agents && agents.values.length > 0) {
                agents.values.forEach(row => {
                    const [name, executions, successRate, cost, latency, testCases, providers] = row;
                    html += `
                        <div class="agent-card" onclick="selectAgent('${name}')">
                            <div class="agent-name">${name || 'Unnamed Agent'}</div>
                            <div class="agent-stats">
                                <div class="agent-stat">
                                    <span>Executions:</span>
                                    <span class="agent-stat-value">${executions}</span>
                                </div>
                                <div class="agent-stat">
                                    <span>Success:</span>
                                    <span class="agent-stat-value">${successRate.toFixed(1)}%</span>
                                </div>
                                <div class="agent-stat">
                                    <span>Total Cost:</span>
                                    <span class="agent-stat-value">$${cost.toFixed(4)}</span>
                                </div>
                                <div class="agent-stat">
                                    <span>Avg Latency:</span>
                                    <span class="agent-stat-value">${latency.toFixed(2)}s</span>
                                </div>
                                <div class="agent-stat">
                                    <span>Test Cases:</span>
                                    <span class="agent-stat-value">${testCases}</span>
                                </div>
                                <div class="agent-stat">
                                    <span>Providers:</span>
                                    <span class="agent-stat-value">${providers}</span>
                                </div>
                            </div>
                        </div>
                    `;
                });
            } else {
                html += '<div class="empty-state">No agents found</div>';
            }

            html += '</div>';
            document.getElementById('content').innerHTML = html;
        }

        function selectAgent(agentName) {
            currentAgent = agentName;
            document.getElementById('pageTitle').textContent = `Agent: ${agentName}`;
            loadAgentDetailView(agentName);
        }

        function loadAgentDetailView(agentName) {
            const filter = getDateFilter();
            const whereClause = filter ? `AND ${filter.split('WHERE ')[1]}` : '';

            // Get agent performance over time
            const trends = db.exec(`
                SELECT
                    DATE(er.timestamp) as date,
                    COUNT(er.execution_id) as executions,
                    SUM(CASE WHEN er.overall_success = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(er.execution_id) as success_rate,
                    SUM(er.cost) as cost,
                    AVG(er.time_taken) as latency
                FROM eval_cases ec
                JOIN execution_runs er ON ec.eval_case_id = er.eval_case_id
                WHERE ec.app_name = ? ${whereClause}
                GROUP BY DATE(er.timestamp)
                ORDER BY date
            `, [agentName])[0];

            // Get evaluator performance for this agent
            const evaluatorStats = db.exec(`
                SELECT
                    evr.evaluator_name,
                    evr.evaluator_type,
                    AVG(evr.score) as avg_score,
                    AVG(evr.threshold) as avg_threshold,
                    SUM(CASE WHEN evr.passed = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as pass_rate,
                    COUNT(*) as total_runs
                FROM eval_cases ec
                JOIN execution_runs er ON ec.eval_case_id = er.eval_case_id
                JOIN evaluator_results evr ON er.execution_id = evr.execution_id
                WHERE ec.app_name = ? ${whereClause}
                GROUP BY evr.evaluator_name, evr.evaluator_type
                ORDER BY evr.evaluator_name
            `, [agentName])[0];

            // Get test cases for this agent
            const testCases = db.exec(`
                SELECT
                    ec.eval_case_id,
                    ec.eval_set_id,
                    ec.user_prompt,
                    ec.system_instruction,
                    COUNT(DISTINCT er.execution_id) as execution_count,
                    SUM(CASE WHEN er.overall_success = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(er.execution_id) as success_rate,
                    AVG(er.cost) as avg_cost,
                    AVG(er.time_taken) as avg_latency,
                    MAX(er.timestamp) as last_run
                FROM eval_cases ec
                LEFT JOIN execution_runs er ON ec.eval_case_id = er.eval_case_id
                WHERE ec.app_name = ? ${whereClause}
                GROUP BY ec.eval_case_id
                ORDER BY last_run DESC
            `, [agentName])[0];

            // Get executions for this agent
            const executions = db.exec(`
                SELECT
                    er.execution_id,
                    er.eval_case_id,
                    ec.eval_set_id,
                    er.provider_type,
                    er.provider_model,
                    er.overall_success,
                    er.timestamp,
                    er.cost,
                    er.time_taken,
                    ec.user_prompt
                FROM eval_cases ec
                JOIN execution_runs er ON ec.eval_case_id = er.eval_case_id
                WHERE ec.app_name = ? ${whereClause}
                ORDER BY er.timestamp DESC
                LIMIT 100
            `, [agentName])[0];

            let html = `
                <button class="btn-upload" onclick="currentAgent=null; loadAgentsView()" style="margin-bottom: 20px;">
                    <span>←</span>
                    <span>Back to Agents</span>
                </button>

                <div class="charts-section">
                    <div class="chart-card">
                        <div class="chart-header">
                            <div class="chart-title">Success Rate Over Time</div>
                        </div>
                        <div class="chart-container">
                            ${trends && trends.values.length > 0 ? '<canvas id="agentSuccessChart"></canvas>' : '<div class="no-data">No data</div>'}
                        </div>
                    </div>

                    <div class="chart-card">
                        <div class="chart-header">
                            <div class="chart-title">Cost Over Time</div>
                        </div>
                        <div class="chart-container">
                            ${trends && trends.values.length > 0 ? '<canvas id="agentCostChart"></canvas>' : '<div class="no-data">No data</div>'}
                        </div>
                    </div>

                    <div class="chart-card">
                        <div class="chart-header">
                            <div class="chart-title">Executions Over Time</div>
                        </div>
                        <div class="chart-container">
                            ${trends && trends.values.length > 0 ? '<canvas id="agentExecChart"></canvas>' : '<div class="no-data">No data</div>'}
                        </div>
                    </div>

                    <div class="chart-card">
                        <div class="chart-header">
                            <div class="chart-title">Latency Over Time</div>
                        </div>
                        <div class="chart-container">
                            ${trends && trends.values.length > 0 ? '<canvas id="agentLatencyChart"></canvas>' : '<div class="no-data">No data</div>'}
                        </div>
                    </div>
                </div>

                <div class="chart-card wide" style="margin-bottom: 20px;">
                    <div class="chart-header">
                        <div class="chart-title">Evaluator Performance: Scores vs Thresholds</div>
                        <div class="chart-info">Average scores and thresholds for each evaluator</div>
                    </div>
                    <div class="chart-container tall">
                        ${evaluatorStats && evaluatorStats.values.length > 0 ? '<canvas id="evaluatorScoresChart"></canvas>' : '<div class="no-data">No evaluator data</div>'}
                    </div>
                </div>

                <div class="table-card" style="margin-bottom: 20px;">
                    <div class="table-header">
                        <div class="table-title">Test Cases</div>
                        <div class="chart-info">All test cases for this agent</div>
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th>Test Case ID</th>
                                <th>Dataset</th>
                                <th>Prompt</th>
                                <th>Executions</th>
                                <th>Success Rate</th>
                                <th>Avg Cost</th>
                                <th>Avg Latency</th>
                                <th>Last Run</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            if (testCases && testCases.values.length > 0) {
                testCases.values.forEach(row => {
                    const [caseId, setId, prompt, sysInst, execCount, successRate, avgCost, avgLatency, lastRun] = row;
                    html += `
                        <tr>
                            <td><code>${caseId.substring(0, 15)}...</code></td>
                            <td><code>${setId}</code></td>
                            <td style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${prompt || 'N/A'}">${prompt ? prompt.substring(0, 50) + (prompt.length > 50 ? '...' : '') : 'N/A'}</td>
                            <td>${execCount || 0}</td>
                            <td><span class="status-badge ${successRate >= 80 ? 'status-success' : 'status-error'}">${successRate ? successRate.toFixed(1) : '0.0'}%</span></td>
                            <td>$${avgCost ? avgCost.toFixed(4) : '0.0000'}</td>
                            <td>${avgLatency ? avgLatency.toFixed(2) : '0.00'}s</td>
                            <td>${lastRun ? new Date(lastRun).toLocaleString() : 'Never'}</td>
                        </tr>
                    `;
                });
            } else {
                html += '<tr><td colspan="8" class="empty-state">No test cases found</td></tr>';
            }

            html += `
                        </tbody>
                    </table>
                </div>

                <div class="table-card" style="margin-top: 20px;">
                    <div class="table-header">
                        <div class="table-title">Agent Executions</div>
                        <input type="text" class="table-search" placeholder="Search..." id="agentExecSearch">
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th>Execution ID</th>
                                <th>Dataset</th>
                                <th>Test Case</th>
                                <th>Provider</th>
                                <th>Status</th>
                                <th>Cost</th>
                                <th>Latency</th>
                                <th>Timestamp</th>
                            </tr>
                        </thead>
                        <tbody id="agentExecTableBody">
            `;

            if (executions && executions.values.length > 0) {
                // Group executions by date
                const groupedByDate = {};
                executions.values.forEach(row => {
                    const timestamp = row[6]; // timestamp is at index 6
                    const date = new Date(timestamp).toLocaleDateString('en-US', {
                        weekday: 'long',
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric'
                    });
                    if (!groupedByDate[date]) {
                        groupedByDate[date] = [];
                    }
                    groupedByDate[date].push(row);
                });

                // Get dates in reverse chronological order
                const sortedDates = Object.keys(groupedByDate).sort((a, b) => {
                    const dateA = new Date(groupedByDate[a][0][6]);
                    const dateB = new Date(groupedByDate[b][0][6]);
                    return dateB - dateA; // Latest first
                });

                // Render grouped executions
                sortedDates.forEach(date => {
                    const execsForDate = groupedByDate[date];
                    const execCount = execsForDate.length;
                    const successCount = execsForDate.filter(row => row[5]).length; // success is at index 5

                    // Date header row
                    html += `
                        <tr style="background: #f5f5f5; border-top: 2px solid #ddd;">
                            <td colspan="8" style="padding: 12px 16px; font-weight: 600; color: #333; font-size: 14px;">
                                📅 ${date}
                                <span style="color: #666; font-weight: normal; font-size: 12px; margin-left: 12px;">
                                    ${execCount} execution${execCount !== 1 ? 's' : ''}
                                    (${successCount} passed, ${execCount - successCount} failed)
                                </span>
                            </td>
                        </tr>
                    `;

                    // Execution rows for this date
                    execsForDate.forEach(row => {
                        const [execId, caseId, setId, provider, model, success, timestamp, cost, time, prompt] = row;
                        html += `
                            <tr class="execution-row" data-exec-id="${execId}" style="cursor: pointer;">
                                <td><code>${execId.substring(0, 12)}...</code></td>
                                <td><code>${setId}</code></td>
                                <td><code>${caseId}</code></td>
                                <td>${provider}${model ? ` (${model})` : ''}</td>
                                <td><span class="status-badge ${success ? 'status-success' : 'status-error'}">${success ? '✓' : '✗'}</span></td>
                                <td>$${cost.toFixed(4)}</td>
                                <td>${time.toFixed(2)}s</td>
                                <td>${new Date(timestamp).toLocaleTimeString()}</td>
                            </tr>
                            <tr style="display: none;">
                                <td colspan="8" class="execution-details" id="agent-details-${execId}">
                                    <div class="detail-grid">
                                        <div class="detail-section">
                                            <div class="detail-label">Full Execution ID</div>
                                            <div class="detail-value"><code>${execId}</code></div>
                                        </div>
                                        <div class="detail-section">
                                            <div class="detail-label">Dataset</div>
                                            <div class="detail-value"><code>${setId}</code></div>
                                        </div>
                                        <div class="detail-section">
                                            <div class="detail-label">Test Case</div>
                                            <div class="detail-value"><code>${caseId}</code></div>
                                        </div>
                                        <div class="detail-section">
                                            <div class="detail-label">Provider</div>
                                            <div class="detail-value">${provider}${model ? ` (${model})` : ''}</div>
                                        </div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Prompt</div>
                                        <div class="detail-value">${prompt || 'N/A'}</div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Evaluators</div>
                                        <div id="agent-eval-${execId}"></div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Conversations</div>
                                        <div id="agent-conv-${execId}"></div>
                                    </div>
                                </td>
                            </tr>
                        `;
                    });
                });
            } else {
                html += '<tr><td colspan="8" class="empty-state">No executions found</td></tr>';
            }

            html += '</tbody></table></div>';
            document.getElementById('content').innerHTML = html;

            // Create charts first
            if (trends && trends.values.length > 0) {
                const dates = trends.values.map(r => r[0]);
                const successRates = trends.values.map(r => r[2]);
                const costs = trends.values.map(r => r[3]);
                const executions = trends.values.map(r => r[1]);
                const latencies = trends.values.map(r => r[4]);

                createLineChart('agentSuccessChart', dates, successRates, 'Success Rate (%)', '#4a90e2');
                createBarChart('agentCostChart', dates, costs, 'Cost ($)', '#f5a623');
                createBarChart('agentExecChart', dates, executions, 'Executions', '#7ed321');
                createLineChart('agentLatencyChart', dates, latencies, 'Latency (s)', '#9013fe');
            }

            // Create evaluator scores vs thresholds chart
            if (evaluatorStats && evaluatorStats.values.length > 0) {
                const evaluatorNames = evaluatorStats.values.map(r => `${r[0]} (${r[1]})`);
                const scores = evaluatorStats.values.map(r => r[2]);
                const thresholds = evaluatorStats.values.map(r => r[3]);
                const passRates = evaluatorStats.values.map(r => r[4]);

                new Chart(document.getElementById('evaluatorScoresChart'), {
                    type: 'bar',
                    data: {
                        labels: evaluatorNames,
                        datasets: [
                            {
                                label: 'Average Score',
                                data: scores,
                                backgroundColor: '#4a90e2cc',
                                borderColor: '#4a90e2',
                                borderWidth: 1
                            },
                            {
                                label: 'Threshold',
                                data: thresholds,
                                backgroundColor: '#f5a623cc',
                                borderColor: '#f5a623',
                                borderWidth: 1
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: true, position: 'top' },
                            tooltip: {
                                callbacks: {
                                    afterLabel: function(context) {
                                        const idx = context.dataIndex;
                                        return `Pass Rate: ${passRates[idx].toFixed(1)}%`;
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 1.0,
                                title: { display: true, text: 'Score / Threshold' },
                                ticks: {
                                    callback: function(value) {
                                        return value.toFixed(2);
                                    }
                                }
                            },
                            x: {
                                title: { display: true, text: 'Evaluator' },
                                ticks: {
                                    maxRotation: 45,
                                    minRotation: 45
                                }
                            }
                        }
                    }
                });
            }

            // Add click handlers for execution rows in agent view (after DOM is ready)
            setTimeout(() => {
                document.querySelectorAll('#agentExecTableBody .execution-row').forEach(row => {
                    row.addEventListener('click', function(e) {
                        e.preventDefault();
                        const execId = this.getAttribute('data-exec-id');
                        const detailsRow = this.nextElementSibling;

                        this.classList.toggle('expanded');

                        if (this.classList.contains('expanded')) {
                            detailsRow.style.display = 'table-row';
                            loadAgentExecutionDetails(execId);
                        } else {
                            detailsRow.style.display = 'none';
                        }
                    });
                });
            }, 100);

            // Search functionality
            document.getElementById('agentExecSearch')?.addEventListener('input', function(e) {
                const search = e.target.value.toLowerCase();
                document.querySelectorAll('#agentExecTableBody .execution-row').forEach(row => {
                    const text = row.textContent.toLowerCase();
                    const detailsRow = row.nextElementSibling;
                    if (text.includes(search)) {
                        row.style.display = '';
                        if (row.classList.contains('expanded')) {
                            detailsRow.style.display = 'table-row';
                        } else {
                            detailsRow.style.display = 'none';
                        }
                    } else {
                        row.style.display = 'none';
                        detailsRow.style.display = 'none';
                    }
                });
            });
        }

        function loadExecutionsView() {
            const filter = getDateFilter();
            const executions = db.exec(`
                SELECT
                    er.execution_id,
                    er.eval_set_id,
                    er.eval_case_id,
                    ec.app_name,
                    er.provider_type,
                    er.provider_model,
                    er.overall_success,
                    er.timestamp,
                    er.cost,
                    er.time_taken,
                    er.input_tokens,
                    er.output_tokens,
                    ec.user_prompt,
                    er.source_path
                FROM execution_runs er
                LEFT JOIN eval_cases ec ON er.eval_case_id = ec.eval_case_id
                ${filter}
                ORDER BY er.source_path ASC, er.timestamp DESC
                LIMIT 100
            `)[0];

            let html = `
                <div class="table-card">
                    <div class="table-header">
                        <div class="table-title">All Executions</div>
                        <input type="text" class="table-search" placeholder="Search executions..." id="execSearch">
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th>Execution ID</th>
                                <th>Agent</th>
                                <th>Source</th>
                                <th>Dataset</th>
                                <th>Test Case</th>
                                <th>Provider</th>
                                <th>Status</th>
                                <th>Cost</th>
                                <th>Latency</th>
                                <th>Timestamp</th>
                            </tr>
                        </thead>
                        <tbody id="execTableBody">
            `;

            if (executions && executions.values.length > 0) {
                // Check if any executions have source_path
                const hasSourcePaths = executions.values.some(row => row[13]);

                // Group executions by source directory, then by date
                const groupedByDir = {};
                executions.values.forEach(row => {
                    const sourcePath = row[13] || '';
                    const lastSlash = sourcePath.lastIndexOf('/');
                    const dirKey = lastSlash > 0 ? sourcePath.substring(0, lastSlash) : (sourcePath ? '.' : '');
                    if (!groupedByDir[dirKey]) groupedByDir[dirKey] = [];
                    groupedByDir[dirKey].push(row);
                });

                const sortedDirKeys = Object.keys(groupedByDir).sort();
                const hasMultipleDirs = hasSourcePaths && (sortedDirKeys.length > 1 || (sortedDirKeys.length === 1 && sortedDirKeys[0] !== ''));

                sortedDirKeys.forEach(dirKey => {
                    const dirRows = groupedByDir[dirKey];

                    // Directory header row
                    if (hasMultipleDirs) {
                        const displayDir = dirKey === '' ? 'Ungrouped' : dirKey === '.' ? 'Root' : dirKey;
                        const dirSuccessCount = dirRows.filter(row => row[6]).length;
                        html += `
                            <tr style="background: #eef2ff; border-top: 2px solid #c7d2fe;">
                                <td colspan="10" style="padding: 10px 16px; font-weight: 600; color: #4338ca; font-size: 13px;">
                                    📁 ${displayDir}
                                    <span style="color: #666; font-weight: normal; font-size: 12px; margin-left: 12px;">
                                        ${dirRows.length} execution${dirRows.length !== 1 ? 's' : ''}
                                        (${dirSuccessCount} passed, ${dirRows.length - dirSuccessCount} failed)
                                    </span>
                                </td>
                            </tr>
                        `;
                    }

                    // Group by date within each directory
                    const groupedByDate = {};
                    dirRows.forEach(row => {
                        const timestamp = row[7];
                        const date = new Date(timestamp).toLocaleDateString('en-US', {
                            weekday: 'long',
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric'
                        });
                        if (!groupedByDate[date]) groupedByDate[date] = [];
                        groupedByDate[date].push(row);
                    });

                    const sortedDates = Object.keys(groupedByDate).sort((a, b) => {
                        const dateA = new Date(groupedByDate[a][0][7]);
                        const dateB = new Date(groupedByDate[b][0][7]);
                        return dateB - dateA;
                    });

                // Render grouped executions
                sortedDates.forEach(date => {
                    const execsForDate = groupedByDate[date];
                    const execCount = execsForDate.length;
                    const successCount = execsForDate.filter(row => row[6]).length; // success is at index 6

                    // Date header row
                    html += `
                        <tr style="background: #f5f5f5; border-top: 2px solid #ddd;">
                            <td colspan="10" style="padding: 12px 16px; font-weight: 600; color: #333; font-size: 14px;">
                                📅 ${date}
                                <span style="color: #666; font-weight: normal; font-size: 12px; margin-left: 12px;">
                                    ${execCount} execution${execCount !== 1 ? 's' : ''}
                                    (${successCount} passed, ${execCount - successCount} failed)
                                </span>
                            </td>
                        </tr>
                    `;

                    // Execution rows for this date
                    execsForDate.forEach((row, idx) => {
                        const [execId, setId, caseId, agent, provider, model, success, timestamp, cost, time, inputTokens, outputTokens, prompt, sourcePath] = row;
                        const sourceFile = sourcePath ? sourcePath.split('/').pop() : '';
                        html += `
                            <tr class="execution-row" data-exec-id="${execId}" style="cursor: pointer;">
                                <td><code>${execId.substring(0, 12)}...</code></td>
                                <td>${agent || 'N/A'}</td>
                                <td title="${sourcePath || ''}" style="color:#666;font-size:12px;">${sourceFile || '-'}</td>
                                <td><code>${setId}</code></td>
                                <td><code>${caseId.substring(0, 15)}...</code></td>
                                <td>${provider}${model ? ` (${model})` : ''}</td>
                                <td><span class="status-badge ${success ? 'status-success' : 'status-error'}">${success ? '✓ Pass' : '✗ Fail'}</span></td>
                                <td>$${cost.toFixed(4)}</td>
                                <td>${time.toFixed(2)}s</td>
                                <td>${new Date(timestamp).toLocaleTimeString()}</td>
                            </tr>
                            <tr style="display: none;">
                                <td colspan="10" class="execution-details" id="exec-details-${execId}">
                                <div class="detail-grid">
                                    <div class="detail-section">
                                        <div class="detail-label">Full Execution ID</div>
                                        <div class="detail-value"><code>${execId}</code></div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Agent</div>
                                        <div class="detail-value">${agent || 'N/A'}</div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Source</div>
                                        <div class="detail-value">${sourcePath || 'N/A'}</div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Dataset</div>
                                        <div class="detail-value"><code>${setId}</code></div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Test Case</div>
                                        <div class="detail-value"><code>${caseId}</code></div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Provider</div>
                                        <div class="detail-value">${provider}</div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Model</div>
                                        <div class="detail-value">${model || 'N/A'}</div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Tokens (In/Out)</div>
                                        <div class="detail-value">${inputTokens} / ${outputTokens}</div>
                                    </div>
                                    <div class="detail-section">
                                        <div class="detail-label">Timestamp</div>
                                        <div class="detail-value">${new Date(timestamp).toISOString()}</div>
                                    </div>
                                </div>
                                <div class="detail-section">
                                    <div class="detail-label">Prompt</div>
                                    <div class="detail-value">${prompt || 'N/A'}</div>
                                </div>
                                <div class="detail-section">
                                    <div class="detail-label">Evaluators</div>
                                    <div id="eval-${execId}"></div>
                                </div>
                                <div class="detail-section">
                                    <div class="detail-label">Conversations</div>
                                    <div id="conv-${execId}"></div>
                                </div>
                            </td>
                        </tr>
                        `;
                    });
                }); // end sortedDates
                }); // end sortedDirKeys
            } else {
                html += '<tr><td colspan="10" class="empty-state">No executions found</td></tr>';
            }

            html += '</tbody></table></div>';
            document.getElementById('content').innerHTML = html;

            // Add click handlers
            setTimeout(() => {
                document.querySelectorAll('#execTableBody .execution-row').forEach(row => {
                    row.addEventListener('click', function(e) {
                        e.preventDefault();
                        const execId = this.getAttribute('data-exec-id');
                        const detailsRow = this.nextElementSibling;

                        this.classList.toggle('expanded');

                        if (this.classList.contains('expanded')) {
                            detailsRow.style.display = 'table-row';
                            loadExecutionDetails(execId);
                        } else {
                            detailsRow.style.display = 'none';
                        }
                    });
                });
            }, 100);

            // Search functionality
            document.getElementById('execSearch')?.addEventListener('input', function(e) {
                const search = e.target.value.toLowerCase();
                document.querySelectorAll('#execTableBody .execution-row').forEach(row => {
                    const text = row.textContent.toLowerCase();
                    row.style.display = text.includes(search) ? '' : 'none';
                    row.nextElementSibling.style.display = text.includes(search) ? '' : 'none';
                });
            });
        }

        function loadExecutionDetails(execId) {
            console.log('Loading execution details for:', execId);

            // Load evaluator results
            const evalDiv = document.getElementById(`eval-${execId}`);
            console.log('Evaluator div found:', evalDiv);

            if (!evalDiv) {
                console.error('Could not find evaluator div for:', execId);
                return;
            }

            if (!db) {
                console.error('Database not loaded');
                evalDiv.innerHTML = '<span style="color:#c41e3a;font-size:12px;">Database not loaded</span>';
                return;
            }

            try {
                const result = db.exec(`
                    SELECT evaluator_name, evaluator_type, success, passed, score, threshold, error, details_json
                    FROM evaluator_results
                    WHERE execution_id = ?
                `, [execId]);

                console.log('Evaluator query result:', result);

                if (result && result.length > 0 && result[0].values.length > 0) {
                    const evaluators = result[0];
                    let evalHtml = '<div style="font-size:12px;">';
                    evaluators.values.forEach((e, idx) => {
                        const [name, type, success, passed, score, threshold, error, detailsJson] = e;

                        // Build score display string safely
                        let scoreDisplay = '';
                        if (score !== null && score !== undefined && threshold !== null && threshold !== undefined) {
                            scoreDisplay = `<br><span style="color:#666;">Score: ${score.toFixed(2)}, Threshold: ${threshold.toFixed(2)}</span>`;
                        } else if (score !== null && score !== undefined) {
                            scoreDisplay = `<br><span style="color:#666;">Score: ${score.toFixed(2)}</span>`;
                        }

                        // Parse details JSON
                        let detailsHtml = '';
                        if (detailsJson) {
                            const detailId = `eval-detail-${execId}-${idx}`;
                            detailsHtml = `
                                <br><a href="#" onclick="event.preventDefault(); var el=document.getElementById('${detailId}'); el.style.display=el.style.display==='none'?'block':'none';" style="color:#0d7ff2;font-size:11px;text-decoration:none;">View Details ▾</a>
                                <div id="${detailId}" style="display:none;margin-top:8px;">
                                    <pre style="background:#fff;border:1px solid #ddd;border-radius:4px;padding:8px;overflow:auto;max-height:400px;font-size:11px;white-space:pre-wrap;word-break:break-word;">${(() => { try { return JSON.stringify(JSON.parse(detailsJson), null, 2); } catch(e) { return detailsJson; } })()}</pre>
                                </div>
                            `;
                        }

                        evalHtml += `
                            <div style="padding:8px; background:#f9f9f9; border:1px solid #e0e0e0; border-radius:4px; margin-bottom:8px;">
                                <strong>${name || 'Unknown'}</strong> (${type || 'Unknown'})
                                <span class="status-badge ${passed ? 'status-success' : 'status-error'}">${passed ? '✓ Pass' : '✗ Fail'}</span>
                                ${scoreDisplay}
                                ${error ? `<br><span style="color:#c41e3a;">${error}</span>` : ''}
                                ${detailsHtml}
                            </div>
                        `;
                    });
                    evalHtml += '</div>';
                    evalDiv.innerHTML = evalHtml;
                } else {
                    evalDiv.innerHTML = '<span style="color:#999;font-size:12px;">No evaluator data</span>';
                }
            } catch (error) {
                console.error('Error loading evaluators:', error);
                console.error('Error details:', error.message, error.stack);
                evalDiv.innerHTML = '<span style="color:#c41e3a;font-size:12px;">Error loading evaluators: ' + error.message + '</span>';
            }

            // Load conversations
            loadConversations(execId);
        }

        function loadConversations(execId) {
            console.log('Loading conversations for:', execId);

            const convDiv = document.getElementById(`conv-${execId}`);
            console.log('Conversation div found:', convDiv);

            if (!convDiv) {
                console.error('Could not find conversation div for:', execId);
                return;
            }

            if (!db) {
                console.error('Database not loaded');
                convDiv.innerHTML = '<span style="color:#c41e3a;font-size:12px;">Database not loaded</span>';
                return;
            }

            let invocations;
            try {
                const result = db.exec(`
                    SELECT invocation_type, sequence_order, user_message, assistant_message
                    FROM invocations
                    WHERE execution_id = ?
                    ORDER BY sequence_order, invocation_type
                `, [execId]);

                console.log('Conversation query result:', result);

                if (!result || result.length === 0 || !result[0].values || result[0].values.length === 0) {
                    convDiv.innerHTML = '<div style="color:#999;font-size:12px;">No conversation data</div>';
                    return;
                }

                invocations = result[0];
            } catch (error) {
                console.error('Error loading conversations:', error);
                console.error('Error details:', error.message, error.stack);
                convDiv.innerHTML = '<span style="color:#c41e3a;font-size:12px;">Error loading conversations: ' + error.message + '</span>';
                return;
            }

            const expected = invocations.values.filter(i => i[0] === 'expected');
            const actual = invocations.values.filter(i => i[0] === 'actual');

            let html = '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 10px;">';

            // Expected conversation
            if (expected.length > 0) {
                html += '<div style="border: 1px solid #e0e0e0; border-radius: 8px; padding: 16px; background: #f9f9f9;">';
                html += '<div style="font-weight: bold; margin-bottom: 16px; color: #4a90e2; font-size: 14px; border-bottom: 2px solid #4a90e2; padding-bottom: 8px;">📋 Expected Conversation</div>';
                html += '<div style="display: flex; flex-direction: column; gap: 12px;">';

                expected.forEach((e, idx) => {
                    const [type, seq, userMsg, assistantMsg] = e;

                    // User message
                    html += `
                        <div style="display: flex; flex-direction: column; align-items: flex-start;">
                            <div style="background: #e3f2fd; padding: 10px 14px; border-radius: 12px 12px 12px 2px; max-width: 85%; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                                <div style="font-weight: 600; color: #1976d2; font-size: 11px; margin-bottom: 4px;">👤 User</div>
                                <div style="font-size: 13px; color: #333; white-space: pre-wrap; line-height: 1.4;">${userMsg || 'N/A'}</div>
                            </div>
                        </div>
                    `;

                    // Assistant message
                    html += `
                        <div style="display: flex; flex-direction: column; align-items: flex-end;">
                            <div style="background: #f5f5f5; padding: 10px 14px; border-radius: 12px 12px 2px 12px; max-width: 85%; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                                <div style="font-weight: 600; color: #666; font-size: 11px; margin-bottom: 4px;">🤖 Assistant</div>
                                <div style="font-size: 13px; color: #333; white-space: pre-wrap; line-height: 1.4;">${assistantMsg || 'N/A'}</div>
                            </div>
                        </div>
                    `;
                });

                html += '</div></div>';
            }

            // Actual conversation
            if (actual.length > 0) {
                html += '<div style="border: 1px solid #e0e0e0; border-radius: 8px; padding: 16px; background: #f9f9f9;">';
                html += '<div style="font-weight: bold; margin-bottom: 16px; color: #7ed321; font-size: 14px; border-bottom: 2px solid #7ed321; padding-bottom: 8px;">✅ Actual Conversation</div>';
                html += '<div style="display: flex; flex-direction: column; gap: 12px;">';

                actual.forEach((a, idx) => {
                    const [type, seq, userMsg, assistantMsg] = a;

                    // User message
                    html += `
                        <div style="display: flex; flex-direction: column; align-items: flex-start;">
                            <div style="background: #e3f2fd; padding: 10px 14px; border-radius: 12px 12px 12px 2px; max-width: 85%; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                                <div style="font-weight: 600; color: #1976d2; font-size: 11px; margin-bottom: 4px;">👤 User</div>
                                <div style="font-size: 13px; color: #333; white-space: pre-wrap; line-height: 1.4;">${userMsg || 'N/A'}</div>
                            </div>
                        </div>
                    `;

                    // Assistant message
                    html += `
                        <div style="display: flex; flex-direction: column; align-items: flex-end;">
                            <div style="background: #f5f5f5; padding: 10px 14px; border-radius: 12px 12px 2px 12px; max-width: 85%; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                                <div style="font-weight: 600; color: #666; font-size: 11px; margin-bottom: 4px;">🤖 Assistant</div>
                                <div style="font-size: 13px; color: #333; white-space: pre-wrap; line-height: 1.4;">${assistantMsg || 'N/A'}</div>
                            </div>
                        </div>
                    `;
                });

                html += '</div></div>';
            }

            html += '</div>';
            convDiv.innerHTML = html;
        }

        function loadAgentExecutionDetails(execId) {
            console.log('Loading agent execution details for:', execId);

            // Load evaluator results
            const evalDiv = document.getElementById(`agent-eval-${execId}`);
            console.log('Evaluator div found:', evalDiv);

            if (!evalDiv) {
                console.error('Could not find evaluator div for:', execId);
                return;
            }

            if (!db) {
                console.error('Database not loaded');
                evalDiv.innerHTML = '<span style="color:#c41e3a;font-size:12px;">Database not loaded</span>';
                return;
            }

            try {
                const result = db.exec(`
                    SELECT evaluator_name, evaluator_type, success, passed, score, threshold, error, details_json
                    FROM evaluator_results
                    WHERE execution_id = ?
                `, [execId]);

                console.log('Evaluator query result:', result);

                if (result && result.length > 0 && result[0].values.length > 0) {
                    const evaluators = result[0];
                    let evalHtml = '<div style="font-size:12px;">';
                    evaluators.values.forEach((e, idx) => {
                        const [name, type, success, passed, score, threshold, error, detailsJson] = e;

                        // Build score display string safely
                        let scoreDisplay = '';
                        if (score !== null && score !== undefined && threshold !== null && threshold !== undefined) {
                            scoreDisplay = `<br><span style="color:#666;">Score: ${score.toFixed(2)}, Threshold: ${threshold.toFixed(2)}</span>`;
                        } else if (score !== null && score !== undefined) {
                            scoreDisplay = `<br><span style="color:#666;">Score: ${score.toFixed(2)}</span>`;
                        }

                        // Parse details JSON
                        let detailsHtml = '';
                        if (detailsJson) {
                            const detailId = `agent-eval-detail-${execId}-${idx}`;
                            detailsHtml = `
                                <br><a href="#" onclick="event.preventDefault(); var el=document.getElementById('${detailId}'); el.style.display=el.style.display==='none'?'block':'none';" style="color:#0d7ff2;font-size:11px;text-decoration:none;">View Details ▾</a>
                                <div id="${detailId}" style="display:none;margin-top:8px;">
                                    <pre style="background:#fff;border:1px solid #ddd;border-radius:4px;padding:8px;overflow:auto;max-height:400px;font-size:11px;white-space:pre-wrap;word-break:break-word;">${(() => { try { return JSON.stringify(JSON.parse(detailsJson), null, 2); } catch(e) { return detailsJson; } })()}</pre>
                                </div>
                            `;
                        }

                        evalHtml += `
                            <div style="padding:8px; background:#f9f9f9; border:1px solid #e0e0e0; border-radius:4px; margin-bottom:8px;">
                                <strong>${name || 'Unknown'}</strong> (${type || 'Unknown'})
                                <span class="status-badge ${passed ? 'status-success' : 'status-error'}">${passed ? '✓ Pass' : '✗ Fail'}</span>
                                ${scoreDisplay}
                                ${error ? `<br><span style="color:#c41e3a;">${error}</span>` : ''}
                                ${detailsHtml}
                            </div>
                        `;
                    });
                    evalHtml += '</div>';
                    evalDiv.innerHTML = evalHtml;
                } else {
                    evalDiv.innerHTML = '<span style="color:#999;font-size:12px;">No evaluator data</span>';
                }
            } catch (error) {
                console.error('Error loading evaluators:', error);
                console.error('Error details:', error.message, error.stack);
                evalDiv.innerHTML = '<span style="color:#c41e3a;font-size:12px;">Error loading evaluators: ' + error.message + '</span>';
            }

            // Load conversations with comparison
            loadAgentConversations(execId);
        }

        function loadAgentConversations(execId) {
            console.log('Loading agent conversations for:', execId);

            const convDiv = document.getElementById(`agent-conv-${execId}`);
            console.log('Conversation div found:', convDiv);

            if (!convDiv) {
                console.error('Could not find conversation div for:', execId);
                return;
            }

            if (!db) {
                console.error('Database not loaded');
                convDiv.innerHTML = '<span style="color:#c41e3a;font-size:12px;">Database not loaded</span>';
                return;
            }

            let invocations;
            try {
                const result = db.exec(`
                    SELECT invocation_type, sequence_order, user_message, assistant_message
                    FROM invocations
                    WHERE execution_id = ?
                    ORDER BY sequence_order, invocation_type
                `, [execId]);

                console.log('Conversation query result:', result);

                if (!result || result.length === 0 || !result[0].values || result[0].values.length === 0) {
                    convDiv.innerHTML = '<div style="color:#999;font-size:12px;">No conversation data</div>';
                    return;
                }

                invocations = result[0];
            } catch (error) {
                console.error('Error loading conversations:', error);
                console.error('Error details:', error.message, error.stack);
                convDiv.innerHTML = '<span style="color:#c41e3a;font-size:12px;">Error loading conversations: ' + error.message + '</span>';
                return;
            }

            const expected = invocations.values.filter(i => i[0] === 'expected');
            const actual = invocations.values.filter(i => i[0] === 'actual');

            let html = '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 10px;">';

            // Expected conversation
            if (expected.length > 0) {
                html += '<div style="border: 1px solid #e0e0e0; border-radius: 8px; padding: 16px; background: #f9f9f9;">';
                html += '<div style="font-weight: bold; margin-bottom: 16px; color: #4a90e2; font-size: 14px; border-bottom: 2px solid #4a90e2; padding-bottom: 8px;">📋 Expected Conversation</div>';
                html += '<div style="display: flex; flex-direction: column; gap: 12px;">';

                expected.forEach((e, idx) => {
                    const [type, seq, userMsg, assistantMsg] = e;

                    // User message
                    html += `
                        <div style="display: flex; flex-direction: column; align-items: flex-start;">
                            <div style="background: #e3f2fd; padding: 10px 14px; border-radius: 12px 12px 12px 2px; max-width: 85%; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                                <div style="font-weight: 600; color: #1976d2; font-size: 11px; margin-bottom: 4px;">👤 User</div>
                                <div style="font-size: 13px; color: #333; white-space: pre-wrap; line-height: 1.4;">${userMsg || 'N/A'}</div>
                            </div>
                        </div>
                    `;

                    // Assistant message
                    html += `
                        <div style="display: flex; flex-direction: column; align-items: flex-end;">
                            <div style="background: #f5f5f5; padding: 10px 14px; border-radius: 12px 12px 2px 12px; max-width: 85%; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                                <div style="font-weight: 600; color: #666; font-size: 11px; margin-bottom: 4px;">🤖 Assistant</div>
                                <div style="font-size: 13px; color: #333; white-space: pre-wrap; line-height: 1.4;">${assistantMsg || 'N/A'}</div>
                            </div>
                        </div>
                    `;
                });

                html += '</div></div>';
            }

            // Actual conversation
            if (actual.length > 0) {
                html += '<div style="border: 1px solid #e0e0e0; border-radius: 8px; padding: 16px; background: #f9f9f9;">';
                html += '<div style="font-weight: bold; margin-bottom: 16px; color: #7ed321; font-size: 14px; border-bottom: 2px solid #7ed321; padding-bottom: 8px;">✅ Actual Conversation</div>';
                html += '<div style="display: flex; flex-direction: column; gap: 12px;">';

                actual.forEach((a, idx) => {
                    const [type, seq, userMsg, assistantMsg] = a;

                    // User message
                    html += `
                        <div style="display: flex; flex-direction: column; align-items: flex-start;">
                            <div style="background: #e3f2fd; padding: 10px 14px; border-radius: 12px 12px 12px 2px; max-width: 85%; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                                <div style="font-weight: 600; color: #1976d2; font-size: 11px; margin-bottom: 4px;">👤 User</div>
                                <div style="font-size: 13px; color: #333; white-space: pre-wrap; line-height: 1.4;">${userMsg || 'N/A'}</div>
                            </div>
                        </div>
                    `;

                    // Assistant message
                    html += `
                        <div style="display: flex; flex-direction: column; align-items: flex-end;">
                            <div style="background: #f5f5f5; padding: 10px 14px; border-radius: 12px 12px 2px 12px; max-width: 85%; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                                <div style="font-weight: 600; color: #666; font-size: 11px; margin-bottom: 4px;">🤖 Assistant</div>
                                <div style="font-size: 13px; color: #333; white-space: pre-wrap; line-height: 1.4;">${assistantMsg || 'N/A'}</div>
                            </div>
                        </div>
                    `;
                });

                html += '</div></div>';
            }

            html += '</div>';
            convDiv.innerHTML = html;
        }

        function loadProvidersView() {
            const filter = getDateFilter();
            const providers = db.exec(`
                SELECT
                    provider_type,
                    provider_model,
                    COUNT(*) as runs,
                    SUM(CASE WHEN overall_success = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as success_rate,
                    AVG(cost) as avg_cost,
                    AVG(time_taken) as avg_latency
                FROM execution_runs
                ${filter}
                GROUP BY provider_type, provider_model
                ORDER BY runs DESC
            `)[0];

            let html = `
                <div class="table-card">
                    <div class="table-header">
                        <div class="table-title">Provider Performance</div>
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th>Provider</th>
                                <th>Model</th>
                                <th>Executions</th>
                                <th>Success Rate</th>
                                <th>Avg Cost</th>
                                <th>Avg Latency</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            if (providers && providers.values.length > 0) {
                providers.values.forEach(row => {
                    const [type, model, runs, successRate, avgCost, avgLatency] = row;
                    html += `
                        <tr>
                            <td><strong>${type}</strong></td>
                            <td>${model || 'N/A'}</td>
                            <td>${runs}</td>
                            <td>${successRate.toFixed(1)}%</td>
                            <td>$${avgCost.toFixed(4)}</td>
                            <td>${avgLatency.toFixed(2)}s</td>
                        </tr>
                    `;
                });
            } else {
                html += '<tr><td colspan="6" class="empty-state">No provider data</td></tr>';
            }

            html += '</tbody></table></div>';
            document.getElementById('content').innerHTML = html;
        }

        function loadTestCasesView() {
            const filter = getDateFilter();
            const cases = db.exec(`
                SELECT
                    ec.eval_case_id,
                    ec.user_prompt,
                    COUNT(er.execution_id) as runs,
                    SUM(CASE WHEN er.overall_success = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(er.execution_id) as pass_rate,
                    AVG(er.cost) as avg_cost,
                    AVG(er.time_taken) as avg_time
                FROM eval_cases ec
                LEFT JOIN execution_runs er ON ec.eval_case_id = er.eval_case_id
                ${filter ? 'WHERE ' + filter.split('WHERE ')[1] : ''}
                GROUP BY ec.eval_case_id
                ORDER BY runs DESC
            `)[0];

            let html = `
                <div class="table-card">
                    <div class="table-header">
                        <div class="table-title">Test Cases</div>
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th>Test Case ID</th>
                                <th>Prompt</th>
                                <th>Runs</th>
                                <th>Pass Rate</th>
                                <th>Avg Cost</th>
                                <th>Avg Time</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            if (cases && cases.values.length > 0) {
                cases.values.forEach(row => {
                    const [id, prompt, runs, passRate, avgCost, avgTime] = row;
                    html += `
                        <tr>
                            <td><code>${id}</code></td>
                            <td>${(prompt || '').substring(0, 60)}${prompt && prompt.length > 60 ? '...' : ''}</td>
                            <td>${runs || 0}</td>
                            <td>${(passRate || 0).toFixed(1)}%</td>
                            <td>$${(avgCost || 0).toFixed(4)}</td>
                            <td>${(avgTime || 0).toFixed(2)}s</td>
                        </tr>
                    `;
                });
            } else {
                html += '<tr><td colspan="6" class="empty-state">No test cases</td></tr>';
            }

            html += '</tbody></table></div>';
            document.getElementById('content').innerHTML = html;
        }

        function loadEvaluatorsView() {
            const filter = getDateFilter();
            const evaluators = db.exec(`
                SELECT
                    ev.evaluator_name,
                    ev.evaluator_type,
                    COUNT(*) as total,
                    SUM(CASE WHEN ev.passed = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as pass_rate,
                    AVG(ev.score) as avg_score,
                    AVG(ev.threshold) as avg_threshold
                FROM evaluator_results ev
                JOIN execution_runs er ON ev.execution_id = er.execution_id
                ${filter}
                GROUP BY ev.evaluator_name, ev.evaluator_type
            `)[0];

            let html = `
                <div class="table-card">
                    <div class="table-header">
                        <div class="table-title">Evaluator Performance</div>
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th>Evaluator</th>
                                <th>Type</th>
                                <th>Total Evals</th>
                                <th>Pass Rate</th>
                                <th>Avg Score</th>
                                <th>Avg Threshold</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            if (evaluators && evaluators.values.length > 0) {
                evaluators.values.forEach((row, idx) => {
                    const [name, type, total, passRate, avgScore, avgThreshold] = row;
                    const detailRowId = `evaluator-drill-${idx}`;
                    html += `
                        <tr style="cursor:pointer;" onclick="var el=document.getElementById('${detailRowId}'); if(el.style.display==='none'){el.style.display='table-row'; loadEvaluatorDrilldown('${name}','${detailRowId}');}else{el.style.display='none';}">
                            <td><strong>${name}</strong> <span style="color:#0d7ff2;font-size:10px;">▾</span></td>
                            <td>${type}</td>
                            <td>${total}</td>
                            <td>${passRate.toFixed(1)}%</td>
                            <td>${avgScore ? avgScore.toFixed(2) : 'N/A'}</td>
                            <td>${avgThreshold ? avgThreshold.toFixed(2) : 'N/A'}</td>
                        </tr>
                        <tr id="${detailRowId}" style="display:none;">
                            <td colspan="6" style="padding:12px;background:#f5f5f5;">
                                <div style="color:#999;font-size:12px;">Loading details...</div>
                            </td>
                        </tr>
                    `;
                });
            } else {
                html += '<tr><td colspan="6" class="empty-state">No evaluator data</td></tr>';
            }

            html += '</tbody></table></div>';
            document.getElementById('content').innerHTML = html;
        }

        function loadEvaluatorDrilldown(evaluatorName, rowId) {
            const row = document.getElementById(rowId);
            if (!row || !db) return;
            const cell = row.querySelector('td');

            try {
                const results = db.exec(`
                    SELECT ev.passed, ev.score, ev.threshold, ev.error, ev.details_json, ev.evaluated_at, er.eval_case_id, er.execution_id
                    FROM evaluator_results ev
                    JOIN execution_runs er ON ev.execution_id = er.execution_id
                    WHERE ev.evaluator_name = ?
                    ORDER BY ev.evaluated_at DESC
                    LIMIT 20
                `, [evaluatorName]);

                if (!results || results.length === 0 || results[0].values.length === 0) {
                    cell.innerHTML = '<div style="color:#999;font-size:12px;">No detailed results found</div>';
                    return;
                }

                let drillHtml = '<div style="font-size:12px;"><strong>Recent Results (last 20):</strong><div style="margin-top:8px;">';
                results[0].values.forEach((r, i) => {
                    const [passed, score, threshold, error, detailsJson, evaluatedAt, caseId, execId] = r;
                    const statusBadge = passed ? '<span style="color:#2e7d32;font-weight:600;">✓ Pass</span>' : '<span style="color:#c41e3a;font-weight:600;">✗ Fail</span>';
                    const scoreText = score !== null && score !== undefined ? `Score: ${score.toFixed(2)}` : '';
                    const threshText = threshold !== null && threshold !== undefined ? ` / Threshold: ${threshold.toFixed(2)}` : '';
                    const detailToggleId = `drill-detail-${rowId}-${i}`;

                    let detailsButton = '';
                    if (detailsJson) {
                        detailsButton = `<a href="#" onclick="event.preventDefault();event.stopPropagation();var el=document.getElementById('${detailToggleId}');el.style.display=el.style.display==='none'?'block':'none';" style="color:#0d7ff2;font-size:11px;text-decoration:none;margin-left:8px;">View Details ▾</a>`;
                    }

                    let detailsBlock = '';
                    if (detailsJson) {
                        detailsBlock = `<div id="${detailToggleId}" style="display:none;margin-top:6px;"><pre style="background:#fff;border:1px solid #ddd;border-radius:4px;padding:8px;overflow:auto;max-height:400px;font-size:11px;white-space:pre-wrap;word-break:break-word;">${(() => { try { return JSON.stringify(JSON.parse(detailsJson), null, 2); } catch(e) { return detailsJson; } })()}</pre></div>`;
                    }

                    drillHtml += `
                        <div style="padding:8px;background:#fff;border:1px solid #e0e0e0;border-radius:4px;margin-bottom:6px;" onclick="event.stopPropagation();">
                            ${statusBadge}
                            <code style="font-size:11px;margin-left:6px;">${caseId || ''}</code>
                            <span style="color:#666;font-size:11px;margin-left:6px;">${scoreText}${threshText}</span>
                            ${error ? `<span style="color:#c41e3a;font-size:11px;margin-left:6px;">${error}</span>` : ''}
                            ${detailsButton}
                            ${detailsBlock}
                        </div>
                    `;
                });
                drillHtml += '</div></div>';
                cell.innerHTML = drillHtml;
            } catch (err) {
                console.error('Error loading evaluator drilldown:', err);
                cell.innerHTML = `<div style="color:#c41e3a;font-size:12px;">Error: ${err.message}</div>`;
            }
        }

        function loadDatasetsView() {
            const datasets = db.exec(`
                SELECT
                    es.eval_set_id,
                    es.name,
                    COUNT(DISTINCT ec.eval_case_id) as test_cases,
                    COUNT(er.execution_id) as executions,
                    es.first_seen
                FROM eval_sets es
                LEFT JOIN eval_cases ec ON es.eval_set_id = ec.eval_set_id
                LEFT JOIN execution_runs er ON ec.eval_case_id = er.eval_case_id
                GROUP BY es.eval_set_id
                ORDER BY es.first_seen DESC
            `)[0];

            let html = `
                <div class="table-card">
                    <div class="table-header">
                        <div class="table-title">Datasets</div>
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th>Dataset ID</th>
                                <th>Name</th>
                                <th>Test Cases</th>
                                <th>Total Executions</th>
                                <th>First Seen</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            if (datasets && datasets.values.length > 0) {
                datasets.values.forEach(row => {
                    const [id, name, cases, execs, firstSeen] = row;
                    html += `
                        <tr>
                            <td><code>${id}</code></td>
                            <td>${name || 'N/A'}</td>
                            <td>${cases || 0}</td>
                            <td>${execs || 0}</td>
                            <td>${new Date(firstSeen).toLocaleString()}</td>
                        </tr>
                    `;
                });
            } else {
                html += '<tr><td colspan="5" class="empty-state">No datasets</td></tr>';
            }

            html += '</tbody></table></div>';
            document.getElementById('content').innerHTML = html;
        }

        function loadReportsView() {
            const reports = db.exec(`
                SELECT
                    report_id,
                    generated_at,
                    total_cost,
                    total_time,
                    success_rate,
                    overall_success
                FROM reports
                ORDER BY generated_at DESC
                LIMIT 50
            `)[0];

            let html = `
                <div class="table-card">
                    <div class="table-header">
                        <div class="table-title">Evaluation Reports</div>
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th>Report ID</th>
                                <th>Generated At</th>
                                <th>Success Rate</th>
                                <th>Total Cost</th>
                                <th>Total Time</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            if (reports && reports.values.length > 0) {
                reports.values.forEach(row => {
                    const [id, date, cost, time, rate, success] = row;
                    html += `
                        <tr>
                            <td><code>${id.substring(0, 30)}...</code></td>
                            <td>${new Date(date).toLocaleString()}</td>
                            <td>${(rate * 100).toFixed(1)}%</td>
                            <td>$${cost.toFixed(4)}</td>
                            <td>${time.toFixed(2)}s</td>
                            <td><span class="status-badge ${success ? 'status-success' : 'status-error'}">${success ? '✓ Pass' : '✗ Fail'}</span></td>
                        </tr>
                    `;
                });
            } else {
                html += '<tr><td colspan="6" class="empty-state">No reports</td></tr>';
            }

            html += '</tbody></table></div>';
            document.getElementById('content').innerHTML = html;
        }

        // Chart helpers
        function createLineChart(id, labels, data, label, color) {
            new Chart(document.getElementById(id), {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: label,
                        data: data,
                        borderColor: color,
                        backgroundColor: color + '20',
                        borderWidth: 2,
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false }
                    },
                    scales: {
                        y: { beginAtZero: true }
                    }
                }
            });
        }

        function createBarChart(id, labels, data, label, color) {
            new Chart(document.getElementById(id), {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: label,
                        data: data,
                        backgroundColor: color + 'cc',
                        borderColor: color,
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false }
                    },
                    scales: {
                        y: { beginAtZero: true }
                    }
                }
            });
        }
    </script>
</body>
</html>
