/* global React, PFGlyph */
/* Let's Talk — contact page. Header/Footer come from homepage.jsx + sections.jsx. */
const { useState: useStateCT } = React;

const ENGAGE_STEPS = [
{ n: "01", glyph: "eye", title: "You write to us",
  body: "A few lines is plenty. Tell us who you are, the question you cannot stop asking, and roughly when you would want to begin. The good notes are usually a little too long." },
{ n: "02", glyph: "chevron", title: "We reply within three days",
  body: "A real person — most often Daniel or Estefania — reads every note and answers within three working days. Sometimes the answer is a question back." },
{ n: "03", glyph: "branching", title: "We have a first conversation",
  body: "Thirty minutes, no brief required. We are most useful in the months before an RFP exists, when the question is still unstable. If we are not the right fit, we will say so — and point you somewhere better." }];


/* ============================================================
   HERO
   ============================================================ */
const ctHero = {
  wrap: { background: "var(--paper)", borderBottom: "1px solid var(--line)", padding: "clamp(48px, 7vw, 104px) var(--gutter) clamp(40px, 5vw, 72px)", position: "relative", overflow: "hidden" },
  inner: { maxWidth: "var(--container)", margin: "0 auto", position: "relative", zIndex: 1 },
  strip: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, paddingBottom: 20, borderBottom: "1px solid var(--line)", marginBottom: "clamp(34px, 5vw, 60px)", flexWrap: "wrap" },
  crumb: { fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-2)", letterSpacing: "0.04em" },
  crumbHome: { color: "var(--ink-2)", textDecoration: "none", borderBottom: "1px solid var(--line-2)" },
  pageMark: { fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.1em", textTransform: "uppercase" },
  comp: { display: "grid", gridTemplateColumns: "1.45fr 1fr", gap: "clamp(28px, 5vw, 72px)", alignItems: "end" },
  title: { fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "clamp(56px, 9vw, 140px)", lineHeight: 0.9, letterSpacing: "-0.03em", color: "var(--ink)", margin: 0, textWrap: "balance" },
  titleEm: { color: "var(--accent-deep)" },
  lede: { fontFamily: "var(--font-body)", fontSize: "clamp(17px, 1.5vw, 21px)", lineHeight: 1.55, color: "var(--ink)", margin: 0, textWrap: "pretty" },
  ledeEm: { fontStyle: "italic", color: "var(--ink-2)" }
};

function ContactHero() {
  return (
    <section style={ctHero.wrap} data-ink="ember" data-screen-label="Lets Talk Hero">
      <div className="pf-motif pf-motif--rings pf-motif--fade-l" data-ink="ember" style={{ opacity: 0.1 }}></div>
      <div style={ctHero.inner}>
        <div style={ctHero.strip}>
          <div style={ctHero.crumb}>
            <a href="index.html" style={ctHero.crumbHome}>Plural Futures</a>
            <span style={{ margin: "0 10px", color: "var(--ink-3)" }}>/</span>
            <span style={{ color: "var(--ink)" }}>Let's talk</span>
          </div>
          <div style={ctHero.pageMark}></div>
        </div>
        <div style={ctHero.comp} className="pf-collapse-2">
          <div>
            <span className="eyebrow" style={{ display: "block", marginBottom: 22 }}>Start the conversation</span>
            <h1 style={ctHero.title}>Let's <span style={ctHero.titleEm}>talk.</span></h1>
          </div>
          <p style={ctHero.lede}>
            We take on a small number of engagements each year. The best ones begin not with a brief, but with a question someone has been <span style={ctHero.ledeEm}>carrying for a while</span>.
          </p>
        </div>
      </div>
    </section>);

}
window.ContactHero = ContactHero;

/* ============================================================
   FORM + DIRECT DETAILS
   ============================================================ */
