{% extends "base.html" %}

{% block title %}Optimize - MHA Flow{% endblock %}

{% block content %}
<!-- Main Header -->
<div class="main-header">
    <h1>🔬 New Optimization Experiment</h1>
    <p>Follow the 4-step guided workflow: Task Selection → Dataset → Algorithms → Configure & Run</p>
</div>

<!-- 4-Tab Interface -->
<ul class="nav nav-tabs mb-4" id="optimizeTabs" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link active" id="step0-tab" data-bs-toggle="tab" data-bs-target="#step0" type="button">
            <strong>Step 0: Select Task</strong>
        </button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="step1-tab" data-bs-toggle="tab" data-bs-target="#step1" type="button">
            <strong>Step 1: Select Dataset</strong>
        </button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="step2-tab" data-bs-toggle="tab" data-bs-target="#step2" type="button">
            <strong>Step 2: Choose Algorithms</strong>
        </button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="step3-tab" data-bs-toggle="tab" data-bs-target="#step3" type="button">
            <strong>Step 3: Configure & Run</strong>
        </button>
    </li>
</ul>

<div class="tab-content" id="optimizeTabsContent">
    <!-- TAB 0: TASK SELECTION -->
    <div class="tab-pane fade show active" id="step0" role="tabpanel">
        <h4 class="mb-4">🎯 Select Your Task Type</h4>
        <p class="text-muted mb-4">Choose what you want to optimize. The system will recommend the best algorithms for your task.</p>
        
        <div class="row g-4">
            <div class="col-md-4">
                <div class="card task-card" data-task="optimization">
                    <div class="card-body text-center p-4">
                        <div class="task-icon mb-3">🎯</div>
                        <h5>General Optimization</h5>
                        <p class="text-muted small">
                            Optimize objective functions, find global optima, solve continuous/discrete problems
                        </p>
                        <button class="btn btn-primary w-100 select-task-btn">Select Task</button>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card task-card" data-task="feature_selection">
                    <div class="card-body text-center p-4">
                        <div class="task-icon mb-3">🎨</div>
                        <h5>Feature Selection</h5>
                        <p class="text-muted small">
                            Select optimal subset of features from your dataset for better ML performance
                        </p>
                        <button class="btn btn-primary w-100 select-task-btn">Select Task</button>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card task-card" data-task="hyperparameter">
                    <div class="card-body text-center p-4">
                        <div class="task-icon mb-3">⚙️</div>
                        <h5>Hyperparameter Tuning</h5>
                        <p class="text-muted small">
                            Find optimal hyperparameters for your machine learning models
                        </p>
                        <button class="btn btn-primary w-100 select-task-btn">Select Task</button>
                    </div>
                </div>
            </div>
        </div>
        
        <div id="taskPreview" class="alert alert-info mt-4 d-none">
            <strong>Selected Task:</strong> <span id="selectedTaskName"></span><br>
            <button class="btn btn-sm btn-success mt-2" onclick="goToStep(1)">Continue to Dataset Selection →</button>
        </div>
    </div>
    
    <!-- TAB 1: DATASET SELECTION -->
    <div class="tab-pane fade" id="step1" role="tabpanel">
        <h4 class="mb-4">📦 Select Your Dataset</h4>
        
        <!-- Data Source Radio Buttons -->
        <div class="btn-group w-100 mb-4" role="group">
            <input type="radio" class="btn-check" name="dataSource" id="sampleDatasets" value="sample" checked>
            <label class="btn btn-outline-primary" for="sampleDatasets">📦 Sample Datasets</label>
            
            <input type="radio" class="btn-check" name="dataSource" id="uploadCSV" value="upload">
            <label class="btn btn-outline-primary" for="uploadCSV">📤 Upload CSV</label>
            
            <input type="radio" class="btn-check" name="dataSource" id="generateRandom" value="generate">
            <label class="btn btn-outline-primary" for="generateRandom">🎲 Generate Random</label>
        </div>

        <!-- WORKFLOW 1: Sample Datasets -->
        <div id="sampleDatasetSection">
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="card dataset-card">
                        <div class="card-body">
                            <h5>🎗️ Breast Cancer</h5>
                            <p class="text-muted small mb-2">
                                <strong>Samples:</strong> 569 | <strong>Features:</strong> 30
                            </p>
                            <button class="btn btn-primary w-100 select-dataset-btn" data-name="breast_cancer" data-samples="569" data-features="30">
                                Select Dataset
                            </button>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card dataset-card">
                        <div class="card-body">
                            <h5>🍷 Wine</h5>
                            <p class="text-muted small mb-2">
                                <strong>Samples:</strong> 178 | <strong>Features:</strong> 13
                            </p>
                            <button class="btn btn-primary w-100 select-dataset-btn" data-name="wine" data-samples="178" data-features="13">
                                Select Dataset
                            </button>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card dataset-card">
                        <div class="card-body">
                            <h5>🌸 Iris</h5>
                            <p class="text-muted small mb-2">
                                <strong>Samples:</strong> 150 | <strong>Features:</strong> 4
                            </p>
                            <button class="btn btn-primary w-100 select-dataset-btn" data-name="iris" data-samples="150" data-features="4">
                                Select Dataset
                            </button>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card dataset-card">
                        <div class="card-body">
                            <h5>🔢 Digits</h5>
                            <p class="text-muted small mb-2">
                                <strong>Samples:</strong> 1797 | <strong>Features:</strong> 64
                            </p>
                            <button class="btn btn-primary w-100 select-dataset-btn" data-name="digits" data-samples="1797" data-features="64">
                                Select Dataset
                            </button>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card dataset-card">
                        <div class="card-body">
                            <h5>🏠 California Housing</h5>
                            <p class="text-muted small mb-2">
                                <strong>Samples:</strong> 20640 | <strong>Features:</strong> 8
                            </p>
                            <button class="btn btn-primary w-100 select-dataset-btn" data-name="california_housing" data-samples="20640" data-features="8">
                                Select Dataset
                            </button>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card dataset-card">
                        <div class="card-body">
                            <h5>💉 Diabetes</h5>
                            <p class="text-muted small mb-2">
                                <strong>Samples:</strong> 442 | <strong>Features:</strong> 10
                            </p>
                            <button class="btn btn-primary w-100 select-dataset-btn" data-name="diabetes" data-samples="442" data-features="10">
                                Select Dataset
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div id="datasetPreview" class="mt-4 d-none">
                <div class="alert alert-success">
                    <h5><i class="fas fa-check-circle"></i> Dataset Selected</h5>
                    <p><strong>Name:</strong> <span id="selectedDatasetName"></span> | <strong>Samples:</strong> <span id="selectedSamples"></span> | <strong>Features:</strong> <span id="selectedFeatures"></span></p>
                </div>
                <button class="btn btn-primary btn-lg w-100" onclick="goToStep(2)">
                    <i class="fas fa-arrow-right me-2"></i> Continue to Algorithm Selection
                </button>
            </div>
        </div>

        <!-- WORKFLOW 2: Upload CSV -->
        <div id="uploadCSVSection" class="d-none">
            <div class="alert alert-info mb-4">
                <strong>📤 Upload Your Dataset</strong><br>
                Upload a CSV file with features and optional target column.
            </div>
            <div class="card">
                <div class="card-body">
                    <input type="file" class="form-control" id="csvFile" accept=".csv">
                    <button class="btn btn-primary mt-3 w-100" onclick="uploadCSV()">Upload & Analyze</button>
                </div>
            </div>
        </div>
        
        <!-- WORKFLOW 3: Generate Random Dataset -->
        <div id="generateRandomSection" class="d-none">
            <div class="alert alert-info mb-4">
                <strong>🎲 Generate Random Dataset</strong><br>
                Create synthetic datasets for testing algorithms.
            </div>
            <div class="card">
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Problem Type</label>
                            <select class="form-select" id="genProblemType">
                                <option value="classification">Classification</option>
                                <option value="regression">Regression</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Number of Samples</label>
                            <input type="number" class="form-control" id="genSamples" value="1000" min="10" max="100000">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Number of Features</label>
                            <input type="number" class="form-control" id="genFeatures" value="10" min="2" max="1000">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Number of Classes</label>
                            <input type="number" class="form-control" id="genClasses" value="2" min="2" max="10">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Noise Level: <span id="noiseValue">0.1</span></label>
                            <input type="range" class="form-range" id="genNoise" min="0" max="0.5" step="0.05" value="0.1" 
                                   oninput="document.getElementById('noiseValue').textContent=this.value">
                        </div>
                        <div class="col-md-12">
                            <button class="btn btn-success w-100" onclick="generateRandomDataset()">
                                <i class="fas fa-magic"></i> Generate Dataset
                            </button>
                        </div>
                    </div>
                    
                    <div id="generatedDatasetInfo" class="alert alert-success mt-3 d-none">
                        <h6><i class="fas fa-check-circle"></i> Dataset Generated!</h6>
                        <p id="generatedInfo" class="mb-2"></p>
                        <button class="btn btn-sm btn-primary" onclick="downloadGeneratedDataset()">
                            <i class="fas fa-download"></i> Download CSV
                        </button>
                        <button class="btn btn-sm btn-success" onclick="useGeneratedDataset()">
                            <i class="fas fa-arrow-right"></i> Use This Dataset
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- TAB 2: ALGORITHM SELECTION -->
    <div class="tab-pane fade" id="step2" role="tabpanel">
        <h4 class="mb-4">🧬 Choose Algorithms</h4>
        
        <!-- AI Recommendations Section -->
        <div id="aiRecommendations" class="alert alert-primary d-none mb-4">
            <h5><i class="fas fa-robot"></i> AI-Powered Recommendations</h5>
            <p id="recommendationReason" class="mb-2"></p>
            <div id="recommendedAlgorithms" class="d-flex flex-wrap gap-2"></div>
        </div>
        
        <div id="selectionSummary" class="alert alert-info d-none">
            <strong id="selectedCount">0</strong> algorithms selected
        </div>

        <div class="row mb-3">
            <div class="col-md-6">
                <input type="text" class="form-control" id="algorithmSearch" placeholder="🔎 Search algorithms...">
            </div>
            <div class="col-md-6">
                <div class="btn-group w-100">
                    <button class="btn btn-outline-success btn-sm" id="selectRecommended">✨ Select AI Recommended</button>
                    <button class="btn btn-outline-danger btn-sm" id="clearAlgos">Clear All</button>
                </div>
            </div>
        </div>

        <div class="alert alert-info" id="algoCountAlert">
            <strong>📊 Loading algorithms...</strong>
        </div>

        <div class="accordion" id="algoAccordion">
            <!-- Algorithm categories will be populated dynamically -->
        </div>

        <button class="btn btn-primary btn-lg w-100 mt-4" onclick="goToStep(3)">
            <i class="fas fa-arrow-right me-2"></i> Continue to Configuration
        </button>
    </div>

    <!-- TAB 3: CONFIGURE & RUN -->
    <div class="tab-pane fade" id="step3" role="tabpanel">
        <div class="row">
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5><i class="fas fa-cog"></i> Parameters</h5>
                    </div>
                    <div class="card-body">
                        <form id="optimizeForm">
                            <div class="mb-3">
                                <label class="form-label">Objective Function</label>
                                <select class="form-select" id="objectiveFunction" required>
                                    {% for func in objective_functions %}
                                    <option value="{{ func }}">{{ func }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="mb-3">
                                <label>Population Size</label>
                                <input type="number" class="form-control" id="populationSize" value="30" min="10">
                            </div>
                            <div class="mb-3">
                                <label>Max Iterations</label>
                                <input type="number" class="form-control" id="maxIterations" value="100" min="10">
                            </div>
                            <div class="mb-3">
                                <label>Dimensions</label>
                                <input type="number" class="form-control" id="dimensions" value="10" min="2">
                            </div>
                            <button type="submit" class="btn btn-success w-100" id="runBtn">
                                <i class="fas fa-play"></i> Run Optimization
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h5><i class="fas fa-chart-line"></i> Results</h5>
                    </div>
                    <div class="card-body">
                        <div id="loadingSpinner" class="text-center d-none">
                            <div class="spinner-border"></div>
                            <p class="mt-2">Running optimization...</p>
                        </div>
                        <div id="results" class="d-none">
                            <div class="alert alert-success">
                                <strong>Best Fitness:</strong> <span id="bestFitness"></span><br>
                                <strong>Time:</strong> <span id="execTime"></span>s
                            </div>
                            <div id="convergencePlot" style="height:400px"></div>
                        </div>
                        <div id="noResults" class="text-center text-muted">
                            <i class="fas fa-chart-line fa-5x mb-3"></i>
                            <p>Run optimization to see results</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.plot.ly/plotly-2.18.0.min.js"></script>
<script>
let selectedDataset = null;
let selectedAlgorithms = [];
let selectedTask = 'optimization';
let aiRecommendations = [];
let allAlgorithms = {}; // Will store all algorithms by category

document.addEventListener('DOMContentLoaded', async function() {
    await loadAllAlgorithms();
    populateAlgos();
    setupListeners();
});

async function loadAllAlgorithms() {
    try {
        console.log('Loading algorithms from API...');
        const response = await fetch('/api/algorithms');
        const data = await response.json();
        if (response.ok) {
            allAlgorithms = data.algorithms_by_category || {};
            console.log(`✓ Loaded ${data.total} algorithms across ${data.categories ? data.categories.length : 0} categories`);
            console.log('Categories:', Object.keys(allAlgorithms));
        } else {
            console.error('Failed to load algorithms:', data);
        }
    } catch (error) {
        console.error('Failed to load algorithms:', error);
        // Fallback to basic algorithms
        allAlgorithms = {
            'Swarm Intelligence': ['PSO', 'GWO', 'WOA', 'SSA', 'ALO'],
            'Evolutionary': ['GA', 'DE', 'ES']
        };
        console.log('Using fallback algorithms');
    }
}

function populateAlgos() {
    const accordion = document.getElementById('algoAccordion');
    if (!accordion) {
        console.error('algoAccordion element not found!');
        return;
    }
    
    console.log('Populating algorithms...');
    accordion.innerHTML = ''; // Clear existing
    
    const categoryIcons = {
        'Swarm Intelligence': '🐝',
        'Evolutionary': '🧬',
        'Physics-based': '⚛️',
        'Human-based': '👥',
        'Mathematics-based': '🔢',
        'Nature-inspired': '🌿',
        'Bio-inspired': '🧬',
        'Hybrid': '🔄',
        'Other': '📊'
    };
    
    let categoryIndex = 0;
    for (const [category, algorithms] of Object.entries(allAlgorithms)) {
        if (!algorithms || algorithms.length === 0) continue;
        
        const icon = categoryIcons[category] || '📊';
        const collapseId = `collapse${categoryIndex}`;
        const isFirst = categoryIndex === 0;
        
        const accordionItem = `
            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button ${isFirst ? '' : 'collapsed'}" type="button" 
                            data-bs-toggle="collapse" data-bs-target="#${collapseId}">
                        ${icon} ${category} <span class="badge bg-secondary ms-2">${algorithms.length}</span>
                    </button>
                </h2>
                <div id="${collapseId}" class="accordion-collapse collapse ${isFirst ? 'show' : ''}">
                    <div class="accordion-body">
                        <div class="row g-2" id="${collapseId}List">
                            ${algorithms.map(algo => `
                                <div class="col-md-3">
                                    <div class="form-check">
                                        <input class="form-check-input algo-checkbox" type="checkbox" 
                                               value="${algo}" id="algo_${algo}" onchange="updateSelection()">
                                        <label class="form-check-label" for="algo_${algo}">${algo}</label>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        accordion.innerHTML += accordionItem;
        categoryIndex++;
    }
    
    // Update algorithm count
    const totalCount = Object.values(allAlgorithms).reduce((sum, algos) => sum + algos.length, 0);
    const alertEl = document.getElementById('algoCountAlert');
    if (alertEl) {
        alertEl.innerHTML = `<strong>📊 ${totalCount} Algorithms Available</strong> across ${categoryIndex} categories`;
        alertEl.className = 'alert alert-success';
    }
    console.log(`✓ Populated ${categoryIndex} categories with ${totalCount} total algorithms`);
}

async function getAIRecommendations() {
    if (!selectedDataset) return;
    
    try {
        const response = await fetch('/api/recommend', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                dataset_name: selectedDataset.name,
                task_type: selectedTask
            })
        });
        
        const result = await response.json();
        
        if (response.ok && result.recommendations) {
            aiRecommendations = result.recommendations;
            
            // Show AI recommendations section
            const aiSection = document.getElementById('aiRecommendations');
            const reasonText = document.getElementById('recommendationReason');
            const algoList = document.getElementById('recommendedAlgorithms');
            
            reasonText.textContent = result.reason || 'Recommended based on dataset analysis';
            algoList.innerHTML = '';
            
            result.recommendations.slice(0, 10).forEach((algo, idx) => {
                const badge = document.createElement('span');
                badge.className = 'badge bg-success';
                badge.textContent = `${idx + 1}. ${algo}`;
                algoList.appendChild(badge);
            });
            
            aiSection.classList.remove('d-none');
        }
    } catch (error) {
        console.error('Failed to get recommendations:', error);
    }
}

