// Dataset Upload JavaScript

document.addEventListener('DOMContentLoaded', function() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    const problemType = document.getElementById('problemType');
    const uploadStatus = document.getElementById('uploadStatus');
    const errorAlert = document.getElementById('errorAlert');
    const successAlert = document.getElementById('successAlert');
    const profileSection = document.getElementById('profileSection');

    // Drag and drop handling
    uploadArea.addEventListener('click', () => fileInput.click());

    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            fileInput.files = files;
            handleFileSelect();
        }
    });

    fileInput.addEventListener('change', handleFileSelect);

    function handleFileSelect() {
        const file = fileInput.files[0];
        if (!file) return;

        // Show loading status
        uploadStatus.classList.remove('d-none');
        errorAlert.classList.add('d-none');
        successAlert.classList.add('d-none');
        profileSection.classList.add('d-none');

        // Prepare form data
        const formData = new FormData();
        formData.append('file', file);
        formData.append('problem_type', problemType.value);

        // Upload file
        fetch('/api/dataset/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            uploadStatus.classList.add('d-none');

            if (data.success) {
                successAlert.classList.remove('d-none');
                displayDatasetProfile(data.profile, data.report);
                profileSection.classList.remove('d-none');
            } else {
                errorAlert.classList.remove('d-none');
                document.getElementById('errorMessage').textContent = data.error || 'Upload failed';
            }
        })
        .catch(error => {
            uploadStatus.classList.add('d-none');
            errorAlert.classList.remove('d-none');
            document.getElementById('errorMessage').textContent = error.message;
        });
    }

    function displayDatasetProfile(profile, report) {
        // Display basic stats
        document.getElementById('numSamples').textContent = profile.num_samples.toLocaleString();
        document.getElementById('numFeatures').textContent = profile.dimensions.toLocaleString();
        document.getElementById('complexity').textContent = (profile.estimated_complexity * 100).toFixed(0) + '%';
        document.getElementById('quality').textContent = (profile.data_quality_score * 100).toFixed(0) + '%';

        // Display characteristics
        const charContainer = document.getElementById('characteristics');
        const chars = profile.characteristics || [];
        if (chars.length > 0) {
            charContainer.innerHTML = chars.map(c => 
                `<span class="badge bg-info me-2 mb-2">${c.replace('_', ' ')}</span>`
            ).join('');
        } else {
            charContainer.innerHTML = '<p class="text-muted">No characteristics detected</p>';
        }

        // Display recommendations
        const recContainer = document.getElementById('recommendations');
        const recs = profile.recommended_algorithms || [];
        if (recs.length > 0) {
            recContainer.innerHTML = recs.map((algo, i) => 
                `<div class="mb-2">
                    <span class="badge bg-success">${i + 1}</span>
                    <strong>${algo}</strong>
                </div>`
            ).join('');
        } else {
            recContainer.innerHTML = '<p class="text-muted">No recommendations available</p>';
        }
    }
});
