// ============================================================
// CONTACT PAGE — Formspree-backed with subject dropdown
// ============================================================

const SHARD_FORMSPREE_ID = "mkoanzol";

const SHARD_SUBJECTS = [
  { slug: "general", label: "General enquiry" },
  { slug: "demo", label: "Book a demo" },
  { slug: "demo-starter", label: "Book a demo: Starter" },
  { slug: "demo-team", label: "Book a demo: Team" },
  { slug: "demo-enterprise", label: "Book a demo: Enterprise" },
  { slug: "pilot", label: "Pilot programme: early access" },
  { slug: "partnership", label: "Partnership / press" },
];

const { useState: useStateContact, useEffect: useEffectContact } = React;

function ContactHero({ theme, prefs }) {
  const { isMobile } = window.useViewport();
  return (
    <section
      style={{
        position: "relative",
        background: theme.dark
          ? "radial-gradient(ellipse at 30% 20%, rgba(26,34,68,0.85) 0%, rgba(10,16,32,0.55) 55%, rgba(6,9,18,0.2) 100%)"
          : "radial-gradient(ellipse at 30% 20%, rgba(251,245,230,0.9) 0%, rgba(243,234,208,0.7) 55%, rgba(234,217,168,0.4) 100%)",
        color: theme.ink,
        overflow: "hidden",
        paddingTop: isMobile ? 100 : 140,
        paddingBottom: isMobile ? 40 : 56,
      }}
    >
      <div
        aria-hidden
        style={{
          position: "absolute",
          inset: 0,
          backgroundImage:
            "linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px)",
          backgroundSize: "56px 56px",
          maskImage: "radial-gradient(ellipse at center, black 25%, transparent 75%)",
          pointerEvents: "none",
        }}
      />
      <div
        style={{
          position: "relative",
          maxWidth: 1240,
          margin: "0 auto",
          padding: isMobile ? "0 22px" : "0 48px",
          zIndex: 2,
        }}
      >
        <div
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 10,
            padding: "6px 14px",
            borderRadius: 999,
            background: theme.chip,
            border: `1px solid ${theme.chipBorder}`,
            color: theme.chipText,
            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>
        <h1
          style={{
            fontFamily: "'Lexend', sans-serif",
            fontSize: "clamp(32px, 5.4vw, 78px)",
            lineHeight: 1.02,
            fontWeight: 600,
            letterSpacing: -1.6,
            margin: "0 0 24px 0",
            textWrap: "balance",
            maxWidth: 1000,
          }}
        >
          Tell us what you're{" "}
          <span style={{ color: theme.accent, fontStyle: "italic", fontWeight: 600 }}>
            evaluating.
          </span>
        </h1>
        <p
          style={{
            fontSize: isMobile ? 16 : 19,
            lineHeight: 1.55,
            color: theme.sub,
            margin: 0,
            maxWidth: 620,
          }}
        >
          A person reads every message. We reply with intent, not autoresponders. Pick
          the subject closest to why you're getting in touch and we'll route from
          there.
        </p>
      </div>
    </section>
  );
}

function ContactForm({ theme }) {
  const { isMobile } = window.useViewport();
  const [status, setStatus] = useStateContact("idle");
  const [subjectSlug, setSubjectSlug] = useStateContact("general");

  useEffectContact(() => {
    try {
      const params = new URLSearchParams(window.location.search);
      const s = params.get("subject");
      if (s && SHARD_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/${SHARD_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={{ fontFamily: "'Lexend', sans-serif", fontSize: 24, fontWeight: 600, 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. We'll reply personally, usually within a few business days.
        </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="shard-contact-name" style={fieldLabelStyle}>Your name</label>
        <input
          id="shard-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="shard-contact-email" style={fieldLabelStyle}>Work email</label>
        <input
          id="shard-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="shard-contact-org" style={fieldLabelStyle}>Company (optional)</label>
        <input
          id="shard-contact-org"
          name="company"
          type="text"
          placeholder="Acme Co."
          style={inputStyle}
          onFocus={(e) => (e.currentTarget.style.borderColor = theme.accent)}
          onBlur={(e) => (e.currentTarget.style.borderColor = theme.cardBorder)}
        />
      </div>

      <div>
        <label htmlFor="shard-contact-subject" style={fieldLabelStyle}>Subject</label>
        <select
          id="shard-contact-subject"
          name="_subject"
          value={SHARD_SUBJECTS.find((s) => s.slug === subjectSlug)?.label || SHARD_SUBJECTS[0].label}
          onChange={(e) => {
            const found = SHARD_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)}
        >
          {SHARD_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="shard-contact-message" style={fieldLabelStyle}>Message</label>
        <textarea
          id="shard-contact-message"
          name="message"
          required
          rows={7}
          placeholder="What you're evaluating, where you're stuck, who needs the evidence."
          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>

      <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: theme.onAccent,
            border: "none",
            fontSize: 15,
            fontWeight: 600,
            cursor: status === "submitting" ? "wait" : "pointer",
            opacity: status === "submitting" ? 0.7 : 1,
            fontFamily: "inherit",
            boxShadow: `0 10px 30px -10px ${theme.accent}aa`,
            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.
          </span>
        )}
      </div>
    </form>
  );
}

function ContactSection({ theme }) {
  const { Section } = window;
  const { isMobile } = window.useViewport();
  return (
    <Section id="contact" padding="64px 0 120px" mobilePadding="40px 0 64px">
      <div
        style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "1fr" : "1.4fr 1fr",
          gap: isMobile ? 36 : 64,
          alignItems: "start",
        }}
      >
        <ContactForm theme={theme} />

        <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 few days"],
            ["Reply from", "A person, not a bot"],
            ["Marketing list", "We don't run one"],
            ["Pilot status", "Active intake"],
          ].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>
      </div>
    </Section>
  );
}

window.ContactHero = ContactHero;
window.ContactSection = ContactSection;

// ============================================================
// CONTACT PAGE — orchestrator
// ============================================================

function ShardContactPage() {
  const theme = window.useActiveTheme();
  const [prefs] = window.usePrefs();
  const { Nav, ContactHero, ContactSection, Footer, ShardField } = window;

  React.useEffect(() => {
    document.body.style.background = theme.page;
    document.body.style.color = theme.ink;
  }, [theme.page, theme.ink]);

  return (
    <div style={{ background: "transparent", color: theme.ink, minHeight: "100vh", position: "relative" }}>
      {ShardField && <ShardField />}
      <div style={{ position: "relative", zIndex: 1 }}>
        <Nav />
        <ContactHero theme={theme} prefs={prefs} />
        <ContactSection theme={theme} />
        <Footer />
      </div>
    </div>
  );
}

const shardContactRoot = ReactDOM.createRoot(document.getElementById("root"));
shardContactRoot.render(<ShardContactPage />);
