/* ProHippo — Email OTP Verification Screen */

function OtpScreen({ user, onVerified, onSignOut }) {
  const [digits,      setDigits]      = React.useState(["","","",""]);
  const [generatedOtp,setGeneratedOtp]= React.useState(null);
  const [sending,     setSending]     = React.useState(true);
  const [error,       setError]       = React.useState("");
  const [countdown,   setCountdown]   = React.useState(30);
  const [attempts,    setAttempts]    = React.useState(0);
  const refs = [React.useRef(), React.useRef(), React.useRef(), React.useRef()];

  /* Generate a 4-digit OTP and send it */
  const sendOtp = React.useCallback(async () => {
    setSending(true);
    setError("");
    const code = String(Math.floor(1000 + Math.random() * 9000));
    setGeneratedOtp(code);
    setDigits(["","","",""]);

    try {
      await emailjs.send(
        window.EMAILJS_SERVICE_ID,
        window.EMAILJS_TEMPLATE_ID,
        {
          email:     user.email,        // matches {{email}} in template "To Email"
          to_name:   user.displayName || user.email.split("@")[0],
          otp_code:  code,              // matches {{otp_code}} in template
        },
        window.EMAILJS_PUBLIC_KEY
      );
      setCountdown(30);
    } catch (e) {
      setError("Could not send OTP. Check your EmailJS setup or try again.");
      console.error("EmailJS error:", e);
    }
    setSending(false);
  }, [user]);

  /* Send on first mount */
  React.useEffect(() => { sendOtp(); }, []);

  /* Countdown timer for resend */
  React.useEffect(() => {
    if (countdown <= 0) return;
    const t = setInterval(() => setCountdown(n => n - 1), 1000);
    return () => clearInterval(t);
  }, [countdown]);

  /* Auto-focus first box once OTP is sent */
  React.useEffect(() => {
    if (!sending) setTimeout(() => refs[0].current?.focus(), 100);
  }, [sending]);

  /* Handle single-digit input */
  const handleChange = (i, raw) => {
    const val = raw.replace(/\D/g, "").slice(-1);
    const next = [...digits];
    next[i] = val;
    setDigits(next);
    setError("");
    if (val && i < 3) refs[i+1].current?.focus();
    if (next.every(d => d !== "") && val) verify(next.join(""));
  };

  /* Backspace moves to previous box */
  const handleKeyDown = (i, e) => {
    if (e.key === "Backspace" && !digits[i] && i > 0) refs[i-1].current?.focus();
  };

  /* Paste support — user can paste the 4-digit code */
  const handlePaste = (e) => {
    const pasted = e.clipboardData.getData("text").replace(/\D/g,"").slice(0,4);
    if (pasted.length === 4) {
      setDigits(pasted.split(""));
      refs[3].current?.focus();
      verify(pasted);
    }
    e.preventDefault();
  };

  /* Verify the entered code */
  const verify = (code) => {
    if (code === generatedOtp) {
      sessionStorage.setItem("ph_otp_ok_" + user.uid, "1");
      onVerified();
    } else {
      setAttempts(a => a + 1);
      setError("Incorrect code — please try again.");
      setDigits(["","","",""]);
      setTimeout(() => refs[0].current?.focus(), 80);
    }
  };

  /* Mask email for display: vi***** @gmail.com */
  const maskedEmail = user.email
    ? user.email.replace(/^(.{2})([^@]*)/, (_, a, b) => a + "*".repeat(Math.min(b.length, 5)))
    : "your email";

  return (
    <div className="otp-page">
      <div className="otp-card">

        {/* Logo */}
        <div className="auth-logo-row" style={{justifyContent:"center", marginBottom:24}}>
          <div className="auth-logo-mark" style={{width:46,height:46,borderRadius:14,background:"var(--p-primary)"}}>
            <svg viewBox="0 0 24 24" fill="none" style={{width:22,height:22}}>
              <path d="M6 4c3 0 3 4 6 4s3-4 6-4v16c-3 0-3-4-6-4s-3 4-6 4V4z" fill="white"/>
            </svg>
          </div>
          <span className="auth-logo-text" style={{color:"var(--p-primary)"}}>ProHippo</span>
        </div>

        <div className="otp-icon">📬</div>
        <h2 className="otp-title">Check your email</h2>
        <p className="otp-sub">
          {sending
            ? "Sending your verification code…"
            : <>We sent a <strong>4-digit code</strong> to<br/><span className="otp-email">{maskedEmail}</span></>
          }
        </p>

        {/* 4 digit boxes */}
        <div className="otp-boxes" onPaste={handlePaste}>
          {digits.map((d, i) => (
            <input
              key={i}
              ref={refs[i]}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={d}
              className={`otp-box ${error ? "otp-error-shake" : ""} ${d ? "otp-filled" : ""}`}
              onChange={e => handleChange(i, e.target.value)}
              onKeyDown={e => handleKeyDown(i, e)}
              disabled={sending}
              autoComplete="one-time-code"
            />
          ))}
        </div>

        {error && <p className="otp-error-msg">{error}</p>}
        {sending && <p className="otp-sending-msg">Sending…</p>}

        {/* Resend */}
        {!sending && (
          <div className="otp-resend-row">
            {countdown > 0
              ? <span className="otp-countdown">Resend in {countdown}s</span>
              : <button className="auth-link-btn" style={{fontWeight:700}} onClick={sendOtp}>
                  Resend code
                </button>
            }
          </div>
        )}

        {attempts >= 3 && (
          <p className="otp-hint">
            Can't find the email? Check your Spam folder.
          </p>
        )}

        <button className="otp-back-link" onClick={onSignOut}>
          ← Use a different account
        </button>
      </div>
    </div>
  );
}

window.OtpScreen = OtpScreen;
