{% extends "base.html" %}

{% block title %}Compare Algorithms - MHA Flow{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-4">
        <div class="card shadow">
            <div class="card-header bg-info text-white">
                <h5><i class="fas fa-list-check"></i> Select Algorithms</h5>
            </div>
            <div class="card-body">
                <form id="compareForm">
                    <div class="mb-3">
                        <label class="form-label">Algorithms to Compare</label>
                        <select class="form-select" id="algorithmsList" multiple size="10">
                            {% for algo in algorithms %}
                            <option value="{{ algo }}">{{ algo }}</option>
                            {% endfor %}
                        </select>
                        <small class="form-text text-muted">Hold Ctrl/Cmd to select multiple</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Objective Function</label>
                        <select class="form-select" id="objectiveFunction">
                            {% for func in objective_functions %}
                            <option value="{{ func }}">{{ func }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Population Size</label>
                        <input type="number" class="form-control" id="populationSize" value="30">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Max Iterations</label>
                        <input type="number" class="form-control" id="maxIterations" value="100">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Dimensions</label>
                        <input type="number" class="form-control" id="dimensions" value="10">
                    </div>
                    
                    <button type="submit" class="btn btn-info w-100">
                        <i class="fas fa-chart-bar"></i> Compare Algorithms
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <div class="card shadow">
            <div class="card-header bg-info text-white">
                <h5><i class="fas fa-chart-bar"></i> Comparison Results</h5>
            </div>
            <div class="card-body">
                <div id="loadingSpinner" class="text-center d-none">
                    <div class="spinner-border text-info" role="status"></div>
                    <p class="mt-3">Running comparison...</p>
                </div>
                
                <div id="comparisonResults" class="d-none">
                    <div id="fitnessChart" style="height:400px;"></div>
                    <div id="timeChart" style="height:400px;" class="mt-4"></div>
                    <div id="convergenceChart" style="height:500px;" class="mt-4"></div>
                    
                    <div class="table-responsive mt-4">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Algorithm</th>
                                    <th>Best Fitness</th>
                                    <th>Time (s)</th>
                                    <th>Rank</th>
                                </tr>
                            </thead>
                            <tbody id="resultsTable"></tbody>
                        </table>
                    </div>
                </div>
                
                <div id="noResults" class="text-center text-muted">
                    <i class="fas fa-chart-bar fa-5x mb-3"></i>
                    <p>Select at least 2 algorithms and run comparison</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('compareForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const selectedOptions = Array.from(document.getElementById('algorithmsList').selectedOptions);
    const algorithms = selectedOptions.map(opt => opt.value);
    
    if (algorithms.length < 2) {
        alert('Please select at least 2 algorithms');
        return;
    }
    
    const data = {
        algorithms: algorithms,
        objective_function: document.getElementById('objectiveFunction').value,
        population_size: parseInt(document.getElementById('populationSize').value),
        max_iterations: parseInt(document.getElementById('maxIterations').value),
        dimensions: parseInt(document.getElementById('dimensions').value)
    };
    
    document.getElementById('noResults').classList.add('d-none');
    document.getElementById('comparisonResults').classList.add('d-none');
    document.getElementById('loadingSpinner').classList.remove('d-none');
    
    try {
        const response = await fetch('/api/compare', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            displayComparisonResults(result.results);
        } else {
            alert('Error: ' + result.error);
        }
    } catch (error) {
        alert('Request failed: ' + error.message);
    } finally {
        document.getElementById('loadingSpinner').classList.add('d-none');
    }
});

function displayComparisonResults(results) {
    // Sort by fitness
    results.sort((a, b) => a.best_fitness - b.best_fitness);
    
    // Fitness comparison chart
    const fitnessTrace = {
        x: results.map(r => r.algorithm),
        y: results.map(r => r.best_fitness),
        type: 'bar',
        marker: {color: '#0dcaf0'}
    };
    
    Plotly.newPlot('fitnessChart', [fitnessTrace], {
        title: 'Best Fitness Comparison',
        yaxis: {title: 'Fitness (lower is better)', type: 'log'}
    });
    
    // Time comparison chart
    const timeTrace = {
        x: results.map(r => r.algorithm),
        y: results.map(r => r.execution_time),
        type: 'bar',
        marker: {color: '#198754'}
    };
    
    Plotly.newPlot('timeChart', [timeTrace], {
        title: 'Execution Time Comparison',
        yaxis: {title: 'Time (seconds)'}
    });
    
    // Convergence curves
    const convergenceTraces = results.map(r => ({
        y: r.convergence,
        type: 'scatter',
        mode: 'lines',
        name: r.algorithm
    }));
    
    Plotly.newPlot('convergenceChart', convergenceTraces, {
        title: 'Convergence Curves',
        xaxis: {title: 'Iteration'},
        yaxis: {title: 'Best Fitness', type: 'log'}
    });
    
    // Results table
    const tableBody = document.getElementById('resultsTable');
    tableBody.innerHTML = '';
    
    results.forEach((r, idx) => {
        const row = tableBody.insertRow();
        row.innerHTML = `
            <td><strong>${r.algorithm}</strong></td>
            <td>${r.best_fitness.toExponential(6)}</td>
            <td>${r.execution_time.toFixed(4)}</td>
            <td><span class="badge bg-${idx === 0 ? 'success' : 'secondary'}">#${idx + 1}</span></td>
        `;
    });
    
    document.getElementById('comparisonResults').classList.remove('d-none');
}
</script>
{% endblock %}
