// ============================================================
// CONTACT PAGE — Formspree-backed form with subject dropdown
//
// SETUP NOTE — replace `FORMSPREE_ID` below with the form ID
// from your Formspree dashboard (https://formspree.io). The ID
// is the part after /f/ in your endpoint URL.
// ============================================================

const FORMSPREE_ID = "mgobeyrw";

const CONTACT_SUBJECTS = [
  { slug: "general", label: "General enquiry" },
  { slug: "founding", label: "Founding partner enquiry" },
  { slug: "trust", label: "Trust seat: expression of interest" },
  { slug: "incubator", label: "Incubator build proposal" },
  { slug: "partner", label: "Partner application" },
  { slug: "accessibility", label: "Accessibility report" },
  { slug: "privacy", label: "Privacy enquiry" },
];

const { useState: useStateC, useEffect: useEffectC } = React;

function ContactHero({ theme, prefs }) {
  const { Constellation } = window;
  const { isMobile } = window.useViewport();
  const motion = !prefs.dyslexia;
  return (
    <section
      style={{
        position: "relative",
        background: theme.heroBg,
        color: theme.ink,
        overflow: "hidden",
        paddingTop: isMobile ? 100 : 140,
        paddingBottom: isMobile ? 40 : 64,
      }}
    >
      <Constellation density={0.55} speed={0.7} accent={theme.accent} glow dark={theme.dark} motion={motion} />
      <div
        aria-hidden
        style={{
          position: "absolute",
          inset: 0,
          backgroundImage: theme.dark
            ? "linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px)"
            : "linear-gradient(rgba(22,26,43,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(22,26,43,0.04) 1px, transparent 1px)",
          backgroundSize: "56px 56px",
          maskImage: "radial-gradient(ellipse at center, black 25%, transparent 75%)",
          pointerEvents: "none",
        }}
      />
      <div
        style={{
          position: "relative",
          maxWidth: 1280,
          margin: "0 auto",
          padding: isMobile ? "0 22px" : "0 48px",
          zIndex: 2,
        }}
      >
        <window.Reveal>
        <div
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 10,
            padding: "6px 14px",
            borderRadius: 999,
            background: theme.chip,
            border: `1px solid ${theme.chipBorder}`,
            color: theme.accent,
            fontSize: 11.5,
            letterSpacing: 1.4,
            textTransform: "uppercase",
            fontWeight: 600,
            marginBottom: 28,
            fontFamily: "'JetBrains Mono', monospace",
          }}
        >
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: theme.accent, boxShadow: `0 0 10px ${theme.accent}` }} />
          Contact
        </div>
        </window.Reveal>
        <window.Reveal delay={90}>
        <h1
          style={{
            fontSize: "clamp(32px, 5.4vw, 78px)",
            lineHeight: 0.98,
            fontWeight: 700,
            letterSpacing: -1.5,
            margin: "0 0 24px 0",
            textWrap: "balance",
            maxWidth: 1000,
          }}
        >
          One inbox.{" "}
          <span style={{ color: theme.accent, fontStyle: "italic", fontWeight: 600 }}>
            Many doors in.
          </span>
        </h1>
        </window.Reveal>
        <window.Reveal delay={180}>
        <p
          style={{
            fontSize: isMobile ? 16 : 19,
            lineHeight: 1.55,
            color: theme.sub,
            margin: 0,
            maxWidth: 620,
            textWrap: "pretty",
          }}
        >
          Tell us which door applies and we'll route accordingly. Most replies land
          within a week, and never from an unattended autoresponder.
        </p>
        </window.Reveal>
      </div>
    </section>
  );
}