function setupListeners() {
    // Task selection
    document.querySelectorAll('.select-task-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const card = this.closest('.task-card');
            selectedTask = card.dataset.task;
            const taskNameEl = document.getElementById('selectedTaskName');
            if (taskNameEl) taskNameEl.textContent = this.parentElement.querySelector('h5').textContent;
            const taskPreviewEl = document.getElementById('taskPreview');
            if (taskPreviewEl) taskPreviewEl.classList.remove('d-none');
            document.querySelectorAll('.task-card').forEach(c => c.classList.remove('border-success', 'border-3'));
            card.classList.add('border-success', 'border-3');
        });
    });
    
    document.querySelectorAll('input[name="dataSource"]').forEach(radio => {
        radio.addEventListener('change', function() {
            document.getElementById('sampleDatasetSection').classList.toggle('d-none', this.value !== 'sample');
            document.getElementById('uploadCSVSection').classList.toggle('d-none', this.value !== 'upload');
            document.getElementById('generateRandomSection').classList.toggle('d-none', this.value !== 'generate');
        });
    });

    document.querySelectorAll('.select-dataset-btn').forEach(btn => {
        btn.addEventListener('click', async function() {
            selectedDataset = {name: this.dataset.name, samples: this.dataset.samples, features: this.dataset.features};
            const nameEl = document.getElementById('selectedDatasetName');
            const samplesEl = document.getElementById('selectedSamples');
            const featuresEl = document.getElementById('selectedFeatures');
            if (nameEl) nameEl.textContent = this.dataset.name.replace('_', ' ').toUpperCase();
            if (samplesEl) samplesEl.textContent = this.dataset.samples;
            if (featuresEl) featuresEl.textContent = this.dataset.features;
            const previewEl = document.getElementById('datasetPreview');
            if (previewEl) previewEl.classList.remove('d-none');
            document.querySelectorAll('.dataset-card').forEach(c => c.classList.remove('border-primary'));
            this.closest('.dataset-card').classList.add('border-primary');
            
            // Get AI recommendations
            await getAIRecommendations();
        });
    });

    const selectRecommendedBtn = document.getElementById('selectRecommended');
    if (selectRecommendedBtn) {
        selectRecommendedBtn.addEventListener('click', () => {
            const toSelect = aiRecommendations.length > 0 ? aiRecommendations : ['PSO', 'GWO', 'WOA', 'GA', 'DE'];
            toSelect.forEach(algo => {
                const cb = document.getElementById(`algo_${algo}`);
                if (cb) cb.checked = true;
            });
            updateSelection();
        });
    }

    const clearAlgosBtn = document.getElementById('clearAlgos');
    if (clearAlgosBtn) {
        clearAlgosBtn.addEventListener('click', () => {
            document.querySelectorAll('.algo-checkbox').forEach(cb => cb.checked = false);
            updateSelection();
        });
    }

    const optimizeForm = document.getElementById('optimizeForm');
    if (optimizeForm) {
        optimizeForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            if (!selectedAlgorithms.length) return alert('⚠️ Please select at least one algorithm');
        
        const data = {
            algorithms: selectedAlgorithms,
            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('results').classList.add('d-none');
        document.getElementById('loadingSpinner').classList.remove('d-none');
        document.getElementById('runBtn').disabled = true;
        
        try {
            const response = await fetch('/api/optimize', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });
            
            const result = await response.json();
            
            if (response.ok) {
                // Store results in localStorage for comprehensive results page
                localStorage.setItem('optimization_results', JSON.stringify(result.results || []));
                
                // Update quick summary display
                const bestFitnessEl = document.getElementById('bestFitness');
                const execTimeEl = document.getElementById('execTime');
                if (bestFitnessEl) bestFitnessEl.textContent = result.best_fitness.toExponential(6);
                if (execTimeEl) execTimeEl.textContent = result.execution_time.toFixed(2);
                
                // Create convergence plot with all algorithms
                if (result.all_convergences && result.all_convergences.length > 0) {
                    const traces = result.all_convergences.map((conv, idx) => ({
                        y: conv.data,
                        type: 'scatter',
                        mode: 'lines',
                        name: conv.name,
                        line: {
                            width: 2.5,
                            color: ['#667eea', '#f093fb', '#4facfe', '#43e97b', '#fa709a'][idx % 5]
                        }
                    }));
                    
                    Plotly.newPlot('convergencePlot', traces, {
                        title: {
                            text: 'Convergence Curves - All Algorithms',
                            font: {size: 18, family: 'Inter, sans-serif'}
                        },
                        xaxis: {
                            title: 'Iteration',
                            gridcolor: '#e0e0e0',
                            showgrid: true
                        },
                        yaxis: {
                            title: 'Fitness Value',
                            type: 'log',
                            gridcolor: '#e0e0e0',
                            showgrid: true
                        },
                        plot_bgcolor: '#f9f9f9',
                        paper_bgcolor: 'white',
                        legend: {
                            x: 1,
                            xanchor: 'right',
                            y: 1,
                            bgcolor: 'rgba(255,255,255,0.8)',
                            bordercolor: '#ddd',
                            borderwidth: 1
                        },
                        hovermode: 'x unified'
                    });
                }
                
                // Show success message with link to comprehensive results
                const successMsg = document.createElement('div');
                successMsg.className = 'alert alert-success mb-3';
                successMsg.innerHTML = `
                    <strong>🎉 Success!</strong> ${result.message}<br>
                    Best performer: <strong>${result.best_algorithm || 'N/A'}</strong><br><br>
                    <a href="/results" class="btn btn-primary">
                        <i class="fas fa-chart-line"></i> View Comprehensive Results
                    </a>
                    <a href="/history" class="btn btn-info ms-2">
                        <i class="fas fa-history"></i> View History
                    </a>
                `;
                document.getElementById('results').prepend(successMsg);
                
                document.getElementById('results').classList.remove('d-none');
                
                console.log('✅ Results stored in localStorage. Click "View Comprehensive Results" for detailed analysis.');
            } else {
                alert('❌ Optimization failed: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            alert('❌ Network error: ' + error.message);
        } finally {
            document.getElementById('loadingSpinner').classList.add('d-none');
            document.getElementById('runBtn').disabled = false;
        }
        });
    }
}

