// 赛博宝宝前端（2026-10-21 从 index.html 的内联 <script type="text/babel"> 原样搬出）：登录 / 领养 / 找回宝宝。
// index.html 按顺序加载 app/*.jsx，前面文件定义的全局（函数、常量、组件）后面的文件直接用。

// ═══════════════ 登录页 ═══════════════
function LoginPage({ onLogin }) {
  const [token, setToken] = useState('');
  const [error, setError] = useState('');
  // 分享出去的链接带 ?adopt=1，朋友点开直接是领养表（2026-10-21）
  const [showRegister, setShowRegister] = useState(() => new URLSearchParams(window.location.search).get('adopt') === '1');
  const [showRecover, setShowRecover] = useState(false);
  const [regResult, setRegResult] = useState(null);

  async function handleLogin() {
    const cleaned = token.replace(/bearer/gi, '').replace(/\s+/g, '');
    if (!cleaned) return;
    localStorage.setItem('xz_token', cleaned);
    try {
      const res = await api('/status');
      if (res.error) {
        setError(res.error);
        localStorage.removeItem('xz_token');
      } else {
        onLogin();
      }
    } catch (e) {
      setError('连接失败');
      localStorage.removeItem('xz_token');
    }
  }

  function quickLogin(t) {
    setToken(t);
    localStorage.setItem('xz_token', t);
    api('/status').then(res => {
      if (res.error) { setError(res.error); localStorage.removeItem('xz_token'); }
      else onLogin();
    }).catch(() => { setError('连接失败'); localStorage.removeItem('xz_token'); });
  }

  if (regResult) {
    const parents = [
      { ...regResult.parent1, type: regResult.parent1Type || 'human', key: 'parent1' },
      { ...regResult.parent2, type: regResult.parent2Type || 'ai', key: 'parent2' },
    ];
    const humanParents = parents.filter(p => p.type === 'human');
    const aiParents = parents.filter(p => p.type === 'ai');
    return (
    <div className="login-page">
      <div className="login-card" style={{ maxWidth: 400 }}>
        <h1>准备好了！</h1>
        <p style={{ color: '#f44336', fontSize: 13, fontWeight: 'bold', marginBottom: 8 }}>⚠️ 请截图保存这个页面！换设备登录需要用到 token</p>
        <p style={{ color: '#A08D7D', fontSize: 13, marginBottom: 16 }}>进入游戏后，点击蛋蛋孵化你的宝宝~</p>
        <div style={{ background: '#FFFDF9', border: '1px solid #EEDFCC', borderRadius: 12, padding: 16, marginBottom: 16, textAlign: 'left' }}>
          {humanParents.map(p => (
            <div key={p.key} style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 13, fontWeight: 'bold', color: '#6E5A4B', marginBottom: 6 }}>🧑 {p.name}（真人）</div>
              <div style={{ fontSize: 12, color: '#7d6b5c', marginBottom: 4 }}>你的 token（换设备登录用）：</div>
              <div style={{ background: '#FDF6EE', padding: '8px 10px', borderRadius: 8, fontSize: 11, wordBreak: 'break-all', fontFamily: 'monospace', userSelect: 'all' }}>{p.token}</div>
            </div>
          ))}
          {aiParents.map(p => (
            <div key={p.key} style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 13, fontWeight: 'bold', color: '#6E5A4B', marginBottom: 6 }}>🤖 {p.name}（AI）</div>
              <div style={{ fontSize: 12, color: '#7d6b5c', marginBottom: 4 }}>MCP 地址（填到 AI 客户端里）：</div>
              <div style={{ background: '#FDF6EE', padding: '8px 10px', borderRadius: 8, fontSize: 11, wordBreak: 'break-all', fontFamily: 'monospace', userSelect: 'all' }}>{p.mcpUrl}</div>
              <div style={{ fontSize: 12, color: '#7d6b5c', marginTop: 6, marginBottom: 4 }}>token（备用）：</div>
              <div style={{ background: '#FDF6EE', padding: '8px 10px', borderRadius: 8, fontSize: 11, wordBreak: 'break-all', fontFamily: 'monospace', userSelect: 'all', color: '#bbb' }}>{p.token}</div>
            </div>
          ))}
        </div>
        {humanParents.length > 0 ? (
          <div style={{ display: 'flex', gap: 8 }}>
            {humanParents.map(p => (
              <button key={p.key} className="login-submit" style={{ flex: 1, background: 'linear-gradient(135deg, #D79B6D, #b8845a)' }}
                onClick={() => quickLogin(p.token)}>以{p.name}身份进入</button>
            ))}
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 8 }}>
            {parents.map(p => (
              <button key={p.key} className="login-submit" style={{ flex: 1, background: 'linear-gradient(135deg, #90caf9, #42a5f5)' }}
                onClick={() => quickLogin(p.token)}>以{p.name}身份进入</button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
  }

  if (showRegister) return <RegisterPage onBack={() => setShowRegister(false)} onResult={setRegResult} />;
  if (showRecover) return <RecoverPage onBack={() => setShowRecover(false)} onLogin={onLogin} />;

  return (
    <div className="login-page">
      <div className="login-card">
        <h1>赛博宝宝</h1>
        <p style={{ color: '#A08D7D', fontSize: 12, marginBottom: 8 }}>输入你的 token 进入</p>
        <input className="login-input" type="password" value={token}
          onChange={e => setToken(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && handleLogin()}
          placeholder="Token" />
        <button className="login-submit" onClick={handleLogin}>进入</button>
        {error && <div style={{ color: '#f44336', fontSize: 13, marginTop: 8 }}>{error}</div>}
        <div style={{ borderTop: '1px solid #EEDFCC', marginTop: 20, paddingTop: 16, display: 'flex', gap: 8 }}>
          <button className="login-submit" style={{ flex: 1, background: 'linear-gradient(135deg, #a8d8a8, #7bc47b)' }}
            onClick={() => setShowRegister(true)}>领养新宝宝</button>
          <button className="login-submit" style={{ flex: 1, background: 'linear-gradient(135deg, #f0c27f, #d4a05a)' }}
            onClick={() => setShowRecover(true)}>找回宝宝</button>
        </div>
      </div>
    </div>
  );
}

function RegisterPage({ onBack, onResult }) {
  const [p1, setP1] = useState('爸爸');
  const [p2, setP2] = useState('妈妈');
  const [t1, setT1] = useState('human');
  const [t2, setT2] = useState('ai');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const toggleStyle = (active) => ({
    flex: 1, padding: '6px 0', border: 'none', borderRadius: 8, fontSize: 12, cursor: 'pointer',
    background: active ? 'linear-gradient(135deg, #D79B6D, #e0ac80)' : '#f5ede4',
    color: active ? '#fff' : '#A08D7D', fontWeight: active ? 'bold' : 'normal',
    transition: 'all 0.2s',
  });

  async function submit() {
    setLoading(true);
    setError('');
    try {
      const res = await fetch(`${API}/register`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ parent1Name: p1.trim() || '爸爸', parent2Name: p2.trim() || '妈妈' }),
      });
      const data = await res.json();
      if (data.error) { setError(data.error); }
      else { onResult({ ...data, parent1Type: t1, parent2Type: t2 }); }
    } catch (e) {
      setError('注册失败了，再试一次？');
    }
    setLoading(false);
  }

  return (
    <div className="login-page">
      <div className="login-card">
        <h1>领养宝宝</h1>
        <p style={{ color: '#A08D7D', fontSize: 13, marginBottom: 16 }}>宝宝的名字进去以后再起~先填两位家长的称呼吧</p>
        <p style={{ color: '#D4956A', fontSize: 12, marginBottom: 12 }}>宝宝会用这个称呼叫你哦～换设备找回宝宝时也需要填一样的称呼</p>
        {[{ val: p1, set: setP1, type: t1, setType: setT1, ph: '如：爸爸、粑粑' },
          { val: p2, set: setP2, type: t2, setType: setT2, ph: '如：妈妈、麻麻' }].map((p, i) => (
          <div key={i} style={{ marginBottom: 10 }}>
            <input className="login-input" style={{ width: '100%', marginBottom: 6 }} value={p.val} onChange={e => p.set(e.target.value)} placeholder={p.ph} maxLength={10} />
            <div style={{ display: 'flex', gap: 4 }}>
              <button style={toggleStyle(p.type === 'human')} onClick={() => p.setType('human')}>🧑 真人</button>
              <button style={toggleStyle(p.type === 'ai')} onClick={() => p.setType('ai')}>🤖 AI</button>
            </div>
          </div>
        ))}
        <button className="login-submit" style={{ background: 'linear-gradient(135deg, #a8d8a8, #7bc47b)', marginTop: 4 }} onClick={submit} disabled={loading}>
          {loading ? '注册中……' : '领养！'}
        </button>
        {error && <div style={{ color: '#f44336', fontSize: 13, marginTop: 8 }}>{error}</div>}
        <button style={{ background: 'none', border: 'none', color: '#A08D7D', cursor: 'pointer', marginTop: 12, fontSize: 13 }} onClick={onBack}>返回登录</button>
      </div>
    </div>
  );
}

