document.addEventListener("DOMContentLoaded", () => {
  const form = document.getElementById("registrationForm");
  const inputs = form.querySelectorAll("input");
  const togglePassword = document.getElementById("togglePassword");
  const passwordInput = document.getElementById("password");

  if (togglePassword && passwordInput) {
    togglePassword.addEventListener("click", () => {
      const isPassword = passwordInput.getAttribute("type") === "password";
      passwordInput.setAttribute("type", isPassword ? "text" : "password");
      togglePassword.classList.toggle("text-white");
    });
  }

  form.addEventListener("submit", (e) => {
    e.preventDefault();
    let hasError = false;

    inputs.forEach((input) => {
      const errorSpan = document.getElementById(`${input.id}-error`);
      let isInvalid = false;

      if (!input.value.trim() && input.type !== "checkbox") {
        isInvalid = true;
      } else if (input.type === "email" && !input.value.includes("@")) {
        isInvalid = true;
      } else if (input.id === "password" && input.value.length < 8) {
        isInvalid = true;
      } else if (input.type === "checkbox" && !input.checked) {
        isInvalid = true;
      }

      if (isInvalid) {
        hasError = true;
        if (errorSpan) {
          errorSpan.style.display = "block";
          errorSpan.classList.remove("hidden");
        }

        if (input.id === "phoneNumber") {
          document
            .getElementById("phone-container")
            .classList.add("border-red-500");
        } else if (input.type !== "checkbox") {
          input.classList.add("border-red-500");
        }
      } else {
        if (errorSpan) {
          errorSpan.style.display = "none";
          errorSpan.classList.add("hidden");
        }
        if (input.id === "phoneNumber") {
          document
            .getElementById("phone-container")
            .classList.remove("border-red-500");
        } else {
          input.classList.remove("border-red-500");
        }
      }
    });

    if (!hasError) {
      window.location.href = "./login.html";
    }
  });

  inputs.forEach((input) => {
    input.addEventListener("input", () => {
      const errorSpan = document.getElementById(`${input.id}-error`);
      input.classList.remove("border-red-500");
      if (errorSpan) {
        errorSpan.style.display = "none";
        errorSpan.classList.add("hidden");
      }
      if (input.id === "phoneNumber") {
        document
          .getElementById("phone-container")
          .classList.remove("border-red-500");
      }
    });

    if (input.type === "checkbox") {
      input.addEventListener("change", () => {
        const errorSpan = document.getElementById("terms-error");
        if (input.checked && errorSpan) {
          errorSpan.style.display = "none";
          errorSpan.classList.add("hidden");
        }
      });
    }
  });
});
