/* apply-page.jsx — /apply: SDK-access application.
   Centered CTA hero; "Apply now" reveals + scrolls to the form. Stacks cleanly on mobile.
   Reuses Nav, Footer, Reveal, and the BP_* design tokens (loaded before this script). */

const APPLY_GENRES = [
  "Markets & Trading",
  "Payments & Money",
  "Infrastructure",
  "Social & Communications",
  "Gaming",
];

const APPLY_INPUT = {
  width: "100%", background: "rgba(255,255,255,0.025)", border: "1px solid var(--line)",
  borderRadius: 8, padding: "13px 15px", color: "var(--text)", fontFamily: "var(--body)",
  fontSize: 15, outline: "none", boxSizing: "border-box",
};

function ApplyField({ label, optional, children }) {
  return (
    <label style={{ display: "block", textAlign: "left" }}>
      <span style={{ display: "block", fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.1em",
        textTransform: "uppercase", color: "var(--faint)", marginBottom: 8 }}>
        {label}{optional ? <span style={{ opacity: 0.55 }}> · optional</span> : null}
      </span>
      {children}
    </label>
  );
}

function ApplyPage() {
  const [name, setName] = React.useState("");
  const [contact, setContact] = React.useState("");
  const [build, setBuild] = React.useState("");
  const [genres, setGenres] = React.useState([]);
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [error, setError] = React.useState(null);
  const [showForm, setShowForm] = React.useState(false);
  const formRef = React.useRef(null);

  const toggleGenre = (g) =>
    setGenres((cur) => (cur.includes(g) ? cur.filter((x) => x !== g) : [...cur, g]));

  function openForm() {
    setShowForm(true);
    requestAnimationFrame(() => {
      setTimeout(() => { if (formRef.current) formRef.current.scrollIntoView({ behavior: "smooth", block: "start" }); }, 70);
    });
  }

  async function onSubmit(e) {
    e.preventDefault();
    if (!contact.trim() || !build.trim() || status === "sending") return;
    setStatus("sending");
    setError(null);
    try {
      const message = build.trim() + (genres.length ? "\n\nSpaces of interest: " + genres.join(", ") : "");
      const res = await fetch("/rfp/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, contact, idea: "SDK access", message }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || "Something went wrong.");
      }
      setStatus("sent");
    } catch (err) {
      setStatus("error");
      setError(err && err.message ? err.message : "Something went wrong.");
    }
  }

  return (
    <React.Fragment>
      <Nav />

      {/* ── centered CTA hero ── */}
      <section style={{ position: "relative", minHeight: "100vh", display: "flex", flexDirection: "column",
        justifyContent: "center", alignItems: "center", textAlign: "center",
        padding: "clamp(120px,16vh,180px) clamp(20px,5vw,40px) clamp(60px,9vh,100px)" }}>
        <div style={{ position: "absolute", inset: 0, zIndex: 0,
          background: "radial-gradient(ellipse 60% 50% at 50% 42%, rgba(197,52,0,0.10), transparent 62%)" }} />
        <div style={{ position: "relative", zIndex: 1, width: "100%", maxWidth: 780,
          display: "flex", flexDirection: "column", alignItems: "center" }}>
          <Reveal><div style={{ ...BP_EYE, justifyContent: "center" }}>{BP_DASH} Apply</div></Reveal>
          <Reveal delay={0.05}>
            <h1 style={{ ...BP_H, marginTop: 20, fontSize: "clamp(32px,5vw,62px)", maxWidth: "15ch", marginInline: "auto" }}>
              Want to plug privacy into your app?
            </h1>
          </Reveal>
          <Reveal delay={0.1}>
            <p style={{ marginTop: 24, fontFamily: "var(--body)", fontSize: "clamp(15px,1.2vw,18px)",
              lineHeight: 1.7, color: "var(--dim)", maxWidth: 560, marginInline: "auto" }}>
              Hey &mdash; we&rsquo;re genuinely happy you&rsquo;re building a startup on top of STRK20.
              That&rsquo;s exactly what we&rsquo;re here for. The SDK is yours: tell us what you&rsquo;re
              making and we&rsquo;ll get you access. No gatekeeping, no long review.
            </p>
          </Reveal>
          <Reveal delay={0.16}>
            <div style={{ marginTop: 38, display: "flex", flexWrap: "wrap", gap: 16, justifyContent: "center" }}>
              <button type="button" onClick={openForm} className="btn btn-orange"
                style={{ padding: "13px 30px", fontSize: 14 }}>Apply now</button>
              <a href="https://cal.com/adithyadinesh" target="_blank" rel="noreferrer" className="apply-callbtn"
                style={{ display: "inline-flex", alignItems: "center", gap: 9, border: "1px solid var(--line)",
                  borderRadius: 8, padding: "13px 24px", fontFamily: "var(--mono)", fontSize: 13,
                  letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text)",
                  transition: "border-color .2s, background .2s, box-shadow .2s" }}>
                <span style={{ color: "var(--green)", fontSize: 14 }}>✦</span> Book a call <span className="arrow">&rarr;</span>
              </a>
            </div>
          </Reveal>
          {!showForm ? (
            <Reveal delay={0.22}>
              <button type="button" onClick={openForm} aria-label="Scroll to form"
                style={{ marginTop: 46, background: "none", border: "none", cursor: "pointer", color: "var(--faint)",
                  fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
                  display: "inline-flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
                or fill the form <span style={{ fontSize: 14 }}>↓</span>
              </button>
            </Reveal>
          ) : null}
        </div>
      </section>

      {/* ── form (revealed on "Apply now") ── */}
      {showForm ? (
        <section ref={formRef} style={{ borderTop: "1px solid var(--line)",
          padding: "clamp(64px,10vh,120px) clamp(20px,5vw,40px)" }}>
          <div style={{ maxWidth: 620, marginInline: "auto", width: "100%" }}>
            {status === "sent" ? (
              <Reveal>
                <div style={{ textAlign: "center" }}>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 800, textTransform: "uppercase",
                    letterSpacing: "-0.01em", fontSize: "clamp(26px,3.4vw,40px)", color: "var(--text)" }}>You&rsquo;re in.</div>
                  <p style={{ marginTop: 16, fontFamily: "var(--body)", fontSize: 16, lineHeight: 1.65,
                    color: "var(--dim)", maxWidth: 460, marginInline: "auto" }}>
                    Thanks for reaching out{name.trim() ? ", " + name.trim() : ""} &mdash; we&rsquo;ll be in touch
                    shortly with SDK access and anything you need to start building.
                  </p>
                  <a href="https://cal.com/adithyadinesh" target="_blank" rel="noreferrer" className="btn btn-orange"
                    style={{ marginTop: 26, display: "inline-flex" }}>Book a call &rarr;</a>
                </div>
              </Reveal>
            ) : (
              <Reveal>
                <h2 style={{ ...BP_H, fontSize: "clamp(24px,3vw,38px)", textAlign: "center" }}>Tell us what you&rsquo;re building</h2>
                <form onSubmit={onSubmit} style={{ marginTop: 34 }}>
                  <div className="mono-label" style={{ fontSize: 10, color: "var(--faint)", marginBottom: 13, textAlign: "center" }}>
                    Not sure where to start? Pick a space &mdash; optional
                  </div>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 9, marginBottom: 30, justifyContent: "center" }}>
                    {APPLY_GENRES.map((g) => {
                      const on = genres.includes(g);
                      return (
                        <button key={g} type="button" onClick={() => toggleGenre(g)} className="apply-chip"
                          style={{ fontFamily: "var(--mono)", fontSize: 12, letterSpacing: "0.02em",
                            padding: "8px 14px", borderRadius: 999, cursor: "pointer",
                            border: on ? "1px solid var(--green)" : "1px solid var(--line)",
                            background: on ? "rgba(197,52,0,0.14)" : "transparent",
                            color: on ? "var(--text)" : "var(--dim)", transition: "border-color .18s, background .18s, color .18s" }}>
                          {on ? "✦ " : ""}{g}
                        </button>
                      );
                    })}
                  </div>

                  <div style={{ display: "grid", gap: 16 }}>
                    <ApplyField label="Your name" optional>
                      <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Satoshi" style={APPLY_INPUT} />
                    </ApplyField>
                    <ApplyField label="How can we reach you?">
                      <input value={contact} onChange={(e) => setContact(e.target.value)}
                        placeholder="Telegram / email / X" style={APPLY_INPUT} />
                    </ApplyField>
                    <ApplyField label="What are you building?">
                      <textarea value={build} onChange={(e) => setBuild(e.target.value)} rows={4}
                        placeholder="A private payroll app, a shielded DEX, an anonymous tipping bot…"
                        style={{ ...APPLY_INPUT, resize: "vertical", minHeight: 104, lineHeight: 1.5 }} />
                    </ApplyField>
                  </div>

                  {status === "error" ? (
                    <div style={{ marginTop: 14, fontFamily: "var(--mono)", fontSize: 12.5, color: "var(--green)", textAlign: "center" }}>{error}</div>
                  ) : null}

                  <button type="submit" disabled={status === "sending"} className="btn btn-orange"
                    style={{ marginTop: 26, width: "100%", justifyContent: "center",
                      opacity: status === "sending" ? 0.6 : 1, cursor: status === "sending" ? "default" : "pointer" }}>
                    {status === "sending" ? "Sending…" : "Apply now"}
                  </button>
                </form>
              </Reveal>
            )}
          </div>
        </section>
      ) : null}

      <Footer />
      <style>{`
        .apply-chip:hover{border-color:var(--green)!important;color:var(--text)!important;}
        .apply-callbtn:hover{border-color:var(--green)!important;background:rgba(197,52,0,0.08);box-shadow:0 0 26px -6px var(--green-glow);}
        .apply-callbtn:hover .arrow{transform:translateX(3px);}
        .apply-callbtn .arrow{display:inline-block;transition:transform .2s;}
      `}</style>
    </React.Fragment>
  );
}

window.ApplyPage = ApplyPage;
