const sendBtn   = document.getElementById("sendEmailCodeBtn");
const verifyBtn = document.getElementById("verifyEmailBtn");
const resendBtn = document.getElementById("resendEmailBtn");

const emailStep = document.getElementById("emailStep");
const codeStep  = document.getElementById("codeStep");

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

let countdown = 60;
let timer;

/* SEND EMAIL CODE */
sendBtn.addEventListener("click", () => {
  const email = document.getElementById("email").value.trim();

  if (!email || !email.includes("@")) {
    alert("Please enter a valid email address.");
    return;
  }

  const onboarding = JSON.parse(localStorage.getItem("flowpesa_onboarding")) || {};
  onboarding.email = email;
  onboarding.email_verified = false;

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

  // MOCK: send email code
  console.log("Email verification code sent to:", email);

  emailStep.classList.add("hidden");
  codeStep.classList.remove("hidden");

  startCountdown();
});

/* VERIFY EMAIL CODE */
verifyBtn.addEventListener("click", () => {
  const code = document.getElementById("emailCode").value.trim();

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

  // MOCK verification
  if (code === "654321") {
    const onboarding = JSON.parse(localStorage.getItem("flowpesa_onboarding"));
    onboarding.email_verified = true;
    onboarding.step = "email_verified";

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

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

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

  console.log("Email verification code resent");
});

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

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

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