document.addEventListener("DOMContentLoaded", () => {
  const inputs = document.querySelectorAll(".otp-input-box");
  const countdownElement = document.querySelector(".resend-link");
  const resendButton = document.querySelector(".p-resend-text button");
  const successModal = document.getElementById("success-modal");

  let timeLeft = 56;
  let timerId;

  // Countdown timer logic
  function startTimer() {
    resendButton.disabled = true;
    resendButton.style.opacity = "0.5";
    resendButton.style.cursor = "not-allowed";

    timerId = setInterval(() => {
      if (timeLeft <= 0) {
        clearInterval(timerId);
        if (countdownElement && countdownElement.parentElement) {
          countdownElement.parentElement.innerHTML =
            "You can now resend the code";
        }
        resendButton.disabled = false;
        resendButton.style.opacity = "1";
        resendButton.style.cursor = "pointer";
      } else {
        if (countdownElement) {
          countdownElement.textContent = timeLeft;
        }
        timeLeft--;
      }
    }, 1000);
  }

  // OTP Input logic: Auto-focus and Modal trigger
  inputs.forEach((input, index) => {
    // Handle typing and auto-forward
    input.addEventListener("input", (e) => {
      // Prevent more than 1 character
      if (e.target.value.length > 1) {
        e.target.value = e.target.value.slice(0, 1);
      }

      // Move to next input
      if (e.target.value !== "" && index < inputs.length - 1) {
        inputs[index + 1].focus();
      }

      // Check if all inputs are filled to show success modal
      const isComplete = Array.from(inputs).every((inp) => inp.value !== "");
      if (isComplete) {
        setTimeout(() => {
          if (successModal) {
            successModal.classList.remove("hidden");
          }
        }, 500);
      }
    });

    // Handle backspace to move backward
    input.addEventListener("keydown", (e) => {
      if (e.key === "Backspace" && e.target.value === "" && index > 0) {
        inputs[index - 1].focus();
      }
    });
  });

  // Resend button logic
  if (resendButton) {
    resendButton.addEventListener("click", () => {
      if (!resendButton.disabled) {
        // Resetting logic or reloading
        location.reload();
      }
    });
  }

  // Initialize timer on load
  startTimer();
});
