const FaceLoginScreen = ({ onLoggedIn, onCancel }) => {
  const [login, setLogin] = React.useState('');
  const [error, setError] = React.useState('');
  const [phase, setPhase] = React.useState('input');
  const [sessionId, setSessionId] = React.useState(null);
  const descriptorRef = React.useRef(null);
  const [challenges, setChallenges] = React.useState([]);
  const [loading, setLoading] = React.useState(false);

  const startScan = async () => {
    setError('');
    if (!login.trim()) { setError('Введите логин'); return; }
    setLoading(true);
    try {
      const { sessionId: sid, challenges: ch } = await api.face.loginChallenge(login.trim());
      setSessionId(sid); setChallenges(ch);
      setPhase('scan');
    } catch (e) {
      setLoading(false);
      if (e.status === 404) setError('У этого пользователя не настроен Face ID');
      else setError('Ошибка: ' + (e.message || e.status));
      return;
    }
    setLoading(false);
  };

  const onScanComplete = async (desc) => {
    descriptorRef.current = desc;
    try {
      const res = await api.face.loginVerify(sessionId, desc, []);
      if (res?.needChallenge) {
        setChallenges(res.challenges);
        setPhase('challenge');
      } else {
        onLoggedIn(res);
      }
    } catch (e) {
      if (e.status === 401) setError('Не удалось подтвердить личность');
      else if (e.status === 410) setError('Сессия истекла, начните заново');
      else setError('Ошибка: ' + (e.message || e.status));
      setPhase('input');
    }
  };

  const onChallengeComplete = async (completed) => {
    if (!descriptorRef.current) { setError('Сессия потеряна, начните заново'); setPhase('input'); return; }
    try {
      const res = await api.face.loginVerify(sessionId, descriptorRef.current, completed);
      onLoggedIn(res);
    } catch (e) {
      if (e.status === 401) setError('Не удалось подтвердить личность');
      else if (e.status === 410) setError('Сессия истекла, начните заново');
      else setError('Ошибка: ' + (e.message || e.status));
      setPhase('input');
    }
  };

  return (
    <AuthLayout title="Вход по лицу" subtitle="Введите логин — дальше подставим камеру." side={<AuthSidePanel/>}>
      {phase === 'input' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 12 }}>
          {error && <div style={{ padding: 10, borderRadius: 10, background:'#FBE1DA', color:'#9A3218', fontSize: 13 }}>{error}</div>}
          <div>
            <Label>Логин</Label>
            <Input leading={<IconUser size={16}/>} placeholder="ivan.p" value={login} onChange={e=> setLogin(e.target.value)} autoComplete="username"/>
          </div>
          <div style={{ display:'flex', gap: 8, marginTop: 6 }}>
            <Button variant="ghost" size="lg" type="button" onClick={onCancel}>Назад</Button>
            <Button variant="primary" size="lg" full type="button" onClick={startScan} disabled={loading} trailing={<IconArrow size={16}/>}>
              {loading ? 'Подождите…' : 'Начать'}
            </Button>
          </div>
        </div>
      )}
      {phase === 'scan' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          {error && <div style={{ padding: 10, borderRadius: 10, background:'#FBE1DA', color:'#9A3218', fontSize: 13 }}>{error}</div>}
          <FaceScanCamera
            onComplete={onScanComplete}
            onCancel={()=> setPhase('input')}
            onError={(msg)=> { setError(msg); setPhase('input'); }}
          />
        </div>
      )}
      {phase === 'challenge' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          <div style={{ padding: 12, borderRadius: 10, background:'var(--accent-soft)', color:'var(--accent-hover)', fontSize: 13 }}>
            Нужна дополнительная проверка — выполните жесты.
          </div>
          {error && <div style={{ padding: 10, borderRadius: 10, background:'#FBE1DA', color:'#9A3218', fontSize: 13 }}>{error}</div>}
          <LivenessChallengeOverlay
            challenges={challenges}
            onComplete={onChallengeComplete}
            onCancel={()=> setPhase('input')}
            onError={(msg)=> { setError(msg); setPhase('input'); }}
          />
        </div>
      )}
    </AuthLayout>
  );
};

Object.assign(window, { FaceLoginScreen });
