// =============================================================
// CONFIG — REPLACE THESE BEFORE GOING LIVE
// User to provide:
//   FORMSPREE_URL  — sign up free at https://formspree.io, create a form,
//                    paste the endpoint (looks like https://formspree.io/f/xxxxxxxx)
//   MAYA_CALENDLY_URL — Maya creates a "Curiosity Call · 15 min" event on
//                    https://calendly.com and pastes her booking link here
// Until both are set, the form will show a "config pending" notice.
// =============================================================
const FORMSPREE_URL = "https://formspree.io/f/REPLACE_ME";
const MAYA_CALENDLY_URL = "https://calendly.com/REPLACE_ME";

const IS_FORMSPREE_CONFIGURED = !FORMSPREE_URL.endsWith("REPLACE_ME");

function Petition() {
  // Two modes based on URL hash:
  //   #petition           → apply (full form, default)
  //   #petition-waitlist  → waitlist (mini form)
  const [intent, setIntent] = React.useState(() =>
    typeof window !== "undefined" && window.location.hash === "#petition-waitlist"
      ? "waitlist"
      : "apply"
  );
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [name, setName] = React.useState("");

  // Listen for hash changes (CTA clicks update the hash before scrolling)
  React.useEffect(() => {
    const onHash = () => {
      setIntent(window.location.hash === "#petition-waitlist" ? "waitlist" : "apply");
      setSubmitted(false);
      setError(null);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  async function onSubmit(e) {
    e.preventDefault();
    if (!IS_FORMSPREE_CONFIGURED) {
      setError("Form endpoint isn't configured yet. Tell Wojtek to plug in the Formspree URL.");
      return;
    }
    setSubmitting(true);
    setError(null);
    const fd = new FormData(e.currentTarget);
    try {
      const res = await fetch(FORMSPREE_URL, {
        method: "POST",
        body: fd,
        headers: { Accept: "application/json" },
      });
      if (res.ok) {
        setSubmitted(true);
      } else {
        const data = await res.json().catch(() => ({}));
        setError(data.error || "Something didn't send. Try again in a moment.");
      }
    } catch (err) {
      setError("No connection. Try again in a moment.");
    } finally {
      setSubmitting(false);
    }
  }

  const isApply = intent === "apply";
  const subjectLine = isApply
    ? "Apply · Witches & Bitches Ed01"
    : "Waitlist · Edition 02";

  return (
    <section className="dark petition" id="petition">
      <div className="grain"></div>
      <div className="vignette"></div>
      <div className="container narrow">
        <SectionHead
          eyebrow={isApply ? "Apply to Neverland · VII" : "Edition 02 Waitlist · VII"}
          title={isApply ? (
            <>
              <img className="title-char title-char--left" src="./characters/dwarf.webp" alt="" aria-hidden="true" />
              Cast your name.
            </>
          ) : (
            "Take your seat in line."
          )}
          lede={isApply
            ? "Twelve seats. We read every application by candle. Maya answers within forty-eight hours."
            : "Edition 02 will be larger and more produced. Drop your name — Maya writes to you before anyone else."}
          ornaments={["all-seeing-eye", "star-seven", "all-seeing-eye"]}
        />
        {submitted ? (
          <Reveal className="form" delay={120}>
            <div style={{ textAlign: "center", padding: "60px 0" }}>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 48, color: "var(--gold)", textTransform: "uppercase", letterSpacing: "0.04em", lineHeight: 1, marginBottom: 18 }}>
                {isApply
                  ? <>Thy petition is heard{name ? `, ${name.split(" ")[0]}` : ""}.</>
                  : <>You are on the list{name ? `, ${name.split(" ")[0]}` : ""}.</>}
              </div>
              <div style={{ fontFamily: "var(--font-body)", fontStyle: "italic", fontSize: 20, color: "var(--fg-on-ink-muted)", maxWidth: 520, margin: "0 auto" }}>
                {isApply
                  ? "Maya will write back within forty-eight hours. If you do not hear from us, check your spam — and the moon."
                  : "When Edition 02 opens, you will hear first. No spam in between."}
              </div>
              <div style={{ fontFamily: "var(--font-script)", fontSize: 40, color: "var(--gold-pale)", marginTop: 32 }}>— Maya</div>
            </div>
          </Reveal>
        ) : (
          <Reveal as="form" className="form" delay={120} onSubmit={onSubmit}>
            {/* Honeypot — bots fill it, humans don't see it */}
            <input type="text" name="_gotcha" tabIndex="-1" autoComplete="off"
                   style={{ position: "absolute", left: "-9999px" }} aria-hidden="true" />
            {/* Hidden meta for Maya */}
            <input type="hidden" name="_subject" value={subjectLine} />
            <input type="hidden" name="intent" value={intent} />
            {!isApply && (
              <input type="hidden" name="form_mode" value="waitlist" />
            )}

            {isApply ? (
              <>
                <div className="field-row">
                  <div className="field">
                    <label className="lbl" htmlFor="petition-name">Thy Name</label>
                    <input id="petition-name" name="name" required
                           value={name} onChange={(e) => setName(e.target.value)}
                           placeholder="As it shall be inscribed" />
                    <span className="hint">First <span className="amp">&amp;</span> last. The name you came in with.</span>
                  </div>
                  <div className="field">
                    <label className="lbl" htmlFor="petition-email">A Whisper Where We May Find Thee</label>
                    <input id="petition-email" name="email" type="email" required
                           placeholder="you@example.com" />
                    <span className="hint">We answer by email. Sometimes also by post.</span>
                  </div>
                </div>
                <div className="field">
                  <label className="lbl" htmlFor="petition-instagram">Instagram (Optional)</label>
                  <input id="petition-instagram" name="instagram"
                         placeholder="@handle — so we can see you a little" />
                  <span className="hint">Not required. Helps us recognise you.</span>
                </div>
                <div className="field">
                  <label className="lbl" htmlFor="petition-why">Why Neverland · Why Now</label>
                  <textarea id="petition-why" name="why" rows="4"
                            placeholder="Three honest sentences. No essay. Maya reads these out loud."></textarea>
                  <span className="hint">A paragraph. Not a CV.</span>
                </div>
              </>
            ) : (
              <>
                <div className="field-row">
                  <div className="field">
                    <label className="lbl" htmlFor="waitlist-name">Thy Name</label>
                    <input id="waitlist-name" name="name" required
                           value={name} onChange={(e) => setName(e.target.value)}
                           placeholder="As it shall be inscribed" />
                  </div>
                  <div className="field">
                    <label className="lbl" htmlFor="waitlist-email">Email</label>
                    <input id="waitlist-email" name="email" type="email" required
                           placeholder="you@example.com" />
                  </div>
                </div>
                <div className="field">
                  <label className="lbl" htmlFor="waitlist-note">A line, if you want (Optional)</label>
                  <input id="waitlist-note" name="note"
                         placeholder="What pulls you toward Edition 02?" />
                  <span className="hint">Optional. Helps Maya remember you when the time comes.</span>
                </div>
              </>
            )}

            <div style={{ display: "flex", gap: 18, alignItems: "center", marginTop: 18, flexWrap: "wrap" }}>
              <button type="submit" className="btn solid on-dark" disabled={submitting}>
                {submitting
                  ? "Sending…"
                  : isApply ? "Apply to Neverland ☞" : "Join the Waitlist ☞"}
              </button>
              <span style={{ fontFamily: "var(--font-body)", fontStyle: "italic", fontSize: 14, color: "var(--fg-on-ink-muted)" }}>
                {isApply ? "You may withdraw at any time before the boat." : "We never sell or share your name."}
              </span>
            </div>
            {error && (
              <div style={{ marginTop: 16, color: "#e6a77a", fontFamily: "var(--font-body)", fontStyle: "italic" }}>
                {error}
              </div>
            )}
            {!IS_FORMSPREE_CONFIGURED && (
              <div style={{ marginTop: 18, padding: "10px 14px", border: "1px dashed var(--gold-deep)",
                            color: "var(--gold-pale)", fontFamily: "var(--font-smallcaps)",
                            fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase" }}>
                Form endpoint not configured — submissions won't send yet
              </div>
            )}
          </Reveal>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { Petition, MAYA_CALENDLY_URL });
