document.addEventListener('DOMContentLoaded', function () { const dropZone = document.getElementById('drop-zone'); const fileInput = document.getElementById('csv-file'); const fileNameDisplay = document.getElementById('file-name-display'); const uploadForm = document.getElementById('upload-form'); const resultsSection = document.getElementById('results-section'); const analysisOutput = document.getElementById('analysis-output'); const submitButton = uploadForm.querySelector('button[type="submit"]'); const spinner = submitButton.querySelector('.spinner-border'); // Open file dialog when drop zone is clicked dropZone.addEventListener('click', () => fileInput.click()); // Drag and drop events dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); }); dropZone.addEventListener('dragleave', () => { dropZone.classList.remove('drag-over'); }); dropZone.addEventListener('drop', (e) => { e.preventDefault(); dropZone.classList.remove('drag-over'); const files = e.dataTransfer.files; if (files.length > 0) { fileInput.files = files; updateFileName(); } }); // Update file name display on change fileInput.addEventListener('change', updateFileName); function updateFileName() { if (fileInput.files.length > 0) { fileNameDisplay.textContent = fileInput.files[0].name; } else { fileNameDisplay.textContent = 'No file selected'; } } // Handle form submission uploadForm.addEventListener('submit', function (e) { e.preventDefault(); if (fileInput.files.length === 0) { alert('Please select a CSV file to analyze.'); return; } // Show spinner and disable button spinner.classList.remove('d-none'); submitButton.disabled = true; const formData = new FormData(uploadForm); // Show loading state resultsSection.style.display = 'block'; analysisOutput.innerHTML = `
Loading...

AI is analyzing your data, this may take a moment...

`; resultsSection.scrollIntoView({ behavior: 'smooth' }); fetch('upload.php', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { if (data.success) { analysisOutput.innerHTML = data.analysis; } else { analysisOutput.innerHTML = `
${data.error || 'An unknown error occurred.'}
`; } }) .catch(error => { console.error('Error:', error); analysisOutput.innerHTML = `
An error occurred while communicating with the server.
`; }) .finally(() => { // Hide spinner and re-enable button spinner.classList.add('d-none'); submitButton.disabled = false; }); }); });