const LoginScreen = ({ onLoggedIn, onGoRegister, onGoFaceLogin, onGoForgot, onGoPatternLogin, onGoEmojiPinLogin }) => {
  const [login, setLogin] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [show, setShow] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [stubMessage, setStubMessage] = React.useState('');

  const submit = async (e) => {
    e?.preventDefault();
    setError('');
    if (!login.trim() || !pw) {
      setError('Заполните оба поля');
      return;
    }
    setLoading(true);
    try {
      const bundle = await api.login(login.trim(), pw);
      onLoggedIn?.(bundle);
    } catch (err) {
      if (err.status === 401) setError('Неверный логин или пароль');
      else setError('Не удалось войти: ' + (err.message || err.status));
      setLoading(false);
    }
  };

  const alt = async (kind) => {
    if (kind === 'forgot') { setStubMessage(''); setError(''); onGoForgot?.(); return; }
    if (kind === 'face') { setStubMessage(''); setError(''); onGoFaceLogin?.(); return; }
    if (kind === 'passkey') {
      setError(''); setStubMessage('');
      setLoading(true);
      try {
        const bundle = await loginWithPasskey();
        onLoggedIn?.(bundle);
      } catch (e) {
        const msg = e?.message || String(e);
        if (!msg.toLowerCase().includes('abort') && !msg.toLowerCase().includes('cancel')) {
          if (e?.status === 401) setError('Passkey не распознан. Попробуйте войти по паролю.');
          else setError('Passkey-вход не удался: ' + msg);
        }
        setLoading(false);
      }
    }
  };

  return (
    <AuthLayout title="С возвращением" subtitle="Войдите, чтобы продолжить наблюдать за прогрессом ребёнка." side={<AuthSidePanel/>}>
      <form onSubmit={submit} style={{ display:'flex', flexDirection:'column', gap: 12 }}>
        {error && (
          <div style={{ padding: 10, borderRadius: 10, background:'#FBE1DA', color:'#9A3218', fontSize: 13 }}>{error}</div>
        )}
        <div>
          <label className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.06em', textTransform:'uppercase', marginBottom: 6, display:'block' }}>Логин</label>
          <Input leading={<IconUser size={16}/>} placeholder="ivan.p" value={login} onChange={e=>setLogin(e.target.value)} autoComplete="username"/>
        </div>
        <div>
          <label className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.06em', textTransform:'uppercase', marginBottom: 6, display:'block' }}>Пароль</label>
          <Input
            leading={<IconLock size={16}/>}
            type={show ? 'text' : 'password'}
            placeholder="Ваш пароль"
            value={pw} onChange={e=>setPw(e.target.value)}
            autoComplete="current-password"
            trailing={
              <button type="button" onClick={()=>setShow(s=>!s)} style={{ background:'none', border:'none', color:'var(--fg-subtle)', cursor:'pointer', padding: 4, display:'flex' }}>
                {show ? <IconEyeOff size={16}/> : <IconEye size={16}/>}
              </button>
            }
          />
        </div>

        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop: 4 }}>
          <label style={{ display:'inline-flex', alignItems:'center', gap: 8, fontSize: 13, color:'var(--fg-muted)', cursor:'pointer' }}>
            <input type="checkbox" defaultChecked style={{ accentColor:'var(--accent)' }} />
            Запомнить меня
          </label>
          <button type="button" onClick={()=> alt('forgot')} style={{ background:'none', border:'none', color:'var(--accent)', cursor:'pointer', fontSize: 13 }}>
            Забыли пароль?
          </button>
        </div>

        <Button variant="primary" size="lg" full type="submit" disabled={loading}
          trailing={loading ? null : <IconArrow size={16}/>}>
          {loading ? 'Входим…' : 'Войти'}
        </Button>

        <div style={{ display:'flex', alignItems:'center', gap: 12, margin:'8px 0' }}>
          <Divider style={{ flex: 1 }}/>
          <span className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)' }}>ИЛИ</span>
          <Divider style={{ flex: 1 }}/>
        </div>

        <Button variant="ghost" size="lg" full type="button" onClick={()=> alt('face')}
          leading={<IconFace size={18}/>}>
          Войти по лицу · Face ID
        </Button>
        <Button variant="ghost" size="lg" full type="button" onClick={()=> alt('passkey')}
          leading={<IconLock size={18}/>}>
          Войти по Passkey
        </Button>
        <div style={{ display:'flex', gap: 8 }}>
          <Button variant="ghost" size="lg" full type="button" onClick={()=> onGoPatternLogin?.()}
            leading={<span style={{fontSize:16}}>✏️</span>}>
            Рисунком
          </Button>
          <Button variant="ghost" size="lg" full type="button" onClick={()=> onGoEmojiPinLogin?.()}
            leading={<span style={{fontSize:16}}>🙂</span>}>
            Эмодзи
          </Button>
        </div>

        <div style={{ textAlign:'center', marginTop: 12, fontSize: 14, color:'var(--fg-muted)' }}>
          Впервые здесь?{' '}
          <button type="button" onClick={onGoRegister} style={{ background:'none', border:'none', color:'var(--accent)', cursor:'pointer', fontWeight: 500, padding: 0 }}>
            Создать аккаунт
          </button>
        </div>

        {stubMessage && (
          <div style={{ marginTop: 8, padding: 10, borderRadius: 10, background:'var(--surface-2)', color:'var(--fg-muted)', fontSize: 12, textAlign:'center' }}>
            {stubMessage}
          </div>
        )}
      </form>
    </AuthLayout>
  );
};

Object.assign(window, { LoginScreen });