function ContactForm({ theme }) {
  const { isMobile } = window.useViewport();
  const [status, setStatus] = useStateC("idle"); // idle | submitting | success | error
  const [subjectSlug, setSubjectSlug] = useStateC("general");

  useEffectC(() => {
    try {
      const params = new URLSearchParams(window.location.search);
      const s = params.get("subject");
      if (s && CONTACT_SUBJECTS.find((x) => x.slug === s)) {
        setSubjectSlug(s);
      }
    } catch (e) {}
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus("submitting");
    const form = e.target;
    const data = new FormData(form);
    try {
      const res = await fetch(`https://formspree.io/f/${FORMSPREE_ID}`, {
        method: "POST",
        body: data,
        headers: { Accept: "application/json" },
      });
      if (res.ok) {
        setStatus("success");
        form.reset();
      } else {
        setStatus("error");
      }
    } catch (err) {
      setStatus("error");
    }
  };

  const fieldLabelStyle = {
    fontSize: 11,
    letterSpacing: 1.4,
    textTransform: "uppercase",
    color: theme.sub,
    fontWeight: 600,
    fontFamily: "'JetBrains Mono', monospace",
    marginBottom: 10,
    display: "block",
  };

  const inputStyle = {
    width: "100%",
    padding: "14px 16px",
    background: theme.dark ? "rgba(0,0,0,0.3)" : "rgba(255,255,255,0.6)",
    border: `1px solid ${theme.cardBorder}`,
    borderRadius: 10,
    color: theme.ink,
    fontSize: 15,
    fontFamily: "inherit",
    outline: "none",
    transition: "border-color 150ms",
  };

  if (status === "success") {
    return (
      <div
        style={{
          padding: isMobile ? "28px 22px" : "48px 56px",
          background: `${theme.success}14`,
          border: `1px solid ${theme.success}55`,
          borderRadius: 18,
          textAlign: "center",
          maxWidth: 720,
        }}
      >
        <div
          style={{
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            width: 56,
            height: 56,
            borderRadius: "50%",
            background: `${theme.success}22`,
            border: `1.5px solid ${theme.success}`,
            marginBottom: 22,
          }}
        >
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M5 12l5 5L20 6" stroke={theme.success} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
        <h2 style={{ fontSize: 24, fontWeight: 700, letterSpacing: -0.6, color: theme.ink, margin: "0 0 12px 0" }}>
          Message sent.
        </h2>
        <p style={{ fontSize: 15.5, lineHeight: 1.6, color: theme.sub, margin: "0 0 22px 0" }}>
          Thanks for getting in touch. We'll reply personally, usually within a week.
        </p>
        <button
          onClick={() => setStatus("idle")}
          style={{
            padding: "11px 22px",
            borderRadius: 999,
            background: "transparent",
            color: theme.ink,
            border: `1px solid ${theme.chipBorder}`,
            fontSize: 14,
            fontWeight: 500,
            cursor: "pointer",
            fontFamily: "inherit",
          }}
        >
          Send another message
        </button>
      </div>
    );
  }

  return (
    <form
      onSubmit={handleSubmit}
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 22,
        maxWidth: 720,
      }}
    >
      <div>
        <label htmlFor="contact-name" style={fieldLabelStyle}>
          Your name
        </label>
        <input
          id="contact-name"
          name="name"
          type="text"
          required
          placeholder="Jordan Hart"
          style={inputStyle}
          onFocus={(e) => (e.currentTarget.style.borderColor = theme.accent)}
          onBlur={(e) => (e.currentTarget.style.borderColor = theme.cardBorder)}
        />
      </div>

      <div>
        <label htmlFor="contact-email" style={fieldLabelStyle}>
          Email
        </label>
        <input
          id="contact-email"
          name="email"
          type="email"
          required
          placeholder="you@yourorg.com"
          style={inputStyle}
          onFocus={(e) => (e.currentTarget.style.borderColor = theme.accent)}
          onBlur={(e) => (e.currentTarget.style.borderColor = theme.cardBorder)}
        />
      </div>

      <div>
        <label htmlFor="contact-subject" style={fieldLabelStyle}>
          What can we help with?
        </label>
        <select
          id="contact-subject"
          name="_subject"
          value={CONTACT_SUBJECTS.find((s) => s.slug === subjectSlug)?.label || CONTACT_SUBJECTS[0].label}
          onChange={(e) => {
            const found = CONTACT_SUBJECTS.find((s) => s.label === e.target.value);
            if (found) setSubjectSlug(found.slug);
          }}
          required
          style={{
            ...inputStyle,
            appearance: "none",
            backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8' fill='none'><path d='M1 1l5 5 5-5' stroke='${encodeURIComponent(theme.accent)}' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>")`,
            backgroundRepeat: "no-repeat",
            backgroundPosition: "right 18px center",
            paddingRight: 44,
          }}
          onFocus={(e) => (e.currentTarget.style.borderColor = theme.accent)}
          onBlur={(e) => (e.currentTarget.style.borderColor = theme.cardBorder)}
        >
          {CONTACT_SUBJECTS.map((s) => (
            <option key={s.slug} value={s.label} style={{ background: theme.surface, color: theme.ink }}>
              {s.label}
            </option>
          ))}
        </select>
      </div>

      <div>
        <label htmlFor="contact-message" style={fieldLabelStyle}>
          Message
        </label>
        <textarea
          id="contact-message"
          name="message"
          required
          rows={7}
          placeholder="A few sentences. No autoresponder reply: a person reads every message."
          style={{
            ...inputStyle,
            resize: "vertical",
            minHeight: 160,
            lineHeight: 1.55,
            fontFamily: "inherit",
          }}
          onFocus={(e) => (e.currentTarget.style.borderColor = theme.accent)}
          onBlur={(e) => (e.currentTarget.style.borderColor = theme.cardBorder)}
        />
      </div>

      {/* honeypot for spam */}
      <input type="text" name="_gotcha" style={{ display: "none" }} tabIndex={-1} autoComplete="off" />

      <div style={{ display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap" }}>
        <button
          type="submit"
          disabled={status === "submitting"}
          style={{
            padding: "15px 28px",
            borderRadius: 999,
            background: theme.accent,
            color: "#161a2b",
            border: "none",
            fontSize: 15,
            fontWeight: 600,
            cursor: status === "submitting" ? "wait" : "pointer",
            opacity: status === "submitting" ? 0.7 : 1,
            fontFamily: "inherit",
            boxShadow: theme.dark
              ? `0 10px 30px -10px ${theme.accent}aa`
              : "0 10px 30px -10px rgba(22,26,43,0.4)",
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            transition: "opacity 200ms",
          }}
        >
          {status === "submitting" ? "Sending…" : "Send message →"}
        </button>

        {status === "error" && (
          <span style={{ fontSize: 13.5, color: theme.fail || "#ef4444", lineHeight: 1.5 }}>
            Something went wrong sending the message. Please try again in a moment.
          </span>
        )}
      </div>

      <p style={{ fontSize: 12, color: theme.mute, lineHeight: 1.55, margin: 0, fontFamily: "'JetBrains Mono', monospace" }}>
        By sending this message you agree to be contacted in reply. We don't add you
        to any list. See the{" "}
        <a href="/privacy" style={{ color: theme.accent, textDecoration: "none" }}>
          privacy policy ↗
        </a>
        .
      </p>
    </form>
  );
}

function ContactSection({ theme }) {
  const { Section } = window;
  const { isMobile } = window.useViewport();
  return (
    <Section id="contact" theme={theme} padding="80px 0 120px" mobilePadding="48px 0 80px">
      <div
        style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "1fr" : "1.4fr 1fr",
          gap: isMobile ? 36 : 64,
          alignItems: "start",
        }}
      >
        <window.Reveal>
          <ContactForm theme={theme} />
        </window.Reveal>

        {/* Sidecar — what to expect */}
        <window.Reveal delay={140}>
        <div
          style={{
            position: "relative",
            background: theme.dark ? "rgba(8,16,30,0.55)" : "rgba(250,246,234,0.75)",
            backdropFilter: "blur(10px)",
            border: `1px solid ${theme.cardBorder}`,
            borderRadius: 18,
            padding: isMobile ? "22px 22px" : "28px 30px",
            fontFamily: "'JetBrains Mono', 'SF Mono', ui-monospace, monospace",
          }}
        >
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              marginBottom: 22,
              fontSize: 11,
              letterSpacing: 1.4,
              textTransform: "uppercase",
              color: theme.sub,
              fontWeight: 600,
            }}
          >
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: theme.success, boxShadow: `0 0 10px ${theme.success}` }} />
            What to expect
          </div>
          {[
            ["Response", "Within a week"],
            ["Reply from", "A person, not a bot"],
            ["Marketing list", "We don't run one"],
            ["Data kept", "Only the thread itself"],
          ].map(([k, v], i, arr) => (
            <div
              key={k}
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "baseline",
                padding: "10px 0",
                borderBottom: i === arr.length - 1 ? "none" : `1px solid ${theme.cardBorder}`,
                fontSize: 13,
                gap: 12,
              }}
            >
              <span style={{ color: theme.sub, whiteSpace: "nowrap" }}>{k}</span>
              <span style={{ color: theme.ink, fontWeight: 500, textAlign: "right" }}>
                {v}
              </span>
            </div>
          ))}
          <div style={{ marginTop: 18, paddingTop: 14, borderTop: `1px solid ${theme.cardBorder}`, fontSize: 11, color: theme.mute, lineHeight: 1.55 }}>
            If your message fits one of the structured routes (Trust seat, partner
            application, founding round), pick that subject and we'll route it
            internally. Otherwise, "General enquiry" is fine.
          </div>
        </div>
        </window.Reveal>
      </div>
    </Section>
  );
}

