// Phone + password login / registration screen. No separate signup flow —
// the first login with a phone auto-registers a trial account with that
// password. (SMS verification is deferred until an enterprise SMS qualification
// is available; see backend src/routes/auth.js.)
function Auth({ onNav }) {
  const { Button, Input, Field, Checkbox, Alert } = window.TaDesignSystem_e6b037;
  const [phone, setPhone] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [agreed, setAgreed] = React.useState(false);
  const [err, setErr] = React.useState(false);
  const [apiErr, setApiErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [contactOpen, setContactOpen] = React.useState(false);

  const phoneValid = /^1[3-9]\d{9}$/.test(phone);
  const canSubmit = phoneValid && password.length >= 6 && !busy;

  async function handleLogin() {
    if (!agreed) { setErr(true); return; }
    setApiErr(""); setBusy(true);
    try {
      await window.TaAPI.login(phone, password);
      onNav("app");
    } catch (e) {
      setApiErr(e.message || "操作失败，请稍后再试");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={{ minHeight: "100vh", display: "grid", gridTemplateColumns: "1fr 1fr" }} className="ta-auth">
      {/* Brand panel */}
      <div style={{ background: "var(--ink-900)", padding: "48px", display: "flex", flexDirection: "column", justifyContent: "space-between" }} className="ta-auth-aside">
        <a onClick={() => onNav("landing")} style={{ cursor: "pointer" }}><Logo size={28} color="var(--ink-50)" /></a>
        <div>
          <h2 style={{ fontSize: 34, fontWeight: 700, color: "var(--ink-50)", letterSpacing: "-0.02em", lineHeight: 1.2, margin: 0 }}>
            读懂没说<br />出口的话。
          </h2>
          <p style={{ fontSize: 16, color: "var(--ink-300)", lineHeight: 1.7, marginTop: 16, maxWidth: 360 }}>
            Ta说 Ta不说的 它帮你说 · 仅供娱乐参考
          </p>
        </div>
        <p style={{ fontSize: 13, color: "var(--ink-400)", display: "flex", alignItems: "center", gap: 8, margin: 0 }}>
          <Icon name="info" size={16} color="var(--ink-400)" /> 由 Ta说 智能分析引擎驱动 · 仅供娱乐参考
        </p>
      </div>

      {/* Form */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: "48px" }}>
        <div style={{ width: "100%", maxWidth: 380 }}>
          <h1 style={{ fontSize: 26, fontWeight: 700, margin: "0 0 4px" }}>登录 / 注册</h1>
          <p style={{ color: "var(--text-secondary)", fontSize: 15, margin: "0 0 24px" }}>手机号 + 密码，首次登录自动注册</p>

          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Field label="手机号">
              <Input
                inputMode="numeric"
                maxLength={11}
                placeholder="1xxxxxxxxxx"
                value={phone}
                onChange={e => { setPhone(e.target.value.replace(/\D/g, "")); setApiErr(""); }}
                leadingIcon={<Icon name="phone" size={18} />}
              />
            </Field>

            <Field label="密码">
              <Input
                type="password"
                maxLength={64}
                placeholder="至少 6 位"
                value={password}
                onChange={e => { setPassword(e.target.value); setApiErr(""); }}
                onKeyDown={e => { if (e.key === "Enter" && canSubmit && agreed) handleLogin(); }}
                leadingIcon={<Icon name="key" size={18} />}
              />
            </Field>

            <Alert variant="info" title="隐私与免责声明">你上传的内容仅用于本次分析，Ta说 不会保存你的聊天记录。本服务采用合规 AI 技术，分析结果仅供娱乐参考，由此产生的任何后果本平台概不负责。</Alert>

            <Checkbox checked={agreed} onChange={e => { setAgreed(e.target.checked); setErr(false); }}>
              我已阅读并同意 <a href="./legal/terms.html" target="_blank" rel="noopener" onClick={e => e.stopPropagation()} style={{ cursor: "pointer", color: "var(--primary)" }}>《用户协议》</a> 与 <a href="./legal/privacy.html" target="_blank" rel="noopener" onClick={e => e.stopPropagation()} style={{ cursor: "pointer", color: "var(--primary)" }}>《隐私政策》</a>
            </Checkbox>
            {err && <Alert variant="danger">请先阅读并同意条款，再继续。</Alert>}

            {apiErr && <Alert variant="danger">{apiErr}</Alert>}

            <Button variant="primary" size="lg" block disabled={!canSubmit} onClick={handleLogin}>
              {busy ? "请稍候…" : "登录 / 注册"}
            </Button>
          </div>

          <p style={{ textAlign: "center", fontSize: 13, color: "var(--text-tertiary)", marginTop: 20 }}>
            遇到问题？<a onClick={() => setContactOpen(true)} style={{ cursor: "pointer" }}>联系我们</a>
          </p>
        </div>
      </div>

      {window.ContactDialog && <window.ContactDialog open={contactOpen} onClose={() => setContactOpen(false)} />}
    </div>
  );
}
Object.assign(window, { Auth });
