// ─── Auth screen ─── Real login/register against /api/auth/*
function AuthScreen({ setScreen, toast, onAuthed }) {
  const [tab, setTab] = React.useState('login');
  const [email, setEmail] = React.useState('');
  const [pwd, setPwd] = React.useState('');
  const [code, setCode] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [requireInvite, setRequireInvite] = React.useState(false);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    apiFetch('/api/auth/config')
      .then(r => r.json())
      .then(d => setRequireInvite(!!d.require_invite_code))
      .catch(() => {});
  }, []);

  async function submit(e) {
    e.preventDefault();
    setErr('');
    setLoading(true);
    const endpoint = tab === 'register' ? '/api/auth/register' : '/api/auth/login';
    const payload = { email, password: pwd };
    if (tab === 'register' && requireInvite) payload.invite_code = code;
    try {
      await apiRequest(endpoint, {
        method: 'POST',
        body: JSON.stringify(payload),
        skipAuth: true,
      });
      toast(tab === 'register' ? '注册成功，欢迎加入' : '登录成功');
      onAuthed();
    } catch (ex) {
      setErr(errText(ex.code || ex.message));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="stage stage--center">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32, maxWidth: 880, width: '100%', alignItems: 'center' }}>

        {/* Left: shrimp tank hero */}
        <div className="tank" style={{ aspectRatio: '1', padding: 24, position: 'relative', minHeight: 360 }}>
          <div className="tank__bubbles">
            <i style={{ left: '15%', animationDelay: '0s' }}/>
            <i style={{ left: '30%', animationDelay: '1.2s' }}/>
            <i style={{ left: '55%', animationDelay: '2.4s' }}/>
            <i style={{ left: '75%', animationDelay: '3.6s' }}/>
            <i style={{ left: '88%', animationDelay: '4.8s' }}/>
          </div>
          <div className="between" style={{ position: 'absolute', top: 12, left: 16, right: 16 }}>
            <div className="tiny upper muted mono">TANK_01 · 水族缸</div>
            <div className="tiny mono muted">24.0°C · PH 7.2</div>
          </div>
          <div className="center" style={{ height: '100%', animation: 'shrimp-bob 3.4s ease-in-out infinite' }}>
            <Shrimp size={220} mood="happy"/>
          </div>
          <div style={{
            position: 'absolute', left: 0, right: 0, bottom: 0, height: 24,
            background: 'var(--paper-3)',
            borderTop: '1.5px solid var(--line)',
            backgroundImage: 'radial-gradient(circle at 3px 3px, var(--ink-mute) 1px, transparent 0)',
            backgroundSize: '6px 6px',
          }}/>
        </div>

        {/* Right: auth card */}
        <div className="win">
          <div className="win__bar">
            <div className="dots"><i/><i/><i/></div>
            <div className="title">xiaoxia.login</div>
            <div className="meta">v4.2.0</div>
          </div>
          <div className="win__body" style={{ padding: 28 }}>
            <h1 style={{ fontSize: 22, marginBottom: 6 }}>
              欢迎回到 <span style={{ color: 'var(--shrimp-d)' }}>小虾</span><span className="caret"/>
            </h1>
            <p className="small muted mono" style={{ marginBottom: 22 }}>
              {'>'} OpenClaw 🦞 云托管控制台
            </p>

            <div className="seg" style={{ marginBottom: 20 }}>
              <button className={tab==='login'?'active':''} onClick={()=>{setTab('login');setErr('');}}>登录</button>
              <button className={tab==='register'?'active':''} onClick={()=>{setTab('register');setErr('');}}>注册</button>
            </div>

            <form onSubmit={submit} className="col gap-3">
              <div className="field">
                <label className="field__label">邮箱 / email</label>
                <input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@example.com" required autoComplete="email"/>
              </div>
              <div className="field">
                <label className="field__label">密码 / password</label>
                <input type="password" value={pwd} onChange={e=>setPwd(e.target.value)} placeholder="至少 6 位" required minLength={6} autoComplete="current-password"/>
              </div>
              {tab === 'register' && requireInvite && (
                <div className="field">
                  <label className="field__label">邀请码 / invite</label>
                  <input type="text" value={code} onChange={e=>setCode(e.target.value)} placeholder="happy-panda-1234" required autoComplete="off"/>
                  <div className="tiny muted mono mt-2">{'// 注册需要邀请码，可向已注册用户索取'}</div>
                </div>
              )}

              {err && (
                <div className="tiny mono" style={{ color: 'var(--shrimp-d)', padding: '6px 10px', background: 'var(--shrimp-l)', border: '1.5px solid var(--shrimp-d)', borderRadius: 3 }}>
                  ⚠ {err}
                </div>
              )}

              <button type="submit" className="btn btn--primary btn--full btn--lg mt-2" disabled={loading}>
                {loading ? '处理中...' : (tab === 'register' ? '创建账号 →' : '进入控制台 →')}
              </button>
            </form>

            <div className="row mt-4" style={{ justifyContent: 'space-between' }}>
              <div className="tiny muted mono">
                <span className="kbd">↵</span> 提交 &nbsp; <span className="kbd">TAB</span> 切换
              </div>
              <div className="tiny muted mono">CONN: <span style={{ color: 'var(--lime-d)' }}>● OK</span></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
window.AuthScreen = AuthScreen;
