/* global React, TOKENS, FONTS, Icon, hexA, AppleGlyph */
// Eighty4 · TestFlight email-capture modal. Opens on any primary "Join the TestFlight" CTA.

function JoinModal() {
  const T = TOKENS;
  const [open, setOpen] = React.useState(false);
  const [email, setEmail] = React.useState("");
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState("");
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const onOpen = () => { setSent(false); setError(""); setOpen(true); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("eighty4-join", onOpen);
    window.addEventListener("keydown", onKey);
    return () => { window.removeEventListener("eighty4-join", onOpen); window.removeEventListener("keydown", onKey); };
  }, []);

  React.useEffect(() => {
    if (open && !sent) { const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 60); return () => clearTimeout(t); }
  }, [open, sent]);

  if (!open) return null;
  const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const submit = async (e) => {
    e.preventDefault();
    setError("");
    if (!valid || sending) return;

    setSending(true);
    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email.trim(), source: "TestFlight join modal" }),
      });

      if (!response.ok) {
        throw new Error("Invite request failed.");
      }

      setSent(true);
    } catch (error) {
      setError("Something went wrong. Email hello@eighty4.app and I'll add you.");
    } finally {
      setSending(false);
    }
  };

  return (
    <div
      onMouseDown={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position: "fixed", inset: 0, zIndex: 2000, display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
        background: hexA(T.ink, 0.42), backdropFilter: "blur(4px)",
        animation: "e4fade 180ms cubic-bezier(.32,.72,0,1)",
      }}>
      <style>{`@keyframes e4fade{from{opacity:0}to{opacity:1}}@keyframes e4pop{from{opacity:0;transform:translateY(10px) scale(.98)}to{opacity:1;transform:none}}`}</style>
      <div style={{
        position: "relative", width: "100%", maxWidth: 440, background: T.card, borderRadius: T.rXl,
        border: `1px solid ${T.hair}`, boxShadow: T.shadowLg, padding: "32px 30px 28px", fontFamily: FONTS.sans,
        animation: "e4pop 220ms cubic-bezier(.32,.72,0,1)",
      }}>
        <button onClick={() => setOpen(false)} aria-label="Close" style={{
          position: "absolute", top: 16, right: 16, width: 30, height: 30, borderRadius: 999, border: "none",
          background: T.input, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <Icon name="close" size={14} color={T.textDim} />
        </button>

        {!sent ? (
          <React.Fragment>
            <div style={{ display: "inline-flex", width: 46, height: 46, borderRadius: T.rMd, background: T.accentSoft, alignItems: "center", justifyContent: "center", marginBottom: 18 }}>
              <AppleGlyph size={20} color={T.accent} />
            </div>
            <h3 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: -0.6, color: T.ink }}>Try Eighty4 on TestFlight</h3>
            <p style={{ margin: "10px 0 0", fontSize: 15, lineHeight: 1.55, color: T.textDim }}>
              Drop your email and we'll send you a TestFlight invite if you'd like to try it. No list, no spam, just the invite.
            </p>
            <form onSubmit={submit} style={{ marginTop: 20 }}>
              <input
                ref={inputRef} type="email" inputMode="email" autoComplete="email" placeholder="you@email.com"
                value={email} onChange={(e) => { setEmail(e.target.value); setError(""); }}
                disabled={sending}
                style={{
                  width: "100%", height: 48, padding: "0 15px", fontSize: 15, fontFamily: FONTS.sans, color: T.ink,
                  background: T.bg, border: `1px solid ${T.hairStrong}`, borderRadius: T.rMd, outline: "none", boxSizing: "border-box",
                }}
                onFocus={(e) => (e.target.style.borderColor = T.accent)}
                onBlur={(e) => (e.target.style.borderColor = T.hairStrong)}
              />
              <button type="submit" disabled={!valid || sending} style={{
                width: "100%", height: 48, marginTop: 12, border: "none", borderRadius: T.rMd, cursor: valid && !sending ? "pointer" : "not-allowed",
                background: T.accent, color: "#fff", fontSize: 15, fontWeight: 600, fontFamily: FONTS.sans,
                opacity: valid && !sending ? 1 : 0.5, boxShadow: valid ? `0 1px 2px ${hexA(T.accent, 0.4)}, inset 0 1px 0 rgba(255,255,255,0.18)` : "none",
                display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
              }}>
                <AppleGlyph size={16} color="#fff" /> {sending ? "Sending..." : "Request my invite"}
              </button>
            </form>
            {error && <p style={{ margin: "10px 0 0", fontSize: 12.5, color: "#8A2D2D", textAlign: "center", lineHeight: 1.45 }}>{error}</p>}
            <p style={{ margin: "14px 0 0", fontSize: 12.5, color: T.textMuted, textAlign: "center", lineHeight: 1.5 }}>
              Free during the beta · iOS 18 & macOS 15 · no AI, ever
            </p>
          </React.Fragment>
        ) : (
          <div style={{ textAlign: "center", padding: "8px 0 4px" }}>
            <div style={{ display: "inline-flex", width: 56, height: 56, borderRadius: 999, background: T.accent, alignItems: "center", justifyContent: "center", marginBottom: 18, boxShadow: `0 8px 22px -6px ${hexA(T.accent, 0.6)}` }}>
              <Icon name="habits" size={26} color="#fff" strokeWidth={2.4} />
            </div>
            <h3 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: -0.6, color: T.ink }}>You're on the list.</h3>
            <p style={{ margin: "10px auto 0", fontSize: 15, lineHeight: 1.55, color: T.textDim, maxWidth: 320 }}>
              Watch <strong style={{ color: T.ink, fontWeight: 600 }}>{email.trim()}</strong> for a TestFlight invite. It lands as soon as the next round opens up.
            </p>
            <button onClick={() => setOpen(false)} style={{
              marginTop: 22, height: 44, padding: "0 22px", border: `1px solid ${T.hairStrong}`, borderRadius: T.rMd,
              background: T.bg, color: T.ink, fontSize: 14.5, fontWeight: 600, fontFamily: FONTS.sans, cursor: "pointer",
            }}>Done</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { JoinModal });
