const loginForm = document.getElementById("loginForm");
const modal = document.getElementById("success-modal");
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");
const emailError = document.getElementById("email-error");
const passwordError = document.getElementById("password-error");
const togglePassword = document.getElementById("togglePassword");
const eyeIcon = document.getElementById("eyeIcon");

if (togglePassword && passwordInput) {
  togglePassword.addEventListener("click", function () {
    const type =
      passwordInput.getAttribute("type") === "password" ? "text" : "password";
    passwordInput.setAttribute("type", type);

    if (eyeIcon) {
      if (type === "text") {
        eyeIcon.src = "../assets/icons/eye-on.svg";
      } else {
        eyeIcon.src = "../assets/icons/eye-off.svg";
      }
    }
  });
}

function closeModal() {
  if (modal) {
    modal.classList.add("hidden");
  }
}

if (loginForm) {
  loginForm.addEventListener("submit", function (e) {
    e.preventDefault();

    let isValid = true;
    const emailValue = emailInput.value.trim();
    const passwordValue = passwordInput.value;

    if (!emailValue || !emailValue.includes("@")) {
      if (emailError) emailError.classList.remove("hidden");
      emailInput.classList.add("border-red-500");
      isValid = false;
    } else {
      if (emailError) emailError.classList.add("hidden");
      emailInput.classList.remove("border-red-500");
    }

    if (passwordValue.length < 8) {
      if (passwordError) passwordError.classList.remove("hidden");
      passwordInput.classList.add("border-red-500");
      isValid = false;
    } else {
      if (passwordError) passwordError.classList.add("hidden");
      passwordInput.classList.remove("border-red-500");
    }

    if (isValid) {
      if (modal) {
        modal.classList.remove("hidden");
        setTimeout(() => {
          window.location.href = "./home-page.html";
        }, 2000);
      }
    }
  });
}

if (emailInput) {
  emailInput.addEventListener("input", () => {
    if (emailError) emailError.classList.add("hidden");
    emailInput.classList.remove("border-red-500");
  });
}

if (passwordInput) {
  passwordInput.addEventListener("input", () => {
    if (passwordError) passwordError.classList.add("hidden");
    passwordInput.classList.remove("border-red-500");
  });
}

window.showToast = function () {
  const toast = document.getElementById("coming-soon-toast");
  if (toast) {
    toast.style.display = "block";
    setTimeout(() => {
      toast.style.display = "none";
    }, 3000);
  }
};