const ctForm = {
  inner: { maxWidth: "var(--container)", margin: "0 auto", padding: "0 var(--gutter)", display: "grid", gridTemplateColumns: "1.25fr 0.75fr", gap: "clamp(36px, 5vw, 80px)", alignItems: "start" },
  formCard: { display: "flex", flexDirection: "column", gap: 24 },
  headRow: { borderTop: "var(--stroke-bold) solid var(--ink)", paddingTop: 20, marginBottom: 4 },
  formTitle: { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(24px, 2.6vw, 34px)", lineHeight: 1.05, letterSpacing: "-0.02em", color: "var(--ink)", margin: "0 0 8px" },
  formNote: { fontFamily: "var(--font-body)", fontSize: 16, lineHeight: 1.5, color: "var(--ink-2)", margin: 0 },
  twoCol: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 },
  field: { display: "flex", flexDirection: "column", gap: 9 },
  label: { fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 500, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--ink-2)" },
  opt: { color: "var(--ink-3)", textTransform: "none", letterSpacing: 0, fontStyle: "italic" },
  chips: { display: "flex", flexWrap: "wrap", gap: 8 },
  submitRow: { display: "flex", alignItems: "center", gap: 18, marginTop: 6, flexWrap: "wrap" },
  fine: { fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.04em" },

  aside: { display: "flex", flexDirection: "column", gap: 24, position: "sticky", top: 90 },
  detailCard: { border: "1px solid var(--line)", borderRadius: "var(--radius)", background: "var(--surface)", padding: "clamp(24px, 2.6vw, 32px)", display: "flex", flexDirection: "column", gap: 22 },
  dLabel: { fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 500, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--accent-deep)", marginBottom: 8 },
  dBig: { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(20px, 1.9vw, 25px)", letterSpacing: "-0.015em", color: "var(--ink)", textDecoration: "none", lineHeight: 1.15, display: "inline-flex", alignItems: "baseline", gap: 6, wordBreak: "break-word" },
  dRow: { display: "flex", flexDirection: "column", gap: 6, paddingTop: 20, borderTop: "1px solid var(--line)" },
  dVal: { fontFamily: "var(--font-body)", fontSize: 16, lineHeight: 1.5, color: "var(--ink)", margin: 0 },
  dLink: { color: "var(--accent-deep)", textDecoration: "none", borderBottom: "1px solid var(--line-2)" }
};

const SUBJECTS = ["A potential engagement", "A workshop or talk", "Press or speaking", "Just saying hello"];

/* ------------------------------------------------------------------
   EMAIL DELIVERY
   To send submissions to hello@pluralfutures.com without a backend:
   1. Go to https://web3forms.com → enter hello@pluralfutures.com → get a
      free Access Key by email (no account needed).
   2. Paste that key below. That's it — submissions will be emailed to you,
      and the visitor stays on the page and sees the "Thank you" state.
   Until a key is set, the form falls back to opening the visitor's own mail
   app with a pre-filled message to hello@pluralfutures.com.
------------------------------------------------------------------ */
const WEB3FORMS_ACCESS_KEY = "a2e959c3-532d-4aea-b259-7781199268bf";
const CONTACT_EMAIL = "hello@pluralfutures.com";

function ContactForm() {
  const [sent, setSent] = useStateCT(false);
  const [sending, setSending] = useStateCT(false);
  const [error, setError] = useStateCT(null);
  const [subject, setSubject] = useStateCT(SUBJECTS[0]);

  async function handleSubmit(e) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const name = (fd.get("name") || "").trim();
    const org = (fd.get("organisation") || "").trim();
    const email = (fd.get("email") || "").trim();
    const message = (fd.get("message") || "").trim();
    const mailSubject = `[Let's Talk] ${subject}${name ? " \u2014 " + name : ""}`;

    // Fallback: no service key yet — hand off to the visitor's mail client.
    if (!WEB3FORMS_ACCESS_KEY) {
      const body = `Name: ${name}\nOrganisation: ${org || "\u2014"}\nEmail: ${email}\nAbout: ${subject}\n\n${message}`;
      window.location.href = `mailto:${CONTACT_EMAIL}?subject=${encodeURIComponent(mailSubject)}&body=${encodeURIComponent(body)}`;
      setSent(true);
      return;
    }

    setSending(true);
    setError(null);
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          access_key: WEB3FORMS_ACCESS_KEY,
          subject: mailSubject,
          from_name: name || "Plural Futures — Let's Talk",
          replyto: email,
          name, organisation: org, email, about: subject, message
        })
      });
      const json = await res.json();
      if (json.success) {setSent(true);} else
      {setError("Something went wrong on our end. Please email us directly \u2014 " + CONTACT_EMAIL + ".");}
    } catch (err) {
      setError("We couldn't send that just now. Please email us directly \u2014 " + CONTACT_EMAIL + ".");
    } finally {
      setSending(false);
    }
  }

  if (sent) {
    return (
      <section className="pf-section pf-bg-1" data-ink="sprout" data-screen-label="Lets Talk Form">
        <div style={ctForm.inner} className="pf-collapse-2">
          <div style={ctForm.formCard}>
            <div style={ctForm.headRow}>
              <span style={{ ...ctForm.dLabel, color: "var(--accent-deep)" }}>Note received</span>
            </div>
            <h2 style={{ ...ctHero.title, fontSize: "clamp(34px, 4.4vw, 60px)" }}>Thank you.</h2>
            <p style={{ ...ctForm.formNote, fontSize: "clamp(18px, 1.6vw, 22px)", maxWidth: "44ch", color: "var(--ink)" }}>
              Your note is with us. A real person — most likely Daniel or Estefania — will read it and reply within three working days.
            </p>
            <div>
              <button type="button" className="btn btn--outline btn--lg" onClick={() => setSent(false)}>Write another note</button>
            </div>
          </div>
          <Aside />
        </div>
      </section>);

  }

  return (
    <section className="pf-section pf-bg-1" data-ink="ember" data-screen-label="Lets Talk Form">
      <div style={ctForm.inner} className="pf-collapse-2">
        <form style={ctForm.formCard} onSubmit={handleSubmit}>
          <div style={ctForm.headRow}>
            <h2 style={ctForm.formTitle}>Write us a note.</h2>
            <p style={ctForm.formNote}>No form is a substitute for a conversation — this just starts one.</p>
          </div>

          <div style={ctForm.twoCol} className="pf-collapse-2">
            <div style={ctForm.field}>
              <label style={ctForm.label} htmlFor="ct-name">Your name</label>
              <input id="ct-name" name="name" className="pf-field" type="text" required placeholder="First and last" />
            </div>
            <div style={ctForm.field}>
              <label style={ctForm.label} htmlFor="ct-org">Organisation <span style={ctForm.opt}>— optional</span></label>
              <input id="ct-org" name="organisation" className="pf-field" type="text" placeholder="Where you work" />
            </div>
          </div>

          <div style={ctForm.field}>
            <label style={ctForm.label} htmlFor="ct-email">Email</label>
            <input id="ct-email" name="email" className="pf-field" type="email" required placeholder="you@organisation.org" />
          </div>

          <div style={ctForm.field}>
            <span style={ctForm.label}>What is this about?</span>
            <div style={ctForm.chips}>
              {SUBJECTS.map((s) =>
              <button type="button" key={s} onClick={() => setSubject(s)}
              className="pf-pill-link"
              style={subject === s ? { background: "var(--accent)", color: "var(--accent-on)", borderColor: "transparent" } : null}>
                  {s}
                </button>
              )}
            </div>
          </div>

          <div style={ctForm.field}>
            <label style={ctForm.label} htmlFor="ct-msg">The question you cannot stop asking</label>
            <textarea id="ct-msg" name="message" className="pf-field pf-field--area" required rows={6}
            placeholder="A few lines is plenty. What are you trying to see more clearly?"></textarea>
          </div>

          <div style={ctForm.submitRow}>
            <button type="submit" className="btn btn--primary btn--lg" disabled={sending} style={sending ? { opacity: 0.7, cursor: "wait" } : null}>
              {sending ? "Sending\u2026" : <>Send your note <span className="arr" aria-hidden>↗</span></>}
            </button>
            <span style={ctForm.fine}>Or email us directly — whichever is easier.</span>
          </div>
          {error &&
          <p style={{ fontFamily: "var(--font-body)", fontSize: 15, color: "var(--bloom-deep)", margin: 0 }} role="alert">{error}</p>}
        </form>

        <Aside />
      </div>
    </section>);

}
window.ContactForm = ContactForm;

