{% extends "base.html" %}

{% block title %}Optimization Results - MHA Flow{% endblock %}

{% block extra_css %}
<style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
    
    * {
        font-family: 'Inter', sans-serif;
    }
    
    body {
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        min-height: 100vh;
    }
    
    .results-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 50px;
        border-radius: 20px;
        margin-bottom: 40px;
        text-align: center;
        box-shadow: 0 20px 60px rgba(102, 126, 234, 0.4);
        position: relative;
        overflow: hidden;
    }
    
    .results-header::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
        animation: pulse 4s ease-in-out infinite;
    }
    
    @keyframes pulse {
        0%, 100% { opacity: 0.5; transform: scale(1); }
        50% { opacity: 1; transform: scale(1.05); }
    }
    
    .results-header h1 {
        font-size: 3rem;
        font-weight: 800;
        margin: 0;
        position: relative;
        z-index: 1;
        text-shadow: 2px 4px 8px rgba(0,0,0,0.2);
    }
    
    .results-header p {
        font-size: 1.2rem;
        margin: 10px 0 0 0;
        position: relative;
        z-index: 1;
        opacity: 0.95;
    }
    
    .metric-card {
        background: white;
        border-radius: 15px;
        padding: 30px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        margin-bottom: 20px;
        text-align: center;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border: 2px solid transparent;
    }
    
    .metric-card:hover {
        transform: translateY(-8px) scale(1.02);
        box-shadow: 0 15px 40px rgba(102, 126, 234, 0.3);
        border-color: #667eea;
    }
    
    .metric-value {
        font-size: 3rem;
        font-weight: 800;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        margin: 15px 0;
        animation: fadeInUp 0.6s ease-out;
    }
    
    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .info-panel {
        background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
        color: white;
        padding: 20px 30px;
        border-radius: 15px;
        margin-bottom: 25px;
        box-shadow: 0 10px 30px rgba(52, 152, 219, 0.3);
    }
    
    .info-panel h5 {
        margin: 0 0 10px 0;
        font-weight: 700;
        font-size: 1.1rem;
    }
    
    .info-panel p {
        margin: 0;
        opacity: 0.95;
        font-size: 0.95rem;
    }
    
    .view-mode-selector {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        justify-content: center;
        flex-wrap: wrap;
    }
    
    .view-mode-selector button {
        min-width: 200px;
    }
    
    .metric-label {
        color: #555;
        font-size: 0.95rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 1.5px;
        margin-bottom: 10px;
    }
    
    .metric-sublabel {
        color: #888;
        font-size: 0.85rem;
        margin-top: 8px;
        font-weight: 500;
    }
    
    .chart-container {
        background: white;
        padding: 35px;
        border-radius: 20px;
        box-shadow: 0 8px 25px rgba(0,0,0,0.08);
        margin-bottom: 35px;
        border: 1px solid rgba(102, 126, 234, 0.1);
        transition: all 0.3s ease;
    }
    
    .chart-container:hover {
        box-shadow: 0 12px 35px rgba(102, 126, 234, 0.15);
        transform: translateY(-2px);
    }
    
    .chart-title {
        font-size: 1.6rem;
        font-weight: 700;
        color: #2d3748;
        margin-bottom: 25px;
        padding-bottom: 15px;
        border-bottom: 3px solid #667eea;
        display: inline-block;
    }
    
    .info-box {
        background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
        border-left: 5px solid #667eea;
        padding: 20px 25px;
        border-radius: 12px;
        margin: 25px 0;
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
        animation: slideInLeft 0.5s ease-out;
    }
    
    @keyframes slideInLeft {
        from {
            opacity: 0;
            transform: translateX(-20px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }
    
    .info-box strong {
        color: #667eea;
        font-weight: 700;
    }
    
    .info-box ul {
        margin-bottom: 0;
    }
    
    .info-box li {
        margin: 8px 0;
    }
    
    .nav-tabs {
        border-bottom: 2px solid #e0e0e0;
        margin-bottom: 30px;
    }
    
    .nav-tabs .nav-link {
        color: #666;
        font-weight: 600;
        font-size: 1.05rem;
        padding: 15px 25px;
        border: none;
        border-radius: 12px 12px 0 0;
        margin-right: 5px;
        transition: all 0.3s ease;
        position: relative;
    }
    
    .nav-tabs .nav-link:hover {
        color: #667eea;
        background: rgba(102, 126, 234, 0.05);
        transform: translateY(-2px);
    }
    
    .nav-tabs .nav-link.active {
        color: #667eea;
        font-weight: 700;
        background: white;
        border-bottom: 3px solid #667eea;
        box-shadow: 0 -3px 10px rgba(102, 126, 234, 0.2);
    }
    
    .nav-tabs .nav-link.active::after {
        content: '';
        position: absolute;
        bottom: -2px;
        left: 0;
        right: 0;
        height: 3px;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    }
    
    .export-btn {
        margin: 10px 5px;
        padding: 14px 28px;
        border-radius: 12px;
        font-weight: 600;
        font-size: 1rem;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        border: 2px solid transparent;
    }
    
    .export-btn:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
    }
    
    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
    }
    
    .btn-primary:hover {
        background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
    }
    
    .btn-success {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        border: none;
    }
    
    .btn-success:hover {
        background: linear-gradient(135deg, #38ef7d 0%, #11998e 100%);
    }
    
    .btn-info {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        border: none;
    }
    
    .btn-info:hover {
        background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%);
    }
    
    .ranking-medal {
        font-size: 1.5rem;
        margin-right: 10px;
    }
    
    table.results-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        border-radius: 12px;
        overflow: hidden;
    }
    
    table.results-table th {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 16px;
        font-weight: 700;
        font-size: 0.95rem;
        text-transform: uppercase;
        letter-spacing: 1px;
        border: none;
    }
    
    table.results-table td {
        padding: 14px 16px;
        border-bottom: 1px solid #e8e8e8;
        font-size: 0.95rem;
        transition: all 0.2s ease;
    }
    
    table.results-table tbody tr {
        transition: all 0.3s ease;
    }
    
    table.results-table tbody tr:hover {
        background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
        transform: scale(1.01);
        box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    }
    
    table.results-table tbody tr:nth-child(even) {
        background: #fafafa;
    }
    
    .threshold-control {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        padding: 25px;
        border-radius: 15px;
        margin-bottom: 25px;
        border: 2px solid rgba(102, 126, 234, 0.2);
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
    }
    
    .threshold-value {
        font-size: 1.8rem;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        font-weight: 800;
    }
    
    .form-range {
        height: 8px;
        background: linear-gradient(90deg, #e0e0e0 0%, #667eea 100%);
        border-radius: 5px;
    }
    
    .form-range::-webkit-slider-thumb {
        width: 24px;
        height: 24px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 50%;
        box-shadow: 0 4px 10px rgba(102, 126, 234, 0.4);
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .form-range::-webkit-slider-thumb:hover {
        transform: scale(1.2);
        box-shadow: 0 6px 15px rgba(102, 126, 234, 0.6);
    }
    
    .ranking-medal {
        font-size: 1.8rem;
        margin-right: 12px;
        filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.2));
    }
    
    /* Loading animation for charts */
    .plotly-graph-div {
        animation: fadeIn 0.8s ease-out;
    }
    
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    /* Smooth scrolling */
    html {
        scroll-behavior: smooth;
    }
    
    /* Custom scrollbar */
    ::-webkit-scrollbar {
        width: 10px;
        height: 10px;
    }
    
    ::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
        background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid px-4">
    <!-- Header -->
    <div class="results-header">
        <h1>📊 Optimization Results</h1>
        <p class="mb-0">Comprehensive analysis and visualization of your optimization run</p>
    </div>

    <!-- Summary Metrics -->
        <!-- Info Panel -->
    <div class="alert alert-info mb-4">
        <h6><i class="fas fa-info-circle"></i> Understanding Execution Times & Iterations</h6>
        <p class="mb-0"><strong>Quick runs (0.2-0.5s for 100 iterations):</strong> Normal for simple objective functions like Sphere. 
        <strong>Long runs (10-15 min):</strong> Occur with higher iterations (1000+), complex functions (Rosenbrock, Rastrigin), 
        large populations (100+), or high dimensions (50+). Adjust these parameters in optimization settings for longer, more thorough searches.</p>
    </div>
    
    <!-- View Mode Buttons -->
    <div class="text-center mb-4">
        <div class="btn-group" role="group">
            <button type="button" class="btn btn-primary" onclick="loadLatestOptimization()">
                <i class="fas fa-sync-alt"></i> Latest Optimization
            </button>
            <button type="button" class="btn btn-info" onclick="loadAllHistory()">
                <i class="fas fa-history"></i> All History (Grouped)
            </button>
            <a href="/history" class="btn btn-secondary">
                <i class="fas fa-table"></i> Detailed Table
            </a>
        </div>
    </div>
