const sendOtpBtn   = document.getElementById("sendOtpBtn");
const verifyOtpBtn = document.getElementById("verifyOtpBtn");
const resendBtn    = document.getElementById("resendBtn");

const phoneStep = document.getElementById("phoneStep");
const otpStep   = document.getElementById("otpStep");

const countdownEl = document.getElementById("countdown");

let countdown = 60;
let timer;

/* SEND OTP */
sendOtpBtn.addEventListener("click", () => {
  const countryCode = document.getElementById("countryCode").value;
  const phoneNumber = document.getElementById("phoneNumber").value.trim();

  if (phoneNumber.length < 9) {
    alert("Please enter a valid phone number.");
    return;
  }

  const fullPhone = countryCode + phoneNumber;

  // Save phone temporarily
  const onboarding = JSON.parse(localStorage.getItem("flowpesa_onboarding")) || {};
  onboarding.phone = fullPhone;
  onboarding.phone_verified = false;

  localStorage.setItem("flowpesa_onboarding", JSON.stringify(onboarding));

  // MOCK: send OTP
  console.log("OTP sent to:", fullPhone);

  phoneStep.classList.add("hidden");
  otpStep.classList.remove("hidden");

  startCountdown();
});

/* VERIFY OTP */
verifyOtpBtn.addEventListener("click", () => {
  const otp = document.getElementById("otpCode").value.trim();

  if (otp.length !== 6) {
    alert("Enter the 6-digit code.");
    return;
  }

  // MOCK verification (replace with API later)
  if (otp === "123456") {
    const onboarding = JSON.parse(localStorage.getItem("flowpesa_onboarding"));
    onboarding.phone_verified = true;
    onboarding.step = "phone_verified";

    localStorage.setItem("flowpesa_onboarding", JSON.stringify(onboarding));

    window.location.href = "email-verification.html";
  } else {
    alert("Invalid code. Try again.");
  }
});

/* RESEND OTP */
resendBtn.addEventListener("click", () => {
  countdown = 60;
  resendBtn.classList.add("hidden");
  startCountdown();

  console.log("OTP resent");
});

/* TIMER */
function startCountdown() {
  countdownEl.textContent = countdown;

  timer = setInterval(() => {
    countdown--;
    countdownEl.textContent = countdown;

    if (countdown <= 0) {
      clearInterval(timer);
      resendBtn.classList.remove("hidden");
    }
  }, 1000);
}
