/* Reusable newsletter signup. Writes the email to the Supabase `subscribers`
   table. Two layouts via the `variant` prop:
     "banner"  — compact inline bar (album pages, mid-homepage)
     "feature" — slightly larger card (kept available if needed)

   `cadence` decides what the form PROMISES: "weekly" (the Wednesday deep dive,
   the historic default) or "daily" (Album of the Day). This is not cosmetic —
   the cadence line and the post-subscribe confirmation were hardcoded to weekly,
   so an end-of-essay block pitching "a record in your inbox every morning" sat
   directly above the words "One email a week", and anyone who subscribed was
   then told they would receive weekly deep dives. Both promises come out of one
   `subscribers` row (weekend_pick_recipients is the shared audience), so the only
   thing that has to change per placement is what we say.

   Usage: <NewsletterSignup variant="banner" source="album:dark-side" />
          <NewsletterSignup variant="banner" cadence="daily" source="album:daily:x" hideCopy /> */

(function () {
  const { useState } = React;

  const COPY = {
    weekly: {
      title: "One legendary album, written up in full, every Wednesday.",
      sub: "No filler, no roundups, no sponsored picks.",
      foot: "One email a week · unsubscribe anytime, no dark patterns.",
      doneNote: "You’ll receive new deep dives each week.",
      doneLong: "You’re on the list. The next deep dive lands in your inbox Wednesday.",
      alreadyLong: "You’re already on the list. The next deep dive lands in your inbox Wednesday.",
    },
    daily: {
      title: "One record from the hundred, in your inbox every morning.",
      sub: "The case for it in a paragraph, and what a copy is worth.",
      foot: "One email a morning · unsubscribe anytime, no dark patterns.",
      doneNote: "Tomorrow morning’s record will be your first.",
      doneLong: "You’re on the list. Tomorrow morning’s record will be your first.",
      alreadyLong: "You’re already on the list — tomorrow morning’s record is on its way.",
    },
  };

  function NewsletterSignup({ variant = "banner", source = "homepage", hideCopy = false, cadence = "weekly", onDone }) {
    const c = COPY[cadence] || COPY.weekly;
    const [email, setEmail] = useState("");
    const [state, setState] = useState("idle"); // idle | saving | done | already | error
    const [msg, setMsg] = useState("");

    async function submit() {
      const value = (email || "").trim();
      if (!value || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) {
        setState("error");
        setMsg("Please enter a valid email address.");
        return;
      }
      setState("saving");
      try {
        if (window.BBR_supabase) {
          const { error } = await window.BBR_supabase
            .from("subscribers")
            .insert({ email: value, source });
          if (error) {
            // A duplicate email (unique constraint) isn't a failure — they're
            // already on the list. Show a distinct confirmation, not the
            // generic new-signup one.
            if (/duplicate|unique/i.test(error.message || "")) {
              setState("already");
              if (onDone) onDone("already");
              return;
            }
            throw error;
          }
        }
        setState("done");
        if (onDone) onDone("done");
      } catch (e) {
        console.error("[BBR] subscribe failed", e);
        setState("error");
        setMsg("Something went wrong. Please try again.");
      }
    }

    if (state === "done" || state === "already") {
      const already = state === "already";
      return (
        <div className={"nl-signup nl-" + variant + " nl-done"}>
          <span className="nl-tick">✓</span>
          {variant === "banner" ? (
            <span className="nl-done-text">
              <span className="nl-done-title">{already ? "Already subscribed" : "Subscribed"}</span>
              <span className="nl-done-note">
                {already
                  ? "This email is already on the list — you’re all set."
                  : c.doneNote}
              </span>
            </span>
          ) : (
            <span className="nl-done-text">
              {already
                ? c.alreadyLong
                : c.doneLong}
            </span>
          )}
        </div>
      );
    }

    return (
      <div className={"nl-signup nl-" + variant}>
        {!hideCopy && (
          <div className="nl-copy">
            <div className="nl-title">{c.title}</div>
            <div className="nl-sub">{c.sub}</div>
          </div>
        )}
        <div className="nl-form">
          <input
            className="nl-input"
            type="email"
            inputMode="email"
            placeholder="your@email"
            value={email}
            onChange={(e) => { setEmail(e.target.value); if (state === "error") setState("idle"); }}
            onKeyDown={(e) => { if (e.key === "Enter") submit(); }}
            aria-label="Email address"
          />
          <button className="nl-btn" onClick={submit} disabled={state === "saving"}>
            {state === "saving" ? "…" : "Subscribe"}
            {state !== "saving" && (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
            )}
          </button>
        </div>
        {state === "error" && <div className="nl-err">{msg}</div>}
        <div className="nl-foot">{c.foot}</div>
      </div>
    );
  }

  window.NewsletterSignup = NewsletterSignup;
})();
