// Give module — two-path checkout:
//   1. Recommended: create an account (or sign in) → tax-deductible receipt + lifetime tracking
//   2. Anonymous: card-only, no personal info captured

const { useState: useStateG, useEffect: useEffectG, useRef: useRefG } = React;

// Lazily build the Stripe.js instance once Stripe.js + the publishable key are both available.
let _stripeSingleton = null;
function getStripe() {
  if (_stripeSingleton) return _stripeSingleton;
  if (typeof window === "undefined" || !window.Stripe) return null;
  const pk = window.NE_CONFIG && window.NE_CONFIG.stripePublishableKey;
  if (!pk) return null;
  _stripeSingleton = window.Stripe(pk);
  return _stripeSingleton;
}

function GiveCard({ raised, onGive }) {
  const presets = [10, 25, 50, 100, 250, 500];
  const [amount, setAmount] = useStateG(50);
  const [custom, setCustom] = useStateG("");
  const [addOne, setAddOne] = useStateG(true);
  const [freq, setFreq] = useStateG("once");
  const [dedication, setDedication] = useStateG("");
  const [tributeType, setTributeType] = useStateG("none");
  const [tributeName, setTributeName] = useStateG("");
  const [notifyEmail, setNotifyEmail] = useStateG("");

  // Auth-flow state for the give checkout
  const [loggedIn, setLoggedIn] = useStateG(typeof NE_API !== "undefined" && NE_API.isLoggedIn());
  const [me, setMe] = useStateG(null);
  const [authPath, setAuthPath] = useStateG("choose"); // choose | register | signin
  const [busy, setBusy] = useStateG(false);
  const [err, setErr] = useStateG("");

  // Register form
  const [regName, setRegName] = useStateG("");
  const [regEmail, setRegEmail] = useStateG("");
  const [regPhone, setRegPhone] = useStateG("");
  const [regPw, setRegPw] = useStateG("");

  // Sign-in form
  const [siEmail, setSiEmail] = useStateG("");
  const [siPw, setSiPw] = useStateG("");

  // Stripe card-collection step
  const [pendingIntent, setPendingIntent] = useStateG(null); // { donationId, clientSecret }
  const [cardReady, setCardReady] = useStateG(false);
  const cardMountRef = useRefG(null);
  const elementsRef = useRefG(null);
  const paymentElementRef = useRefG(null);

  useEffectG(() => {
    if (loggedIn && !me) {
      NE_API.me().then(setMe).catch(() => {});
    }
  }, [loggedIn]);

  // Mount the Stripe Payment Element once we have a clientSecret + a DOM node.
  useEffectG(() => {
    if (!pendingIntent || !cardMountRef.current) return;
    const stripe = getStripe();
    if (!stripe) return;
    const elements = stripe.elements({
      clientSecret: pendingIntent.clientSecret,
      appearance: { theme: "stripe", variables: { colorPrimary: "#B5A86B", fontFamily: "Inter, sans-serif" } },
    });
    const paymentElement = elements.create("payment", { layout: "tabs" });
    paymentElement.on("ready", () => setCardReady(true));
    paymentElement.mount(cardMountRef.current);
    elementsRef.current = elements;
    paymentElementRef.current = paymentElement;
    return () => {
      try { paymentElement.unmount(); } catch {}
      elementsRef.current = null;
      paymentElementRef.current = null;
      setCardReady(false);
    };
  }, [pendingIntent]);

  const baseAmount = custom ? Number(custom) || 0 : amount;
  const effective = baseAmount + (addOne ? 1 : 0);
  const moneyLabel = formatMoney(effective);
  const frequency = freq === "monthly" ? "MONTHLY" : "ONCE";

  const buildMessage = () => {
    const parts = [];
    if (tributeType === "honor" && tributeName.trim()) parts.push("In honor of " + tributeName.trim());
    if (tributeType === "memory" && tributeName.trim()) parts.push("In memory of " + tributeName.trim());
    if (dedication.trim()) parts.push(dedication.trim());
    return parts.length ? parts.join(" — ") : undefined;
  };

  const submitDonation = async () => {
    if (effective <= 0) { setErr("Choose an amount to give."); return; }
    setBusy(true); setErr("");
    try {
      const result = await NE_API.createDonationIntent(Math.round(effective * 100), {
        frequency: frequency,
        addedDollar: addOne,
        message: buildMessage(),
      });
      // If Stripe is configured (clientSecret returned + Stripe.js loaded), collect card.
      // Otherwise the gift is recorded as PENDING and we just confirm to the donor.
      if (result && result.clientSecret && getStripe()) {
        setPendingIntent(result);
      } else {
        onGive(effective);
      }
    } catch (e) {
      setErr(e.message || "Gift failed. Please try again.");
    } finally {
      setBusy(false);
    }
  };

  const confirmCard = async () => {
    const stripe = getStripe();
    const elements = elementsRef.current;
    if (!stripe || !elements || !pendingIntent) return;
    setBusy(true); setErr("");
    const isSetup = String(pendingIntent.clientSecret).startsWith("seti_");
    const confirmFn = isSetup ? stripe.confirmSetup : stripe.confirmPayment;
    try {
      const { error } = await confirmFn.call(stripe, {
        elements,
        confirmParams: { return_url: window.location.origin + "/account.html?gift=ok" },
        redirect: "if_required",
      });
      if (error) {
        setErr(error.message || "Card declined. Please try a different payment method.");
        setBusy(false);
        return;
      }
      // Success — clear the panel and let the parent celebrate.
      setPendingIntent(null);
      setBusy(false);
      onGive(effective);
    } catch (e) {
      setErr(e.message || "Payment failed. Please try again.");
      setBusy(false);
    }
  };

  const cancelCard = () => {
    setPendingIntent(null);
    setErr("");
  };

  const giveAnonymously = async () => {
    if (effective <= 0) { setErr("Choose an amount to give."); return; }
    NE_API.logout();
    setLoggedIn(false); setMe(null);
    await submitDonation();
  };

  const registerAndGive = async () => {
    if (effective <= 0) { setErr("Choose an amount to give."); return; }
    const fullName = regName.trim();
    const parts = fullName.split(/\s+/).filter(Boolean);
    if (parts.length < 1) { setErr("Please enter your full name."); return; }
    const lastName = parts.length > 1 ? parts.pop() : parts[0];
    const firstName = parts.join(" ") || lastName;
    const email = regEmail.trim().toLowerCase();
    if (!email) { setErr("Please enter your email."); return; }
    if (regPw.length < 8) { setErr("Password must be at least 8 characters."); return; }
    setBusy(true); setErr("");
    try {
      await NE_API.register(email, regPw, firstName, lastName, regPhone.trim() || undefined);
      setLoggedIn(true);
      const profile = await NE_API.me();
      setMe(profile);
    } catch (e) {
      setErr(e.message || "Could not create account.");
      setBusy(false);
      return;
    }
    await submitDonation();
  };

  const signInAndGive = async () => {
    if (effective <= 0) { setErr("Choose an amount to give."); return; }
    const email = siEmail.trim().toLowerCase();
    if (!email || !siPw) { setErr("Enter email and password."); return; }
    setBusy(true); setErr("");
    try {
      await NE_API.login(email, siPw);
      setLoggedIn(true);
      const profile = await NE_API.me();
      setMe(profile);
    } catch (e) {
      setErr(e.message || "Incorrect email or password.");
      setBusy(false);
      return;
    }
    await submitDonation();
  };

  const fieldStyle = { width: "100%", padding: "12px 14px", border: "1px solid rgba(47,51,29,0.2)", borderRadius: 2, fontSize: 14, background: "white" };
  const labelStyle = { display: "block", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(47,51,29,0.55)", marginBottom: 6, marginTop: 14 };

  return (
    <div className="give-card" style={{ background: "var(--cream-50)", padding: 40, border: "1px solid rgba(47,51,29,0.1)", boxShadow: "0 30px 60px -30px rgba(47,51,29,0.35)", minWidth: 0, maxWidth: "100%", overflow: "hidden" }}>
      <div className="rule left" style={{ marginBottom: 18 }}>Give · Every amount plants something</div>

      <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 8 }}>
        <span style={{ fontFamily: "var(--serif)", fontSize: 52, lineHeight: 1, color: "var(--navy-900)" }}>
          {moneyLabel}
        </span>
        <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(47,51,29,0.55)" }}>
          {freq === "monthly" ? "per month" : "one gift"}
        </span>
      </div>
      <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold-600, rgb(138,125,77))", marginBottom: 24 }}>
        Community total · {formatMoney(raised)}
      </div>

      {/* Preset grid */}
      <div className="preset-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginBottom: 14 }}>
        {presets.map(p => (
          <button key={p} type="button"
            onClick={() => { setAmount(p); setCustom(""); }}
            style={{
              padding: "18px 0",
              border: "1px solid " + (amount === p && !custom ? "var(--gold-500)" : "rgba(47,51,29,0.15)"),
              background: amount === p && !custom ? "rgba(181,168,107,0.08)" : "transparent",
              color: "var(--navy-900)",
              fontFamily: "var(--serif)", fontSize: 22,
              transition: "all 180ms",
            }}>
            ${p}
          </button>
        ))}
      </div>

      <label className="field" style={{ marginTop: 18 }}>Or a custom amount</label>
      <div style={{ display: "flex", alignItems: "center", gap: 0, border: "1px solid rgba(47,51,29,0.2)" }}>
        <span style={{ padding: "14px 14px", fontFamily: "var(--serif)", fontSize: 20, color: "rgba(47,51,29,0.5)" }}>$</span>
        <input
          type="text" inputMode="decimal" placeholder="Enter amount"
          value={custom}
          onChange={e => setCustom(e.target.value.replace(/[^0-9.]/g, ""))}
          style={{ border: "none", padding: "14px 4px", background: "transparent", fontSize: 18 }}
        />
      </div>

      {/* frequency */}
      <div style={{ marginTop: 20, display: "flex", gap: 8 }}>
        {[["once", "One gift"], ["monthly", "Monthly"]].map(([v, l]) => (
          <button key={v} type="button" onClick={() => setFreq(v)}
            style={{
              flex: 1, padding: "12px 0",
              border: "1px solid " + (freq === v ? "var(--navy-800)" : "rgba(47,51,29,0.15)"),
              background: freq === v ? "var(--navy-800)" : "transparent",
              color: freq === v ? "var(--cream-50)" : "var(--navy-900)",
              fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
              transition: "all 180ms",
            }}>
            {l}
          </button>
        ))}
      </div>

      {/* Add $1 */}
      <label style={{ display: "flex", alignItems: "flex-start", gap: 12, marginTop: 22, cursor: "pointer" }}>
        <input type="checkbox" checked={addOne} onChange={e => setAddOne(e.target.checked)}
          style={{ marginTop: 4, accentColor: "var(--gold-500)", width: 16, height: 16 }} />
        <div>
          <div style={{ fontSize: 14, color: "var(--navy-900)" }}>Add <strong>$1</strong> to help build New Eden Academy</div>
          <div style={{ fontSize: 12, color: "rgba(47,51,29,0.55)", marginTop: 2 }}>Small seeds grow tall trees. $1 goes straight to the academy fund.</div>
        </div>
      </label>

      {/* Tribute / memorial gift */}
      <div style={{ marginTop: 26, paddingTop: 22, borderTop: "1px dashed rgba(47,51,29,0.15)" }}>
        <label className="field" style={{ marginBottom: 10 }}>Give in tribute (optional)</label>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 6 }}>
          {[
            ["none", "No tribute"],
            ["honor", "In honor of"],
            ["memory", "In memory of"],
          ].map(([v, l]) => (
            <button key={v} type="button" onClick={() => setTributeType(v)}
              style={{
                padding: "10px 6px",
                border: "1px solid " + (tributeType === v ? "var(--gold-500)" : "rgba(47,51,29,0.15)"),
                background: tributeType === v ? "rgba(181,168,107,0.1)" : "transparent",
                color: "var(--navy-900)",
                fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase",
                transition: "all 180ms",
              }}>{l}</button>
          ))}
        </div>

        {tributeType !== "none" && (
          <div style={{ marginTop: 14, display: "grid", gap: 10 }}>
            <input type="text"
              placeholder={tributeType === "honor" ? "Whom are you honoring?" : "Whom are you remembering?"}
              value={tributeName} onChange={e => setTributeName(e.target.value)} />
            <input type="email"
              placeholder={tributeType === "honor" ? "Honoree email (we'll send a card)" : "Family email (optional)"}
              value={notifyEmail} onChange={e => setNotifyEmail(e.target.value)} />
            <div style={{ fontSize: 12, color: "rgba(47,51,29,0.6)", fontStyle: "italic", lineHeight: 1.5 }}>
              We'll send {tributeType === "honor" ? "them" : "the family"} a simple note — no amount shown — letting them know a gift was made {tributeType === "honor" ? "in their honor" : "in loving memory"}.
            </div>
          </div>
        )}
      </div>

      <label className="field" style={{ marginTop: 22 }}>Personal note (optional)</label>
      <input type="text" placeholder="A word of blessing, a prayer, a reason"
        value={dedication} onChange={e => setDedication(e.target.value)} />

      {/* ========== TWO-PATH CHECKOUT ========== */}
      <div style={{ marginTop: 30, paddingTop: 26, borderTop: "1px solid rgba(47,51,29,0.12)" }}>

        {/* === STRIPE CARD PANEL (active once an intent has been created) === */}
        {pendingIntent && (
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, margin: 0, color: "var(--navy-900)" }}>
                Card details
              </h3>
              <button type="button" onClick={cancelCard} disabled={busy}
                style={{ background: "transparent", color: "rgba(47,51,29,0.55)", fontSize: 12, padding: "4px 8px" }}>
                ← Back
              </button>
            </div>
            <div style={{ fontSize: 13, color: "rgba(47,51,29,0.65)", marginBottom: 16, lineHeight: 1.5 }}>
              Secure checkout via Stripe. Your card is charged {moneyLabel}{freq === "monthly" ? " each month" : ""} once you confirm.
            </div>
            <div ref={cardMountRef} style={{ minHeight: 80 }} />
            {!cardReady && (
              <div style={{ marginTop: 10, fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(47,51,29,0.5)" }}>
                Loading secure card form…
              </div>
            )}

            {err && <div style={{ marginTop: 14, padding: "10px 14px", background: "rgba(180,89,58,0.1)", color: "#8b3f26", fontSize: 13, border: "1px solid rgba(180,89,58,0.3)" }}>{err}</div>}

            <button type="button" onClick={confirmCard} disabled={busy || !cardReady}
              className="btn btn-gold" style={{ marginTop: 18, width: "100%", padding: 16, opacity: (busy || !cardReady) ? 0.6 : 1 }}>
              {busy ? "Processing…" : "Pay " + moneyLabel + (freq === "monthly" ? " / month" : "")}
            </button>
            <div style={{ marginTop: 10, fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(47,51,29,0.5)", textAlign: "center" }}>
              Stripe · 256-bit Encryption · No Card Stored on Our Server
            </div>
          </div>
        )}

        {/* === LOGGED IN: one-tap give === */}
        {!pendingIntent && loggedIn && (
          <div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(47,51,29,0.55)", marginBottom: 10 }}>
              Signed in {me ? "as " + (me.firstName ? me.firstName + " " + me.lastName : me.email) : ""}
            </div>
            <button type="button" onClick={submitDonation} disabled={busy}
              className="btn btn-gold" style={{ width: "100%", padding: 18, opacity: busy ? 0.6 : 1 }}>
              {busy ? "Processing…" : "Plant this Gift · " + moneyLabel}
            </button>
            <div style={{ marginTop: 10, textAlign: "center" }}>
              <button type="button" onClick={() => { NE_API.logout(); setLoggedIn(false); setMe(null); setAuthPath("choose"); }}
                style={{ background: "transparent", color: "rgba(47,51,29,0.55)", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", padding: "6px 10px" }}>
                Sign out & give anonymously
              </button>
            </div>
          </div>
        )}

        {/* === NOT LOGGED IN: choose path === */}
        {!pendingIntent && !loggedIn && authPath === "choose" && (
          <>
            {/* Recommended: account path */}
            <div style={{ background: "linear-gradient(180deg, rgba(181,168,107,0.10), rgba(181,168,107,0.04))", border: "1px solid rgba(181,168,107,0.45)", borderRadius: 2, padding: 22, position: "relative" }}>
              <div style={{ position: "absolute", top: -10, left: 18, background: "var(--gold-500)", color: "var(--navy-900)", padding: "3px 10px", fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.24em", textTransform: "uppercase", fontWeight: 600 }}>
                Recommended
              </div>
              <h3 style={{ marginTop: 6, fontFamily: "var(--serif)", fontSize: 22, color: "var(--navy-900)" }}>
                Create an account &amp; give
              </h3>
              <p style={{ marginTop: 8, fontSize: 13.5, color: "rgba(47,51,29,0.75)", lineHeight: 1.55 }}>
                Your gift to New Eden Academy, Inc. (501(c)(3) · EIN 42-2122862) is fully tax-deductible. With an account you'll receive a year-end giving statement ready for filing, and you can track every gift in one place.
              </p>
              <ul style={{ marginTop: 14, paddingLeft: 0, listStyle: "none", display: "grid", gap: 7 }}>
                {[
                  "501(c)(3) tax-deductible — claim it on your return",
                  "Year-end statement, ready every January",
                  "Lifetime giving history at a glance",
                  "Update or pause monthly gifts any time",
                ].map((line, i) => (
                  <li key={i} style={{ display: "flex", alignItems: "flex-start", gap: 10, fontSize: 13, color: "rgba(47,51,29,0.8)" }}>
                    <span style={{ flex: "0 0 auto", width: 16, height: 16, borderRadius: "50%", background: "var(--moss-500)", color: "white", display: "grid", placeItems: "center", fontSize: 11, marginTop: 1, lineHeight: 1 }}>✓</span>
                    {line}
                  </li>
                ))}
              </ul>
              <button type="button" onClick={() => { setErr(""); setAuthPath("register"); }}
                className="btn btn-gold" style={{ marginTop: 18, width: "100%", padding: 16 }}>
                Continue with an Account · {moneyLabel}
              </button>
              <div style={{ textAlign: "center", marginTop: 10, fontSize: 12, color: "rgba(47,51,29,0.6)" }}>
                Already have an account?{" "}
                <button type="button" onClick={() => { setErr(""); setAuthPath("signin"); }}
                  style={{ background: "transparent", color: "var(--gold-600, rgb(138,125,77))", padding: 0, fontWeight: 500, textDecoration: "underline" }}>
                  Sign in
                </button>
              </div>
            </div>

            {/* Anonymous path */}
            <div style={{ marginTop: 18, paddingTop: 18, borderTop: "1px dashed rgba(47,51,29,0.18)", textAlign: "center" }}>
              <button type="button" onClick={giveAnonymously} disabled={busy}
                className="cta-wide"
                style={{ background: "transparent", color: "var(--navy-900)", border: "1px solid rgba(47,51,29,0.25)", padding: "14px 22px", width: "100%", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", opacity: busy ? 0.6 : 1 }}>
                {busy ? "Processing…" : "Give Anonymously · " + moneyLabel}
              </button>
              <div style={{ fontSize: 11.5, color: "rgba(47,51,29,0.55)", marginTop: 8, lineHeight: 1.5 }}>
                Quick · card only · no account · no year-end receipt
              </div>
            </div>
          </>
        )}

        {/* === REGISTER PATH === */}
        {!pendingIntent && !loggedIn && authPath === "register" && (
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, margin: 0, color: "var(--navy-900)" }}>Your information</h3>
              <button type="button" onClick={() => setAuthPath("choose")}
                style={{ background: "transparent", color: "rgba(47,51,29,0.55)", fontSize: 12, padding: "4px 8px" }}>
                ← Back
              </button>
            </div>
            <div style={{ fontSize: 13, color: "rgba(47,51,29,0.65)", marginBottom: 16, lineHeight: 1.5 }}>
              We use this to send your tax-deductible receipt and keep you updated on the academy.
            </div>
            <label style={labelStyle}>Full name</label>
            <input type="text" value={regName} onChange={e => setRegName(e.target.value)} placeholder="Your full name" style={fieldStyle} />
            <label style={labelStyle}>Email</label>
            <input type="email" value={regEmail} onChange={e => setRegEmail(e.target.value)} placeholder="you@example.com" style={fieldStyle} />
            <label style={labelStyle}>Phone <span style={{ textTransform: "none", letterSpacing: 0, color: "rgba(47,51,29,0.4)", fontSize: 11 }}>(optional)</span></label>
            <input type="tel" value={regPhone} onChange={e => setRegPhone(e.target.value)} placeholder="(555) 555-1234" style={fieldStyle} />
            <label style={labelStyle}>Password <span style={{ textTransform: "none", letterSpacing: 0, color: "rgba(47,51,29,0.4)", fontSize: 11 }}>(8+ characters)</span></label>
            <input type="password" value={regPw} onChange={e => setRegPw(e.target.value)} style={fieldStyle} />

            {err && <div style={{ marginTop: 14, padding: "10px 14px", background: "rgba(180,89,58,0.1)", color: "#8b3f26", fontSize: 13, border: "1px solid rgba(180,89,58,0.3)" }}>{err}</div>}

            <button type="button" onClick={registerAndGive} disabled={busy}
              className="btn btn-gold" style={{ marginTop: 18, width: "100%", padding: 16, opacity: busy ? 0.6 : 1 }}>
              {busy ? "Processing…" : "Create Account & Give · " + moneyLabel}
            </button>
            <div style={{ marginTop: 10, fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(47,51,29,0.5)", textAlign: "center" }}>
              Secure · 501(c)(3) Tax-Deductible · No Fees Taken
            </div>
          </div>
        )}

        {/* === SIGN-IN PATH === */}
        {!pendingIntent && !loggedIn && authPath === "signin" && (
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, margin: 0, color: "var(--navy-900)" }}>Sign in</h3>
              <button type="button" onClick={() => setAuthPath("choose")}
                style={{ background: "transparent", color: "rgba(47,51,29,0.55)", fontSize: 12, padding: "4px 8px" }}>
                ← Back
              </button>
            </div>
            <label style={labelStyle}>Email</label>
            <input type="email" value={siEmail} onChange={e => setSiEmail(e.target.value)} placeholder="you@example.com" style={fieldStyle} />
            <label style={labelStyle}>Password</label>
            <input type="password" value={siPw} onChange={e => setSiPw(e.target.value)} style={fieldStyle} />

            {err && <div style={{ marginTop: 14, padding: "10px 14px", background: "rgba(180,89,58,0.1)", color: "#8b3f26", fontSize: 13, border: "1px solid rgba(180,89,58,0.3)" }}>{err}</div>}

            <button type="button" onClick={signInAndGive} disabled={busy}
              className="btn btn-gold" style={{ marginTop: 18, width: "100%", padding: 16, opacity: busy ? 0.6 : 1 }}>
              {busy ? "Processing…" : "Sign In & Give · " + moneyLabel}
            </button>
            <div style={{ textAlign: "center", marginTop: 10, fontSize: 12, color: "rgba(47,51,29,0.6)" }}>
              New here?{" "}
              <button type="button" onClick={() => { setErr(""); setAuthPath("register"); }}
                style={{ background: "transparent", color: "var(--gold-600, rgb(138,125,77))", padding: 0, fontWeight: 500, textDecoration: "underline" }}>
                Create an account
              </button>
            </div>
          </div>
        )}

        {err && authPath === "choose" && (
          <div style={{ marginTop: 14, padding: "10px 14px", background: "rgba(180,89,58,0.1)", color: "#8b3f26", fontSize: 13, border: "1px solid rgba(180,89,58,0.3)" }}>{err}</div>
        )}
      </div>
    </div>
  );
}

function GiveSection({ raised, onGive }) {
  return (
    <section id="give" className="night give-section" style={{ padding: "120px 0", position: "relative" }}>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "center" }} className="give-grid">
          <div>
            <div className="rule left" style={{ marginBottom: 24 }}>Give · The academy grows with you</div>
            <h2 style={{ fontSize: "clamp(40px, 5vw, 64px)", color: "var(--cream-50)" }}>
              Every gift<br/><em style={{ fontWeight: 400, color: "var(--gold-400)" }}>builds a room.</em>
            </h2>
            <p style={{ marginTop: 24, fontSize: 17, lineHeight: 1.7, color: "rgba(255,241,212,0.78)", maxWidth: 460 }}>
              $1 pays for a single brick. $50 furnishes a reading nook. $500 equips a classroom for a week. There is no small gift — only a rising wall. Give once, or walk with us monthly.
            </p>

            <div className="give-tiers" style={{ marginTop: 40, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, maxWidth: 460 }}>
              {[
                { k: "$1", v: "A single brick in the wall" },
                { k: "$50", v: "A reading nook in the library" },
                { k: "$500", v: "A classroom for a week" },
                { k: "$5,000", v: "A stained-glass window" },
              ].map((r, i) => (
                <div key={i} style={{ borderTop: "1px solid rgba(255,241,212,0.15)", paddingTop: 12 }}>
                  <div style={{ fontFamily: "var(--serif)", fontSize: 30, color: "var(--gold-400)" }}>{r.k}</div>
                  <div style={{ fontSize: 13, color: "rgba(255,241,212,0.7)", marginTop: 2 }}>{r.v}</div>
                </div>
              ))}
            </div>

            <div style={{ marginTop: 40, padding: 20, background: "rgba(181,168,107,0.08)", border: "1px solid rgba(181,168,107,0.25)", borderRadius: 2 }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--gold-400)", marginBottom: 8 }}>Tax-deductible</div>
              <div style={{ fontSize: 14, lineHeight: 1.65, color: "rgba(255,241,212,0.85)" }}>
                New Eden Academy, Inc. is a registered 501(c)(3) public charity (EIN 42-2122862). Donors who create an account receive a consolidated annual giving statement every January, ready to attach to a tax return.
              </div>
            </div>
          </div>

          <GiveCard raised={raised} onGive={onGive} />
        </div>
      </div>

      <style>{`
        .give-section, .give-section .container, .give-grid { min-width: 0; }
        .give-grid > * { min-width: 0; }
        .give-section h2, .give-section p { overflow-wrap: anywhere; word-break: normal; }
        .give-card .btn { max-width: 100%; }
        @media (max-width: 900px) {
          .give-section { padding: 72px 0 !important; }
          .give-grid { grid-template-columns: 1fr !important; gap: 48px !important; }
        }
        @media (max-width: 640px) {
          .give-card { padding: 24px !important; }
          .give-section h2 { font-size: 36px !important; }
          .give-section p { font-size: 15px !important; }
          .give-tiers { gap: 16px !important; }
          .give-card .preset-grid { gap: 6px !important; }
          .give-card .preset-grid button { font-size: 18px !important; padding: 14px 0 !important; }
          .give-card .btn,
          .give-card .cta-wide {
            white-space: normal !important;
            letter-spacing: 0.10em !important;
            font-size: 12px !important;
            line-height: 1.35 !important;
            padding: 14px 12px !important;
            text-align: center;
            word-break: keep-all;
          }
        }
        @media (max-width: 380px) {
          .give-tiers { grid-template-columns: 1fr !important; max-width: 100% !important; gap: 14px !important; }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { GiveSection });
