document.addEventListener("DOMContentLoaded", () => {
  const inputs = document.querySelectorAll(".otp-input-box");
  const timerDisplay = document.getElementById("timer");
  const timerContainer = document.getElementById("timerContainer");
  const resendBtn = document.getElementById("resendBtn");

  let timeLeft = 30;
  let timerId;

  function startCountdown() {
    timeLeft = 30;
    resendBtn.style.display = "none";
    timerContainer.style.display = "block";
    timerDisplay.textContent = timeLeft;

    timerId = setInterval(() => {
      timeLeft--;
      timerDisplay.textContent = timeLeft;

      if (timeLeft <= 0) {
        clearInterval(timerId);
        timerContainer.style.display = "none";
        resendBtn.style.display = "inline";
      }
    }, 1000);
  }

  // Initialize countdown on load
  startCountdown();

  // Resend button click handler
  resendBtn.addEventListener("click", () => {
    // Add your API call logic here to resend the OTP
    startCountdown();
  });

  // Existing OTP input logic
  inputs.forEach((input, index) => {
    input.addEventListener("input", (e) => {
      e.target.value = e.target.value.replace(/[^0-9]/g, "");

      if (e.target.value.length === 1 && index < inputs.length - 1) {
        inputs[index + 1].focus();
      }
      checkAndRedirect();
    });

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

  function checkAndRedirect() {
    const otpValue = Array.from(inputs)
      .map((input) => input.value)
      .join("");

    if (otpValue.length === 5) {
      window.location.href = "./create-new-password.html";
    }
  }
});
