/* Chameleon Space — sections A: hero, mission, vision, values. */
const CSA = window.ChameleonSpaceDesignSystem_1abbe1;
const { Button: BtnA, Badge: BadgeA, Eyebrow: EyebrowA, Card: CardA, Input: InputA } = CSA;

/* ---------- LAUNCH EMAIL CAPTURE (low-friction conversion) ---------- */
function LaunchSignup() {
  const [done, setDone] = 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: "waitlist_start", form_id: "launch_notify" });
  };

  const submit = async (e) => {
    e.preventDefault();
    if (sending) return;
    const fd = new FormData(e.target);
    const first_name = (fd.get("first_name") || "").toString().trim();
    const last_name = (fd.get("last_name") || "").toString().trim();
    const email = (fd.get("email") || "").toString().trim();
    const cs_hp = (fd.get("cs_hp") || "").toString();
    if (!first_name) { setError("Add your first name."); return; }
    if (!last_name) { setError("Add your last name."); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setError("Enter a valid email."); return; }
    setError(""); setSending(true);
    try {
      const res = await fetch("/api/notify", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ first_name, last_name, email, cs_hp }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || "Something went wrong on our end.");
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ event: "waitlist_signup", form_id: "launch_notify" });
      setDone(true);
    } catch (err) {
      setError((err && err.message) || "Couldn’t sign you up just now. Try again.");
    } finally { setSending(false); }
  };

  if (done) {
    return (
      <div style={{ background: "var(--ink)", color: "var(--paper)", border: "3px solid var(--ink)", borderRadius: "var(--radius-2)", boxShadow: "6px 6px 0 var(--accent)", padding: "16px 20px", maxWidth: 520 }}>
        <div style={{ fontFamily: "var(--font-display)", textTransform: "uppercase", fontSize: 22, lineHeight: .95, color: "var(--accent)" }}>You’re on the list.</div>
        <div style={{ fontFamily: "var(--font-text)", fontSize: 14, lineHeight: 1.5, marginTop: 6 }}>We’ll email you the moment we launch — and invite you to come see the space at our first events.</div>
      </div>
    );
  }

  return (
    <form onSubmit={submit} onFocus={onFirstFocus} style={{ maxWidth: 520 }} noValidate>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }} className="cs-notify-row">
        <InputA name="first_name" placeholder="First name" aria-label="First name" autoComplete="given-name" />
        <InputA name="last_name" placeholder="Last name" aria-label="Last name" autoComplete="family-name" />
        <InputA name="email" type="email" placeholder="Email" aria-label="Email" autoComplete="email" />
      </div>
      <div style={{ marginTop: 10 }}>
        <BtnA type="submit" size="lg" disabled={sending}>{sending ? "Sending…" : "Find out when we launch"}</BtnA>
      </div>
      {/* Honeypot */}
      <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" />
      </div>
      {error ? (
        <div style={{ fontFamily: "var(--font-text)", fontSize: 13, color: "#b00020", marginTop: 8 }}>{error}</div>
      ) : null}
      <style>{`@media (max-width: 560px){ .cs-notify-row{ grid-template-columns: 1fr !important; } }`}</style>
    </form>
  );
}

