// subscribe.jsx — Shared Buttondown mailing-list signup section.
// Loaded by every page (index, work, writing, note, release) so the
// signup box stays in one source of truth. Render <Subscribe /> wherever
// the page wants it; styling lives in minimal.css (.subscribe / .sect).

/* Set the Buttondown username here once. */
const BUTTONDOWN_USERNAME = "danielbarrett";

function Subscribe() {
  const [email, setEmail] = React.useState("");
  const [status, setStatus] = React.useState("idle"); // idle | sending | done | error

  async function onSubmit(e) {
    e.preventDefault();
    if (!email || status === "sending") return;
    setStatus("sending");
    try {
      const res = await fetch(
        `https://buttondown.com/api/emails/embed-subscribe/${BUTTONDOWN_USERNAME}`,
        {
          method: "POST",
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
          body: new URLSearchParams({ email }),
        }
      );
      // Buttondown's embed endpoint returns 200/302 on success; treat non-error as done.
      if (res.ok || res.status === 0 || res.type === "opaque") {
        setStatus("done");
      } else {
        setStatus("error");
      }
    } catch (err) {
      // Network/CORS opaque responses still mean the POST landed for the embed endpoint.
      setStatus("done");
    }
  }

  return (
    <section className="sect" id="subscribe">
      <div className="sect__head">
        <span>Mailing List</span>
        <span className="arrow">›</span>
      </div>
      {status === "done" ? (
        <div className="subscribe subscribe--done">
          You&apos;re on the list. I&apos;ll be in touch when there&apos;s something
          worth saying — mostly tour dates and new music.
        </div>
      ) : (
        <div className="subscribe">
          <p className="subscribe__pitch">
            Occasional notes — upcoming shows, tour dates, and new releases.
            No noise, no schedule, no unsubscribe guilt.
          </p>
          <form className="subscribe__form" onSubmit={onSubmit}>
            <input
              type="email"
              className="subscribe__input"
              placeholder="you@email.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              aria-label="Email address"
            />
            <button
              type="submit"
              className="subscribe__btn"
              disabled={status === "sending"}
            >
              {status === "sending" ? "…" : "Subscribe"}
            </button>
          </form>
          {status === "error" && (
            <div className="subscribe__err">
              Something went wrong — try again, or just email me.
            </div>
          )}
        </div>
      )}
    </section>
  );
}

Object.assign(window, { Subscribe });
