document.addEventListener("DOMContentLoaded", function () {
  const forms = document.querySelectorAll("form");

  forms.forEach((form) => {
    form.addEventListener("submit", function (e) {
      let isValid = true;
      const inputs = form.querySelectorAll("input");

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

        if (errorSpan) {
          const isEmpty = !input.value.trim();
          const isEmailInvalid = input.type === "email" && !input.value.includes("@");
          const isPassTooShort = input.type === "password" && input.value.length < 8;

          if (isEmpty || isEmailInvalid || isPassTooShort) {
            e.preventDefault(); 
            isValid = false;

            errorSpan.classList.remove("hidden");
            errorSpan.style.display = "block";
            errorSpan.style.color = "#ef4444";
            
            input.classList.add("border-red-500");
          } else {
            errorSpan.classList.add("hidden");
            errorSpan.style.display = "none";
            input.classList.remove("border-red-500");
          }
        }
      });

      if (isValid && form.id === "loginForm") {
        e.preventDefault();
        const modal = document.getElementById("success-modal");
        if (modal) modal.classList.remove("hidden");
      }
    });

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