// Launch-waitlist email capture. Self-contained (inline styles + site CSS vars),
// uses React.useState directly (matching the other component files; only app.jsx
// destructures hooks). POSTs to /api/subscribe → Vercel KV. Render <Signup /> in
// the footer/landing. Idempotent on the server (SADD), so re-submits are safe.
function Signup() {
  const [email, setEmail] = React.useState("");
  const [state, setState] = React.useState("idle"); // idle | loading | ok | already | error

  async function submit(e) {
    e.preventDefault();
    if (!email || state === "loading") return;
    setState("loading");
    try {
      const r = await fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email.trim() }),
      });
      const j = await r.json().catch(() => ({}));
      setState(r.ok && j.ok ? (j.status === "already" ? "already" : "ok") : "error");
    } catch (_) { setState("error"); }
  }

  const wrap = { maxWidth: 420, margin: "0 auto", textAlign: "center", fontFamily: "var(--sans)" };
  const label = { fontFamily: "var(--serif)", fontSize: 20, marginBottom: 10, color: "var(--ink)" };
  const row = { display: "flex", gap: 8, justifyContent: "center", flexWrap: "wrap" };
  const input = {
    flex: "1 1 220px", minWidth: 0, padding: "10px 12px", fontSize: 14, fontFamily: "var(--sans)",
    border: "1px solid var(--line, rgba(127,127,127,.35))", borderRadius: 8,
    background: "var(--card, transparent)", color: "var(--ink)",
  };
  const btn = {
    padding: "10px 16px", fontSize: 14, fontWeight: 600, border: "none", borderRadius: 8,
    background: "var(--accent)", color: "#fff", cursor: state === "loading" ? "default" : "pointer",
    opacity: state === "loading" ? 0.7 : 1,
  };
  const fine = { fontSize: 12, color: "var(--muted, #8a8f98)", marginTop: 8 };

  if (state === "ok" || state === "already") {
    return (
      <div style={{ ...wrap, color: "var(--ink)" }}>
        <div style={label}>✓ {state === "already" ? "You're already on the list." : "You're on the list."}</div>
        <div style={fine}>We'll email you when theclaudetrader launches.</div>
      </div>
    );
  }
  return (
    <form style={wrap} onSubmit={submit}>
      <div style={label}>Get launch updates</div>
      <div style={row}>
        <input type="email" required placeholder="you@email.com" value={email}
          disabled={state === "loading"} aria-label="Email address"
          onChange={(e) => setEmail(e.target.value)} style={input} />
        <button type="submit" disabled={state === "loading"} style={btn}>
          {state === "loading" ? "…" : "Notify me"}
        </button>
      </div>
      {state === "error" && (
        <div style={{ ...fine, color: "var(--neg, #b3462d)" }}>Something went wrong — please try again.</div>
      )}
      <div style={fine}>No spam — launch &amp; major milestones only.</div>
    </form>
  );
}
