/*
 * 로그인 2단계 — challengeToken + OTP 코드 검증. secureLogin 이 OTP_REQUIRED 를 반환하면 노출한다.
 * 성공 시 최종 LoginResponse 를 상위에 전달(토큰 세팅은 상위 authStore 책임).
 */
import { useState } from 'react';
import { twoFactorApi } from '@/api/common';
import type { LoginResponse } from '@/api/types';

interface Props {
  challengeToken: string;
  onVerified: (login: LoginResponse) => void;
}

export function OtpChallengeForm({ challengeToken, onVerified }: Props): JSX.Element {
  const [code, setCode] = useState<string>('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState<boolean>(false);

  const submit = async (): Promise<void> => {
    setError(null);
    setBusy(true);
    try {
      const login = await twoFactorApi.verifyOtp(challengeToken, code.trim());
      onVerified(login);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <form
      className="otp-challenge"
      onSubmit={(e) => {
        e.preventDefault();
        void submit();
      }}
    >
      <label htmlFor="otp-verify-code">OTP 인증 코드</label>
      <input
        id="otp-verify-code"
        inputMode="numeric"
        maxLength={6}
        value={code}
        onChange={(e) => setCode(e.target.value)}
        autoFocus
      />
      <button type="submit" disabled={busy || code.trim().length < 6}>
        인증
      </button>
      {error && <p role="alert">{error}</p>}
    </form>
  );
}