/* ---------- HERO ---------- */
function Hero({ skinName, SkinSwitcher, onApply }) {
  // Hero headline A/B test (50/50, sticky per visitor via localStorage). The
  // chosen variant is pushed to the dataLayer so conversions can be segmented
  // by variant in GA4/GTM. To end the test, hard-code `variant` to the winner.
  const [variant] = React.useState(() => {
    try {
      let v = localStorage.getItem("cs_hero_v");
      if (v !== "A" && v !== "B") { v = Math.random() < 0.5 ? "A" : "B"; localStorage.setItem("cs_hero_v", v); }
      return v;
    } catch (e) { return "A"; }
  });
  React.useEffect(() => {
    (window.dataLayer = window.dataLayer || []).push({ event: "experiment_view", experiment: "hero_headline", variant });
  }, [variant]);
  const hl = { background: "linear-gradient(var(--accent), var(--accent)) no-repeat", backgroundSize: "100% 0.74em", backgroundPosition: "0 0.16em", color: "var(--ink)", padding: "0 .1em", WebkitBoxDecorationBreak: "clone", boxDecorationBreak: "clone" };
  return (
    <section id="top" style={{
      position: "relative", overflow: "hidden",
      padding: "clamp(24px,3.5vw,44px) clamp(16px,4vw,36px) clamp(36px,5vw,60px)",
      background: "repeating-linear-gradient(45deg, var(--paper) 0 22px, var(--paper-2) 22px 23px)"
    }}>
      <div style={{ display: "grid", gridTemplateColumns: "1.25fr .75fr", gap: 48, alignItems: "center", maxWidth: 1180, margin: "0 auto" }} className="cs-hero-grid">
        <div>
          <Reveal><EyebrowA>An intentional members club in Gainesville</EyebrowA></Reveal>
          <Reveal delay={60}>
            <h1 style={{
              fontFamily: "var(--font-display)", textTransform: "uppercase",
              fontSize: "clamp(38px, 5.6vw, 74px)", lineHeight: .92, letterSpacing: "-.02em",
              margin: "14px 0 0", color: "var(--ink)", textWrap: "balance"
            }}>
              {variant === "B" ? (
                <React.Fragment>A coworking club for <span style={hl}>Gainesville’s makers</span>, remote workers, and dreamers.</React.Fragment>
              ) : (
                <React.Fragment>A space that <span style={hl}>changes shape</span> for the people who fill it.</React.Fragment>
              )}
            </h1>
          </Reveal>
          <Reveal delay={120}>
            <p style={{ fontFamily: "var(--font-text)", fontSize: "clamp(16px,1.4vw,19px)", lineHeight: 1.5, maxWidth: 520, margin: "20px 0 22px", color: "#332f28" }}>
              A members club for Gainesville with gig-up, gig-down GRU fiber — where work, making, and good company share one roof.
            </p>
          </Reveal>
          <Reveal delay={180}>
            <div>
              <div style={{ fontFamily: "var(--font-text)", fontWeight: 700, fontSize: 15, lineHeight: 1.45, color: "var(--ink)", marginBottom: 12, maxWidth: 520 }}>
                Founding members are moving in now — and we’re hosting our first events so you can come see the space.
              </div>
              <LaunchSignup />
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 16, flexWrap: "wrap" }}>
                <span style={{ fontFamily: "var(--font-text)", fontSize: 14, color: "#332f28" }}>Ready to commit?</span>
                <BtnA variant="outline" onClick={onApply}>Apply to join →</BtnA>
              </div>
            </div>
          </Reveal>
          <Reveal delay={240}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 34, flexWrap: "wrap" }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".12em", color: "var(--text-dim)" }}>Change our colors →</span>
              <SkinSwitcher value={skinName} />
            </div>
          </Reveal>
        </div>
        <Reveal delay={140} className="cs-hero-art">
          <div style={{ position: "relative" }}>
            <div style={{ background: "var(--accent)", border: "3px solid var(--ink)", borderRadius: "var(--radius-2)", boxShadow: "14px 14px 0 var(--ink)", padding: "34px 30px", transform: "rotate(-1.5deg)" }}>
              <img src="assets/logo/chameleon-mark.png" alt="Chameleon Space" style={{ width: "100%", display: "block" }} />
            </div>
            <div style={{ position: "absolute", bottom: -16, left: -16, transform: "rotate(3deg)" }}>
              <BadgeA tone="ink" square>// Founding members · now</BadgeA>
            </div>
            <div style={{ position: "absolute", top: -14, right: -10, transform: "rotate(-4deg)" }}>
              <BadgeA tone="ok" dot>Opening in phases</BadgeA>
            </div>
          </div>
        </Reveal>
      </div>
      <style>{`@media (max-width: 860px){ .cs-hero-grid{ grid-template-columns: 1fr !important; } .cs-hero-art{ max-width: 360px; } }`}</style>
    </section>
  );
}

/* ---------- MISSION ---------- */
function Mission() {
  return (
    <section id="mission" style={{ padding: "clamp(56px,8vw,96px) clamp(16px,4vw,36px)", maxWidth: 1180, margin: "0 auto" }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 48, alignItems: "start" }} className="cs-two">
        <div>
          <Reveal><EyebrowA>Our mission</EyebrowA></Reveal>
          <Reveal delay={60}>
            <h2 style={{ fontFamily: "var(--font-display)", textTransform: "uppercase", fontSize: "clamp(32px,4.5vw,58px)", lineHeight: .92, letterSpacing: "-.015em", margin: "14px 0 0", color: "var(--ink)", textWrap: "balance" }}>
              A home for your work, and the life around it.
            </h2>
          </Reveal>
        </div>
        <Reveal delay={120}>
          <p style={{ fontFamily: "var(--font-text)", fontSize: "clamp(16px,1.4vw,19px)", lineHeight: 1.6, color: "#332f28", margin: 0 }}>
            Chameleon Space exists to give Gainesville a place to belong while you make the things you care about. Work, making, learning, and plain old gathering, all under one roof, chosen on purpose and tended with care.
            <span style={{ display: "block", marginTop: 18, fontWeight: 700, color: "var(--ink)" }}>Not a desk farm. Not a coffee shop you tolerate. A place for people who would rather not go it alone.</span>
          </p>
        </Reveal>
      </div>
      <style>{`@media (max-width: 760px){ .cs-two{ grid-template-columns: 1fr !important; gap: 24px !important; } }`}</style>
    </section>
  );
}

