// register.jsx — Everest new account registration

function RegisterForm({ onLogin, onBack }) {
  const [step, setStep] = React.useState("register"); // "register" | "totp"
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState(null);
  const [totpData, setTotpData] = React.useState(null); // {token, totp_secret, totp_qr}
  const [code, setCode] = React.useState("");
  const [loading, setLoading] = React.useState(false);

  async function handleRegister(e) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch("/api/v1/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, email, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || "Registration failed");
      setTotpData(data);
      setStep("totp");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  async function handleTotp(e) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch("/api/v1/auth/verify-totp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token: totpData.token, code }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || "Invalid code");
      onLogin();
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  if (step === "totp") {
    return (
      <div style={LS.overlay}>
        <div style={LS.card}>
          <div style={LS.logo}>
            <span style={LS.logoMark}>&#9650;</span>
            <span style={LS.logoText}>Everest</span>
          </div>
          <p style={LS.subtitle}>Set up authenticator</p>
          <p style={LS.hint}>Scan this QR code with your authenticator app</p>
          {totpData?.totp_qr && (
            <img
              src={totpData.totp_qr}
              alt="TOTP QR"
              style={{ display: "block", margin: "0 auto 1rem", width: 180, height: 180, borderRadius: "6px", background: "#fff", padding: "6px" }}
            />
          )}
          {totpData?.totp_secret && (
            <div style={LS.secretBox}>
              <span style={LS.secretLabel}>Manual key</span>
              <code style={LS.secret}>{totpData.totp_secret}</code>
            </div>
          )}
          <form onSubmit={handleTotp}>
            <input
              style={{ ...LS.input, letterSpacing: "0.25em", textAlign: "center", fontSize: "1.5rem" }}
              type="text"
              inputMode="numeric"
              placeholder="6-digit code"
              value={code}
              onChange={e => setCode(e.target.value.replace(/\D/g, ""))}
              autoFocus
              maxLength={6}
              required
            />
            {error && <p style={LS.error}>{error}</p>}
            <button style={LS.btn} type="submit" disabled={loading || code.length !== 6}>
              {loading ? "Verifying…" : "Activate"}
            </button>
          </form>
        </div>
      </div>
    );
  }

  return (
    <div style={LS.overlay}>
      <div style={LS.card}>
        <div style={LS.logo}>
          <span style={LS.logoMark}>&#9650;</span>
          <span style={LS.logoText}>Everest</span>
        </div>
        <p style={LS.subtitle}>Create account</p>
        <p style={LS.hint}>Mission Control — new expedition member</p>
        <form onSubmit={handleRegister}>
          <label style={LS.label}>Name</label>
          <input
            style={LS.input}
            type="text"
            placeholder="Your name"
            value={name}
            onChange={e => setName(e.target.value)}
            required
            autoFocus
          />
          <label style={LS.label}>Email</label>
          <input
            style={LS.input}
            type="email"
            placeholder="Email"
            value={email}
            onChange={e => setEmail(e.target.value)}
            required
          />
          <label style={LS.label}>Password</label>
          <input
            style={LS.input}
            type="password"
            placeholder="Password"
            value={password}
            onChange={e => setPassword(e.target.value)}
            required
          />
          {error && <p style={LS.error}>{error}</p>}
          <button style={LS.btn} type="submit" disabled={loading}>
            {loading ? "Creating…" : "Create account"}
          </button>
        </form>
        <p style={{ margin: "1rem 0 0", textAlign: "center", fontSize: "0.82rem", color: "#888" }}>
          Already have an account?{" "}
          <button style={LS.linkBtn} onClick={onBack}>Sign in</button>
        </p>
      </div>
    </div>
  );
}
