// Donate page — Stripe-wired giving flow

function DonateHero() {
  return (
    <section style={{
      position: 'relative', background: P.bg, color: P.surface,
      padding: '180px 56px 100px', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
        color: P.accent, opacity: 0.1, pointerEvents: 'none',
      }}>
        <FlowerOfLife size={1000} rings={5} stroke={0.5} />
      </div>
      <div style={{ maxWidth: 1100, margin: '0 auto', position: 'relative', textAlign: 'center' }}>
        <div style={{
          fontFamily: P.mono, fontSize: 10, letterSpacing: '0.36em',
          textTransform: 'uppercase', color: P.accent, marginBottom: 32,
        }}>Give · Support the Work</div>
        <h1 style={{
          fontFamily: P.display, fontSize: 96, fontWeight: 500,
          letterSpacing: '-0.02em', lineHeight: 1.2, margin: '0 0 44px', paddingBottom: 12,
        }}>
          Your giving<br/>
          <span style={{ fontStyle: 'italic', color: P.accent }}>becomes repair.</span>
        </h1>
        <p style={{
          fontFamily: P.serif, fontSize: 20, lineHeight: 1.55,
          color: P.mute, margin: '0 auto', maxWidth: 680,
        }}>
          Every dollar flows through the Reparations Accelerator to descendants, elders, and communities carrying out the work of repair. Tax-deductible under our 501(c)(3) status.
        </p>
      </div>
    </section>
  );
}

