let imageInput = $("#imageInput")
let imagePreview = $("#preview")

let uploadForm = $("#imageForm")

let currentFile = null;

imageInput.on("change", function() {
    currentFile = this.files[0];
    if (currentFile) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
        }
        reader.readAsDataURL(currentFile);
    } else {
        preview.style.display = 'none';
    }
})

uploadForm.on("submit", function(e) {
    e.preventDefault();
    
    if (!currentFile) {
        alert("Please select a file first.");
        return;
    }
    console.log(currentFile);
    
    let formData = new FormData(this);
    formData.append("image", currentFile);

    $.ajax({
        url: "/api/upload",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            alert("Image uploaded successfully!");
            preview.style.display = 'none';
            currentFile = null;
        },
        error: function(xhr, status, error) {
            alert("Error uploading image: " + xhr.responseText);
        }
    });
})