/* global React */
const { useState, useRef, useEffect } = React;
const MM = window.MM;

/* ---- tiny inline icons (Lucide-style, 1.75 stroke) ---- */
function Icon({ name, ...p }) {
  const paths = {
    heart: <path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.6l-1-1a5.5 5.5 0 0 0-7.8 7.8l1 1L12 21l7.8-7.6 1-1a5.5 5.5 0 0 0 0-7.8z"/>,
    users: <><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></>,
    sign: <><path d="M4 3v18"/><path d="M4 4h13l-2.5 4L17 12H4"/></>,
    arrow: <><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></>,
  };
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.85"
         strokeLinecap="round" strokeLinejoin="round" {...p}>
      {paths[name]}
    </svg>
  );
}
const Star = (p) => <span className="star" aria-hidden="true" {...p} />;

/* ---- modal trigger helper (decoupled from triggers) ---- */
function openModal(type) {
  window.dispatchEvent(new CustomEvent("mm:modal", { detail: type }));
}

/* ---- POST helper: submit a form payload to the serverless backend ---- */
async function postSignup(endpoint, payload) {
  const res = await fetch("/api/signups/" + endpoint, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    let detail = "";
    try { detail = (await res.json()).error || ""; } catch (e) {}
    throw new Error(detail || ("http_" + res.status));
  }
  return res.json().catch(() => ({}));
}

const SUBMIT_ERROR = "Something went wrong on our end. Please try again, or email us directly.";

/* ---- spam honeypot: hidden off-screen field real users never fill ---- */
function Honeypot({ value, onChange }) {
  return (
    <div aria-hidden="true" style={{
      position: "absolute", left: "-9999px", top: "auto",
      width: 1, height: 1, overflow: "hidden",
    }}>
      <label>
        Website
        <input type="text" name="website" tabIndex={-1} autoComplete="off"
          value={value} onChange={onChange} />
      </label>
    </div>
  );
}

/* ---- phone input formatter: renders as (123) 555-1234 ---- */
function formatPhone(value) {
  const d = (value || "").replace(/\D/g, "").slice(0, 10);
  if (d.length === 0) return "";
  if (d.length < 4) return "(" + d;
  if (d.length < 7) return "(" + d.slice(0, 3) + ") " + d.slice(3);
  return "(" + d.slice(0, 3) + ") " + d.slice(3, 6) + "-" + d.slice(6);
}

/* ---- official campaign logo lockup ---- */
function Wordmark({ dark }) {
  return (
    <a className="brand" href="#top" aria-label="Matt Marshall for State House">
      <img className="brand__logo" src="/site/logo.png"
        alt="Matt Marshall — Republican · Washington State House District Two, Position Two" />
    </a>
  );
}

/* ============================ HERO ============================ */
function Hero({ heroStyle }) {
  const split = heroStyle === "split";
  const content = (
    <div className="hero__content">
      <h1 className="hero__logo">
        <img src="/site/logo.png"
          alt="Matt Marshall — Republican · Washington State House District Two, Position Two" />
      </h1>
      <p className="hero__tag">{MM.heroTagline}</p>
      <div className="hero__actions">
        <a className="btn btn--lg" href={MM.donateUrl} target="_blank" rel="noopener">Donate Today</a>
        <a className="btn btn--ghost-light btn--lg" href="#involved">Join the Team</a>
      </div>
    </div>
  );

  if (split) {
    return (
      <header className="hero hero--split" id="top">
        <div className="hero__inner">
          <div className="container" style={{ padding: 0, maxWidth: "640px", marginLeft: 0 }}>{content}</div>
        </div>
        <div className="hero__media">
          <img className="hero__photo" src="/site/matt-portrait.jpg" alt="Matt Marshall" />
        </div>
      </header>
    );
  }

  return (
    <header className="hero" id="top">
      <div className="hero__media">
        <img className="hero__photo" src="/site/hero-matt.jpg" alt="Matt Marshall" />
      </div>
      <div className="hero__scrim" />
      <div className="hero__inner">{content}</div>
    </header>
  );
}

