var Register = function (props) {
  var navigate = props.navigate;
  var _step = React.useState(1); var step = _step[0], setStep = _step[1];
  var _name = React.useState(''); var displayName = _name[0], setDisplayName = _name[1];
  var _email = React.useState(''); var email = _email[0], setEmail = _email[1];
  var _pw = React.useState(''); var password = _pw[0], setPassword = _pw[1];
  var _pw2 = React.useState(''); var confirm = _pw2[0], setConfirm = _pw2[1];
  var _err = React.useState(''); var error = _err[0], setError = _err[1];
  var _loading = React.useState(false); var loading = _loading[0], setLoading = _loading[1];
  var _pendingId = React.useState(''); var pendingId = _pendingId[0], setPendingId = _pendingId[1];
  var _code = React.useState(''); var code = _code[0], setCode = _code[1];
  var _cooldown = React.useState(0); var cooldown = _cooldown[0], setCooldown = _cooldown[1];

  var strengthLabel = password.length < 8 ? 'WEAK' : password.length < 12 ? 'OK' : 'STRONG';
  var strengthColor = password.length < 8 ? '#ff6b35' : password.length < 12 ? 'var(--amber)' : '#6bcf6b';
  var maskedEmail = React.useMemo(function () {
    var at = email.indexOf('@');
    return at < 2 ? email : email[0] + '***' + email.slice(at);
  }, [email]);

  React.useEffect(function () {
    if (cooldown <= 0) return;
    var t = setTimeout(function () { setCooldown(cooldown - 1); }, 1000);
    return function () { clearTimeout(t); };
  }, [cooldown]);

  var wrap = { maxWidth: '460px', margin: '0 auto', padding: '64px 28px 80px', minHeight: '60vh' };
  var inp = { width: '100%', padding: '12px 14px', fontFamily: 'var(--font-mono)', fontSize: '14px', color: 'var(--text)', background: 'var(--bg-2)', border: '1px solid var(--border)', outline: 'none', borderRadius: '2px' };
  var lbl = { fontFamily: 'var(--font-mono)', fontSize: '12px', color: 'var(--amber-dim)', letterSpacing: '0.08em', marginBottom: '6px', display: 'block' };
  var btn = { width: '100%', padding: '14px', background: 'var(--amber)', color: 'var(--bg)', border: 'none', fontFamily: 'var(--font-mono)', fontSize: '13px', fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer', borderRadius: '2px', opacity: loading ? 0.6 : 1 };
  var oBtn = { flex: 1, padding: '11px 0', background: 'transparent', border: '1px solid var(--border)', color: 'var(--text-2)', fontFamily: 'var(--font-mono)', fontSize: '11px', letterSpacing: '0.06em', textTransform: 'uppercase', cursor: 'pointer', borderRadius: '2px', textAlign: 'center' };
  var errStyle = { fontFamily: 'var(--font-mono)', fontSize: '12px', color: '#ff6b35', marginBottom: '14px' };
  var title = function (t) { return { fontFamily: 'var(--font-display)', fontSize: '28px', color: 'var(--text)', letterSpacing: '0.02em', marginBottom: '4px' }; };
  var sub = { fontFamily: 'var(--font-mono)', fontSize: '13px', color: 'var(--text-muted)', marginBottom: '32px' };

  var postAuth = function (body, onOk) {
    setLoading(true);
    fetch('/api/auth', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
      .then(function (r) { return r.json().then(function (d) { return { ok: r.ok, data: d }; }); })
      .then(function (res) { setLoading(false); if (!res.ok) { setError(res.data.error || 'request failed'); return; } onOk(res.data); })
      .catch(function () { setLoading(false); setError('network error -- try again'); });
  };

  var regPayload = { action: 'register', payload: { email: email, password: password, displayName: displayName.trim() }, turnstileToken: '' };

  var handleRegister = function () {
    setError('');
    if (!displayName.trim()) { setError('display name required'); return; }
    if (!email || !email.includes('@')) { setError('valid email required'); return; }
    if (password.length < 8) { setError('password must be at least 8 characters'); return; }
    if (password !== confirm) { setError('passwords do not match'); return; }
    postAuth(regPayload, function (d) { setPendingId(d.pendingId); setCooldown(60); setStep(2); });
  };

  var handleVerify = function () {
    setError('');
    if (code.length !== 6) { setError('enter the 6-digit code'); return; }
    postAuth({ action: 'register_verify', payload: { pendingId: pendingId, code: code } }, function () { navigate('account'); });
  };

  var handleResend = function () {
    if (cooldown > 0) return;
    setCooldown(60);
    postAuth(regPayload, function (d) { if (d.pendingId) setPendingId(d.pendingId); });
  };

  if (step === 2) {
    return (
      <div style={wrap}>
        <div style={title()}>$ verify --email</div>
        <div style={sub}>verification code sent to {maskedEmail}</div>
        <input type="text" inputMode="numeric" maxLength={6} value={code}
          onChange={function (e) { setCode(e.target.value.replace(/\D/g, '').slice(0, 6)); }}
          onKeyDown={function (e) { if (e.key === 'Enter') handleVerify(); }}
          placeholder="000000"
          style={Object.assign({}, inp, { textAlign: 'center', fontSize: '28px', letterSpacing: '0.3em', padding: '18px 14px', marginBottom: '20px' })} />
        {error && <div style={errStyle}>[{'>'}] {error}</div>}
        <button onClick={handleVerify} disabled={loading} style={btn}>{loading ? '...' : 'VERIFY'}</button>
        <div style={{ textAlign: 'center', marginTop: '20px' }}>
          <span onClick={handleResend} style={{ fontFamily: 'var(--font-mono)', fontSize: '12px', cursor: cooldown > 0 ? 'default' : 'pointer', color: cooldown > 0 ? 'var(--text-muted)' : 'var(--amber)', letterSpacing: '0.06em' }}>
            {cooldown > 0 ? 'resend in ' + cooldown + 's' : 'resend code'}
          </span>
        </div>
      </div>
    );
  }

  return (
    <div style={wrap}>
      <div style={title()}>$ useradd --create</div>
      <div style={sub}>create your account</div>

      <div style={{ marginBottom: '16px' }}>
        <label style={lbl}>$ display_name:</label>
        <input type="text" value={displayName} onChange={function (e) { setDisplayName(e.target.value); }} style={inp} placeholder="what others see" />
      </div>
      <div style={{ marginBottom: '16px' }}>
        <label style={lbl}>$ email:</label>
        <input type="email" value={email} onChange={function (e) { setEmail(e.target.value); }} style={inp} placeholder="you@example.com" />
      </div>
      <div style={{ marginBottom: '6px' }}>
        <label style={lbl}>$ password:</label>
        <input type="password" value={password} onChange={function (e) { setPassword(e.target.value); }} style={inp} placeholder="min 8 characters" />
      </div>
      {password.length > 0 && (
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: '11px', color: strengthColor, marginBottom: '16px', letterSpacing: '0.08em' }}>
          [{strengthLabel}]
        </div>
      )}
      <div style={{ marginBottom: '24px' }}>
        <label style={lbl}>$ confirm:</label>
        <input type="password" value={confirm} onChange={function (e) { setConfirm(e.target.value); }}
          onKeyDown={function (e) { if (e.key === 'Enter') handleRegister(); }} style={inp} placeholder="repeat password" />
      </div>

      <div id="ib-turnstile" style={{ marginBottom: '20px' }}></div>
      {error && <div style={errStyle}>[{'>'}] {error}</div>}
      <button onClick={handleRegister} disabled={loading} style={btn}>{loading ? '...' : 'CREATE ACCOUNT'}</button>

      <div style={{ textAlign: 'center', marginTop: '20px' }}>
        <span onClick={function () { navigate('login'); }} style={{ fontFamily: 'var(--font-mono)', fontSize: '12px', color: 'var(--amber)', cursor: 'pointer', letterSpacing: '0.06em' }}>
          already have an account?
        </span>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: '14px', margin: '28px 0 20px' }}>
        <div style={{ flex: 1, height: '1px', background: 'var(--border)' }}></div>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: '11px', color: 'var(--text-muted)', letterSpacing: '0.1em' }}>or sign up with</span>
        <div style={{ flex: 1, height: '1px', background: 'var(--border)' }}></div>
      </div>
      <div style={{ display: 'flex', gap: '10px' }}>
        <button style={oBtn}>Discord</button>
        <button style={oBtn}>GitHub</button>
        <button style={oBtn}>Google</button>
      </div>
    </div>
  );
};

window.Register = Register;
