// Levify Transformation JavaScript

let currentTransformation = null;

document.addEventListener('DOMContentLoaded', function() {
    const algorithmSelect = document.getElementById('algorithmSelect');
    const transformType = document.getElementById('transformType');
    const intensity = document.getElementById('intensity');
    const intensityValue = document.getElementById('intensityValue');
    const transformBtn = document.getElementById('transformBtn');
    const statusAlert = document.getElementById('statusAlert');
    const errorAlert = document.getElementById('errorAlert');
    const resultsSection = document.getElementById('resultsSection');
    const resetBtn = document.getElementById('resetBtn');

    // Load algorithms
    loadAlgorithms();

    // Intensity slider
    intensity.addEventListener('input', function() {
        intensityValue.textContent = this.value;
    });

    // Algorithm selection
    algorithmSelect.addEventListener('change', function() {
        if (this.value) {
            loadAlgorithmCharacteristics(this.value);
        } else {
            document.getElementById('characteristicsPanel').innerHTML = 
                '<p class="text-muted">Select an algorithm to view its characteristics</p>';
        }
    });

    // Transform button
    transformBtn.addEventListener('click', function() {
        const algo = algorithmSelect.value;
        if (!algo) {
            alert('Please select an algorithm');
            return;
        }

        showLoading('Applying Levify transformation...');

        fetch('/api/levify/transform', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                algorithm: algo,
                type: transformType.value,
                intensity: parseFloat(intensity.value)
            })
        })
        .then(response => response.json())
        .then(data => {
            hideLoading();

            if (data.success) {
                currentTransformation = data.transformation;
                displayTransformationResults(data.transformation);
                resultsSection.classList.remove('d-none');
            } else {
                showError(data.error || 'Transformation failed');
            }
        })
        .catch(error => {
            hideLoading();
            showError(error.message);
        });
    });

    // Reset button
    resetBtn.addEventListener('click', function() {
        resultsSection.classList.add('d-none');
        currentTransformation = null;
    });

    function loadAlgorithms() {
        fetch('/api/algorithms/list')
            .then(response => response.json())
            .then(data => {
                data.algorithms.forEach(algo => {
                    const option = document.createElement('option');
                    option.value = algo;
                    option.textContent = algo;
                    algorithmSelect.appendChild(option);
                });
            });
    }

    function loadAlgorithmCharacteristics(algorithm) {
        fetch(`/api/algorithms/characteristics/${algorithm}`)
            .then(response => response.json())
            .then(chars => {
                displayCharacteristics(chars, 'characteristicsPanel');
            });
    }

    function displayCharacteristics(chars, containerId) {
        const container = document.getElementById(containerId);
        
        const explorationBar = createProgressBar(
            'Exploration Score',
            chars.exploration_score * 100,
            '#ff6b6b'
        );
        
        const exploitationBar = createProgressBar(
            'Exploitation Score',
            chars.exploitation_score * 100,
            '#51cf66'
        );
        
        const convergenceBar = createProgressBar(
            'Convergence Speed',
            chars.convergence_speed * 100,
            '#4dabf7'
        );
        
        const diversityBar = createProgressBar(
            'Diversity Maintenance',
            chars.diversity_maintenance * 100,
            '#ffd43b'
        );

        container.innerHTML = `
            ${explorationBar}
            ${exploitationBar}
            ${convergenceBar}
            ${diversityBar}
            <div class="mt-3">
                <small class="text-muted">
                    <strong>Parameters:</strong> ${chars.parameter_count} |
                    <strong>Scalability:</strong> ${chars.dimension_scalability}
                </small>
            </div>
        `;
    }

    function createProgressBar(label, value, color) {
        return `
            <div class="mb-3">
                <div class="d-flex justify-content-between mb-1">
                    <label class="form-label mb-0">${label}</label>
                    <span>${value.toFixed(1)}%</span>
                </div>
                <div class="progress" style="height: 8px;">
                    <div class="progress-bar" style="width: ${value}%; background-color: ${color};" 
                         role="progressbar"></div>
                </div>
            </div>
        `;
    }

    function displayTransformationResults(transformation) {
        const original = transformation.original;
        const transformed = transformation.transformed;

        // Original characteristics
        document.getElementById('originalCharacteristics').innerHTML = `
            <h6>${original.name}</h6>
            ${createProgressBar('Exploration', original.exploration_score * 100, '#ff6b6b')}
            ${createProgressBar('Exploitation', original.exploitation_score * 100, '#51cf66')}
            ${createProgressBar('Convergence Speed', original.convergence_speed * 100, '#4dabf7')}
            ${createProgressBar('Local Optima Avoidance', original.local_optima_avoidance * 100, '#a8e6cf')}
        `;

        // Transformed characteristics
        document.getElementById('transformedCharacteristics').innerHTML = `
            <h6>${transformed.name}</h6>
            ${createProgressBar('Exploration', transformed.exploration_score * 100, '#ff6b6b')}
            ${createProgressBar('Exploitation', transformed.exploitation_score * 100, '#51cf66')}
            ${createProgressBar('Convergence Speed', transformed.convergence_speed * 100, '#4dabf7')}
            ${createProgressBar('Local Optima Avoidance', transformed.local_optima_avoidance * 100, '#a8e6cf')}
        `;

        // Parameter adjustments
        const adjustments = transformation.parameter_adjustments;
        let adjustmentsHTML = '<table class="table table-sm">';
        adjustmentsHTML += '<thead><tr><th>Parameter</th><th>Original Range</th><th>New Range</th><th>Reason</th></tr></thead>';
        adjustmentsHTML += '<tbody>';

        for (const [param, details] of Object.entries(adjustments)) {
            if (param !== 'note' && param !== 'phase' && param !== 'recommendation') {
                const orig = Array.isArray(details.original_range) ? 
                    details.original_range.join(' - ') : details.original_range;
                const newRange = Array.isArray(details.new_range) ? 
                    details.new_range.join(' - ') : details.new_range;
                
                adjustmentsHTML += `
                    <tr>
                        <td><code>${param}</code></td>
                        <td>${orig}</td>
                        <td><strong>${newRange}</strong></td>
                        <td><small>${details.reason}</small></td>
                    </tr>
                `;
            }
        }
        adjustmentsHTML += '</tbody></table>';

        document.getElementById('parameterAdjustments').innerHTML = adjustmentsHTML;
    }

    function showLoading(message) {
        const statusAlert = document.getElementById('statusAlert');
        document.getElementById('statusMessage').textContent = message;
        statusAlert.classList.remove('d-none');
    }

    function hideLoading() {
        document.getElementById('statusAlert').classList.add('d-none');
    }

    function showError(message) {
        const errorAlert = document.getElementById('errorAlert');
        document.getElementById('errorMessage').textContent = message;
        errorAlert.classList.remove('d-none');
    }
});
