<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Optimization Dashboard - MHA Flow</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-dark bg-dark sticky-top">
        <div class="container-fluid">
            <span class="navbar-brand mb-0 h1">
                <i class="fas fa-brain"></i> MHA Flow
            </span>
            <ul class="nav navbar-nav ms-auto">
                <li class="nav-item"><a class="nav-link" href="/">Home</a></li>
                <li class="nav-item"><a class="nav-link active" href="/dashboard">Dashboard</a></li>
                <li class="nav-item"><a class="nav-link" href="/dataset-upload">Upload Data</a></li>
                <li class="nav-item"><a class="nav-link" href="/algorithm-recommend">Recommend</a></li>
                <li class="nav-item"><a class="nav-link" href="/optimization">Optimize</a></li>
                <li class="nav-item"><a class="nav-link" href="/results">Results</a></li>
            </ul>
        </div>
    </nav>

    <div class="container-fluid py-5">
        <!-- Alert if no dataset loaded -->
        <div id="noDatasetAlert" class="alert alert-warning" style="display: none;">
            <i class="fas fa-exclamation-triangle"></i> Please <a href="/dataset-upload">upload and analyze a dataset</a> first.
        </div>

        <!-- Optimization Configuration -->
        <div id="mainContent" style="display: none;">
            <div class="row mb-5">
                <div class="col-lg-10 offset-lg-1">
                    <div class="card shadow-lg border-0">
                        <div class="card-header bg-gradient text-white py-4">
                            <h3 class="mb-0">
                                <i class="fas fa-cogs"></i> Optimization Configuration
                            </h3>
                        </div>
                        <div class="card-body p-4">
                            <div class="row mb-4">
                                <div class="col-md-3">
                                    <label for="algorithmSelect" class="form-label"><strong>Select Algorithm:</strong></label>
                                    <select class="form-select" id="algorithmSelect">
                                        <option value="">-- Choose algorithm --</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="populationSize" class="form-label"><strong>Population Size:</strong></label>
                                    <input type="number" class="form-control" id="populationSize" value="30" min="10" max="200">
                                </div>
                                <div class="col-md-3">
                                    <label for="iterations" class="form-label"><strong>Iterations:</strong></label>
                                    <input type="number" class="form-control" id="iterations" value="100" min="10" max="1000">
                                </div>
                                <div class="col-md-3">
                                    <label for="runCount" class="form-label"><strong>Number of Runs:</strong></label>
                                    <input type="number" class="form-control" id="runCount" value="3" min="1" max="10">
                                </div>
                            </div>

                            <hr>
                            <h5 class="mb-3">Objective Function</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="benchmarkSelect" class="form-label"><strong>Select Benchmark:</strong></label>
                                    <select class="form-select" id="benchmarkSelect">
                                        <option value="sphere">Sphere (f(x) = Σx²)</option>
                                        <option value="rastrigin">Rastrigin</option>
                                        <option value="rosenbrock">Rosenbrock</option>
                                        <option value="ackley">Ackley</option>
                                        <option value="schwefel">Schwefel</option>
                                    </select>
                                </div>
                            </div>

                            <button class="btn btn-success btn-lg w-100 mt-4" id="startOptimizationBtn">
                                <i class="fas fa-rocket"></i> Start Optimization
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Real-time Optimization Progress -->
            <div id="optimizationProgress" class="row mb-5" style="display: none;">
                <div class="col-lg-10 offset-lg-1">
                    <div class="card shadow-lg border-0">
                        <div class="card-header bg-gradient text-white py-4">
                            <h3 class="mb-0">
                                <i class="fas fa-spinner fa-spin"></i> Optimization in Progress
                            </h3>
                        </div>
                        <div class="card-body p-4">
                            <div class="row mb-4">
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="currentIteration" class="text-primary">0 / 100</h4>
                                        <p class="text-muted">Iteration</p>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="bestFitness" class="text-success">-</h4>
                                        <p class="text-muted">Best Fitness</p>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="convergenceRate" class="text-warning">-</h4>
                                        <p class="text-muted">Convergence</p>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="elapsedTime" class="text-info">0s</h4>
                                        <p class="text-muted">Time Elapsed</p>
                                    </div>
                                </div>
                            </div>

                            <div class="progress mb-4" style="height: 25px;">
                                <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" 
                                     role="progressbar" style="width: 0%">
                                    <span id="progressPercent">0%</span>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-lg-6">
                                    <h5 class="mb-3">Convergence Curve</h5>
                                    <canvas id="convergenceChart"></canvas>
                                </div>
                                <div class="col-lg-6">
                                    <h5 class="mb-3">Fitness Distribution</h5>
                                    <canvas id="fitnessChart"></canvas>
                                </div>
                            </div>

                            <button class="btn btn-danger mt-4" id="stopOptimizationBtn">
                                <i class="fas fa-stop"></i> Stop Optimization
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Results Summary -->
            <div id="resultsSection" class="row mb-5" style="display: none;">
                <div class="col-lg-10 offset-lg-1">
                    <div class="card shadow-lg border-0">
                        <div class="card-header bg-gradient text-white py-4">
                            <h3 class="mb-0">
                                <i class="fas fa-check-circle"></i> Optimization Complete
                            </h3>
                        </div>
                        <div class="card-body p-4">
                            <div class="row mb-4">
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="finalBestFitness" class="text-success">-</h4>
                                        <p class="text-muted">Best Fitness</p>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="finalAvgFitness" class="text-info">-</h4>
                                        <p class="text-muted">Avg Fitness</p>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="finalIterations" class="text-warning">-</h4>
                                        <p class="text-muted">Iterations</p>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="finalTime" class="text-primary">-</h4>
                                        <p class="text-muted">Total Time</p>
                                    </div>
                                </div>
                            </div>

                            <hr>

                            <div class="row">
                                <div class="col-lg-6">
                                    <h5 class="mb-3">Final Convergence Curve</h5>
                                    <canvas id="finalConvergenceChart"></canvas>
                                </div>
                                <div class="col-lg-6">
                                    <h5 class="mb-3">Statistics Summary</h5>
                                    <table class="table">
                                        <tbody>
                                            <tr>
                                                <td><strong>Algorithm</strong></td>
                                                <td id="resultAlgorithm">-</td>
                                            </tr>
                                            <tr>
                                                <td><strong>Objective Function</strong></td>
                                                <td id="resultObjective">-</td>
                                            </tr>
                                            <tr>
                                                <td><strong>Population Size</strong></td>
                                                <td id="resultPopSize">-</td>
                                            </tr>
                                            <tr>
                                                <td><strong>Number of Runs</strong></td>
                                                <td id="resultRuns">-</td>
                                            </tr>
                                            <tr>
                                                <td><strong>Success Rate</strong></td>
                                                <td id="resultSuccess">-</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div class="mt-4">
                                <a href="/results" class="btn btn-primary btn-lg me-2">
                                    <i class="fas fa-chart-line"></i> View Detailed Results
                                </a>
                                <button class="btn btn-secondary btn-lg" onclick="location.reload()">
                                    <i class="fas fa-redo"></i> Run Again
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <script>
        let convergenceChart = null;
        let fitnessChart = null;
        let finalConvergenceChart = null;
        let optimizationStartTime = null;
        let timerInterval = null;

        async function initializeDashboard() {
            try {
                const response = await fetch('/api/dataset/profile');
                if (response.status === 400) {
                    document.getElementById('noDatasetAlert').style.display = 'block';
                    return;
                }

                document.getElementById('mainContent').style.display = 'block';

                // Fetch and populate algorithms
                const algResponse = await fetch('/api/algorithms/list');
                const algData = await algResponse.json();
                
                const select = document.getElementById('algorithmSelect');
                algData.algorithms.forEach(algo => {
                    const option = document.createElement('option');
                    option.value = algo;
                    option.textContent = algo.toUpperCase();
                    select.appendChild(option);
                });

                // Add event listeners
                document.getElementById('startOptimizationBtn').addEventListener('click', startOptimization);
                document.getElementById('stopOptimizationBtn').addEventListener('click', stopOptimization);
            } catch (error) {
                console.error('Error initializing dashboard:', error);
            }
        }

        async function startOptimization() {
            const algorithm = document.getElementById('algorithmSelect').value;
            const popSize = parseInt(document.getElementById('populationSize').value);
            const iterations = parseInt(document.getElementById('iterations').value);
            const runs = parseInt(document.getElementById('runCount').value);
            const benchmark = document.getElementById('benchmarkSelect').value;

            if (!algorithm) {
                alert('Please select an algorithm');
                return;
            }

            document.getElementById('startOptimizationBtn').disabled = true;
            document.getElementById('optimizationProgress').style.display = 'block';

            optimizationStartTime = Date.now();
            startTimer();

            try {
                // Initialize charts
                initializeCharts();

                // Simulate optimization progress
                await simulateOptimization(algorithm, iterations, runs, benchmark);

            } catch (error) {
                alert('Error: ' + error.message);
                document.getElementById('startOptimizationBtn').disabled = false;
            }
        }

        function initializeCharts() {
            const convergenceCtx = document.getElementById('convergenceChart').getContext('2d');
            convergenceChart = new Chart(convergenceCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Best Fitness',
                        data: [],
                        borderColor: '#0d6efd',
                        backgroundColor: 'rgba(13, 110, 253, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { display: true }
                    },
                    scales: {
                        y: {
                            beginAtZero: false,
                            title: { display: true, text: 'Fitness Value' }
                        }
                    }
                }
            });

            const fitnessCtx = document.getElementById('fitnessChart').getContext('2d');
            fitnessChart = new Chart(fitnessCtx, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Fitness Distribution',
                        data: [],
                        backgroundColor: '#198754'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { display: false }
                    }
                }
            });
        }

        async function simulateOptimization(algorithm, iterations, runs, benchmark) {
            const totalIterations = iterations * runs;
            const fitnessList = [];
            const convergenceData = [];

            for (let iter = 1; iter <= totalIterations; iter++) {
                // Simulate fitness value (decreasing trend)
                const noise = Math.random() * 0.1;
                const fitness = Math.exp(-iter / (totalIterations * 0.3)) * 100 + noise * 10;
                fitnessList.push(fitness);
                convergenceData.push(Math.min(...fitnessList));

                // Update UI
                const currentRun = Math.ceil(iter / iterations);
                const currentIter = ((iter - 1) % iterations) + 1;
                
                document.getElementById('currentIteration').textContent = 
                    `${currentIter} / ${iterations} (Run ${currentRun}/${runs})`;
                document.getElementById('bestFitness').textContent = convergenceData[convergenceData.length - 1].toFixed(4);
                
                const convergenceRate = ((1 - fitness / 100) * 100).toFixed(1);
                document.getElementById('convergenceRate').textContent = convergenceRate + '%';

                const progress = (iter / totalIterations) * 100;
                document.getElementById('progressBar').style.width = progress + '%';
                document.getElementById('progressPercent').textContent = Math.round(progress) + '%';

                // Update convergence chart
                convergenceChart.data.labels.push(iter);
                convergenceChart.data.datasets[0].data.push(convergenceData[convergenceData.length - 1]);
                convergenceChart.update();

                // Simulate slight delay
                await new Promise(resolve => setTimeout(resolve, 10));
            }

            // Show results
            clearInterval(timerInterval);
            document.getElementById('optimizationProgress').style.display = 'none';
            document.getElementById('resultsSection').style.display = 'block';

            displayResults(algorithm, iterations, runs, benchmark, convergenceData, fitnessList);
        }

        function displayResults(algorithm, iterations, runs, benchmark, convergenceData, fitnessList) {
            const bestFitness = Math.min(...convergenceData);
            const avgFitness = (convergenceData.reduce((a, b) => a + b) / convergenceData.length).toFixed(4);
            const totalTime = ((Date.now() - optimizationStartTime) / 1000).toFixed(2);

            document.getElementById('finalBestFitness').textContent = bestFitness.toFixed(4);
            document.getElementById('finalAvgFitness').textContent = avgFitness;
            document.getElementById('finalIterations').textContent = iterations * runs;
            document.getElementById('finalTime').textContent = totalTime + 's';

            document.getElementById('resultAlgorithm').textContent = algorithm.toUpperCase();
            document.getElementById('resultObjective').textContent = benchmark;
            document.getElementById('resultPopSize').textContent = document.getElementById('populationSize').value;
            document.getElementById('resultRuns').textContent = runs;

            const successRate = ((1 - bestFitness / 100) * 100).toFixed(1);
            document.getElementById('resultSuccess').textContent = successRate + '%';

            // Create final convergence chart
            const ctx = document.getElementById('finalConvergenceChart').getContext('2d');
            finalConvergenceChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: convergenceData.map((_, i) => i + 1),
                    datasets: [{
                        label: 'Best Fitness Over Time',
                        data: convergenceData,
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { display: true }
                    },
                    scales: {
                        y: { beginAtZero: false }
                    }
                }
            });

            document.getElementById('startOptimizationBtn').disabled = false;
        }

        function startTimer() {
            timerInterval = setInterval(() => {
                const elapsed = Math.floor((Date.now() - optimizationStartTime) / 1000);
                document.getElementById('elapsedTime').textContent = elapsed + 's';
            }, 1000);
        }

        function stopOptimization() {
            clearInterval(timerInterval);
            document.getElementById('optimizationProgress').style.display = 'none';
            document.getElementById('startOptimizationBtn').disabled = false;
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', initializeDashboard);
    </script>
</body>
</html>
