let startFile = null;
let endFile = null;
const processBtn = document.getElementById("processBtn");

document.getElementById("startFrame").addEventListener("change", (e) => handleFile(e, "start"));
document.getElementById("endFrame").addEventListener("change", (e) => handleFile(e, "end"));

function handleFile(e, type) {
    const file = e.target.files[0];
    if (!file) return;
    
    const preview = document.getElementById(type + "Preview");
    const fileName = document.getElementById(type + "FileName");
    const previewContainer = document.getElementById(type + "PreviewContainer");
    const card = document.getElementById(type + "Card");
    const uploadContent = card.querySelector('.upload-content');
    
    preview.src = URL.createObjectURL(file);
    fileName.textContent = file.name;
    
    uploadContent.style.display = 'none';
    previewContainer.classList.add('show');
    card.classList.add('active');
    
    if (type === "start") startFile = file;
    else endFile = file;
    
    processBtn.disabled = !(startFile && endFile);
}

processBtn.addEventListener("click", async () => {
    const formData = new FormData();
    formData.append("first_frame", startFile);
    formData.append("last_frame", endFile);

    processBtn.innerHTML = '⏳ Processing<span class="spinner"></span>';
    processBtn.classList.add('processing');
    processBtn.disabled = true;

    try {
    const response = await fetch("/video/video-generator/", { method: "POST", body: formData });
    const data = await response.json();

    processBtn.innerHTML = "🚀 Generate Video";
    processBtn.classList.remove('processing');
    processBtn.disabled = false;

    if (data.video_url) {
        const video = document.getElementById("outputVideo");
        video.src = data.video_url;
        new bootstrap.Modal(document.getElementById("videoModal")).show();
    } else {
        alert("No video URL in response. Check backend output.");
        console.log("Response:", data);
    }
    } catch (err) {
    alert("Error: " + err.message);
    processBtn.innerHTML = "🚀 Generate Video";
    processBtn.classList.remove('processing');
    processBtn.disabled = false;
    }
});
