<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Interactive AE Visualizer{% endblock %}</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Plotly.js -->
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    
    <!-- Custom CSS -->
    <style>
        .sidebar {
            min-height: 100vh;
            background-color: #f8f9fa;
            border-right: 1px solid #dee2e6;
        }
        
        .run-card {
            transition: transform 0.2s, box-shadow 0.2s;
            cursor: pointer;
            margin-bottom: 10px;
        }
        
        .run-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .run-card.selected {
            border: 2px solid #007bff;
            background-color: #e3f2fd;
        }
        
        .metric-badge {
            font-size: 0.85em;
            margin: 2px;
        }
        
        .plot-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            padding: 15px;
        }
        
        .plot-image-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            padding: 5px;
            overflow: hidden;
        }
        
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .navbar-brand {
            font-weight: bold;
            color: #007bff !important;
        }
        
        .stats-summary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }
        
        .status-sequential { background-color: #17a2b8; }
        .status-parallel { background-color: #fd7e14; }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">🔬 Interactive AE Visualizer</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">Dashboard</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/compare">Compare Runs</a>
                    </li>
                    <li class="nav-item">
                        <span class="nav-link" id="runs-count">Loading...</span>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 sidebar p-3">
                <h5 class="mb-3">Optimization Runs</h5>
                
                <!-- Search/Filter -->
                <div class="mb-3">
                    <input type="text" class="form-control form-control-sm" id="search-runs" 
                           placeholder="Search runs...">
                </div>
                
                <!-- Sort Options -->
                <div class="mb-3">
                    <select class="form-select form-select-sm" id="sort-runs">
                        <option value="timestamp">Sort by Date</option>
                        <option value="soft_f1">Sort by F1 Score</option>
                        <option value="soft_recall">Sort by Recall</option>
                        <option value="avg_trial_time">Sort by Time</option>
                    </select>
                </div>
                
                <!-- Runs List -->
                <div id="runs-list" class="mb-3">
                    <div class="loading-spinner">
                        <div class="spinner-border spinner-border-sm" role="status"></div>
                        <div>Loading runs...</div>
                    </div>
                </div>
                
                <!-- Summary Stats -->
                <div class="stats-summary">
                    <h6>Quick Stats</h6>
                    <div id="quick-stats">
                        <small>Total Runs: <span id="total-runs">-</span></small><br>
                        <small>Best F1: <span id="best-f1">-</span></small><br>
                        <small>Avg Time: <span id="avg-time">-</span></small>
                    </div>
                </div>
            </div>
            
            <!-- Main Content Area -->
            <div class="col-md-9 p-3">
                {% block content %}{% endblock %}
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Common JavaScript -->
    <script>
        let allRuns = [];
        let currentRun = null;
        
        // Load runs on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadRuns();
            
            // Check for URL parameter to auto-select a run (for dashboard page)
            if (window.location.pathname === '/') {
                const urlParams = new URLSearchParams(window.location.search);
                const runParam = urlParams.get('run');
                if (runParam) {
                    // Wait a bit for runs to load, then select the specified run
                    setTimeout(() => {
                        selectRun(runParam);
                    }, 1000);
                }
            }
        });
        
        async function loadRuns() {
            try {
                const response = await fetch('/api/runs');
                allRuns = await response.json();
                displayRuns(allRuns);
                updateQuickStats(allRuns);
                document.getElementById('runs-count').textContent = `${allRuns.length} runs`;
            } catch (error) {
                console.error('Error loading runs:', error);
                document.getElementById('runs-list').innerHTML = 
                    '<div class="alert alert-danger">Error loading runs</div>';
            }
        }
        
        function displayRuns(runs) {
            const container = document.getElementById('runs-list');
            
            if (runs.length === 0) {
                container.innerHTML = '<div class="alert alert-info">No runs found</div>';
                return;
            }
            
            container.innerHTML = runs.map(run => `
                <div class="card run-card" data-run-id="${run.run_id}" onclick="selectRun('${run.run_id}')">
                    <div class="card-body p-2">
                        <h6 class="card-title mb-1" style="font-size: 0.9em;">${run.run_id}</h6>
                        <small class="text-muted d-block">${run.timestamp}</small>
                        
                        <div class="mt-2">
                            <span class="badge bg-primary metric-badge">F1: ${run.soft_f1}</span>
                            <span class="badge bg-success metric-badge">R: ${run.soft_recall}</span>
                            <span class="badge bg-warning metric-badge">P: ${run.soft_precision}</span>
                        </div>
                        
                        <div class="mt-1">
                            <small class="text-muted">
                                <span class="status-indicator status-${run.training_mode.toLowerCase()}"></span>
                                ${run.training_mode} | ${run.num_trials}T | ${run.ensemble_size}E | ${run.avg_trial_time}s
                            </small>
                        </div>
                        
                        ${run.selection_mode && run.selection_mode !== 'Legacy (Best Trial)' ? 
                            `<div class="mt-1">
                                <small class="text-primary">
                                    🎯 ${run.selection_mode} (${run.num_qualifying_trials} trials)
                                </small>
                            </div>` : ''}
                        
                        ${run.plots_available.length > 0 ? 
                            `<div class="mt-1"><small class="text-info">📊 ${run.plots_available.length} plots</small></div>` : ''}
                    </div>
                </div>
            `).join('');
        }
        
        function selectRun(runId) {
            // Remove previous selection
            document.querySelectorAll('.run-card').forEach(card => {
                card.classList.remove('selected');
            });
            
            // Add selection to clicked card
            document.querySelector(`[data-run-id="${runId}"]`).classList.add('selected');
            
            currentRun = runId;
            
            // Trigger run selection event (for page-specific handling)
            if (typeof onRunSelected === 'function') {
                onRunSelected(runId);
            }
        }
        
        function updateQuickStats(runs) {
            if (runs.length === 0) return;
            
            const bestF1 = Math.max(...runs.map(r => r.soft_f1));
            const avgTime = runs.reduce((sum, r) => sum + r.avg_trial_time, 0) / runs.length;
            
            document.getElementById('total-runs').textContent = runs.length;
            document.getElementById('best-f1').textContent = bestF1.toFixed(4);
            document.getElementById('avg-time').textContent = avgTime.toFixed(1) + 's';
        }
        
        // Search functionality
        document.getElementById('search-runs').addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const filteredRuns = allRuns.filter(run => 
                run.run_id.toLowerCase().includes(searchTerm) ||
                run.timestamp.toLowerCase().includes(searchTerm)
            );
            displayRuns(filteredRuns);
        });
        
        // Sort functionality
        document.getElementById('sort-runs').addEventListener('change', function(e) {
            const sortBy = e.target.value;
            const sortedRuns = [...allRuns].sort((a, b) => {
                if (sortBy === 'timestamp') {
                    return new Date(b.timestamp) - new Date(a.timestamp);
                } else {
                    return b[sortBy] - a[sortBy];
                }
            });
            displayRuns(sortedRuns);
        });
        
        // Utility function to show loading
        function showLoading(containerId) {
            document.getElementById(containerId).innerHTML = `
                <div class="loading-spinner" style="display: block;">
                    <div class="spinner-border" role="status"></div>
                    <div>Loading...</div>
                </div>
            `;
        }
        
        // Utility function to show error
        function showError(containerId, message) {
            document.getElementById(containerId).innerHTML = `
                <div class="alert alert-danger">${message}</div>
            `;
        }
    </script>
    
    {% block scripts %}{% endblock %}
</body>
</html>