function DonateForm() {
  const presets = [25, 50, 100, 250, 500, 1000];
  const [amount, setAmount] = React.useState(100);
  const [custom, setCustom] = React.useState('');
  const [frequency, setFrequency] = React.useState('once');
  const [loading, setLoading] = React.useState(false);
  const designation = 'where-needed';

  const finalAmount = custom ? parseFloat(custom) || 0 : amount;
  const isMonthly = frequency === 'monthly';

  async function handleSubmit(e) {
    e.preventDefault();
    if (!finalAmount || finalAmount < 1) return;
    setLoading(true);
    // Stripe Checkout integration — swap in your publishable key + price/product IDs
    // This uses Stripe.js redirectToCheckout with line_items for one-time
    // or a subscription price for recurring.
    try {
      const response = await fetch('/api/create-checkout-session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          amount: Math.round(finalAmount * 100),
          frequency, designation,
        }),
      });
      if (!response.ok) {
        const err = await response.json().catch(() => ({}));
        if (err.detail) console.error('Checkout server detail:', err.detail);
        throw new Error(err.error || 'Could not start checkout.');
      }
      const { sessionId, url } = await response.json();
      // Stripe returns a hosted-checkout URL — simplest + most reliable is to redirect.
      if (url) {
        window.location.assign(url);
        return;
      }
      // Fallback path via Stripe.js if backend only returned the session id
      if (window.Stripe && window.STRIPE_PUBLISHABLE_KEY) {
        const stripe = window.Stripe(window.STRIPE_PUBLISHABLE_KEY);
        await stripe.redirectToCheckout({ sessionId });
      } else {
        throw new Error('Stripe not available.');
      }
    } catch (err) {
      alert(err.message || 'Something went wrong starting checkout. Please try again or email christopher@sacredroux.org.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <section style={{ background: P.bg, color: P.surface, padding: '120px 56px', borderTop: `1px solid ${P.rule}` }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 80, alignItems: 'flex-start' }}>

          {/* LEFT — form */}
          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 48 }}>
            {/* Frequency */}
            <div>
              <div style={{
                fontFamily: P.mono, fontSize: 10, letterSpacing: '0.3em',
                textTransform: 'uppercase', color: P.accent, marginBottom: 20,
              }}>01 — Frequency</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                {[
                  { k: 'once', l: 'One-Time Gift' },
                  { k: 'monthly', l: 'Monthly · Sustaining' },
                ].map(f => (
                  <button key={f.k} type="button" onClick={() => setFrequency(f.k)}
                    style={{
                      padding: '20px 24px',
                      background: frequency === f.k ? P.accent : 'transparent',
                      color: frequency === f.k ? P.bg : P.surface,
                      border: `1px solid ${frequency === f.k ? P.accent : P.rule}`,
                      borderRadius: 4, cursor: 'pointer', textAlign: 'left',
                      fontFamily: P.display, fontSize: 20, fontWeight: 500,
                      letterSpacing: '-0.005em',
                    }}>
                    {f.l}
                  </button>
                ))}
              </div>
              {isMonthly && (
                <div style={{
                  marginTop: 14, fontFamily: P.serif, fontSize: 14, fontStyle: 'italic',
                  color: P.mute,
                }}>
                  Sustaining gifts compound over years — the surest way to fund intergenerational work.
                </div>
              )}
            </div>

            {/* Amount */}
            <div>
              <div style={{
                fontFamily: P.mono, fontSize: 10, letterSpacing: '0.3em',
                textTransform: 'uppercase', color: P.accent, marginBottom: 20,
              }}>02 — Gift Amount {isMonthly && <span style={{ color: P.mute }}>· per month</span>}</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 16 }}>
                {presets.map(p => (
                  <button key={p} type="button"
                    onClick={() => { setAmount(p); setCustom(''); }}
                    style={{
                      padding: '20px 0',
                      background: amount === p && !custom ? P.accent : 'transparent',
                      color: amount === p && !custom ? P.bg : P.surface,
                      border: `1px solid ${amount === p && !custom ? P.accent : P.rule}`,
                      borderRadius: 4, cursor: 'pointer',
                      fontFamily: P.display, fontSize: 22, fontWeight: 500,
                    }}>${p}</button>
                ))}
              </div>
              <div style={{ position: 'relative' }}>
                <span style={{
                  position: 'absolute', left: 20, top: '50%', transform: 'translateY(-50%)',
                  fontFamily: P.display, fontSize: 20, color: P.mute,
                }}>$</span>
                <input
                  type="text" inputMode="decimal" placeholder="Other amount"
                  value={custom}
                  onChange={e => setCustom(e.target.value.replace(/[^0-9.]/g, ''))}
                  style={{
                    width: '100%', padding: '18px 20px 18px 40px',
                    background: 'transparent', border: `1px solid ${custom ? P.accent : P.rule}`,
                    borderRadius: 4, color: P.surface,
                    fontFamily: P.display, fontSize: 20, outline: 'none',
                  }} />
              </div>
            </div>

            {/* Submit */}
            <button type="submit" disabled={loading || !finalAmount}
              style={{
                padding: '24px 40px',
                background: P.accent, color: P.bg, border: 'none', borderRadius: 999,
                cursor: loading ? 'wait' : 'pointer',
                fontFamily: P.mono, fontSize: 12, letterSpacing: '0.28em',
                textTransform: 'uppercase', fontWeight: 500,
                opacity: (!finalAmount || loading) ? 0.5 : 1,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16,
              }}>
              <span>
                {loading ? 'Connecting to Stripe…' :
                  `Give $${finalAmount || 0}${isMonthly ? ' / month' : ''} via Stripe`}
              </span>
              <span style={{ fontFamily: P.display, fontStyle: 'italic', fontSize: 18, letterSpacing: '0.04em', textTransform: 'none' }}>→</span>
            </button>
            <div style={{
              fontFamily: P.serif, fontSize: 13, fontStyle: 'italic',
              color: P.mute, textAlign: 'center',
            }}>
              Secure payment via Stripe · Receipt emailed for your records · Tax-deductible
            </div>
          </form>

          {/* RIGHT — why + trust */}
          <aside style={{ position: 'sticky', top: 120 }}>
            <div style={{
              padding: 40, border: `1px solid ${P.rule}`, borderRadius: 4,
              position: 'relative', overflow: 'hidden',
            }}>
              <div style={{
                position: 'absolute', right: -60, top: -60, color: P.accent, opacity: 0.14,
              }}>
                <FlowerOfLife size={260} rings={3} />
              </div>
              <div style={{
                fontFamily: P.mono, fontSize: 10, letterSpacing: '0.3em',
                textTransform: 'uppercase', color: P.accent, marginBottom: 24, position: 'relative',
              }}>Where Your Gift Goes</div>

              <p style={{
                fontFamily: P.serif, fontSize: 15, lineHeight: 1.7,
                color: P.mute, margin: '0 0 28px', position: 'relative', textWrap: 'pretty',
              }}>
                Every gift supports general operating and flows through our four pillars of work. Rather than asking donors to earmark contributions — which creates administrative burden that pulls energy from the work — we pool all gifts and report back transparently on how funds are used.
              </p>

              {[
                ['Reparations', 'Direct repair — land, capital, access'],
                ['Landback', 'Ancestral land return and stewardship'],
                ['Rematriation', 'Cultural restoration and lifeways'],
                ['Repatriation', 'Retreats, ceremony, and reconnection'],
              ].map(([l, r]) => (
                <div key={l} style={{
                  padding: '16px 0', borderTop: `1px solid ${P.rule}`,
                  position: 'relative',
                }}>
                  <div style={{ fontFamily: P.display, fontSize: 18, fontWeight: 500, color: P.surface, marginBottom: 3 }}>{l}</div>
                  <div style={{ fontFamily: P.serif, fontSize: 13, color: P.mute, fontStyle: 'italic' }}>{r}</div>
                </div>
              ))}

              <div style={{
                marginTop: 28, paddingTop: 24, borderTop: `1px solid ${P.rule}`,
                fontFamily: P.serif, fontSize: 14,
                lineHeight: 1.65, color: P.mute, position: 'relative', textWrap: 'pretty',
              }}>
                Distribution is facilitated through our <span style={{ color: P.surface, fontStyle: 'italic' }}>Reparations Accelerator</span> — the mechanism through which our community learns about, participates in, and helps shape our approach to reparative distribution.
              </div>

              <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap', marginTop: 24, position: 'relative' }}>
                <a href="impact.html" style={{
                  fontFamily: P.mono, fontSize: 10, letterSpacing: '0.24em',
                  textTransform: 'uppercase', color: P.accent, textDecoration: 'none',
                  borderBottom: `1px solid ${P.accent}`, paddingBottom: 4,
                }}>Impact Transparency →</a>
                <a href="projects.html" style={{
                  fontFamily: P.mono, fontSize: 10, letterSpacing: '0.24em',
                  textTransform: 'uppercase', color: P.accent, textDecoration: 'none',
                  borderBottom: `1px solid ${P.accent}`, paddingBottom: 4,
                }}>The Accelerator →</a>
              </div>
            </div>

            <div style={{
              marginTop: 32, padding: '28px 32px', border: `1px solid ${P.rule}`, borderRadius: 4,
              display: 'flex', gap: 20, alignItems: 'center',
            }}>
              <div style={{
                width: 48, height: 48, borderRadius: '50%', border: `1px solid ${P.accent}`,
                color: P.accent, display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>
                <Trefoil size={22} />
              </div>
              <div>
                <div style={{ fontFamily: P.display, fontSize: 17, fontWeight: 500, marginBottom: 4 }}>Other ways to give</div>
                <div style={{ fontFamily: P.serif, fontSize: 13, color: P.mute, fontStyle: 'italic' }}>
                  DAFs, stock, crypto, legacy gifts — <a href="mailto:christopher@sacredroux.org" style={{ color: P.accent }}>email us</a>.
                </div>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
}

function DonateTiers() {
  const tiers = [
    { label: 'Kin', amt: '$25 / month', body: 'Keeps the work in motion — a monthly thread in the fabric of repair.' },
    { label: 'Sustainer', amt: '$100 / month', body: 'Funds a month of programming across one pillar — reparations, landback, rematriation, or repatriation.' },
    { label: 'Elder', amt: '$500 / month', body: 'Names you a keeper of the work. Invitations to descendant gatherings and annual circle.' },
    { label: 'Ancestor', amt: '$1,000+ / month', body: 'Underwrites whole initiatives. Deep partnership with the council and quarterly strategic convenings.' },
  ];
  return (
    <section style={{ background: P.bg, color: P.surface, padding: '140px 56px', borderTop: `1px solid ${P.rule}` }}>
      <div style={{ maxWidth: 1400, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 64 }}>
          <div>
            <div style={{
              fontFamily: P.mono, fontSize: 10, letterSpacing: '0.36em',
              textTransform: 'uppercase', color: P.accent, marginBottom: 24,
            }}>Sustaining Circles</div>
            <h2 style={{
              fontFamily: P.display, fontSize: 64, fontWeight: 500,
              letterSpacing: '-0.02em', lineHeight: 1.05, margin: 0,
            }}>Monthly giving holds<br/>the work across generations.</h2>
          </div>
          <p style={{
            maxWidth: 360, fontFamily: P.serif, fontSize: 15,
            lineHeight: 1.65, color: P.mute, margin: 0,
          }}>Named after the lineage from which they flow. Choose the circle that matches your capacity.</p>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, borderTop: `1px solid ${P.rule}` }}>
          {tiers.map((t, i) => (
            <div key={t.label} style={{
              padding: '48px 32px 48px 0',
              borderLeft: i > 0 ? `1px solid ${P.rule}` : 'none',
              paddingLeft: i > 0 ? 32 : 0,
              borderBottom: `1px solid ${P.rule}`,
            }}>
              <div style={{
                fontFamily: P.mono, fontSize: 10, letterSpacing: '0.3em',
                textTransform: 'uppercase', color: P.accent, marginBottom: 20,
              }}>{String(i + 1).padStart(2, '0')} — {t.label}</div>
              <div style={{
                fontFamily: P.display, fontSize: 28, fontStyle: 'italic', fontWeight: 500,
                marginBottom: 20, color: P.surface,
              }}>{t.amt}</div>
              <p style={{
                fontFamily: P.serif, fontSize: 15, lineHeight: 1.7,
                color: P.mute, margin: 0, textWrap: 'pretty',
              }}>{t.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function DonateFAQ() {
  const faqs = [
    { q: 'Is my gift tax-deductible?', a: 'Yes. Sacred Roux is a registered 501(c)(3) nonprofit. A receipt will be emailed to you after your gift completes. Save it for your tax records.' },
    { q: 'How is my gift used?', a: 'Every dollar flows through the Reparations Accelerator. The bulk goes directly to descendants, elders, and community-led projects. A small portion covers operations, processing, and governance. Our allocations are published and audited annually.' },
    { q: 'Can I cancel or change my monthly gift?', a: 'Yes. You can pause, adjust, or cancel any time via the receipt email or by writing to us directly. We never hold recurring gifts hostage — consent is continuous.' },
    { q: 'Do you accept donor-advised funds, stock, or crypto?', a: 'Yes to all three. Email christopher@sacredroux.org and we\'ll send you the transfer instructions and wallet addresses.' },
    { q: 'Can I give in honor or memory of someone?', a: 'Yes. Note their name in the Stripe Checkout comment field and we\'ll send an acknowledgment card to the address you provide. Memorial giving is a way of placing a loved one within the work of repair.' },
    { q: 'Where is Sacred Roux located?', a: 'We are based in Seattle, Washington, and operate across the Pacific Northwest and the broader communities we serve. Our work is rooted in place but reaches wherever descendants carry the memory.' },
  ];
  const [open, setOpen] = React.useState(0);
  return (
    <section style={{ background: P.bg, color: P.surface, padding: '140px 56px', borderTop: `1px solid ${P.rule}` }}>
      <div style={{ maxWidth: 1000, margin: '0 auto' }}>
        <div style={{
          fontFamily: P.mono, fontSize: 10, letterSpacing: '0.36em',
          textTransform: 'uppercase', color: P.accent, marginBottom: 24,
        }}>Common Questions</div>
        <h2 style={{
          fontFamily: P.display, fontSize: 56, fontWeight: 500,
          letterSpacing: '-0.02em', lineHeight: 1.05, margin: '0 0 56px',
        }}>Giving, with clarity.</h2>
        <div style={{ borderTop: `1px solid ${P.rule}` }}>
          {faqs.map((f, i) => (
            <div key={i} style={{ borderBottom: `1px solid ${P.rule}` }}>
              <button type="button" onClick={() => setOpen(open === i ? -1 : i)}
                style={{
                  width: '100%', textAlign: 'left', background: 'transparent', border: 'none',
                  padding: '28px 0', color: P.surface, cursor: 'pointer',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 24,
                }}>
                <div style={{
                  fontFamily: P.display, fontSize: 24, fontWeight: 500, letterSpacing: '-0.005em',
                }}>{f.q}</div>
                <div style={{
                  fontFamily: P.display, fontSize: 28, fontStyle: 'italic', color: P.accent,
                  transform: open === i ? 'rotate(45deg)' : 'rotate(0)',
                  transition: 'transform .3s',
                }}>+</div>
              </button>
              {open === i && (
                <p style={{
                  fontFamily: P.serif, fontSize: 17, lineHeight: 1.7,
                  color: P.mute, margin: 0, padding: '0 0 32px', maxWidth: 760,
                  textWrap: 'pretty',
                }}>{f.a}</p>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function DonatePage() {
  return (
    <PageShell current="donate">
      <DonateHero />
      <DonateForm />
      <DonateTiers />
      <DonateFAQ />
    </PageShell>
  );
}

window.DonatePage = DonatePage;
