const { Section, SectionHead, Panel, PhotoFigure, Field, Input, Textarea, Select, Checkbox, Button, TextLink } =
  window.GEMAdvisoryDesignSystem_b1bc4f;

const PHOTO = "assets/photography/";
const FORM_ENDPOINT = "https://formspree.io/f/xyezwbpg";

function ContactScreen() {
  const d = window.siteData;
  const [form, setForm] = React.useState({ name: "", email: "", org: "", topic: "", note: "", nda: false });
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendError, setSendError] = React.useState(null);
  const [touched, setTouched] = React.useState(false);
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const emailBad = touched && !/.+@.+\..+/.test(form.email);
  const nameBad = touched && !form.name.trim();
  const topicBad = touched && !form.topic;
  const noteBad = touched && !form.note.trim();
  const valid = form.name.trim() && /.+@.+\..+/.test(form.email) && form.topic && form.note.trim();
  const [hp, setHp] = React.useState("");

  const submit = async (e) => {
    e.preventDefault();
    setTouched(true);
    setSendError(null);
    if (!valid) return;
    setSending(true);
    try {
      const res = await fetch(FORM_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          organization: form.org,
          topic: form.topic,
          message: form.note,
          "NDA requested": form.nda ? "Yes" : "No",
          _subject: "New enquiry via gemadvisory.com" + (form.topic ? " — " + form.topic : ""),
          _gotcha: hp,
        }),
      });
      if (res.ok) {
        setSent(true);
      } else {
        const data = await res.json().catch(() => null);
        setSendError(
          (data && data.errors && data.errors.map((x) => x.message).join(" ")) ||
            "Something went wrong sending that. Please try again, or email me directly."
        );
      }
    } catch (err) {
      setSendError("Couldn't reach the server. Please check your connection and try again.");
    } finally {
      setSending(false);
    }
  };

  return (
    <Section tone="field" style={{ background: "var(--gradient-field)" }}>
      <div data-grid2 style={{ display: "grid", gridTemplateColumns: "1.1fr 0.9fr", gap: "var(--gap-grid)", alignItems: "start" }}>
        <div>
          <SectionHead tone="onGreen" eyebrow="Get in touch" title="Let's talk" style={{ marginBottom: 24 }} />
          <p style={{ fontSize: "var(--size-body)", maxWidth: "52ch", color: "var(--text-onGreen-muted)" }}>{d.contact.lede}</p>
          <ul style={{ listStyle: "none", margin: "28px 0 0", padding: 0, maxWidth: "none" }}>
            {[
              { label: "LinkedIn", node: <TextLink tone="onGreen" href={d.contact.linkedinHref}>{d.contact.linkedin}</TextLink> },
              { label: "Based in", node: <span style={{ color: "var(--white)" }}>{d.contact.based}</span> },
            ].map((row, i, arr) => (
              <li
                key={row.label}
                style={{
                  padding: "14px 0",
                  borderTop: "1px solid var(--rule-onGreen-faint)",
                  borderBottom: i === arr.length - 1 ? "1px solid var(--rule-onGreen-faint)" : "none",
                  fontSize: "var(--size-body-sm)",
                  margin: 0,
                }}
              >
                <span style={{ display: "block", fontSize: "var(--size-label)", color: "var(--text-onGreen-muted)", marginBottom: 4 }}>
                  {row.label}
                </span>
                {row.node}
              </li>
            ))}
          </ul>
          <PhotoFigure
            style={{ marginTop: 36, maxWidth: 420 }}
            src={gemImg("media-radio-desk-01.png")}
            alt="Abigail Ross Hopper laughing during a live radio interview"
            ratio={0.66}
          />
        </div>

        <Panel tone="onGreen" title={sent ? "Thank you" : "Start a conversation"}>
          {sent ? (
            <p style={{ margin: 0, fontSize: "var(--size-body-sm)", color: "var(--text-onGreen-muted)" }}>
              Your note is on its way. Abby reads these herself and will follow up to find time to connect.
            </p>
          ) : (
            <form onSubmit={submit} action={FORM_ENDPOINT} method="POST" style={{ display: "grid", gap: "var(--gap-field)" }}>
              <p style={{ margin: "0 0 2px", fontSize: "var(--size-body-sm)", color: "var(--text-onGreen-muted)" }}>
                {d.contact.formNote}
              </p>
              <Field tone="onGreen" label="Name" htmlFor="c-name" required error={nameBad ? "Please tell me your name." : null}>
                <Input tone="onGreen" id="c-name" name="name" required invalid={nameBad} value={form.name} onChange={set("name")} />
              </Field>
              <Field
                tone="onGreen"
                label="Email"
                htmlFor="c-email"
                required
                error={emailBad ? "Enter an email I can reply to." : null}
              >
                <Input tone="onGreen" id="c-email" name="email" type="email" required invalid={emailBad} value={form.email} onChange={set("email")} />
              </Field>
              <Field tone="onGreen" label="Organization" htmlFor="c-org">
                <Input tone="onGreen" id="c-org" name="organization" value={form.org} onChange={set("org")} />
              </Field>
              <Field tone="onGreen" label="How can I help?" htmlFor="c-topic" required error={topicBad ? "Choose the closest fit." : null}>
                <Select
                  tone="onGreen"
                  id="c-topic"
                  name="topic"
                  required
                  invalid={topicBad}
                  placeholder="Choose one"
                  value={form.topic}
                  onChange={set("topic")}
                  options={[...d.pillars.flatMap((p) => p.services.map((s) => s.title)), "Speaking", "Media & press"]}
                />
              </Field>
              <Field
                tone="onGreen"
                label="What are you working on?"
                htmlFor="c-note"
                required
                error={noteBad ? "A sentence or two is plenty." : null}
              >
                <Textarea tone="onGreen" id="c-note" name="message" rows={4} required invalid={noteBad} value={form.note} onChange={set("note")} />
              </Field>
              <Checkbox
                tone="onGreen"
                id="c-nda"
                checked={form.nda}
                onChange={() => setForm({ ...form, nda: !form.nda })}
                label="This conversation needs an NDA first."
              />
              <input
                type="text"
                name="_gotcha"
                tabIndex={-1}
                autoComplete="off"
                aria-hidden="true"
                value={hp}
                onChange={(e) => setHp(e.target.value)}
                style={{ position: "absolute", left: -9999, width: 1, height: 1, opacity: 0 }}
              />
              {sendError ? (
                <p role="alert" style={{ margin: 0, fontSize: "var(--size-body-sm)", color: "var(--white)" }}>
                  {sendError}
                </p>
              ) : null}
              <Button variant="onGreen" type="submit" full disabled={sending}>
                {sending ? "Sending…" : "Send"}
              </Button>
            </form>
          )}
        </Panel>
      </div>
    </Section>
  );
}

Object.assign(window, { ContactScreen });
