const scriptURL = "./api/submit.php";
const form = document.forms["submit-to-google-sheet"];
const btn = document.getElementById("submitInput");

var input = document.querySelector("#PhoneNumber");
var iti = window.intlTelInput(input, {
  initialCountry: "id",
  utilsScript:
    "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
});

let isSubmitting = false;

if (!form.dataset.bound) {
  form.dataset.bound = "true";

  form.addEventListener("submit", async (e) => {
    e.preventDefault();

    if (isSubmitting) return;

    const nameInput = form.querySelector('[name="Name"]');
    if (!nameInput || !nameInput.value.trim()) {
      alert("Please enter your name.");
      return;
    }

    if (!iti.isValidNumber()) {
      alert("Please enter a valid phone number.");
      return;
    }

    try {
      isSubmitting = true;
      btn.disabled = true;
      btn.style.pointerEvents = "none";

      const formData = new FormData(form);
      const phoneNumber = iti.getNumber(intlTelInputUtils.numberFormat.E164);
      formData.set("PhoneNumber", phoneNumber);

      const response = await fetch(scriptURL, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("Network response was not ok");
      }

      const responseData = await response.json();

      if (responseData.error === "Phone number already exists") {
        alert("This phone number has already been used.");
        form.reset();
        iti.setNumber("");
        return;
      }

      if (responseData.success) {
        alert("Submitted Successfully");
        window.location.href = "./assets/load4.html";
      } else {
        throw new Error(responseData.error || "Submission failed");
      }

    } catch (error) {
      console.error("Error submitting form:", error);
      alert("An error occurred. Please try again.");
    } finally {
      isSubmitting = false;
      btn.disabled = false;
      btn.style.pointerEvents = "";
    }
  });
}
