/* Chameleon Space — sections C: how it works, apply form. */
const CSC = window.ChameleonSpaceDesignSystem_1abbe1;
const { Button: BtnC, Card: CardC, Eyebrow: EyebrowC, Input, Textarea, Checkbox, Banner } = CSC;

/* ---------- HOW IT WORKS ---------- */
const STEPS = [
  { n: "01", title: "Tell us about you.", body: "A short note: who you are, what you are working on, and why this space. That is the whole application." },
  { n: "02", title: "Come share a coffee.", body: "We read every word, then invite the people who fit for a tour and a real conversation. Come exactly as you are." },
  { n: "03", title: "Pick your start date.", body: "If it is a match, you are in, and the space is yours. Welcome home." },
];
function HowItWorks() {
  return (
    <section id="how" style={{ padding: "clamp(56px,8vw,96px) clamp(16px,4vw,36px)", background: "var(--paper-2)", borderTop: "3px solid var(--ink)" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto" }}>
        <SectionHead kicker="How it works" title="Three steps. No pitch deck, no blazer." note="// easy" max={760} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 26, marginTop: 48 }} className="cs-steps">
          {STEPS.map((s, i) => (
            <Reveal key={s.n} delay={i * 90}>
              <div style={{ position: "relative" }}>
                <div style={{ fontFamily: "var(--font-display)", fontSize: "clamp(60px,8vw,104px)", lineHeight: .8, color: "var(--ink)", marginBottom: 12 }}>{s.n}</div>
                <h3 style={{ fontFamily: "var(--font-display)", textTransform: "uppercase", fontSize: 26, lineHeight: .98, margin: "0 0 12px" }}>{s.title}</h3>
                <p style={{ fontFamily: "var(--font-text)", fontSize: 15, lineHeight: 1.6, color: "#3a362e", margin: 0, maxWidth: 320 }}>{s.body}</p>
              </div>
            </Reveal>
          ))}
        </div>
        <Reveal delay={120}>
          <div style={{ marginTop: 44, display: "inline-flex", alignItems: "center", gap: 12, background: "var(--ink)", color: "var(--paper)", padding: "12px 20px", borderRadius: 999, fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 13, letterSpacing: ".04em", boxShadow: "4px 4px 0 var(--accent)", transform: "rotate(-1deg)" }}>
            <i className="ph-fill ph-heart" style={{ color: "var(--accent)", fontSize: 16 }} />
            We read every single one. Promise.
          </div>
        </Reveal>
      </div>
      <style>{`@media (max-width: 860px){ .cs-steps{ grid-template-columns: 1fr !important; } }`}</style>
    </section>
  );
}

/* ---------- APPLY ---------- */
const APPLY_ENDPOINT = "/api/apply";

