// MHA Flow v3.0 - JavaScript Functions

// Utility Functions
const MHAFlow = {
    // Show toast notification
    showToast: function(message, type = 'info') {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3`;
        alertDiv.style.zIndex = '9999';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(alertDiv);
        
        setTimeout(() => {
            alertDiv.remove();
        }, 5000);
    },
    
    // Format number for display
    formatNumber: function(num, decimals = 6) {
        if (Math.abs(num) < 0.001 || Math.abs(num) > 1000) {
            return num.toExponential(decimals);
        }
        return num.toFixed(decimals);
    },
    
    // Validate form inputs
    validateForm: function(formId) {
        const form = document.getElementById(formId);
        return form.checkValidity();
    },
    
    // Show loading state
    showLoading: function(elementId) {
        const element = document.getElementById(elementId);
        element.innerHTML = `
            <div class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>
        `;
    },
    
    // API call wrapper
    api: async function(endpoint, method = 'GET', data = null) {
        const options = {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            }
        };
        
        if (data && method !== 'GET') {
            options.body = JSON.stringify(data);
        }
        
        try {
            const response = await fetch(endpoint, options);
            const result = await response.json();
            
            if (!response.ok) {
                throw new Error(result.error || 'Request failed');
            }
            
            return result;
        } catch (error) {
            this.showToast('Error: ' + error.message, 'danger');
            throw error;
        }
    },
    
    // Download data as JSON
    downloadJSON: function(data, filename) {
        const blob = new Blob([JSON.stringify(data, null, 2)], {type: 'application/json'});
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        URL.revokeObjectURL(url);
    },
    
    // Copy to clipboard
    copyToClipboard: function(text) {
        navigator.clipboard.writeText(text).then(() => {
            this.showToast('Copied to clipboard!', 'success');
        }).catch(() => {
            this.showToast('Failed to copy', 'danger');
        });
    },
    
    // Create convergence plot
    createConvergencePlot: function(elementId, convergenceData, title = 'Convergence Curve') {
        const trace = {
            y: convergenceData,
            type: 'scatter',
            mode: 'lines+markers',
            name: 'Best Fitness',
            line: {color: '#198754', width: 2},
            marker: {size: 4}
        };
        
        const layout = {
            title: title,
            xaxis: {title: 'Iteration'},
            yaxis: {title: 'Fitness Value', type: 'log'},
            showlegend: true,
            hovermode: 'closest'
        };
        
        const config = {
            responsive: true,
            displayModeBar: true,
            modeBarButtonsToRemove: ['lasso2d', 'select2d']
        };
        
        Plotly.newPlot(elementId, [trace], layout, config);
    },
    
    // Create comparison chart
    createComparisonChart: function(elementId, algorithms, values, metric = 'Fitness') {
        const trace = {
            x: algorithms,
            y: values,
            type: 'bar',
            marker: {
                color: values.map((v, i) => i === 0 ? '#198754' : '#0d6efd'),
                line: {
                    color: '#fff',
                    width: 1.5
                }
            }
        };
        
        const layout = {
            title: `${metric} Comparison`,
            xaxis: {title: 'Algorithm'},
            yaxis: {title: metric, type: metric === 'Fitness' ? 'log' : 'linear'},
            showlegend: false
        };
        
        const config = {
            responsive: true,
            displayModeBar: true
        };
        
        Plotly.newPlot(elementId, [trace], layout, config);
    },
    
    // Create radar chart
    createRadarChart: function(elementId, categories, values, name = 'Performance') {
        const trace = {
            type: 'scatterpolar',
            r: values,
            theta: categories,
            fill: 'toself',
            name: name,
            marker: {color: '#0d6efd'}
        };
        
        const layout = {
            polar: {
                radialaxis: {
                    visible: true,
                    range: [0, Math.max(...values) * 1.1]
                }
            },
            showlegend: true
        };
        
        Plotly.newPlot(elementId, [trace], layout);
    },
    
    // Initialize tooltips
    initTooltips: function() {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    },
    
    // Format time duration
    formatDuration: function(seconds) {
        if (seconds < 1) {
            return (seconds * 1000).toFixed(0) + ' ms';
        } else if (seconds < 60) {
            return seconds.toFixed(2) + ' s';
        } else {
            const minutes = Math.floor(seconds / 60);
            const secs = (seconds % 60).toFixed(0);
            return `${minutes}m ${secs}s`;
        }
    },
    
    // Get algorithm recommendation
    getRecommendation: async function(problemType, dimensions, hasConstraints, multimodal) {
        try {
            const result = await this.api('/api/recommend', 'POST', {
                problem_type: problemType,
                dimensions: dimensions,
                has_constraints: hasConstraints,
                multimodal: multimodal
            });
            return result.recommendations;
        } catch (error) {
            console.error('Failed to get recommendation:', error);
            return [];
        }
    }
};

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    MHAFlow.initTooltips();
    
    // Auto-hide alerts after 5 seconds
    setTimeout(() => {
        const alerts = document.querySelectorAll('.alert:not(.alert-permanent)');
        alerts.forEach(alert => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
    
    // Add fade-in animation to cards
    const cards = document.querySelectorAll('.card');
    cards.forEach((card, index) => {
        setTimeout(() => {
            card.classList.add('fade-in');
        }, index * 100);
    });
});

// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
    module.exports = MHAFlow;
}
