/* global React */
(function () {
  const { useState } = React;
  const T = window.SC_T;
  const Icon = window.SC_Icon;

  function PasswordInput({ value, onChange, placeholder }) {
    const [show, setShow] = useState(false);
    return (
      <TextInput
        type={show ? 'text' : 'password'}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        rightSlot={
          <button
            type="button"
            onClick={() => setShow(!show)}
            style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: T.inkMuted, display: 'flex', padding: 0 }}
          >
            {show ? Icon.eyeOff(16) : Icon.eye(16)}
          </button>
        }
      />
    );
  }

  function LoginPage() {
    const [tab, setTab]       = useState('login'); // 'login' | 'register'
    const [email, setEmail]   = useState('');
    const [pass, setPass]     = useState('');
    const [pass2, setPass2]   = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError]   = useState('');

    const reset = () => { setError(''); };

    const handleSubmit = async () => {
      setError('');
      if (!email.trim() || !pass.trim()) { setError('Заполните все поля'); return; }
      if (tab === 'register' && pass !== pass2) { setError('Пароли не совпадают'); return; }
      if (tab === 'register' && pass.length < 6) { setError('Пароль минимум 6 символов'); return; }

      setLoading(true);
      try {
        const url  = tab === 'login' ? '/api/auth/login' : '/api/auth/register';
        const resp = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email: email.trim().toLowerCase(), password: pass }),
        });
        const data = await resp.json();
        if (!resp.ok) { setError(data.detail || 'Ошибка'); return; }
        window.SC_Auth.login(data.token, data.email);
      } catch {
        setError('Не удалось подключиться к серверу');
      } finally {
        setLoading(false);
      }
    };

    const handleKey = (e) => { if (e.key === 'Enter') handleSubmit(); };

    return (
      <div style={{
        width: '100%', height: '100%', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        background: T.bg, fontFamily: '"Inter", system-ui, sans-serif',
      }}>
        <div style={{
          width: 420, background: T.surface, borderRadius: 20,
          boxShadow: '0 20px 60px rgba(17,24,39,0.12), 0 1px 3px rgba(17,24,39,0.06)',
          overflow: 'hidden',
          animation: 'sc-scale-in .3s cubic-bezier(0.16, 1, 0.3, 1)',
        }}>
          {/* Header */}
          <div style={{ padding: '32px 32px 24px', borderBottom: `1px solid ${T.borderSoft}`, textAlign: 'center' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 16 }}>
              <Logo size={48} />
            </div>
            <div style={{ fontSize: 22, fontWeight: 700, color: T.ink, letterSpacing: -0.4 }}>Semantic Core</div>
            <div style={{ fontSize: 13, color: T.inkMuted, marginTop: 4 }}>Сборщик семантических ядер</div>
          </div>

          {/* Tabs */}
          <div style={{ display: 'flex', borderBottom: `1px solid ${T.borderSoft}` }}>
            {[['login', 'Войти'], ['register', 'Регистрация']].map(([key, label]) => (
              <button
                key={key}
                onClick={() => { setTab(key); reset(); }}
                style={{
                  flex: 1, padding: '14px 0', border: 'none', background: 'transparent',
                  fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                  color: tab === key ? T.accent : T.inkMuted,
                  borderBottom: `2px solid ${tab === key ? T.accent : 'transparent'}`,
                  marginBottom: -1, transition: 'all .2s ease',
                }}
              >
                {label}
              </button>
            ))}
          </div>

          {/* Form */}
          <div style={{ padding: '28px 32px 32px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontSize: 13, fontWeight: 600, color: T.ink }}>Email</label>
              <TextInput
                type="email"
                value={email}
                onChange={(v) => { setEmail(v); reset(); }}
                placeholder="you@example.com"
              />
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontSize: 13, fontWeight: 600, color: T.ink }}>Пароль</label>
              <PasswordInput
                value={pass}
                onChange={(v) => { setPass(v); reset(); }}
                placeholder="Минимум 6 символов"
              />
            </div>

            {tab === 'register' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, animation: 'sc-fade-in .2s ease' }}>
                <label style={{ fontSize: 13, fontWeight: 600, color: T.ink }}>Повторите пароль</label>
                <PasswordInput
                  value={pass2}
                  onChange={(v) => { setPass2(v); reset(); }}
                  placeholder="Ещё раз"
                />
              </div>
            )}

            {error && (
              <div style={{ padding: '10px 14px', borderRadius: 8, background: T.errSoft, color: '#991B1B', fontSize: 13, fontWeight: 500, animation: 'sc-fade-in .15s ease' }}>
                {error}
              </div>
            )}

            <PrimaryButton onClick={handleSubmit} loading={loading} disabled={loading} style={{ marginTop: 4 }}>
              {tab === 'login' ? 'Войти' : 'Создать аккаунт'}
            </PrimaryButton>
          </div>
        </div>
      </div>
    );
  }

  window.LoginPage = LoginPage;
})();