function Apply() {
  const [sent, setSent] = React.useState(false);
  const [first, setFirst] = React.useState("");
  const [schol, setSchol] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState("");
  const started = React.useRef(false);

  const onFirstFocus = () => {
    if (started.current) return;
    started.current = true;
    (window.dataLayer = window.dataLayer || []).push({ event: "application_start", form_id: "membership_apply" });
  };

  const submit = async (e) => {
    e.preventDefault();
    if (sending) return;
    const form = e.target;
    const fd = new FormData(form);
    const payload = {
      first_name: fd.get("first_name") || "",
      last_name: fd.get("last_name") || "",
      email: fd.get("email") || "",
      linkedin: fd.get("linkedin") || "",
      portfolio: fd.get("portfolio") || "",
      working_on: fd.get("working_on") || "",
      why_now: fd.get("why_now") || "",
      collaborators: fd.get("collaborators") || "",
      contribution: fd.get("contribution") || "",
      scholarship: fd.get("scholarship") === "on",
      scholarship_project: fd.get("scholarship_project") || "",
      cs_hp: fd.get("cs_hp") || "", // honeypot
    };

    // Client-side validation (the design-system Input only draws the "*", it
    // doesn't enforce native `required`, so we check here for inline feedback).
    const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(payload.email);
    const checks = [
      [!payload.first_name, "Please enter your first name.", "first_name"],
      [!payload.last_name, "Please enter your last name.", "last_name"],
      [!emailOk, "Please enter a valid email.", "email"],
      [!payload.linkedin, "Please add your LinkedIn.", "linkedin"],
    ];
    const problem = checks.find(([bad]) => bad);
    if (problem) {
      setError(problem[1]);
      const el = form.querySelector(`[name="${problem[2]}"]`);
      if (el) el.focus();
      return;
    }

    setError("");
    setSending(true);
    try {
      const res = await fetch(APPLY_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || "Something went wrong on our end.");

      // Conversion event for Google Tag Manager. No PII — just the signal,
      // whether a scholarship was requested, and the application id (for dedup).
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({
        event: "application_submitted",
        form_id: "membership_apply",
        scholarship_requested: payload.scholarship,
        application_id: data.id || undefined,
      });

      setSent(true);
      window.requestAnimationFrame(() => {
        const el = document.getElementById("apply-confirm");
        if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
      });
    } catch (err) {
      setError(
        (err && err.message) ||
          "We couldn't send that just now. Try again, or email us at hello@chameleon.space."
      );
    } finally {
      setSending(false);
    }
  };

  return (
    <section id="apply" style={{ padding: "clamp(56px,8vw,100px) clamp(16px,4vw,36px)" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto", display: "grid", gridTemplateColumns: ".85fr 1.15fr", gap: 56, alignItems: "start" }} className="cs-apply">
        <div style={{ position: "sticky", top: 90 }} className="cs-apply-intro">
          <Reveal><EyebrowC>Apply</EyebrowC></Reveal>
          <Reveal delay={60}>
            <h2 style={{ fontFamily: "var(--font-display)", textTransform: "uppercase", fontSize: "clamp(36px,5vw,64px)", lineHeight: .9, letterSpacing: "-.02em", margin: "14px 0 0", textWrap: "balance" }}>
              Knock, and tell us who you are.
            </h2>
          </Reveal>
          <Reveal delay={120}>
            <p style={{ fontFamily: "var(--font-text)", fontSize: "clamp(16px,1.4vw,19px)", lineHeight: 1.6, color: "#332f28", margin: "22px 0 0", maxWidth: 420 }}>
              Every member comes in through this little form. Write us a few honest lines. We read every one and answer within a week, often with an invitation to come see the place.
            </p>
          </Reveal>
        </div>

        <Reveal delay={80}>
          <CardC style={{ padding: "clamp(24px,3vw,40px)" }}>
            {sent ? (
              <div id="apply-confirm">
                <Banner tone="ok" title={"Got it" + (first ? ", " + first : "") + "."}>
                  We are glad you knocked. Give us about a week and watch your inbox for an invitation to come see the place.
                </Banner>
                <div style={{ marginTop: 24, display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
                  <BtnC variant="outline" onClick={() => { setSent(false); setSchol(false); setFirst(""); setError(""); }}>Send another</BtnC>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-dim)", letterSpacing: ".04em" }}>// we read every single one</span>
                </div>
              </div>
            ) : (
              <form onSubmit={submit} onFocus={onFirstFocus} style={{ display: "grid", gap: 20 }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }} className="cs-name-row">
                  <Input name="first_name" label="First name" placeholder="Your first name" required value={first} onChange={(e) => setFirst(e.target.value)} />
                  <Input name="last_name" label="Last name" placeholder="Your last name" required />
                </div>
                <Input name="email" label="Email" type="email" placeholder="Where we’ll send the good news" required />
                <Input name="linkedin" label="LinkedIn" placeholder="linkedin.com/in/your-name" required hint="So we can get to know you a little before we meet." />
                <Input name="portfolio" label="Portfolio or website" placeholder="yoursite.com (optional)" hint="A site, shop, reel, or anything that shows your work. Optional." />
                <Textarea name="working_on" label="What you’re working on" rows={3} placeholder="A project, a passion, a dream with nowhere to live yet. What brings you in?" />
                <Textarea name="why_now" label="Why this space, why now" rows={3} placeholder="What are you hoping to find here?" />
                <Textarea name="collaborators" label="Who you’d like to collaborate with" rows={2} placeholder="Who would make your perfect table? Founders, painters, tinkerers, a glorious mix?" hint="What kind of community members are you interested in working alongside." />
                <Input name="contribution" label="What you’d bring to the community" placeholder="A skill to share, a night to host, a good laugh on a slow Tuesday." />

                {/* Honeypot — hidden from humans, catches bots. Named so browser
                    autofill / password managers won't fill it (which would drop
                    a real submission). data-*ignore tells 1Password/LastPass to skip. */}
                <div aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: 1, height: 1, overflow: "hidden" }}>
                  <input type="text" name="cs_hp" tabIndex={-1} autoComplete="off" data-1p-ignore="true" data-lpignore="true" data-form-type="other" />
                </div>

                <div style={{ background: "var(--paper-2)", border: "2px solid var(--ink)", borderRadius: "var(--radius-2)", padding: "18px 18px" }}>
                  <Checkbox name="scholarship" label="Put me in the running for a scholarship" checked={schol} onChange={(e) => setSchol(e.target.checked)} />
                  <p style={{ fontFamily: "var(--font-text)", fontSize: 13, lineHeight: 1.5, color: "var(--text-dim)", margin: "8px 0 0 30px" }}>
                    We give only a few free scholarships each season. If you’d like to be in the running, check the box and tell us about the project.
                  </p>
                  {schol ? (
                    <div style={{ marginTop: 14 }}>
                      <Textarea name="scholarship_project" label="About the project" rows={2} placeholder="The novel, the prototype, the nonprofit, the album \u2014 what would the time go toward?" />
                    </div>
                  ) : null}
                </div>

                {error ? (
                  <div style={{ background: "var(--paper-2)", border: "2px solid #b00020", borderRadius: "var(--radius-2)", padding: "12px 14px", fontFamily: "var(--font-text)", fontSize: 14, lineHeight: 1.5, color: "#b00020" }}>
                    {error}
                  </div>
                ) : null}

                <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap", marginTop: 4 }}>
                  <BtnC type="submit" size="lg" disabled={sending}>{sending ? "Sending…" : "Send it our way"}</BtnC>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-dim)", letterSpacing: ".04em" }}>// answered within a week</span>
                </div>
              </form>
            )}
          </CardC>
        </Reveal>
      </div>
      <style>{`
        @media (max-width: 860px){
          .cs-apply{ grid-template-columns: 1fr !important; gap: 32px !important; }
          .cs-apply-intro{ position: static !important; }
        }
        @media (max-width: 520px){ .cs-name-row{ grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

Object.assign(window, { HowItWorks, Apply });
