const PatternLoginScreen = ({ onLoggedIn, onCancel }) => {
  const [login, setLogin] = React.useState('');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [resetKey, setResetKey] = React.useState(0);

  const onDraw = async (pattern) => {
    if (!login.trim()) { setError('Введите логин'); return; }
    setError(''); setLoading(true);
    try {
      const bundle = await api.loginWithPattern(login.trim(), pattern);
      onLoggedIn(bundle);
    } catch (e) {
      setLoading(false);
      if (e?.status === 401) setError('Неверный узор или логин');
      else setError('Ошибка: ' + (e?.message || e?.status));
      setResetKey((k) => k + 1);
    }
  };

  return (
    <AuthLayout title="Вход рисунком" subtitle="Введите свой логин и нарисуйте фигуру." side={<AuthSidePanel/>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {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>
        <PatternInput resetKey={resetKey} onComplete={onDraw} disabled={loading}/>
        <div style={{ fontSize: 12, color: 'var(--fg-subtle)', textAlign: 'center' }}>
          {loading ? 'Проверяем…' : 'Нарисуйте, как обычно — минимум 4 точки'}
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button variant="ghost" size="lg" type="button" onClick={onCancel}>Назад</Button>
        </div>
      </div>
    </AuthLayout>
  );
};

Object.assign(window, { PatternLoginScreen });