function updateSelection() {
    selectedAlgorithms = Array.from(document.querySelectorAll('.algo-checkbox:checked')).map(cb => cb.value);
    const summary = document.getElementById('selectionSummary');
    const countEl = document.getElementById('selectedCount');
    if (selectedAlgorithms.length) {
        if (summary) summary.classList.remove('d-none');
        if (countEl) countEl.textContent = selectedAlgorithms.length;
    } else {
        if (summary) summary.classList.add('d-none');
    }
}

function goToStep(step) {
    const tabEl = document.getElementById(`step${step}-tab`);
    if (tabEl) {
        const tab = new bootstrap.Tab(tabEl);
        tab.show();
        console.log(`✓ Navigated to step ${step}`);
    } else {
        console.error(`Tab element step${step}-tab not found`);
    }
}

// Random Dataset Generation
let generatedDatasetCSV = null;

async function generateRandomDataset() {
    const genData = {
        problem_type: document.getElementById('genProblemType').value,
        n_samples: parseInt(document.getElementById('genSamples').value),
        n_features: parseInt(document.getElementById('genFeatures').value),
        n_classes: parseInt(document.getElementById('genClasses').value),
        noise: parseFloat(document.getElementById('genNoise').value)
    };
    
    try {
        const response = await fetch('/api/generate-dataset', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(genData)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            generatedDatasetCSV = result.csv_data;
            const info = result.dataset_info;
            
            document.getElementById('generatedInfo').innerHTML = `
                <strong>Type:</strong> ${info.type} | 
                <strong>Samples:</strong> ${info.samples} | 
                <strong>Features:</strong> ${info.features} | 
                <strong>Size:</strong> ${info.size_kb.toFixed(2)} KB
            `;
            document.getElementById('generatedDatasetInfo').classList.remove('d-none');
            
            // Auto-select for workflow
            selectedDataset = {
                name: 'generated_' + info.type,
                samples: info.samples,
                features: info.features
            };
        } else {
            alert('❌ Generation failed: ' + (result.error || 'Unknown error'));
        }
    } catch (error) {
        alert('❌ Error: ' + error.message);
    }
}

function downloadGeneratedDataset() {
    if (!generatedDatasetCSV) return alert('No dataset generated');
    
    const blob = new Blob([generatedDatasetCSV], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'generated_dataset_' + Date.now() + '.csv';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
}

function useGeneratedDataset() {
    if (!selectedDataset) return alert('No dataset selected');
    
    const previewEl = document.getElementById('datasetPreview');
    const nameEl = document.getElementById('selectedDatasetName');
    const samplesEl = document.getElementById('selectedSamples');
    const featuresEl = document.getElementById('selectedFeatures');
    if (previewEl) previewEl.classList.remove('d-none');
    if (nameEl) nameEl.textContent = selectedDataset.name.toUpperCase();
    if (samplesEl) samplesEl.textContent = selectedDataset.samples;
    if (featuresEl) featuresEl.textContent = selectedDataset.features;
    
    // Get AI recommendations
    getAIRecommendations();
}

function uploadCSV() {
    alert('CSV upload feature coming soon!');
}
</script>
{% endblock %}
