document.addEventListener("DOMContentLoaded", function () {
  const usernameField = document.getElementById("username_field");
  const phoneFields = document.querySelectorAll(".format_phone");
  const accountNumberField = document.getElementById("bank_account_number_input");
  const bankNameField = document.getElementById("bank_account_name_input");
  const passwordField = document.getElementById("password_field");
  const confirmPasswordField = document.getElementById("ConfirmedPassword");
  const passwordValidations = document.getElementById("password_validations");

  const showError = (field, message) => {
    let errorSpan = field.nextElementSibling;
    errorSpan.textContent = message;
    errorSpan.style.display = "block";
  };

  const hideError = (field) => {
    let errorSpan = field.nextElementSibling;
    errorSpan.textContent = "";
    errorSpan.style.display = "none";
  };

  usernameField.addEventListener("input", function () {
    this.value = this.value.toLowerCase().replace(/[^a-z0-9]/g, "");
    if (this.value.length < 8 || this.value.length > 12) {
      showError(this, "Harap masukkan antara 8 - 12 karakter yang terdiri dari huruf kecil dan angka!");
    } else {
      hideError(this);
    }
  });

  phoneFields.forEach((field) => {
    field.addEventListener("input", function () {
      this.value = this.value.replace(/[^0-9]/g, "");
      if (this.value.length < 10 || this.value.length > 13) {
        showError(this, "Nomor Kontak Harus diantara 10 dan 13 digit");
      } else {
        hideError(this);
      }
    });
  });

  accountNumberField.addEventListener("input", function () {
    this.value = this.value.replace(/[^0-9]/g, "");
    if (this.value === "") {
      showError(this, "Nomor rekening bank diperlukan.");
    } else {
      hideError(this);
    }
  });

  bankNameField.addEventListener("input", function () {
    this.value = this.value.replace(/[^a-zA-Z ]/g, "");
    if (this.value === "") {
      showError(this, "Silakan masukkan nama lengkap yang valid.");
    } else {
      hideError(this);
    }
  });

  passwordField.addEventListener("input", function () {
    const value = this.value;

    passwordValidations.style.display = "block";
    const isLongEnough = value.length >= 8 && value.length <= 20;
    const hasLetter = /[a-z]/i.test(value);
    const hasNumber = /\d/.test(value);

    if (!isLongEnough || !(hasLetter && hasNumber)) {
      showError(this, "Password harus terdiri dari 8-20 karakter, dan harus mengandung huruf dan angka.");
    } else {
      hideError(this);
    }
  });

  confirmPasswordField.addEventListener("input", function () {
    if (this.value !== passwordField.value) {
      showError(this, "Konfirmasi kata sandi tidak cocok!");
    } else {
      hideError(this);
    }
  });
});
