// Single file upload handling
document.addEventListener('DOMContentLoaded', function() {
    initializeSingleUpload();
    initializeBatchUpload();
});

function initializeSingleUpload() {
    const dropArea = document.getElementById('dropArea');
    const fileInput = document.getElementById('fileInput');
    const uploadForm = document.getElementById('uploadForm');
    
    if (!dropArea || !fileInput || !uploadForm) return;

    // Drag and drop functionality
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => dropArea.classList.add('highlight'));
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => dropArea.classList.remove('highlight'));
    });

    dropArea.addEventListener('drop', handleDrop);
    fileInput.addEventListener('change', updateFileList);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        fileInput.files = files;
        updateFileList();
    }

    function updateFileList() {
        const fileList = document.getElementById('fileList');
        const selectedFiles = document.getElementById('selectedFiles');
        const fileMsg = dropArea.querySelector('.file-msg');
        
        selectedFiles.innerHTML = '';
        
        if (fileInput.files.length > 0) {
            fileList.style.display = 'block';
            fileMsg.textContent = `Selected ${fileInput.files.length} file(s)`;
            
            Array.from(fileInput.files).forEach(file => {
                const li = document.createElement('li');
                li.textContent = `${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)`;
                selectedFiles.appendChild(li);
            });
        } else {
            fileList.style.display = 'none';
            fileMsg.textContent = 'Choose PDF files or drag here (Multiple files supported)';
        }
    }

    uploadForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const files = fileInput.files;
        if (!files || files.length === 0) {
            alert('Please select at least one PDF file');
            return;
        }
        
        uploadFiles(files);
    });
}

function uploadFiles(files) {
    const statusSection = document.getElementById('statusSection');
    const statusMessage = document.getElementById('statusMessage');
    const uploadBtn = document.getElementById('uploadBtn');
    
    statusSection.style.display = 'block';
    statusMessage.innerHTML = `Processing ${files.length} PDF files...`;
    uploadBtn.disabled = true;
    uploadBtn.textContent = 'Uploading...';

    const formData = new FormData();
    Array.from(files).forEach(file => {
        formData.append('pdf_file[]', file);
    });

    fetch('/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            statusMessage.innerHTML = `✅ ${data.message}`;
            setTimeout(() => {
                window.location.href = '/results';
            }, 2000);
        } else {
            statusMessage.innerHTML = `❌ ${data.message}`;
            uploadBtn.disabled = false;
            uploadBtn.textContent = 'Upload & Process Selected Files';
        }
    })
    .catch(error => {
        statusMessage.innerHTML = `❌ Upload failed: ${error}`;
        uploadBtn.disabled = false;
        uploadBtn.textContent = 'Upload & Process Selected Files';
    });
}

function initializeBatchUpload() {
    const batchDropArea = document.getElementById('batchDropArea');
    const batchFileInput = document.getElementById('batchFileInput');
    const batchForm = document.getElementById('batchForm');
    
    if (!batchDropArea || !batchFileInput || !batchForm) return;

    // Similar drag and drop setup for batch
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        batchDropArea.addEventListener(eventName, preventDefaults, false);
    });

    ['dragenter', 'dragover'].forEach(eventName => {
        batchDropArea.addEventListener(eventName, () => batchDropArea.classList.add('highlight'));
    });

    ['dragleave', 'drop'].forEach(eventName => {
        batchDropArea.addEventListener(eventName, () => batchDropArea.classList.remove('highlight'));
    });

    batchDropArea.addEventListener('drop', handleBatchDrop);
    batchFileInput.addEventListener('change', updateBatchFileList);

    function handleBatchDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        batchFileInput.files = files;
        updateBatchFileList();
    }

    function updateBatchFileList() {
        const fileCount = document.getElementById('fileCount');
        const sizeWarning = document.getElementById('sizeWarning');
        
        if (batchFileInput.files.length > 0) {
            const totalSize = Array.from(batchFileInput.files).reduce((sum, file) => sum + file.size, 0);
            fileCount.textContent = `${batchFileInput.files.length} PDF files selected (${(totalSize / 1024 / 1024).toFixed(1)} MB total)`;
            
            if (batchFileInput.files.length > 10) {
                sizeWarning.style.display = 'block';
                sizeWarning.textContent = `⚠️ Large batch detected (${batchFileInput.files.length} files). Processing may take longer.`;
            } else {
                sizeWarning.style.display = 'none';
            }
        } else {
            fileCount.textContent = 'No files selected';
            sizeWarning.style.display = 'none';
        }
    }

    batchForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const files = batchFileInput.files;
        if (!files || files.length === 0) {
            alert('Please select at least one PDF file');
            return;
        }
        
        uploadBatchFiles(files);
    });
}

function uploadBatchFiles(files) {
    const batchUploadBtn = document.getElementById('batchUploadBtn');
    batchUploadBtn.disabled = true;
    batchUploadBtn.textContent = 'Processing...';

    const formData = new FormData();
    Array.from(files).forEach(file => {
        formData.append('pdf_files[]', file);
    });

    fetch('/batch/process', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert(`Successfully processed ${data.processed_count} files!`);
            window.location.href = '/results';
        } else {
            alert('Batch processing failed: ' + data.message);
            batchUploadBtn.disabled = false;
            batchUploadBtn.textContent = '🚀 Process All PDFs';
        }
    })
    .catch(error => {
        alert('Upload failed: ' + error);
        batchUploadBtn.disabled = false;
        batchUploadBtn.textContent = '🚀 Process All PDFs';
    });
}