/* 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)
   Usage: <NewsletterSignup variant="banner" source="album:dark-side" /> */

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

  function NewsletterSignup({ variant = "banner", source = "homepage" }) {
    const [email, setEmail] = useState("");
    const [state, setState] = useState("idle"); // idle | saving | done | 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 });
          // A duplicate email (unique constraint) is a success from the user's
          // point of view — they're already on the list.
          if (error && !/duplicate|unique/i.test(error.message || "")) {
            throw error;
          }
        }
        setState("done");
      } catch (e) {
        console.error("[BBR] subscribe failed", e);
        setState("error");
        setMsg("Something went wrong. Please try again.");
      }
    }

    if (state === "done") {
      return (
        <div className={"nl-signup nl-" + variant + " nl-done"}>
          <span className="nl-tick">✓</span>
          <span className="nl-done-text">You&rsquo;re on the list. The next deep dive lands in your inbox Wednesday.</span>
        </div>
      );
    }

    return (
      <div className={"nl-signup nl-" + variant}>
        <div className="nl-copy">
          <div className="nl-title">One legendary album, written up in full, every Wednesday.</div>
          <div className="nl-sub">No filler, no roundups. Plus restock alerts when a grail pressing returns.</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">One email a week · unsubscribe anytime, no dark patterns.</div>
      </div>
    );
  }

  window.NewsletterSignup = NewsletterSignup;
})();
