// Function to distribute pasted OTP across inputs
function handlePaste(e) {
  const data = e.clipboardData.getData("text");
  const otpInputs = document.querySelectorAll(".otp-input");

  // Split the pasted data into individual characters and fill the inputs
  data.split("").forEach((value, index) => {
    if (index < otpInputs.length) {
      otpInputs[index].value = value; // Assign each digit to corresponding input
      if (index < otpInputs.length - 1) {
        otpInputs[index + 1].focus(); // Move focus to next input
      }
    }
  });

  // Prevent the default paste behavior
  e.preventDefault();

  enable_disbaled_verify_email();
}

// Function to move focus to next input on input
function handleInput(e) {
  const input = e.target;
  const nextInput = input.nextElementSibling;

  // Move focus to next input if it exists and current input has a value
  if (input.value && nextInput && nextInput.classList.contains("otp-input")) {
    nextInput.focus();
  }

  enable_disbaled_verify_email();
}

// Function to clear the input on backspace if OTP is wrong
function handleBackspace(e) {
  const input = e.target;
  const previousInput = input.previousElementSibling;

  if (e.key === "Backspace" && input.value === "") {
    // Clear the input
    input.value = "";
    // Move focus to previous input if it exists
    if (previousInput && previousInput.classList.contains("otp-input")) {
      previousInput.focus();
    }
  }
}

// Attach event listeners to each OTP input
document.querySelectorAll(".otp-input").forEach((input) => {
  input.addEventListener("paste", handlePaste);
  input.addEventListener("input", handleInput);
  input.addEventListener("keydown", handleBackspace);
});

$(".login form").on("submit", function (e) {
  e.preventDefault();

  $("#otpField").fadeIn();
  $(this).find("button").text("Submit");
});

$("#menuBtnOpen").on("click", function () {
  $(".files .sidebar").toggleClass("open");
});

$("#menuBtnClose").on("click", function () {
  $(".files .sidebar").removeClass("open");
});