document.getElementById("tryNowBtn").addEventListener("click", function () {
  document.getElementById("features").scrollIntoView({ behavior: "smooth" });
});

const fileInput = document.getElementById("resumeUpload");
const fileDisplay = document.getElementById("fileDisplay");
const jobDescriptionInput = document.getElementById("jobDescription");
const submitBtn = document.getElementById("submitBtn");

// When file selected, display its name
fileInput.addEventListener("change", () => {
  const file = fileInput.files[0];
  fileDisplay.value = file ? file.name : "No file chosen";
});

// When submit clicked
submitBtn.addEventListener("click", async () => {
  const file = fileInput.files[0];
  const jobDescription = jobDescriptionInput.value.trim();

  if (!file) {
    alert("⚠️ Please upload your resume before submitting.");
    return;
  }

  // Store filename for display on loading page
  localStorage.setItem("uploadedFileName", file.name);

  // Create FormData to send to backend
  const formData = new FormData();
  formData.append("resume", file);
  formData.append("job_description", jobDescription);

  // Disable button to prevent double submission
  submitBtn.disabled = true;
  submitBtn.textContent = "Submitting...";

  try {
    // Send the data first using keepalive to ensure it completes even after redirect
    fetch("/submit", {
      method: "POST",
      body: formData,
      keepalive: true, // This ensures the request continues even after navigation
    });

    // Small delay to ensure the request is sent, then redirect
    setTimeout(() => {
      window.location.href = "/loading";
    }, 100);
  } catch (error) {
    console.error("Error:", error);
    alert("An error occurred. Please try again.");
    submitBtn.disabled = false;
    submitBtn.textContent = "Submit";
  }
});
