// MailingListSignup — custom name + email form for Kid Link's Mailchimp audience.
// Static-site friendly: submits via Mailchimp's JSONP endpoint (no backend, no CORS).
//
// Pulled from the public sign-up page: account u=9026067eab24bf09555cc40b7,
// audience id=001b4de4f0, data centre us10.
//
// Submit URL from the account's classic embed code, switched to the JSONP variant
// (/subscribe/post -> /subscribe/post-json) so it works from this static site.
const MAILCHIMP_SIGNUP_ACTION = "https://kidlink.us10.list-manage.com/subscribe/post-json?u=9026067eab24bf09555cc40b7&id=3e4a0733b7&f_id=00024de4f0";

// Anti-bot honeypot field name = b_<u>_<id>. Real users leave it blank.
const MAILCHIMP_HONEYPOT = "b_9026067eab24bf09555cc40b7_3e4a0733b7";

// First name lives in MMERGE1 for this audience (not the default FNAME).
// "I want to receive information for" interest group: we tag each signup by the audience
// page it came from. Choices — 32: OTs, 32768: Parents, 65536: Support workers, 131072: Teachers.
const MAILCHIMP_GROUP_ID = "496697";

function mailchimpSubscribe({ email, fname, lname, group }) {
  return new Promise((resolve) => {
    if (!MAILCHIMP_SIGNUP_ACTION) {
      resolve({ result: "error", msg: "Sign-up isn't connected yet — add the Mailchimp form URL." });
      return;
    }
    const cb = "mc_cb_" + Math.random().toString(36).slice(2);
    const sep = MAILCHIMP_SIGNUP_ACTION.includes("?") ? "&" : "?";
    let url = MAILCHIMP_SIGNUP_ACTION
      + sep + "EMAIL=" + encodeURIComponent(email)
      + "&MMERGE1=" + encodeURIComponent(fname)
      + "&MMERGE2=" + encodeURIComponent(lname)
      + "&c=" + cb;
    // Tag the signup with the audience interest group for the page it came from.
    if (group) url += "&" + encodeURIComponent("group[" + MAILCHIMP_GROUP_ID + "][" + group + "]") + "=" + encodeURIComponent(group);
    const script = document.createElement("script");
    let done = false;
    const cleanup = () => { delete window[cb]; if (script.parentNode) script.parentNode.removeChild(script); };
    window[cb] = (data) => { done = true; cleanup(); resolve(data || { result: "error", msg: "No response." }); };
    script.onerror = () => { if (!done) { cleanup(); resolve({ result: "error", msg: "Network error. Please try again." }); } };
    script.src = url;
    document.body.appendChild(script);
    setTimeout(() => { if (!done) { cleanup(); resolve({ result: "error", msg: "Timed out. Please try again." }); } }, 10000);
  });
}

function MailingListSignup({
  scheme = "scheme-1",
  eyebrow = "Stay in the loop",
  heading = "Join our mailing list",
  blurb = "Get upcoming events, new courses and Kid Link updates straight to your inbox. No spam, unsubscribe anytime.",
  group,
}) {
  const [fname, setFname] = useState("");
  const [lname, setLname] = useState("");
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("idle"); // idle | loading | success | error
  const [message, setMessage] = useState("");
  const honeypotRef = useRef(null);

  const inputStyle = {
    width: "100%",
    padding: "12px 14px",
    fontFamily: "var(--kl-font-body)",
    fontSize: "var(--kl-text-regular)",
    color: "var(--kl-fg-1)",
    background: "var(--kl-white)",
    border: "1px solid var(--kl-border)",
    borderRadius: "var(--kl-radius-form)",
    boxSizing: "border-box",
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    // Honeypot: if a bot filled the hidden field, pretend success and skip the call.
    if (honeypotRef.current && honeypotRef.current.value) { setStatus("success"); setMessage("Thanks for subscribing!"); return; }
    setStatus("loading"); setMessage("");
    const data = await mailchimpSubscribe({ email, fname, lname, group });
    if (data.result === "success") {
      setStatus("success");
      if (window.klTrack) window.klTrack("mailing_list_signup", { group: group || "untagged" });
      setMessage("You're on the list! Check your inbox to confirm.");
    } else {
      setStatus("error");
      setMessage((data.msg || "Something went wrong. Please try again.").replace(/<[^>]*>/g, ""));
    }
  };

  return (
    <Section scheme={scheme}>
      <div style={{ maxWidth: 640, marginInline: "auto", textAlign: "center" }}>
        <Eyebrow>{eyebrow}</Eyebrow>
        <h2 style={{ fontSize: "var(--kl-text-h2)", marginTop: 12, marginBottom: 16 }}>{heading}</h2>
        <p style={{ fontSize: "var(--kl-text-medium)", lineHeight: 1.5, marginBottom: 32, color: "var(--kl-fg-2)" }}>{blurb}</p>

        {status === "success" ? (
          <div style={{ display: "inline-flex", alignItems: "center", gap: 12, justifyContent: "center" }}>
            <MIcon name="check_circle" size={28} color="var(--kl-leaf-darker)" />
            <span style={{ fontSize: "var(--kl-text-medium)", fontWeight: 600 }}>{message}</span>
          </div>
        ) : (
          <form onSubmit={onSubmit}>
            <div style={{ maxWidth: 560, marginInline: "auto", textAlign: "left" }}>
              <div className="kl-cols-2" style={{ gap: 16 }}>
                <div>
                  <label htmlFor="ml-fname" style={{ display: "block", fontSize: "var(--kl-text-small)", fontWeight: 600, marginBottom: 6 }}>First name</label>
                  <input id="ml-fname" type="text" required value={fname} onChange={(e) => setFname(e.target.value)} autoComplete="given-name" style={inputStyle} />
                </div>
                <div>
                  <label htmlFor="ml-lname" style={{ display: "block", fontSize: "var(--kl-text-small)", fontWeight: 600, marginBottom: 6 }}>Last name</label>
                  <input id="ml-lname" type="text" required value={lname} onChange={(e) => setLname(e.target.value)} autoComplete="family-name" style={inputStyle} />
                </div>
              </div>
              <div style={{ marginTop: 16 }}>
                <label htmlFor="ml-email" style={{ display: "block", fontSize: "var(--kl-text-small)", fontWeight: 600, marginBottom: 6 }}>Email address</label>
                <input id="ml-email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" style={inputStyle} />
              </div>
            </div>

            {/* Honeypot — hidden from real users, catches bots */}
            <div aria-hidden="true" style={{ position: "absolute", left: "-5000px" }}>
              <input ref={honeypotRef} type="text" name={MAILCHIMP_HONEYPOT} tabIndex={-1} defaultValue="" autoComplete="off" />
            </div>

            <div style={{ marginTop: 16, display: "flex", justifyContent: "center" }}>
              <Button variant="primary" type="submit" iconRight={<ChevronRight />}>{status === "loading" ? "Signing up…" : "Subscribe"}</Button>
            </div>

            {status === "error" && (
              <p style={{ marginTop: 12, color: "var(--kl-plum)", fontSize: "var(--kl-text-small)", fontWeight: 600 }}>{message}</p>
            )}
            <p style={{ marginTop: 12, fontSize: "var(--kl-text-tiny)", color: "var(--kl-fg-3)" }}>We never share your details. Unsubscribe anytime.</p>
          </form>
        )}
      </div>
    </Section>
  );
}

window.MailingListSignup = MailingListSignup;