/* ---------- VISION (ink ground) ---------- */
function Vision() {
  return (
    <section id="vision" data-ground="ink" style={{ padding: "clamp(56px,8vw,100px) clamp(16px,4vw,36px)" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto" }}>
        <Reveal><EyebrowA>Our vision</EyebrowA></Reveal>
        <Reveal delay={60}>
          <h2 style={{ fontFamily: "var(--font-display)", textTransform: "uppercase", fontSize: "clamp(34px,5.6vw,76px)", lineHeight: .9, letterSpacing: "-.02em", margin: "16px 0 28px", color: "var(--paper)", maxWidth: 1000, textWrap: "balance" }}>
            Where <span style={{ color: "var(--accent)" }}>&ldquo;I work from home&rdquo;</span> stops meaning <span style={{ color: "var(--accent)", opacity: .55 }}>&ldquo;I work alone.&rdquo;</span>
          </h2>
        </Reveal>
        <Reveal delay={120}>
          <p style={{ fontFamily: "var(--font-text)", fontSize: "clamp(17px,1.6vw,22px)", lineHeight: 1.55, color: "var(--paper)", opacity: .92, maxWidth: 760, margin: 0 }}>
            We picture a Gainesville where your most ambitious project and your most ordinary Tuesday both have a home. Where the people you sit near become the people you root for. Where a space can be quiet and focused in the morning and full of laughter by night, and shift to fit whatever the day asks of it. We are building toward that, one intentional welcome at a time.
          </p>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- WHAT WE’RE ABOUT (values) ---------- */
const VALUES = [
  { tab: "Value 01", icon: "ph-hand-heart", name: "Intentional", body: "We read every application and share a coffee before anyone joins. Not to keep good people out, but to keep the space kind, curious, and generous. The choosing is the point." },
  { tab: "Value 02", icon: "ph-arrows-out-cardinal", name: "Adaptive", body: "Morning light and quiet keyboards. Afternoon laughter and a whiteboard covered in somebody’s wild idea. Evening string lights and a potluck that smells like five different grandmothers. The space reshapes around whoever is in it \u2014 which is the whole reason we named it Chameleon." },
  { tab: "Value 03", icon: "ph-confetti", name: "More than work", body: "Bring your spreadsheet or bring your embroidery hoop. Come to crush a deadline or come to lose a board game badly. The hobbies and the Tuesday-night nonsense are not a break from the good stuff. They are half the good stuff." },
];
function Values() {
  return (
    <section id="about" style={{ padding: "clamp(56px,8vw,96px) clamp(16px,4vw,36px)", maxWidth: 1180, margin: "0 auto" }}>
      <SectionHead kicker="What we’re about" title="Built on purpose, or not at all." note="03 values" max={760} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 26, marginTop: 48 }} className="cs-vals">
        {VALUES.map((v, i) => (
          <Reveal key={v.name} delay={i * 80}>
            <CardA tab={v.tab} hover style={{ display: "flex", flexDirection: "column", height: "100%" }}>
              <div style={{ width: 54, height: 54, display: "grid", placeItems: "center", background: "var(--accent)", color: "var(--on-accent)", border: "2px solid var(--ink)", borderRadius: "var(--radius-2)", marginBottom: 18, boxShadow: "3px 3px 0 var(--ink)" }}>
                <i className={"ph-bold " + v.icon} style={{ fontSize: 26 }} />
              </div>
              <h3 style={{ fontFamily: "var(--font-display)", textTransform: "uppercase", fontSize: 28, lineHeight: .95, margin: "0 0 12px" }}>{v.name}</h3>
              <p style={{ fontFamily: "var(--font-text)", fontSize: 15, lineHeight: 1.6, color: "#3a362e", margin: 0 }}>{v.body}</p>
            </CardA>
          </Reveal>
        ))}
      </div>
      <style>{`@media (max-width: 860px){ .cs-vals{ grid-template-columns: 1fr !important; } }`}</style>
    </section>
  );
}

Object.assign(window, { Hero, Mission, Vision, Values });
