const { Wordmark: WM, Button: LoginBtn, Input: LoginInput, Checkbox: LoginCheck } = window.OctanexDesignSystem_0e3b75;

const LOGIN_ERRORS = {
  invalid_credentials: 'неверная почта или пароль',
  email_taken: 'почта уже занята — войдите',
  weak_password: 'пароль минимум 6 символов',
  invalid_email: 'некорректная почта',
  too_many_requests: 'слишком много попыток, подождите',
  account_blocked: 'аккаунт заблокирован',
};

function Login({ onLogin }) {
  const [email, setEmail] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [remember, setRemember] = React.useState(true);
  const [loading, setLoading] = React.useState(false);
  const [tgBusy, setTgBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const go = async (mode) => {
    setErr(null);
    if (!email.trim() || !pass) { setErr('введите почту и пароль'); return; }
    setLoading(true);
    try {
      const call = mode === 'register' ? window.api.register : window.api.login;
      const { user } = await call(email.trim(), pass);
      onLogin(user);
    } catch (e) {
      setErr(LOGIN_ERRORS[e.message] || 'ошибка входа, попробуйте ещё');
      setLoading(false);
    }
  };

  // вход через Telegram-бота (он же — восстановление пароля: пароль не нужен)
  const pollRef = React.useRef(null);
  React.useEffect(() => () => { if (pollRef.current) clearTimeout(pollRef.current); }, []);

  const tgLogin = async () => {
    setErr(null); setTgBusy(true);
    try {
      const { code, link } = await window.api.tgStart();
      window.open(link, '_blank', 'noopener');
      const started = Date.now();
      const poll = async () => {
        if (Date.now() - started > 9 * 60 * 1000) { setTgBusy(false); setErr('время вышло, попробуй ещё'); return; }
        try {
          const res = await window.api.tgPoll(code);
          if (res.status === 'authorized') { onLogin(res.user); return; }
          if (res.status === 'expired' || res.status === 'used') { setTgBusy(false); setErr('ссылка устарела, попробуй ещё'); return; }
        } catch (_) { /* транзиентная ошибка — продолжаем поллить */ }
        pollRef.current = setTimeout(poll, 2000);
      };
      poll();
    } catch (e) {
      setTgBusy(false);
      setErr(e.status === 503 ? 'telegram-вход пока не настроен' : 'ошибка, попробуй ещё');
    }
  };

  return (
    <div className="ox-grid-bg" style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', position: 'relative', overflow: 'hidden', padding: 24 }}>
      <span className="ox-glow-spot" style={{ top: -160, left: '18%' }}></span>
      <span className="ox-glow-spot" style={{ bottom: -220, right: '12%', opacity: 0.6 }}></span>
      <div style={{ width: 380, position: 'relative' }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <WM size={34} tagline />
        </div>
        <div style={{
          background: 'var(--surface-1)', border: '1px solid var(--border-strong)',
          borderRadius: 'var(--radius-lg)', padding: 28, boxShadow: 'var(--glow-accent)',
          display: 'flex', flexDirection: 'column', gap: 16,
        }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-secondary)' }}>
            <span style={{ color: 'var(--green-500)' }}>➜</span> вход в панель<span className="ox-caret"></span>
          </div>
          <LoginInput label="почта" placeholder="you@mail.com" value={email} onChange={setEmail} />
          <LoginInput label="пароль" type="password" mono placeholder="••••••••" value={pass} onChange={setPass} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <LoginCheck checked={remember} onChange={setRemember} label={<span style={{ fontSize: 13 }}>запомнить</span>} />
            <a href="#" style={{ fontSize: 12, fontFamily: 'var(--font-mono)' }} onClick={(e) => { e.preventDefault(); tgLogin(); }}>забыл пароль</a>
          </div>
          {err && (
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--danger, #ff5c5c)' }}>✕ {err}</div>
          )}
          <LoginBtn size="lg" loading={loading} onClick={() => go('login')} style={{ width: '100%' }}>{loading ? 'подключение…' : 'войти'}</LoginBtn>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '2px 0' }}>
            <span style={{ flex: 1, height: 1, background: 'var(--border-hairline)' }}></span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>или</span>
            <span style={{ flex: 1, height: 1, background: 'var(--border-hairline)' }}></span>
          </div>
          <LoginBtn variant="secondary" size="lg" loading={tgBusy} onClick={tgLogin} style={{ width: '100%' }}>
            {tgBusy ? 'ждём подтверждение в telegram…' : '✈ войти через telegram'}
          </LoginBtn>
          <div style={{ textAlign: 'center', fontSize: 13, color: 'var(--text-muted)' }}>
            нет аккаунта? <a href="#" onClick={(e) => { e.preventDefault(); go('register'); }}>создать</a>
          </div>
        </div>
        <div style={{ textAlign: 'center', marginTop: 20, fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--text-muted)' }}>
          пополнение через сбп · карта · usdt — после входа
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Login });