<div class="row" id="summaryMetrics">
        <!-- Populated by JavaScript -->
    </div>

    <!-- Main Results Tabs -->
    <div class="chart-container">
        <ul class="nav nav-tabs" id="resultsTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="summary-tab" data-bs-toggle="tab" data-bs-target="#summary" type="button">
                    📈 Summary
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="comparative-tab" data-bs-toggle="tab" data-bs-target="#comparative" type="button">
                    ⚖️ Comparative Analysis
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="convergence-tab" data-bs-toggle="tab" data-bs-target="#convergence" type="button">
                    🔄 Convergence
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="features-tab" data-bs-toggle="tab" data-bs-target="#features" type="button">
                    🎯 Feature Analysis
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="export-tab" data-bs-toggle="tab" data-bs-target="#export" type="button">
                    💾 Export
                </button>
            </li>
        </ul>

        <div class="tab-content mt-4" id="resultsTabContent">
            <!-- SUMMARY TAB -->
            <div class="tab-pane fade show active" id="summary" role="tabpanel">
                <div class="chart-title">📊 Performance Summary</div>
                
                <div class="table-responsive">
                    <table class="results-table">
                        <thead>
                            <tr>
                                <th>Algorithm</th>
                                <th>Best Fitness</th>
                                <th>Mean Fitness</th>
                                <th>Std Dev</th>
                                <th>Time (s)</th>
                                <th>Features</th>
                            </tr>
                        </thead>
                        <tbody id="summaryTableBody"></tbody>
                    </table>
                </div>
                
                <div class="chart-container mt-4">
                    <div class="chart-title">📈 Performance Comparison: Best Fitness</div>
                    <div id="performanceBarChart" style="height: 500px;"></div>
                </div>
            </div>

            <!-- COMPARATIVE ANALYSIS TAB -->
            <div class="tab-pane fade" id="comparative" role="tabpanel">
                <div class="chart-title">⚖️ Comprehensive Comparative Analysis</div>
                
                <div class="info-box">
                    <strong>💡 How to read these charts:</strong>
                    <ul class="mb-0 mt-2">
                        <li><strong>Box Plot:</strong> Distribution across multiple runs. Narrower box = more consistent algorithm.</li>
                        <li><strong>Lower position = Better performance</strong> (lower fitness is better)</li>
                        <li><strong>Whiskers:</strong> Show minimum and maximum values</li>
                    </ul>
                </div>
                
                <!-- Box Plot -->
                <div class="chart-container">
                    <div class="chart-title">📦 Box Plot: Fitness Distribution</div>
                    <div id="fitnessBoxPlot" style="height: 500px;"></div>
                </div>
                
                <!-- Mean Fitness -->
                <div class="chart-container">
                    <div class="chart-title">📊 Mean Fitness with Standard Deviation</div>
                    <div id="meanFitnessChart" style="height: 500px;"></div>
                </div>
                
                <!-- Accuracy -->
                <div class="chart-container">
                    <div class="chart-title">🎯 Accuracy Comparison (Higher is Better)</div>
                    <div id="accuracyChart" style="height: 500px;"></div>
                </div>
                
                <!-- Standard Deviation -->
                <div class="chart-container">
                    <div class="chart-title">📐 Standard Deviation (Consistency)</div>
                    <p class="text-muted">Lower SD = More consistent/reliable algorithm across multiple runs</p>
                    <div id="stdDevChart" style="height: 500px;"></div>
                </div>
                
                <!-- Execution Time -->
                <div class="chart-container">
                    <div class="chart-title">⏱️ Execution Time Comparison</div>
                    <div id="executionTimeChart" style="height: 500px;"></div>
                </div>
                
                <!-- Multi-dimensional Scatter -->
                <div class="chart-container">
                    <div class="chart-title">🔄 Performance vs Speed</div>
                    <p class="text-muted">Ideal position: Bottom-left corner (low fitness, fast time)</p>
                    <div id="scatterChart" style="height: 600px;"></div>
                </div>
                
                <!-- Ranking Table -->
                <div class="chart-container">
                    <div class="chart-title">🏆 Overall Ranking</div>
                    <div class="table-responsive">
                        <table class="results-table">
                            <thead>
                                <tr>
                                    <th>Rank</th>
                                    <th>Algorithm</th>
                                    <th>Best Fitness</th>
                                    <th>Mean Accuracy %</th>
                                    <th>Consistency (SD)</th>
                                    <th>Speed (s)</th>
                                </tr>
                            </thead>
                            <tbody id="rankingTableBody"></tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- CONVERGENCE TAB -->
            <div class="tab-pane fade" id="convergence" role="tabpanel">
                <div class="chart-title">🔄 Convergence Analysis</div>
                
                <div class="chart-container">
                    <div class="chart-title">📈 Convergence Curves: Fitness vs. Iterations</div>
                    <div id="convergencePlot" style="height: 600px;"></div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">📊 Convergence Statistics</div>
                    <div class="table-responsive">
                        <table class="results-table">
                            <thead>
                                <tr>
                                    <th>Algorithm</th>
                                    <th>Initial Fitness</th>
                                    <th>Final Fitness</th>
                                    <th>Improvement</th>
                                    <th>Improvement %</th>
                                    <th>90% Conv. Iter</th>
                                </tr>
                            </thead>
                            <tbody id="convergenceStatsBody"></tbody>
                        </table>
                    </div>
                </div>
                
                <div class="row mt-4">
                    <div class="col-md-6">
                        <div class="metric-card">
                            <div class="metric-label">🏆 Best Improvement</div>
                            <div class="metric-value" id="bestImprovementAlgo">-</div>
                            <div class="metric-sublabel" id="bestImprovementValue">-</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="metric-card">
                            <div class="metric-label">⚡ Fastest Convergence</div>
                            <div class="metric-value" id="fastestConvergenceAlgo">-</div>
                            <div class="metric-sublabel" id="fastestConvergenceValue">-</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- FEATURES TAB -->
            <div class="tab-pane fade" id="features" role="tabpanel">
                <div class="chart-title">🎯 Feature Selection Analysis</div>
                
                <div class="info-box">
                    <strong>💡 Understanding Feature Importance:</strong>
                    <p class="mb-2">MHA agents explore feature space with positions from 0.0 to 1.0. Use the threshold to control selection:</p>
                    <ul class="mb-0">
                        <li><strong>0.5</strong> (Default): Standard selection - significantly important features</li>
                        <li><strong>&gt;0.5</strong> (e.g., 0.75): High selectivity - most critical features only</li>
                        <li><strong>&lt;0.5</strong> (e.g., 0.25): Low selectivity - includes more contributing features</li>
                    </ul>
                </div>
                
                <div class="threshold-control">
                    <label for="featureThreshold" class="form-label">Feature Selection Threshold:</label>
                    <input type="range" class="form-range" id="featureThreshold" min="0" max="1" step="0.05" value="0.5">
                    <div class="text-center mt-2">
                        Current: <span class="threshold-value" id="thresholdValue">0.5</span>
                    </div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">
                        🏆 Best Algorithm: <span id="bestAlgoName">-</span>
                    </div>
                    <p>
                        <strong>Best Fitness:</strong> <span id="bestFitnessValue">-</span> | 
                        <strong>Accuracy:</strong> <span id="bestAccuracyValue">-</span>
                    </p>
                    <div id="featureImportancePlot" style="height: 500px;"></div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">📊 Selected Features Summary</div>
                    <div id="featureSummary" class="row">
                        <!-- Populated by JS -->
                    </div>
                </div>
            </div>

            <!-- EXPORT TAB -->
            <div class="tab-pane fade" id="export" role="tabpanel">
                <div class="chart-title">💾 Export Options</div>
                
                <div class="row">
                    <div class="col-md-6 mb-4">
                        <div class="chart-container text-center">
                            <h5>📥 Summary Export</h5>
                            <p class="text-muted">Export performance summary with all statistics</p>
                            <button class="btn btn-primary export-btn" onclick="exportSummaryCSV()">
                                <i class="fas fa-download"></i> Download Summary (CSV)
                            </button>
                        </div>
                    </div>
                    
                    <div class="col-md-6 mb-4">
                        <div class="chart-container text-center">
                            <h5>📥 Full Results Export</h5>
                            <p class="text-muted">Export complete results with all details</p>
                            <button class="btn btn-primary export-btn" onclick="exportFullJSON()">
                                <i class="fas fa-download"></i> Download Full Results (JSON)
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-4">
                        <div class="chart-container text-center">
                            <h5>📈 Convergence Data Export</h5>
                            <p class="text-muted">Export iteration-by-iteration convergence data</p>
                            <button class="btn btn-success export-btn" onclick="exportConvergenceCSV()">
                                <i class="fas fa-download"></i> Download Convergence (CSV)
                            </button>
                        </div>
                    </div>
                    
                    <div class="col-md-6 mb-4">
                        <div class="chart-container text-center">
                            <h5>🎯 Feature Selection Export</h5>
                            <p class="text-muted">Export feature importance values</p>
                            <button class="btn btn-success export-btn" onclick="exportFeaturesCSV()">
                                <i class="fas fa-download"></i> Download Features (CSV)
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="chart-container mt-4 text-center">
                    <h5>✅ Need More?</h5>
                    <p>View your optimization history to compare with previous runs</p>
                    <a href="{{ url_for('history') }}" class="btn btn-info">
                        <i class="fas fa-history"></i> View Results History
                    </a>
                    <a href="{{ url_for('optimize_page') }}" class="btn btn-success ms-2">
                        <i class="fas fa-rocket"></i> New Optimization
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.plot.ly/plotly-2.18.0.min.js"></script>
<script src="{{ url_for('static', filename='js/results.js') }}?v={{ range(1, 99999) | random }}"></script>
{% endblock %}