window.ContactHero = ContactHero;
window.ContactSection = ContactSection;

// ============================================================
// CONTACT PAGE — orchestrator
// ============================================================

function ContactPage() {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{ "accent": "#f5c14e" }/*EDITMODE-END*/;
  const { useTweaks, TweaksPanel, TweakSection, TweakColor } = window;
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [prefs, setPrefs] = useStateC(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("brains.prefs") || "null");
      if (saved) return saved;
    } catch (e) {}
    return { theme: "midnight", textSize: "M", lineSpacing: "Standard", dyslexia: false };
  });
  useEffectC(() => {
    try { localStorage.setItem("brains.prefs", JSON.stringify(prefs)); } catch (e) {}
  }, [prefs]);
  const [readingOpen, setReadingOpen] = useStateC(false);

  const baseTheme = window.THEMES[prefs.dyslexia ? "light" : prefs.theme];
  const theme = { ...baseTheme, accent: tweaks.accent, rule: tweaks.accent };
  const scale = window.TEXT_SCALES[prefs.textSize];
  const lineMap = { Tight: 1.45, Standard: 1.6, Roomy: 1.8 };
  useEffectC(() => {
    document.body.style.fontSize = `${scale.base}px`;
    document.body.style.lineHeight = `${lineMap[prefs.dyslexia ? "Roomy" : prefs.lineSpacing]}`;
    document.body.style.background = theme.page;
    document.body.style.color = theme.ink;
  }, [prefs.textSize, prefs.lineSpacing, theme.page, theme.ink]);

  const { Nav, ReadingPanel, ContactHero, ContactSection, Footer } = window;

  return (
    <div style={{ background: theme.page, color: theme.ink, minHeight: "100vh" }}>
      <Nav
        theme={theme}
        prefs={prefs}
        setPrefs={setPrefs}
        openReading={readingOpen}
        setOpenReading={setReadingOpen}
        current="contact"
      />
      <ReadingPanel
        open={readingOpen}
        onClose={() => setReadingOpen(false)}
        theme={theme}
        prefs={prefs}
        setPrefs={setPrefs}
      />

      <ContactHero theme={theme} prefs={prefs} />
      <ContactSection theme={theme} />

      <Footer theme={theme} prefs={prefs} />

      <TweaksPanel title="Tweaks">
        <TweakSection title="Brand">
          <TweakColor
            label="Accent color"
            value={tweaks.accent}
            options={["#f5c14e", "#e2a82a", "#7aa3ff", "#5fd28a"]}
            onChange={(v) => setTweak("accent", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

const contactRoot = ReactDOM.createRoot(document.getElementById("root"));
contactRoot.render(<ContactPage />);