function Aside() {
  return (
    <aside style={ctForm.aside}>
      <div style={ctForm.detailCard} data-ink="ember">
        <div>
          <div style={ctForm.dLabel}>Email us</div>
          <a href="mailto:hello@pluralfutures.com" style={ctForm.dBig}>
            hello@pluralfutures.com <span className="arr" aria-hidden style={{ fontFamily: "var(--font-mono)", color: "var(--accent-deep)" }}>↗</span>
          </a>
        </div>
        <div style={ctForm.dRow}>
          <div style={ctForm.dLabel}>Elsewhere</div>
          <p style={ctForm.dVal}>
            <a href="https://www.linkedin.com/company/plural-futures/" target="_blank" rel="noopener" style={ctForm.dLink}>LinkedIn ↗</a>
          </p>
        </div>
        <div style={ctForm.dRow}>
          <div style={ctForm.dLabel}>Studio</div>
          <p style={ctForm.dVal}>A network-shaped practice. Registered in Spain; working across time zones.</p>
        </div>
      </div>
    </aside>);

}

/* ============================================================
   WHAT HAPPENS NEXT
   ============================================================ */
const ctNext = {
  inner: { maxWidth: "var(--container)", margin: "0 auto", padding: "0 var(--gutter)" },
  grid: { display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "clamp(28px, 4vw, 56px)" },
  col: { display: "flex", flexDirection: "column", gap: 16, paddingTop: 26, borderTop: "var(--stroke-bold) solid var(--ink)" },
  top: { display: "flex", alignItems: "center", justifyContent: "space-between" },
  num: { fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-3)", letterSpacing: "0.08em" },
  glyphTile: { width: 50, height: 50, borderRadius: "var(--r-sm)", background: "var(--accent-wash)", color: "var(--accent-deep)", display: "flex", alignItems: "center", justifyContent: "center" },
  title: { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px, 1.9vw, 27px)", lineHeight: 1.1, letterSpacing: "-0.02em", color: "var(--ink)", margin: 0, textWrap: "balance" },
  body: { fontFamily: "var(--font-body)", fontSize: 16, lineHeight: 1.6, color: "var(--ink-2)", margin: 0 }
};

function ContactNext() {
  return (
    <section className="pf-section pf-bg-2" data-screen-label="What Happens Next">
      <div style={ctNext.inner}>
        <div className="pf-headrow" style={{ marginBottom: "clamp(40px, 5vw, 64px)" }}>
          <div>
            <div className="pf-srule"></div>
            <div className="eyebrow" style={{ marginBottom: 18 }}>What happens next</div>
            <h2 className="pf-section-title">After you hit send.</h2>
          </div>
          <p className="pf-section-sub">No funnels, no sequences. Three steps, all of them human.</p>
        </div>
        <div style={ctNext.grid} className="pf-collapse-3">
          {ENGAGE_STEPS.map((s, i) =>
          <div key={s.n} data-ink={["ember", "sky", "sprout"][i]} style={ctNext.col}>
              <div style={ctNext.top}>
                <span style={ctNext.num}>{s.n}</span>
                <span style={ctNext.glyphTile}><PFGlyph name={s.glyph} size={26} /></span>
              </div>
              <h3 style={ctNext.title}>{s.title}</h3>
              <p style={ctNext.body}>{s.body}</p>
            </div>
          )}
        </div>
      </div>
    </section>);

}
window.ContactNext = ContactNext;