function RecoverPage({ onBack, onLogin }) {
  const [babyName, setBabyName] = useState('');
  const [p1, setP1] = useState('');
  const [p2, setP2] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [result, setResult] = useState(null);

  async function submit() {
    setLoading(true);
    setError('');
    try {
      const res = await fetch(`${API}/recover`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ babyName: babyName.trim(), parent1Name: p1.trim(), parent2Name: p2.trim() }),
      });
      const data = await res.json();
      if (data.error) { setError(data.error); }
      else { setResult(data); }
    } catch (e) {
      setError('找回失败了，再试一次？');
    }
    setLoading(false);
  }

  function quickLogin(t) {
    localStorage.setItem('xz_token', t);
    onLogin();
  }

  if (result) return (
    <div className="login-page">
      <div className="login-card" style={{ maxWidth: 400 }}>
        <h1>找到了！</h1>
        <p style={{ color: '#f44336', fontSize: 13, fontWeight: 'bold', marginBottom: 16 }}>请截图保存以下 token，下次登录需要用到！</p>
        <div style={{ background: '#FFFDF9', border: '1px solid #EEDFCC', borderRadius: 12, padding: 16, marginBottom: 16, textAlign: 'left' }}>
          <div style={{ fontSize: 13, color: '#6E5A4B', marginBottom: 12 }}>
            <b>{result.parent1.name}</b> 的 token：
            <div style={{ background: '#FDF6EE', padding: '8px 10px', borderRadius: 8, marginTop: 4, fontSize: 11, wordBreak: 'break-all', fontFamily: 'monospace', userSelect: 'all' }}>{result.parent1.token}</div>
          </div>
          <div style={{ fontSize: 13, color: '#6E5A4B', marginBottom: 12 }}>
            <b>{result.parent2.name}</b> 的 token：
            <div style={{ background: '#FDF6EE', padding: '8px 10px', borderRadius: 8, marginTop: 4, fontSize: 11, wordBreak: 'break-all', fontFamily: 'monospace', userSelect: 'all' }}>{result.parent2.token}</div>
          </div>
          {/* MCP 地址在找回页原本是缺的：域名(baobao)跟前端(baby)不是一个，用户拿到 token 也拼不出来。
              后端 /recover 同步补了 mcpUrl；这里对老响应做兜底，没有该字段时用 token 现拼。 */}
          <div style={{ fontSize: 13, color: '#6E5A4B', marginBottom: 12 }}>
            <b>{result.parent1.name}</b> 的 MCP 地址：
            <div style={{ background: '#FDF6EE', padding: '8px 10px', borderRadius: 8, marginTop: 4, fontSize: 11, wordBreak: 'break-all', fontFamily: 'monospace', userSelect: 'all' }}>{result.parent1.mcpUrl || `https://baobao.animalab-kora.com/mcp/${result.parent1.token}`}</div>
          </div>
          <div style={{ fontSize: 13, color: '#6E5A4B', marginBottom: 12 }}>
            <b>{result.parent2.name}</b> 的 MCP 地址：
            <div style={{ background: '#FDF6EE', padding: '8px 10px', borderRadius: 8, marginTop: 4, fontSize: 11, wordBreak: 'break-all', fontFamily: 'monospace', userSelect: 'all' }}>{result.parent2.mcpUrl || `https://baobao.animalab-kora.com/mcp/${result.parent2.token}`}</div>
          </div>
          <div style={{ fontSize: 11, color: '#A08D7D', lineHeight: 1.6 }}>
            把 MCP 地址填到你的 AI 客户端里，AI 就能照顾宝宝了~
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="login-submit" style={{ flex: 1, background: 'linear-gradient(135deg, #D79B6D, #b8845a)' }}
            onClick={() => quickLogin(result.parent1.token)}>以{result.parent1.name}身份进入</button>
          <button className="login-submit" style={{ flex: 1, background: 'linear-gradient(135deg, #90caf9, #42a5f5)' }}
            onClick={() => quickLogin(result.parent2.token)}>以{result.parent2.name}身份进入</button>
        </div>
      </div>
    </div>
  );

  return (
    <div className="login-page">
      <div className="login-card">
        <h1>找回宝宝</h1>
        <p style={{ color: '#A08D7D', fontSize: 13, marginBottom: 16 }}>输入领养时填的信息来找回（宝宝会用这些称呼叫你哦）</p>
        <input className="login-input" value={babyName} onChange={e => setBabyName(e.target.value)} placeholder="宝宝的名字（领养时取的）" style={{ marginBottom: 8 }} />
        <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
          <input className="login-input" style={{ flex: 1 }} value={p1} onChange={e => setP1(e.target.value)} placeholder="家长1的称呼（如爸爸）" maxLength={10} />
          <input className="login-input" style={{ flex: 1 }} value={p2} onChange={e => setP2(e.target.value)} placeholder="家长2的称呼（如妈妈）" maxLength={10} />
        </div>
        <button className="login-submit" style={{ background: 'linear-gradient(135deg, #f0c27f, #d4a05a)' }} onClick={submit} disabled={loading || !babyName.trim() || !p1.trim() || !p2.trim()}>
          {loading ? '查找中……' : '找回宝宝'}
        </button>
        {error && <div style={{ color: '#f44336', fontSize: 13, marginTop: 8 }}>{error}</div>}
        <button style={{ background: 'none', border: 'none', color: '#A08D7D', cursor: 'pointer', marginTop: 12, fontSize: 13 }} onClick={onBack}>返回登录</button>
      </div>
    </div>
  );
}