/* ============================ CREDS ============================ */
function Creds() {
  return (
    <section className="creds">
      <div className="container container-wide" style={{ padding: 0 }}>
        <div className="creds__grid">
          {MM.bioCreds.map((c) => (
            <div className="creds__item" key={c.k}>
              <div className="creds__k"><Star /> {c.k}</div>
              <div className="creds__v">{c.v}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================ ABOUT ============================ */
function About() {
  return (
    <section className="section about" id="about">
      <div className="container container-wide">
        <div className="about__grid">
          <div className="about__media">
            <img className="about__photo" src="/site/matt-about.jpg" alt="Matt Marshall salmon fishing on the Snake River" />
            <div className="frame-tag"><Star /> Beautiful Washington State</div>
          </div>
          <div>
            <span className="eyebrow">Meet Matt</span>
            <h2 className="section-title">A physician assistant, a soldier, a neighbor.</h2>
            <p className="about__lead">{MM.bio[0]}</p>
            {MM.bio.slice(1).map((para, i) => <p key={i}>{para}</p>)}
            <div className="about__degrees">
              <h4>Education</h4>
              <ul>
                {MM.degrees.map((d) => <li key={d}><Star /> <span>{d}</span></li>)}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================ PRIORITIES ============================ */
function PriorityItem({ p, open, onToggle }) {
  return (
    <div className={"pri__item" + (open ? " is-open" : "")}>
      <button className="pri__btn" onClick={onToggle} aria-expanded={open}>
        <span className="pri__n">{p.n}</span>
        <span className="pri__mid">
          <span className="pri__title">{p.title}</span>
          <span className="pri__short">{p.short}</span>
        </span>
        <span className="pri__plus" aria-hidden="true" />
      </button>
      <div className="pri__panel">
        <div className="pri__panel-inner">
          <span className="spacer" aria-hidden="true" />
          <div>{p.body.map((para, i) => <p key={i}>{para}</p>)}</div>
        </div>
      </div>
    </div>
  );
}

function Priorities() {
  const [open, setOpen] = useState(0);
  return (
    <section className="section pri" id="priorities">
      <div className="container">
        <div className="pri__head">
          <span className="eyebrow">Where Matt Stands</span>
          <h2 className="section-title">Matt&rsquo;s priorities for the 2nd District</h2>
          <p className="lead" style={{ marginTop: 18 }}>
            Seven commitments rooted in affordability, accountability, and freedom &mdash;
            informed by a career in medicine, the military, and local government.
          </p>
        </div>
        <div className="pri__list">
          {MM.priorities.map((p, i) => (
            <PriorityItem key={p.n} p={p} open={open === i}
              onToggle={() => setOpen(open === i ? -1 : i)} />
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================ NEWS ============================ */
function News() {
  return (
    <section className="section news" id="news">
      <div className="container">
        <span className="eyebrow">In the News</span>
        <h2 className="section-title">Op-eds &amp; commentary</h2>
        <div className="news__grid">
          {MM.news.map((n) => (
            <a className="news__card" key={n.url} href={n.url} target="_blank" rel="noopener">
              <div className="news__meta">
                <span className="news__outlet">{n.outlet}</span>
                <span className="news__kind">{n.kind}</span>
              </div>
              <p className="news__title">{n.title}</p>
              <span className="news__read">
                Read article <Icon name="arrow" className="arr" style={{ width: 16, height: 16 }} />
              </span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================ GET INVOLVED ============================ */
function Signup() {
  const [v, setV] = useState({ name: "", email: "", zip: "", website: "" });
  const [err, setErr] = useState({});
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitErr, setSubmitErr] = useState("");
  const set = (k) => (e) => setV({ ...v, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!v.name.trim()) er.name = "Please enter your name.";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email)) er.email = "Enter a valid email address.";
    if (!/^\d{5}$/.test(v.zip)) er.zip = "Enter a 5-digit ZIP.";
    setErr(er);
    if (Object.keys(er).length) return;
    setSubmitting(true);
    setSubmitErr("");
    try {
      await postSignup("supporter", {
        name: v.name.trim(),
        email: v.email.trim(),
        zip: v.zip.trim(),
        website: v.website,
        source: "home-signup",
      });
      setDone(true);
    } catch (e) {
      setSubmitErr(SUBMIT_ERROR);
    } finally {
      setSubmitting(false);
    }
  };
  if (done) {
    return (
      <div className="signup">
        <div className="signup__copy">
          <h3>Join the movement</h3>
          <p>Get campaign updates, events, and ways to help win the 2nd District.</p>
        </div>
        <div className="signup__form">
          <div className="signup__success">
            <Star /> <span>Thanks, {v.name.split(" ")[0]}! You&rsquo;re on the team. We&rsquo;ll be in touch soon.</span>
          </div>
        </div>
      </div>
    );
  }
  return (
    <div className="signup">
      <div className="signup__copy">
        <h3>Join the movement</h3>
        <p>Add your name for campaign updates, events, and ways to help bring accountability back to Olympia.</p>
      </div>
      <form className="signup__form" onSubmit={submit} noValidate>
        <Honeypot value={v.website} onChange={set("website")} />
        <p className="form-legend"><span className="req" aria-hidden="true"></span> Required</p>
        <div className="field field--full">
          <label htmlFor="su-name">Full name <span className="req" aria-hidden="true"></span></label>
          <input id="su-name" value={v.name} onChange={set("name")}
            className={err.name ? "invalid" : ""} placeholder="Jane Smith" />
          <span className="field__err">{err.name}</span>
        </div>
        <div className="field">
          <label htmlFor="su-email">Email <span className="req" aria-hidden="true"></span></label>
          <input id="su-email" type="email" value={v.email} onChange={set("email")}
            className={err.email ? "invalid" : ""} placeholder="jane@email.com" />
          <span className="field__err">{err.email}</span>
        </div>
        <div className="field">
          <label htmlFor="su-zip">ZIP code <span className="req" aria-hidden="true"></span></label>
          <input id="su-zip" inputMode="numeric" maxLength="5" value={v.zip} onChange={set("zip")}
            className={err.zip ? "invalid" : ""} placeholder="98558" />
          <span className="field__err">{err.zip}</span>
        </div>
        {submitErr ? <div className="field--full"><span className="field__err">{submitErr}</span></div> : null}
        <div className="field--full">
          <button className="btn btn--block" type="submit" disabled={submitting}>
            {submitting ? "Submitting…" : "Count me in"}
          </button>
        </div>
      </form>
    </div>
  );
}

function GetInvolved() {
  const acts = [
    { icon: "heart", h: "Donate", p: "Grassroots dollars fund the doors, mail, and ads that win this seat. Every contribution counts.", cta: "Give now", href: MM.donateUrl, ext: true },
    { icon: "users", h: "Volunteer", p: "Knock doors, make calls, and talk to neighbors. The 2nd District is won on the ground.", cta: "Sign up", modal: "volunteer" },
    { icon: "sign", h: "Yard sign", p: "Show your support and spread the word. Request a Marshall sign for your yard or business.", cta: "Request a sign", modal: "sign" },
  ];
  return (
    <section className="section involve" id="involved">
      <div className="container">
        <div className="involve__head">
          <span className="eyebrow eyebrow--onnavy">Get Involved</span>
          <h2 className="section-title">It takes all of us</h2>
          <p className="lead involve__lead" style={{ marginTop: 18 }}>
            Matt isn&rsquo;t backed by Olympia&rsquo;s insiders &mdash; he&rsquo;s backed by you.
            Here&rsquo;s how to put a physician assistant, veteran, and proven reformer back to work for the 2nd District.
          </p>
        </div>
        <div className="involve__cards">
          {acts.map((a) => (
            <div className="act" key={a.h}>
              <span className="act__icon"><Icon name={a.icon} /></span>
              <h4>{a.h}</h4>
              <p>{a.p}</p>
              {a.modal
                ? <button className="btn" type="button" onClick={() => openModal(a.modal)}>{a.cta}</button>
                : <a className="btn" href={a.href} target={a.ext ? "_blank" : undefined} rel={a.ext ? "noopener" : undefined}>{a.cta}</a>}
            </div>
          ))}
        </div>
        <div id="signup"><Signup /></div>
      </div>
    </section>
  );
}

/* ============================ MODALS ============================ */
function Modal({ eyebrow, title, sub, onClose, children, wide }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = prev; };
  }, []);
  return (
    <div className="modal-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className={"modal" + (wide ? " modal--wide" : "")} role="dialog" aria-modal="true" aria-label={title}>
        <button className="modal__close" onClick={onClose} aria-label="Close">&times;</button>
        <div className="modal__head">
          <span className="modal__eyebrow"><Star /> {eyebrow}</span>
          <h3 className="modal__title">{title}</h3>
          {sub ? <p className="modal__sub">{sub}</p> : null}
        </div>
        {children}
      </div>
    </div>
  );
}

function ModalSuccess({ name, children }) {
  return (
    <div className="signup__success modal__success">
      <Star /> <span>Thanks{name ? ", " + name : ""}! {children}</span>
    </div>
  );
}

const VOLUNTEER_INTERESTS = [
  "Door knocking & canvassing",
  "Phone & text banking",
  "Host a sign or event",
  "Yard sign distribution",
  "Data entry & office help",
  "Wherever I'm needed most",
];

function VolunteerForm({ onClose }) {
  const [v, setV] = useState({ first: "", last: "", email: "", phone: "", zip: "", website: "" });
  const [picked, setPicked] = useState([]);
  const [err, setErr] = useState({});
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitErr, setSubmitErr] = useState("");
  const set = (k) => (e) => setV({ ...v, [k]: e.target.value });
  const toggle = (i) => setPicked((p) => p.includes(i) ? p.filter((x) => x !== i) : [...p, i]);
  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!v.first.trim()) er.first = "Required";
    if (!v.last.trim()) er.last = "Required";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email)) er.email = "Enter a valid email.";
    if (v.phone.replace(/\D/g, "").length < 10) er.phone = "Enter a valid phone.";
    if (!/^\d{5}$/.test(v.zip)) er.zip = "Enter a 5-digit ZIP.";
    if (picked.length === 0) er.interests = "Pick at least one.";
    setErr(er);
    if (Object.keys(er).length) return;
    setSubmitting(true);
    setSubmitErr("");
    try {
      await postSignup("volunteer", {
        first: v.first.trim(),
        last: v.last.trim(),
        email: v.email.trim(),
        phone: v.phone.trim(),
        zip: v.zip.trim(),
        interests: picked.map((i) => VOLUNTEER_INTERESTS[i]),
        website: v.website,
        source: "volunteer-modal",
      });
      setDone(true);
    } catch (e) {
      setSubmitErr(SUBMIT_ERROR);
    } finally {
      setSubmitting(false);
    }
  };
  if (done) {
    return (
      <Modal eyebrow="Volunteer" title="Welcome to the team" onClose={onClose}>
        <ModalSuccess name={v.first}>
          We&rsquo;ve got your info and what you&rsquo;d like to help with. A campaign organizer
          will be in touch soon with the next steps.
        </ModalSuccess>
        <div className="modal__actions">
          <button className="btn btn--block" type="button" onClick={onClose}>Done</button>
        </div>
      </Modal>
    );
  }
  return (
    <Modal eyebrow="Volunteer" title="Join the team"
      sub="Tell us a little about yourself and where you&rsquo;d like to pitch in. We&rsquo;ll match you with the work that fits."
      onClose={onClose}>
      <form className="modal__form" onSubmit={submit} noValidate>
        <Honeypot value={v.website} onChange={set("website")} />
        <p className="form-legend"><span className="req" aria-hidden="true"></span> Required</p>
        <div className="field">
          <label htmlFor="vol-first">First name <span className="req" aria-hidden="true"></span></label>
          <input id="vol-first" value={v.first} onChange={set("first")} className={err.first ? "invalid" : ""} placeholder="Jane" />
          <span className="field__err">{err.first}</span>
        </div>
        <div className="field">
          <label htmlFor="vol-last">Last name <span className="req" aria-hidden="true"></span></label>
          <input id="vol-last" value={v.last} onChange={set("last")} className={err.last ? "invalid" : ""} placeholder="Smith" />
          <span className="field__err">{err.last}</span>
        </div>
        <div className="field">
          <label htmlFor="vol-email">Email <span className="req" aria-hidden="true"></span></label>
          <input id="vol-email" type="email" value={v.email} onChange={set("email")} className={err.email ? "invalid" : ""} placeholder="jane@email.com" />
          <span className="field__err">{err.email}</span>
        </div>
        <div className="field">
          <label htmlFor="vol-phone">Phone <span className="req" aria-hidden="true"></span></label>
          <input id="vol-phone" inputMode="tel" value={v.phone}
            onChange={(e) => setV({ ...v, phone: formatPhone(e.target.value) })}
            className={err.phone ? "invalid" : ""} placeholder="(253) 555-0134" />
          <span className="field__err">{err.phone}</span>
        </div>
        <div className="field">
          <label htmlFor="vol-zip">ZIP code <span className="req" aria-hidden="true"></span></label>
          <input id="vol-zip" inputMode="numeric" maxLength="5" value={v.zip} onChange={set("zip")}
            className={err.zip ? "invalid" : ""} placeholder="98558" />
          <span className="field__err">{err.zip}</span>
        </div>
        <div className="field--full">
          <span className="modal__legend">I&rsquo;m interested in&hellip; <span className="req" aria-hidden="true"></span></span>
          <div className="checks">
            {VOLUNTEER_INTERESTS.map((label, i) => (
              <label className={"check" + (picked.includes(i) ? " is-on" : "")} key={i}>
                <input type="checkbox" checked={picked.includes(i)} onChange={() => toggle(i)} />
                <span>{label}</span>
              </label>
            ))}
          </div>
          <span className="field__err" style={{ marginTop: 6 }}>{err.interests}</span>
        </div>
        {submitErr ? <div className="field--full"><span className="field__err">{submitErr}</span></div> : null}
        <div className="field--full">
          <button className="btn btn--block" type="submit" disabled={submitting}>
            {submitting ? "Submitting…" : "Sign me up"}
          </button>
        </div>
      </form>
    </Modal>
  );
}

function SignForm({ onClose }) {
  const [v, setV] = useState({ first: "", last: "", address: "", city: "", state: "WA", zip: "", email: "", phone: "", website: "" });
  const [err, setErr] = useState({});
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitErr, setSubmitErr] = useState("");
  const set = (k) => (e) => setV({ ...v, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!v.first.trim()) er.first = "Required";
    if (!v.last.trim()) er.last = "Required";
    if (!v.address.trim()) er.address = "Required";
    if (!v.city.trim()) er.city = "Required";
    if (!v.state.trim()) er.state = "Required";
    if (!/^\d{5}$/.test(v.zip)) er.zip = "5-digit ZIP";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email)) er.email = "Valid email";
    if (v.phone.replace(/\D/g, "").length < 10) er.phone = "Valid phone";
    setErr(er);
    if (Object.keys(er).length) return;
    setSubmitting(true);
    setSubmitErr("");
    try {
      await postSignup("yardsign", {
        first: v.first.trim(),
        last: v.last.trim(),
        address: v.address.trim(),
        city: v.city.trim(),
        state: v.state.trim(),
        zip: v.zip.trim(),
        email: v.email.trim(),
        phone: v.phone.trim(),
        website: v.website,
      });
      setDone(true);
    } catch (e) {
      setSubmitErr(SUBMIT_ERROR);
    } finally {
      setSubmitting(false);
    }
  };
  if (done) {
    return (
      <Modal eyebrow="Yard Sign" title="Sign requested" onClose={onClose}>
        <ModalSuccess name={v.first}>
          Your yard sign request is in. A member of our team will reach out to
          {" "}{v.address}{v.city ? ", " + v.city : ""} to coordinate delivery.
        </ModalSuccess>
        <div className="modal__actions">
          <button className="btn btn--block" type="button" onClick={onClose}>Done</button>
        </div>
      </Modal>
    );
  }
  return (
    <Modal eyebrow="Yard Sign" title="Request a yard sign" wide
      sub="Show your support across the 2nd District. Fill out the form below and our team will be in touch to coordinate delivery."
      onClose={onClose}>
      <form className="modal__form" onSubmit={submit} noValidate>
        <Honeypot value={v.website} onChange={set("website")} />
        <div className="field">
          <label htmlFor="ys-first">First name <span className="req" aria-hidden="true"></span></label>
          <input id="ys-first" value={v.first} onChange={set("first")} className={err.first ? "invalid" : ""} placeholder="Jane" />
          <span className="field__err">{err.first}</span>
        </div>
        <div className="field">
          <label htmlFor="ys-last">Last name <span className="req" aria-hidden="true"></span></label>
          <input id="ys-last" value={v.last} onChange={set("last")} className={err.last ? "invalid" : ""} placeholder="Smith" />
          <span className="field__err">{err.last}</span>
        </div>
        <div className="field field--full">
          <label htmlFor="ys-address">Delivery address <span className="req" aria-hidden="true"></span></label>
          <input id="ys-address" value={v.address} onChange={set("address")} className={err.address ? "invalid" : ""} placeholder="123 Main St" />
          <span className="field__err">{err.address}</span>
        </div>
        <div className="field--full modal__row3">
          <div className="field">
            <label htmlFor="ys-city">City <span className="req" aria-hidden="true"></span></label>
            <input id="ys-city" value={v.city} onChange={set("city")} className={err.city ? "invalid" : ""} placeholder="McKenna" />
            <span className="field__err">{err.city}</span>
          </div>
          <div className="field">
            <label htmlFor="ys-state">State <span className="req" aria-hidden="true"></span></label>
            <input id="ys-state" maxLength="2" value={v.state} onChange={set("state")} className={err.state ? "invalid" : ""} placeholder="WA" />
            <span className="field__err">{err.state}</span>
          </div>
          <div className="field">
            <label htmlFor="ys-zip">ZIP <span className="req" aria-hidden="true"></span></label>
            <input id="ys-zip" inputMode="numeric" maxLength="5" value={v.zip} onChange={set("zip")} className={err.zip ? "invalid" : ""} placeholder="98558" />
            <span className="field__err">{err.zip}</span>
          </div>
        </div>
        <div className="field">
          <label htmlFor="ys-email">Email <span className="req" aria-hidden="true"></span></label>
          <input id="ys-email" type="email" value={v.email} onChange={set("email")} className={err.email ? "invalid" : ""} placeholder="jane@email.com" />
          <span className="field__err">{err.email}</span>
        </div>
        <div className="field">
          <label htmlFor="ys-phone">Telephone <span className="req" aria-hidden="true"></span></label>
          <input id="ys-phone" inputMode="tel" value={v.phone}
            onChange={(e) => setV({ ...v, phone: formatPhone(e.target.value) })}
            className={err.phone ? "invalid" : ""} placeholder="(253) 555-0134" />
          <span className="field__err">{err.phone}</span>
        </div>
        <p className="modal__note">
          <Star /> All fields are required. Yard signs are delivered by our local volunteer team &mdash;
          after you submit, we&rsquo;ll contact you to coordinate a delivery time.
        </p>
        {submitErr ? <div className="field--full"><span className="field__err">{submitErr}</span></div> : null}
        <div className="field--full">
          <button className="btn btn--block" type="submit" disabled={submitting}>
            {submitting ? "Submitting…" : "Request my sign"}
          </button>
        </div>
      </form>
    </Modal>
  );
}

function Modals() {
  const [type, setType] = useState(null);
  useEffect(() => {
    const h = (e) => setType(e.detail);
    window.addEventListener("mm:modal", h);
    return () => window.removeEventListener("mm:modal", h);
  }, []);
  if (!type) return null;
  const close = () => setType(null);
  if (type === "volunteer") return <VolunteerForm onClose={close} />;
  if (type === "sign") return <SignForm onClose={close} />;
  return null;
}

/* ============================ FOOTER ============================ */
function Footer() {
  const social = {
    fb: { href: "https://www.facebook.com/profile.php?id=61563550869237", label: "Facebook", path: <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/> },
  };
  return (
    <footer className="footer">
      <div className="container container-wide">
        <div className="footer__top">
          <div className="footer__brand">
            <Wordmark dark />
            <p>Bringing medical, military, and common-sense experience to Olympia &mdash; fighting for the families and small towns of Washington&rsquo;s 2nd District.</p>
            <div className="footer__social" style={{ marginTop: 22 }}>
              {Object.entries(social).map(([k, s]) => (
                <a key={k} href={s.href} target="_blank" rel="noopener" aria-label={s.label}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.85" strokeLinecap="round" strokeLinejoin="round">{s.path}</svg></a>
              ))}
            </div>
          </div>
          <div className="footer__col">
            <h5>Explore</h5>
            <ul>
              <li><a href="#about">About Matt</a></li>
              <li><a href="#priorities">Priorities</a></li>
              <li><a href="#news">In the News</a></li>
              <li><a href="#involved">Get Involved</a></li>
            </ul>
          </div>
          <div className="footer__col">
            <h5>Take Action</h5>
            <ul>
              <li><a href={MM.donateUrl} target="_blank" rel="noopener">Donate</a></li>
              <li><a href="#involved" onClick={(e) => { e.preventDefault(); openModal("volunteer"); }}>Volunteer</a></li>
              <li><a href="#involved" onClick={(e) => { e.preventDefault(); openModal("sign"); }}>Request a yard sign</a></li>
              <li><a href={"mailto:" + MM.email}>{MM.email}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer__bottom">
          <span>{MM.address}</span>
          <span>&copy; {MM.year} Marshall for Washington. All rights reserved.</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Wordmark, Hero, Creds, About, Priorities, News, GetInvolved, Footer, Icon, Star, Modals, openModal });
