/* =============================================================
 * Action pages: Donate, Get Involved, Contact, Events, Team Login
 * ============================================================= */

/* ---------- Donate ---------- */
function DonatePage() {
  const [path, setPath] = useState("momo"); // momo | card
  const [amount, setAmount] = useState(30000);
  const [custom, setCustom] = useState("");
  const [freq, setFreq] = useState("monthly");
  const [form, setForm] = useState({ 
    name: "", 
    email: "",
    phone: "", 
    network: "MTN",
    cardNumber: "",
    cardExpiry: "",
    cardCVV: "",
    cardType: "visa",
    anon: false 
  });
  const [errors, setErrors] = useState({});
  const [stage, setStage] = useState("form"); // form | processing | done

  const presets = path === "momo"
    ? [{ v: 30000, l: "USh 30,000", h: "1 father · 1 month" }, { v: 90000, l: "USh 90,000", h: "1 father · 3 months" }, { v: 360000, l: "USh 360,000", h: "1 Forge · 1 month" }]
    : [{ v: 25, l: "$25", h: "1 father · 1 month" }, { v: 75, l: "$75", h: "1 father · 3 months" }, { v: 250, l: "$250", h: "1 Forge · 1 month" }];

  const total = custom ? Number(custom) : amount;

  const detectCardType = (number) => {
    const cleaned = number.replace(/\s/g, '');
    if (/^4/.test(cleaned)) return 'visa';
    if (/^5[1-5]/.test(cleaned)) return 'mastercard';
    if (/^3[47]/.test(cleaned)) return 'amex';
    if (/^6(?:011|5)/.test(cleaned)) return 'discover';
    return 'visa';
  };

  const formatCardNumber = (value) => {
    const cleaned = value.replace(/\s/g, '');
    const type = detectCardType(cleaned);
    setForm({ ...form, cardType: type });
    
    // Format with spaces every 4 digits
    const formatted = cleaned.match(/.{1,4}/g)?.join(' ') || cleaned;
    return formatted.slice(0, 19); // Max 16 digits + 3 spaces
  };

  const formatExpiry = (value) => {
    const cleaned = value.replace(/\D/g, '');
    if (cleaned.length >= 2) {
      return cleaned.slice(0, 2) + '/' + cleaned.slice(2, 4);
    }
    return cleaned;
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim() && !form.anon) e.name = "Required";
    if (!form.email.trim() || !/^[^@]+@[^@]+\.[^@]+$/.test(form.email)) e.email = "Valid email required";
    
    if (path === "momo") {
      if (!/^[+0-9 -]{7,}$/.test(form.phone)) e.phone = "Mobile number required";
    } else {
      // Card validation
      const cardNum = form.cardNumber.replace(/\s/g, '');
      if (cardNum.length < 13 || cardNum.length > 19) e.cardNumber = "Invalid card number";
      if (!/^\d{2}\/\d{2}$/.test(form.cardExpiry)) e.cardExpiry = "MM/YY format required";
      if (!/^\d{3,4}$/.test(form.cardCVV)) e.cardCVV = "Invalid CVV";
    }
    
    if (!total || total <= 0) e.amount = "Pick or enter an amount";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  // Phase 3.9: store receipt details after successful payment for download
  const [receipt, setReceipt] = useState(null);

  // Save donation to Supabase + build a receipt object for the success screen.
  const recordDonation = async (txResponse) => {
    const txRef = (txResponse && (txResponse.tx_ref || txResponse.transaction_id)) || ('FA-' + Date.now());
    const currency = path === "momo" ? "UGX" : "USD";
    const donor = form.anon ? "Anonymous" : form.name;
    const rec = {
      tx_ref: txRef,
      donor_name: donor,
      donor_email: form.email,
      donor_phone: form.phone || null,
      amount: total,
      currency: currency,
      frequency: freq,
      payment_method: path === "momo" ? "Mobile Money" : "Card",
      anonymous: !!form.anon,
      date: new Date().toISOString()
    };
    setReceipt(rec);
    // Best-effort Supabase insert into existing 'donations' table.
    // Extra fields (tx_ref, email, phone, payment_method, anon flag) are folded into `notes`
    // as a pipe-separated string so the OS can parse them back when displaying donation history.
    try {
      if (window.sb) {
        const noteParts = [
          'tx_ref:' + rec.tx_ref,
          'method:' + rec.payment_method,
          rec.donor_email ? 'email:' + rec.donor_email : null,
          rec.donor_phone ? 'phone:' + rec.donor_phone : null,
          rec.anonymous ? 'anon:true' : null
        ].filter(Boolean);
        await window.sb.from('donations').insert({
          donor_name: rec.donor_name,
          amount: rec.amount,
          amount_ugx: rec.currency === 'UGX' ? rec.amount : null,
          donation_date: rec.date.slice(0, 10),
          is_recurring: rec.frequency === 'monthly',
          frequency: rec.frequency,
          notes: noteParts.join(' | ')
        });
      }
    } catch (e) { console.warn('Donation record save failed:', e && e.message); }
  };

  // Build the receipt as a printable HTML window — user can save as PDF via browser print.
  const downloadReceipt = () => {
    if (!receipt) return;
    const dateLabel = new Date(receipt.date).toLocaleDateString(undefined, { year:'numeric', month:'long', day:'numeric' });
    const amountFmt = receipt.currency === 'UGX' ? 'USh ' + Number(receipt.amount).toLocaleString() : '$' + Number(receipt.amount).toLocaleString();
    const html = `<!doctype html><html><head><meta charset="utf-8"><title>Donation Receipt — Fathers Arise</title>
<style>
  body { font-family: 'Open Sans', system-ui, sans-serif; max-width: 720px; margin: 40px auto; padding: 0 30px; color: #0B1130; }
  .header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 20px; border-bottom: 3px solid #E8B830; }
  h1 { font-family: 'Montserrat', sans-serif; color: #0D1147; margin: 0; font-size: 24px; }
  .brand { font-size: 12px; color: #2E96D4; letter-spacing: 0.2em; text-transform: uppercase; font-weight: 700; }
  .receipt-title { margin-top: 30px; font-size: 28px; font-weight: 800; color: #0D1147; }
  table { width: 100%; margin-top: 24px; border-collapse: collapse; }
  td { padding: 10px 0; border-bottom: 1px solid #eee; }
  td:first-child { color: #666; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em; width: 40%; }
  td:last-child { font-weight: 600; }
  .amount { font-size: 32px; font-weight: 900; color: #E8B830; }
  .footer { margin-top: 40px; padding-top: 24px; border-top: 1px solid #eee; font-size: 12px; color: #666; line-height: 1.6; }
  .thanks { margin-top: 40px; padding: 24px; background: #F4F6FA; border-radius: 12px; text-align: center; }
  .thanks p { margin: 0; font-size: 16px; font-style: italic; color: #0D1147; }
  @media print { body { margin: 0; } button { display: none; } }
</style></head><body>
  <div class="header">
    <div><div class="brand">Fathers Arise</div><h1>Restoring fatherhood. Building nations.</h1></div>
    <div style="text-align:right;font-size:11px;color:#666;">Reg. NGO Uganda<br>fathersarize.org</div>
  </div>
  <div class="receipt-title">Donation Receipt</div>
  <table>
    <tr><td>Receipt no.</td><td>${receipt.tx_ref}</td></tr>
    <tr><td>Date</td><td>${dateLabel}</td></tr>
    <tr><td>Donor</td><td>${receipt.donor_name || '—'}</td></tr>
    <tr><td>Email</td><td>${receipt.donor_email || '—'}</td></tr>
    <tr><td>Payment method</td><td>${receipt.payment_method}</td></tr>
    <tr><td>Frequency</td><td>${receipt.frequency === 'monthly' ? 'Monthly recurring' : 'One-time'}</td></tr>
    <tr><td>Amount</td><td class="amount">${amountFmt}</td></tr>
  </table>
  <div class="thanks">
    <p>"Asante! Every shilling you give places a father into a Forge group — a circle of brothers who keep him present, honest, and in his children's lives."</p>
  </div>
  <div class="footer">
    Thank you for partnering with Fathers Arise. This receipt confirms a tax-deductible donation
    where applicable. Keep this document for your records.<br><br>
    For inquiries: hello@fathersarize.org · WhatsApp 0700 669 586
  </div>
  <button onclick="window.print()" style="margin-top:30px;padding:12px 24px;background:#0D1147;color:white;border:0;border-radius:24px;font-weight:700;cursor:pointer;">Print / Save as PDF</button>
</body></html>`;
    const w = window.open('', '_blank');
    if (!w) { alert('Please allow popups to view your receipt'); return; }
    w.document.write(html);
    w.document.close();
  };

  const initFlutterwavePayment = async () => {
    setStage("processing");

    try {
      // Flutterwave payment configuration
      const config = {
        public_key: window.FLUTTERWAVE_PUBLIC_KEY || "FLWPUBK-YOUR-PUBLIC-KEY-HERE",
        tx_ref: 'FA-' + Date.now(),
        amount: total,
        currency: path === "momo" ? "UGX" : "USD",
        payment_options: path === "momo" ? "mobilemoneyuganda" : "card",
        customer: {
          email: form.email,
          phone_number: form.phone,
          name: form.anon ? "Anonymous" : form.name,
        },
        customizations: {
          title: "Fathers Arise",
          description: `${freq === 'monthly' ? 'Monthly' : 'One-time'} donation`,
          logo: window.location.origin + "/uploads/logo.png",
        },
        callback: async function(response) {
          console.log(response);
          if (response && response.status === "successful") {
            await recordDonation(response);
            setStage("done");
          } else {
            setStage("form");
            alert("Payment failed. Please try again.");
          }
        },
        onclose: function() {
          if (stage !== "done") setStage("form");
        }
      };

      // Initialize Flutterwave
      if (window.FlutterwaveCheckout) {
        window.FlutterwaveCheckout(config);
      } else {
        // Fallback: load script and retry
        const script = document.createElement('script');
        script.src = 'https://checkout.flutterwave.com/v3.js';
        script.onload = () => window.FlutterwaveCheckout(config);
        document.body.appendChild(script);
      }
    } catch (error) {
      console.error('Payment error:', error);
      setStage("form");
      alert("Payment initialization failed. Please try again.");
    }
  };

  const submit = (e) => {
    e.preventDefault();
    if (!validate()) return;
    initFlutterwavePayment();
  };

  // Phase 3.7: editable site content
  const [cmsDonate, setCmsDonate] = useState({});
  useEffect(() => {
    if (window.cms && typeof window.cms.getSiteContent === "function") {
      window.cms.getSiteContent("donate").then(setCmsDonate);
    }
  }, []);
  const dHero = cmsDonate.hero || {};
  return (
    <div data-screen-label="06 Donate">
      <PageHero
        breadcrumb={[{ label: "Home", to: "home" }, { label: "Donate" }]}
        eyebrow="Restore A Father"
        title={dHero.headline || "Your gift puts one father in a Forge group."}
        lede={dHero.subhead || "Mobile Money for Ugandan givers, international cards accepted worldwide. Secure payments powered by Flutterwave."}
        bgImage={dHero.image || "uploads/FATHERS ARISE-135.jpg"}
      />

      <section className="py-16">
        <div className="max-w-[1100px] mx-auto px-4 sm:px-6 grid grid-cols-1 lg:grid-cols-12 gap-8">
          <div className="lg:col-span-7">
            <div className="rounded-2xl bg-white border border-navy/8 shadow-card overflow-hidden">
              <div className="grid grid-cols-2 border-b border-navy/8">
                {[["momo", "Mobile Money"], ["card", "Card Payment"]].map(([k, l]) => (
                  <button key={k} onClick={() => { setPath(k); setStage("form"); setAmount(k === "momo" ? 30000 : 25); setCustom(""); setErrors({}); }}
                    className={`p-4 font-display font-bold uppercase text-sm tracking-wider border-b-2 ${path === k ? "border-gold text-navy bg-paper" : "border-transparent text-ink/50"}`}>
                    {l}
                  </button>
                ))}
              </div>

              {stage === "done" ? (
                <div className="p-10 text-center">
                  <div className="mx-auto w-16 h-16 rounded-full bg-gold text-navy flex items-center justify-center">
                    <svg width="28" height="28" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5L20 7" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </div>
                  <h3 className="mt-5 font-display font-extrabold text-3xl text-navy">Asante! You just helped restore a father.</h3>
                  {receipt && (
                    <div className="mt-6 inline-block text-left bg-paper rounded-2xl p-6 border border-navy/8 min-w-[280px]">
                      <div className="text-xs font-display font-bold uppercase tracking-wider text-sky">Receipt</div>
                      <div className="mt-2 text-sm text-ink/75"><span className="text-ink/55">No.</span> <span className="font-mono">{receipt.tx_ref}</span></div>
                      <div className="mt-1 text-sm text-ink/75"><span className="text-ink/55">Amount:</span> <span className="font-display font-bold text-navy">{receipt.currency === 'UGX' ? 'USh ' + Number(receipt.amount).toLocaleString() : '$' + Number(receipt.amount).toLocaleString()}</span></div>
                      <div className="mt-1 text-sm text-ink/75"><span className="text-ink/55">Donor:</span> {receipt.donor_name}</div>
                    </div>
                  )}
                  <div className="mt-6 flex flex-wrap gap-3 justify-center">
                    {receipt && (
                      <button onClick={downloadReceipt} className="inline-flex items-center gap-2 rounded-full px-7 py-3 bg-navy text-white font-display font-bold uppercase tracking-wider text-sm hover:bg-navy/90">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                        Download Receipt
                      </button>
                    )}
                    <button onClick={() => { setStage("form"); setReceipt(null); }} className="text-sm font-display font-bold uppercase tracking-wider text-sky hover:text-navy">Make another gift</button>
                  </div>
                  <p className="mt-4 text-xs text-ink/55">A copy has also been saved in our records.</p>
                </div>
              ) : stage === "processing" ? (
                <div className="p-10 text-center">
                  <div className="inline-block w-12 h-12 border-4 border-paper border-t-gold rounded-full animate-spin" />
                  <p className="mt-4 font-display font-bold text-navy">Processing payment...</p>
                  <p className="mt-2 text-sm text-ink/60">Please complete the payment in the popup window</p>
                </div>
              ) : (
                <form onSubmit={submit} className="p-6 md:p-8 space-y-5">
                  {/* Frequency toggle */}
                  <div>
                    <span className="block text-xs font-display font-semibold uppercase tracking-wider text-navy mb-2">Frequency</span>
                    <div className="inline-flex p-1 bg-paper rounded-full border border-navy/10">
                      {[["once", "Once"], ["monthly", "Monthly · most impact"]].map(([k, l]) => (
                        <button type="button" key={k} onClick={() => setFreq(k)}
                          className={`px-4 py-1.5 rounded-full text-sm font-display font-bold ${freq === k ? "bg-navy text-white" : "text-ink/60"}`}>{l}</button>
                      ))}
                    </div>
                  </div>

                  {/* Amount */}
                  <div>
                    <span className="block text-xs font-display font-semibold uppercase tracking-wider text-navy mb-2">Amount</span>
                    <div className="grid grid-cols-3 gap-2">
                      {presets.map((p) => (
                        <button type="button" key={p.v} onClick={() => { setAmount(p.v); setCustom(""); }}
                          className={`rounded-xl p-3 text-left border ${amount === p.v && !custom ? "border-navy bg-navy text-white" : "border-navy/15 bg-white hover:border-navy/40"}`}>
                          <div className="font-display font-extrabold">{p.l}</div>
                          <div className={`text-xs ${amount === p.v && !custom ? "text-white/70" : "text-ink/55"}`}>{p.h}</div>
                        </button>
                      ))}
                    </div>
                    <div className="mt-3 relative">
                      <span className="absolute left-4 top-1/2 -translate-y-1/2 text-ink/45 text-sm font-display font-bold">{path === "momo" ? "USh" : "$"}</span>
                      <input value={custom} onChange={(e) => { setCustom(e.target.value.replace(/[^0-9]/g, "")); setAmount(0); }}
                        placeholder="Or enter a custom amount"
                        className="w-full pl-14 pr-4 py-3 rounded-xl bg-white border border-navy/15 focus:border-sky focus:ring-2 focus:ring-sky/20 outline-none transition" />
                    </div>
                    {errors.amount && <div className="mt-1 text-xs text-red-600">{errors.amount}</div>}
                  </div>

                  {/* Identity & Contact */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <Field label="Your name" id="d-name" error={errors.name}>
                      <Input id="d-name" disabled={form.anon} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Full name" />
                    </Field>
                    <Field label="Email" id="d-email" error={errors.email}>
                      <Input id="d-email" type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="you@example.com" />
                    </Field>
                  </div>

                  {path === "momo" ? (
                    <>
                      <Field label="Mobile number" id="d-phone" error={errors.phone}>
                        <Input id="d-phone" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="+256 700 245 880" />
                      </Field>
                      <Field label="Network" id="d-net">
                        <div className="flex gap-2">
                          {["MTN", "Airtel"].map((n) => (
                            <button type="button" key={n} onClick={() => setForm({ ...form, network: n })}
                              className={`flex-1 rounded-xl px-4 py-3 border font-display font-bold ${form.network === n ? "bg-navy text-white border-navy" : "bg-white text-navy border-navy/15"}`}>{n} MoMo</button>
                          ))}
                        </div>
                      </Field>
                    </>
                  ) : (
                    <>
                      {/* Card Information */}
                      <Field label="Card Number" id="d-card" error={errors.cardNumber}>
                        <div className="relative">
                          <Input 
                            id="d-card" 
                            value={form.cardNumber} 
                            onChange={(e) => setForm({ ...form, cardNumber: formatCardNumber(e.target.value) })} 
                            placeholder="1234 5678 9012 3456"
                            maxLength="19"
                          />
                          <div className="absolute right-3 top-1/2 -translate-y-1/2">
                            {form.cardType === 'visa' && <svg width="40" height="24" viewBox="0 0 48 32"><rect width="48" height="32" rx="4" fill="#1434CB"/><text x="24" y="20" fill="white" fontSize="14" fontWeight="bold" textAnchor="middle">VISA</text></svg>}
                            {form.cardType === 'mastercard' && <svg width="40" height="24" viewBox="0 0 48 32"><circle cx="18" cy="16" r="10" fill="#EB001B"/><circle cx="30" cy="16" r="10" fill="#F79E1B"/></svg>}
                            {form.cardType === 'amex' && <svg width="40" height="24" viewBox="0 0 48 32"><rect width="48" height="32" rx="4" fill="#006FCF"/><text x="24" y="20" fill="white" fontSize="10" fontWeight="bold" textAnchor="middle">AMEX</text></svg>}
                          </div>
                        </div>
                      </Field>
                      
                      <div className="grid grid-cols-2 gap-4">
                        <Field label="Expiry Date" id="d-expiry" error={errors.cardExpiry}>
                          <Input 
                            id="d-expiry" 
                            value={form.cardExpiry} 
                            onChange={(e) => setForm({ ...form, cardExpiry: formatExpiry(e.target.value) })} 
                            placeholder="MM/YY"
                            maxLength="5"
                          />
                        </Field>
                        <Field label="CVV" id="d-cvv" error={errors.cardCVV}>
                          <Input 
                            id="d-cvv" 
                            type="password"
                            value={form.cardCVV} 
                            onChange={(e) => setForm({ ...form, cardCVV: e.target.value.replace(/\D/g, '').slice(0, 4) })} 
                            placeholder="123"
                            maxLength="4"
                          />
                        </Field>
                      </div>

                      <div className="flex items-center gap-2 p-3 bg-paper rounded-lg text-sm text-ink/70">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" className="text-navy"><path d="M12 22s-8-4.5-8-11.8A8 8 0 0 1 12 2a8 8 0 0 1 8 8.2c0 7.3-8 11.8-8 11.8z" stroke="currentColor" strokeWidth="2"/><path d="M9 11l2 2 4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
                        <span>Payments secured by Flutterwave. We never store your card details.</span>
                      </div>
                    </>
                  )}

                  <label className="flex items-center gap-2 text-sm text-ink/70">
                    <input type="checkbox" checked={form.anon} onChange={(e) => setForm({ ...form, anon: e.target.checked })} className="accent-navy" />
                    Give anonymously
                  </label>

                  <button className="w-full btn-gold rounded-full px-6 py-4 font-display font-black uppercase tracking-wider">
                    Give {custom ? (path === "momo" ? "USh " : "$") + Number(custom).toLocaleString() : presets.find(p => p.v === amount)?.l} {freq === "monthly" ? "/ month" : "now"}
                  </button>
                  <div className="text-center text-[11px] text-ink/45 font-mono">Secured · 100% to programs · Tax-deductible (US/UK/UG)</div>
                </form>
              )}
            </div>
          </div>

          <aside className="lg:col-span-5 space-y-4">
            <div className="rounded-2xl bg-navy text-white p-6 relative overflow-hidden">
              <div className="absolute inset-0 grid-bg opacity-15" />
              <div className="relative">
                <div className="text-xs font-display font-bold uppercase tracking-widest text-gold">Where it goes</div>
                <ul className="mt-3 space-y-3">
                  {[["68%", "Forge groups & curriculum"], ["18%", "Mobile Kanaabe outreach"], ["10%", "Field staff & training"], ["4%", "Admin & overhead"]].map(([p, l]) => (
                    <li key={l} className="flex items-center gap-3">
                      <span className="font-display font-black text-gold w-12">{p}</span>
                      <span className="text-white/85 text-sm">{l}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
            <div className="rounded-2xl bg-white border border-navy/8 p-6">
              <p className="font-quote italic text-xl text-navy leading-snug">"My monthly gift is the smallest line on my budget and the loudest line on my conscience."</p>
              <div className="mt-3 text-sm text-ink/55">— Asha M., Forge donor since 2022</div>
            </div>
            <div className="rounded-2xl bg-paper border border-navy/8 p-6">
              <div className="text-xs font-display font-bold uppercase tracking-widest text-sky">Other ways to give</div>
              <ul className="mt-2 text-sm text-ink/75 space-y-1">
                <li>· Bank transfer (UG, UK, US)</li>
                <li>· Stocks & estate gifts</li>
                <li>· Sponsor a Forge group</li>
                <li>· Corporate matching</li>
              </ul>
              <Link to="contact" className="inline-flex items-center gap-1.5 mt-3 text-navy font-display font-bold text-sm">Talk to our team
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 5l7 7-7 7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </Link>
            </div>
          </aside>
        </div>
      </section>
    </div>
  );
}

/* ---------- Get Involved (brief: 4 pathways + Donation) ---------- */
const PATHWAYS = [
  { k: "register", color: "sky", title: "Register as a Father", desc: "Join a Forge group and begin the 12-week journey. Fill in a short registration form and we will connect you to a group.", cta: "Register Now", img: "uploads/TRG_Father_sBreakfast125.jpg" },
  { k: "chapter", color: "navy", title: "Start a Be A Man Chapter", desc: "Are you a teacher, chaplain, or youth leader? Bring Be A Man to your school or community. We provide the curriculum and training.", cta: "Apply to Start a Chapter", img: "uploads/FA-09310.jpg" },
  { k: "volunteer", color: "gold", title: "Become a Volunteer Mentor", desc: "If you are a stable, mature man willing to invest in the next generation, we need you. Training provided.", cta: "Volunteer Application", img: "uploads/FATHERS ARISE MEETING-66.jpg" },
  { k: "partner", color: "forest", title: "Partner or Donate", desc: "Churches, NGOs, corporates, and individuals — partner with the movement. Your support fuels school chapters, Forge groups, retreats, and media production.", cta: "Give / Partner", img: "uploads/FATHERS ARISE-135-9f499005.jpg" },
];

function GetInvolvedPage() {
  const [active, setActive] = useState(null);
  // Phase 3.7: editable site content
  const [cms, setCms] = useState({});
  useEffect(() => {
    if (window.cms && typeof window.cms.getSiteContent === "function") {
      window.cms.getSiteContent("getinvolved").then(setCms);
    }
  }, []);
  const hero = cms.hero || {};
  return (
    <div data-screen-label="08 Get Involved">
      <section data-cms-section="hero" data-cms-page="getinvolved" className="relative bg-navy text-white overflow-hidden">
        <div className="absolute inset-0">
          <img src={hero.image || "uploads/Get-involved.jpg"} alt="" className="w-full h-full object-cover" />
          <div className="absolute inset-0 bg-gradient-to-br from-navy/95 via-navy/80 to-navy/50" />
        </div>
        <div className={`relative max-w-[1280px] mx-auto px-4 sm:px-6 py-28 md:py-36 ${hero.align === "center" ? "text-center" : hero.align === "right" ? "text-right" : "text-left"}`}>
          <div className="text-xs font-display font-bold uppercase tracking-[0.25em] text-gold">Get Involved</div>
          <h1 className="mt-6 font-display font-black text-5xl sm:text-6xl md:text-7xl leading-[0.95]">{hero.headline || <>There Is a <span className="text-gold">Place for You</span></>}</h1>
          <p className="mt-6 max-w-3xl text-xl md:text-2xl text-white/95 font-display font-medium leading-snug">{hero.subhead || "Whether you want to register, volunteer, partner, or give — the movement needs you."}</p>
        </div>
      </section>

      <section className="py-20 bg-paper">
        <div className="max-w-[1280px] mx-auto px-4 sm:px-6">
          <SectionTitle eyebrow="Four Pathways" title="Find your place" center />
          <div className="mt-14 grid grid-cols-1 md:grid-cols-2 gap-6">
            {PATHWAYS.map((p, i) => {
              const accent = p.color === "sky" ? "border-sky" : p.color === "gold" ? "border-gold" : p.color === "forest" ? "border-forest" : "border-navy";
              const txt = p.color === "sky" ? "text-sky" : p.color === "gold" ? "text-[#A07700]" : p.color === "forest" ? "text-forest" : "text-navy";
              return (
                <article key={p.k} className={`rounded-3xl bg-white shadow-card overflow-hidden lift border-t-8 ${accent}`}>
                  <img src={p.img} alt={p.title} className="w-full object-cover" style={{ aspectRatio: "16/9" }} />
                  <div className="p-8">
                    <div className={`font-display font-black text-5xl tabular-nums ${txt}`}>{String(i + 1).padStart(2, "0")}</div>
                    <h3 className="mt-3 font-display font-black text-2xl text-navy leading-tight">{p.title}</h3>
                    <p className="mt-3 text-ink/75 leading-relaxed">{p.desc}</p>
                    <button onClick={() => {
                      // "Register as a Father" → full OS father form (writes to fa_father_inquiries)
                      // "Start a Be A Man Chapter" → full OS BEAM form (writes to fa_beam_students)
                      // Volunteer & Partner → lightweight modal (writes to fa_volunteer_applications / fa_partner_inquiries)
                      if (p.k === "register") { window.location.href = "father-registration.html"; return; }
                      if (p.k === "chapter")  { window.location.href = "beam-registration.html";   return; }
                      setActive(p.k);
                    }} className={`mt-6 inline-flex items-center gap-2 rounded-full px-6 py-3 font-display font-bold uppercase tracking-wider text-sm ${p.color === "gold" ? "btn-gold" : p.color === "sky" ? "bg-sky text-white hover:bg-navy" : p.color === "forest" ? "btn-green" : "btn-navy"}`}>
                      {p.cta} <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 5l7 7-7 7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
                    </button>
                  </div>
                </article>
              );
            })}
          </div>
        </div>
      </section>

      {/* Impact Report — downloadable */}
      <section className="py-20 bg-white">
        <div className="max-w-[1200px] mx-auto px-4 sm:px-6">
          <div className="rounded-3xl overflow-hidden bg-paper border border-navy/8 shadow-card grid grid-cols-1 md:grid-cols-12">
            <div className="md:col-span-5 relative">
              <img src="uploads/TRG_Father_sBreakfast125.jpg" alt="Fathers Arise Impact Report" className="w-full h-full object-cover" style={{ minHeight: 280 }} />
              <div className="absolute inset-0 bg-gradient-to-t from-navy/40 via-transparent to-transparent" />
              <div className="absolute bottom-4 left-4 right-4 inline-flex items-center gap-2 text-[10px] font-display font-bold uppercase tracking-[0.2em] text-white">
                <span className="px-2 py-0.5 bg-gold/90 text-navy rounded-full">PDF · 2025</span>
                <span className="text-white/80">Annual Report</span>
              </div>
            </div>
            <div className="md:col-span-7 p-8 md:p-12">
              <div className="text-xs font-display font-bold uppercase tracking-[0.25em] text-sky">Transparency</div>
              <h2 className="mt-3 font-display font-black text-3xl md:text-4xl text-navy leading-tight">See what your support builds.</h2>
              <p className="mt-4 text-ink/75 leading-relaxed">
                A year of fathers restored, families rebuilt, and Forge groups planted across Uganda — in the numbers, the photos, and the testimonies. Download the full report and see exactly where every shilling goes.
              </p>
              <dl className="mt-6 grid grid-cols-3 gap-3 text-center">
                <div className="rounded-2xl bg-white border border-navy/8 p-4">
                  <dt className="font-display font-black text-2xl text-navy tabular-nums">547+</dt>
                  <dd className="text-[10px] uppercase tracking-widest font-display font-semibold text-ink/55 mt-1">Fathers</dd>
                </div>
                <div className="rounded-2xl bg-white border border-navy/8 p-4">
                  <dt className="font-display font-black text-2xl text-navy tabular-nums">82</dt>
                  <dd className="text-[10px] uppercase tracking-widest font-display font-semibold text-ink/55 mt-1">Forge Groups</dd>
                </div>
                <div className="rounded-2xl bg-white border border-navy/8 p-4">
                  <dt className="font-display font-black text-2xl text-navy tabular-nums">25</dt>
                  <dd className="text-[10px] uppercase tracking-widest font-display font-semibold text-ink/55 mt-1">Communities</dd>
                </div>
              </dl>
              <div className="mt-8 flex flex-wrap gap-3">
                <a href="uploads/fathers-arise-impact-report.pdf" download className="inline-flex items-center gap-2 btn-gold rounded-full px-7 py-3.5 font-display font-bold uppercase tracking-wider text-sm">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 3v12m0 0l-5-5m5 5l5-5M5 21h14" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  Download Impact Report
                </a>
                <a href="uploads/fathers-arise-impact-report.pdf" target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 rounded-full px-6 py-3.5 border border-navy/15 text-navy font-display font-bold uppercase tracking-wider text-sm hover:border-navy/40">
                  Preview Online
                </a>
              </div>
              <p className="mt-4 text-xs text-ink/50">Last updated: 2025 · 20 pages · Free to share with churches, partners, and donors.</p>
            </div>
          </div>
        </div>
      </section>

      {/* Donation block */}
      <section className="py-24 bg-navy text-white relative overflow-hidden">
        <div className="absolute inset-0 grid-bg opacity-10" />
        <div className="relative max-w-[1100px] mx-auto px-4 sm:px-6">
          <div className="text-center">
            <div className="text-xs font-display font-bold uppercase tracking-[0.3em] text-gold">Donate</div>
            <h2 className="mt-4 font-display font-black text-4xl md:text-6xl leading-[1.05]">Your gift fuels the <span className="text-gold">movement.</span></h2>
            <p className="mt-6 max-w-2xl mx-auto text-lg text-white/85 leading-relaxed">Mobile Money support is critical for Uganda. We also accept bank transfer and international cards.</p>
          </div>
          <div className="mt-14 grid grid-cols-1 md:grid-cols-3 gap-5">
            {[
              { name: "Mobile Money", desc: "MTN MoMo / Airtel Money", detail: "Quick local giving", color: "#FFCC00" },
              { name: "Bank Transfer", desc: "UG / UK / US accounts", detail: "Details on request", color: "#2E96D4" },
              { name: "PayPal / Card", desc: "International donors", detail: "Visa, Mastercard, Amex", color: "#2ECC71" },
            ].map((m) => (
              <article key={m.name} className="rounded-3xl bg-white/5 border border-white/15 backdrop-blur p-7">
                <div className="w-10 h-10 rounded-xl" style={{ background: m.color }} />
                <h3 className="mt-5 font-display font-black text-xl text-white">{m.name}</h3>
                <p className="mt-2 text-white/85">{m.desc}</p>
                <div className="mt-2 text-xs text-white/55">{m.detail}</div>
              </article>
            ))}
          </div>
          <div className="mt-10 text-center">
            <Button to="donate" variant="gold" size="lg">Give Now</Button>
            <p className="mt-4 text-sm text-white/60">Digital receipt provided for every gift.</p>
          </div>
        </div>
      </section>

      {active && <PathwayModal pathway={active} onClose={() => setActive(null)} />}
    </div>
  );
}

function PathwayModal({ pathway, onClose }) {
  const p = PATHWAYS.find((x) => x.k === pathway);
  const fields = {
    register: ["Full name", "Phone (WhatsApp)", "Email", "City / location", "Number of children"],
    chapter: ["School / institution name", "Your name (role)", "Phone (WhatsApp)", "Email", "Number of students"],
    volunteer: ["Your name", "Phone (WhatsApp)", "Email", "City / region", "Skills / availability"],
    partner: ["Organisation name", "Contact person", "Email", "Type of partnership", "Brief about your org"],
  };
  const [vals, setVals] = useState(Array(5).fill(""));
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);

  // Map pathway → Supabase table + row shape (only volunteer & partner use the modal now)
  const submitPathway = async (e) => {
    e.preventDefault();
    if (!window.sb) { setError("Connection error. Please reload."); return; }
    setSubmitting(true);
    setError(null);
    try {
      let table = null, row = null;
      if (pathway === "volunteer") {
        table = "fa_volunteer_applications";
        row = { full_name: vals[0], phone: vals[1], email: vals[2], city: vals[3], skills: vals[4], source: "website" };
      } else if (pathway === "partner") {
        table = "fa_partner_inquiries";
        row = { organisation: vals[0], contact_name: vals[1], email: vals[2], partnership_type: vals[3], about: vals[4], source: "website" };
      } else {
        // Fallback for any future pathway — generic registrations table
        table = "registrations";
        row = { pathway, name: vals[0], phone: vals[1], email: vals[2], city: vals[3], data: { extra: vals[4] }, source: "website" };
      }
      const { error: insertError } = await window.sb.from(table).insert(row);
      if (insertError) throw insertError;
      setDone(true);
    } catch (err) {
      console.error("Pathway submit failed:", err);
      setError("We couldn't send your request. Please try again or WhatsApp +256 700 669 586.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[100] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4" onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} className="w-full max-w-2xl bg-white rounded-3xl shadow-2xl overflow-hidden max-h-[90vh] overflow-y-auto">
        <div className="relative bg-navy text-white p-8">
          <button onClick={onClose} aria-label="Close" className="absolute top-4 right-4 w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" /></svg>
          </button>
          <div className="text-xs font-display font-bold uppercase tracking-[0.25em] text-gold">{p.cta}</div>
          <h2 className="mt-3 font-display font-black text-3xl">{p.title}</h2>
        </div>
        {done ? (
          <div className="p-10 text-center">
            <div className="mx-auto w-14 h-14 rounded-full bg-gold text-navy flex items-center justify-center">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5L20 7" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" /></svg>
            </div>
            <h3 className="mt-5 font-display font-black text-2xl text-navy">Asante! We'll be in touch.</h3>
            <p className="mt-3 text-ink/65">A team member will reach out via WhatsApp or email within five working days.</p>
            <button onClick={onClose} className="mt-6 btn-navy rounded-full px-6 py-3 font-display font-bold uppercase tracking-wider text-sm">Close</button>
          </div>
        ) : (
          <form onSubmit={submitPathway} className="p-8 space-y-4">
            <p className="text-ink/75">{p.desc}</p>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {fields[pathway].map((f, i) => (
                <Field key={f} label={f} id={`pw-${i}`} className={i === fields[pathway].length - 1 ? "md:col-span-2" : ""}>
                  <Input id={`pw-${i}`} required value={vals[i]} onChange={(e) => { const v = [...vals]; v[i] = e.target.value; setVals(v); }} />
                </Field>
              ))}
            </div>
            {error && <div className="rounded-xl bg-red-50 border border-red-200 text-red-700 text-sm p-3">{error}</div>}
            <button disabled={submitting} className="w-full btn-gold rounded-full px-8 py-3.5 font-display font-black uppercase tracking-wider disabled:opacity-60 disabled:cursor-not-allowed">{submitting ? "Sending…" : "Submit"}</button>
          </form>
        )}
      </div>
    </div>
  );
}

function PathwayIcon({ name }) {
  const p = { width: 22, height: 22, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "church": return <svg {...p}><path d="M12 2v6M9 5h6M4 21V11l8-4 8 4v10M9 21v-5h6v5"/></svg>;
    case "handshake": return <svg {...p}><path d="M11 17l2 2 4-4 4 4M3 13l4-4 3 3 5-5 4 4"/></svg>;
    case "user": return <svg {...p}><circle cx="12" cy="8" r="4"/><path d="M4 22a8 8 0 0 1 16 0"/></svg>;
    default: return null;
  }
}

function PathwayForm({ pathway }) {
  const titles = {
    church: "Plant Forge groups in your church",
    partner: "Build something with us",
    volunteer: "Show up where it counts",
  };
  const fields = {
    church: ["Church name", "Your name (Pastor/Elder)", "Phone (WhatsApp)", "Approx. men in congregation"],
    partner: ["Organisation name", "Your name", "Email", "How would you like to partner?"],
    volunteer: ["Your name", "Phone (WhatsApp)", "City / region", "Skills you'd bring"],
  };
  const [vals, setVals] = useState(["", "", "", ""]);
  const [done, setDone] = useState(false);

  if (done) return (
    <div className="h-full flex flex-col justify-center text-center">
      <div className="mx-auto w-14 h-14 rounded-full bg-gold text-navy flex items-center justify-center">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5L20 7" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </div>
      <h3 className="mt-5 font-display font-extrabold text-2xl text-navy">Got it. We'll be in touch this week.</h3>
      <p className="mt-2 text-ink/65">A team member will reach out via WhatsApp or email within five working days.</p>
    </div>
  );

  return (
    <form onSubmit={(e) => { e.preventDefault(); setDone(true); }}>
      <div className="text-xs font-display font-bold uppercase tracking-widest text-sky">{pathway === "volunteer" ? "Volunteer" : pathway === "partner" ? "Partner" : "Church"}</div>
      <h3 className="mt-1 font-display font-extrabold text-3xl text-navy">{titles[pathway]}</h3>
      <p className="mt-2 text-ink/65">Five fields. Five days to respond. That's our promise.</p>
      <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-4">
        {fields[pathway].map((f, i) => (
          <Field key={f} label={f} id={`pw-${i}`}>
            <Input id={`pw-${i}`} required value={vals[i]} onChange={(e) => { const v = [...vals]; v[i] = e.target.value; setVals(v); }} />
          </Field>
        ))}
      </div>
      <button className="mt-6 btn-navy rounded-full px-8 py-3 font-display font-bold uppercase tracking-wider text-sm">Send request</button>
    </form>
  );
}

/* ---------- Contact (per brief) ---------- */
function ContactPage() {
  const [form, setForm] = useState({ name: "", email: "", phone: "", subject: "General", msg: "" });
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);

  const submitContact = async (e) => {
    e.preventDefault();
    if (!window.sb) { setError("Connection error. Please reload the page."); return; }
    setSubmitting(true);
    setError(null);
    try {
      const { error: insertError } = await window.sb.from("fa_contact_messages").insert({
        name: form.name,
        email: form.email,
        phone: form.phone,
        subject: form.subject,
        message: form.msg,
        language: (window.getCurrentLang && window.getCurrentLang()) || "en"
      });
      if (insertError) throw insertError;
      setDone(true);
    } catch (err) {
      console.error("Contact submit failed:", err);
      setError("We couldn't send your message. Please try again or WhatsApp +256 700 669 586.");
    } finally {
      setSubmitting(false);
    }
  };
  // Phase 3.7: editable site content
  const [cmsContact, setCmsContact] = useState({});
  useEffect(() => {
    if (window.cms && typeof window.cms.getSiteContent === "function") {
      window.cms.getSiteContent("contact").then(setCmsContact);
    }
  }, []);
  const hero = cmsContact.hero || {};
  return (
    <div data-screen-label="09 Contact">
      <section data-cms-section="hero" data-cms-page="contact" className="relative bg-navy text-white overflow-hidden">
        <div className="absolute inset-0">
          <img src={hero.image || "uploads/FATHERS ARISE MEETING-49 (1).jpg"} alt="" className="w-full h-full object-cover" />
          <div className="absolute inset-0 bg-gradient-to-br from-navy/95 via-navy/80 to-navy/60" />
        </div>
        <div className={`relative max-w-[1280px] mx-auto px-4 sm:px-6 py-28 md:py-36 ${hero.align === "center" ? "text-center" : hero.align === "right" ? "text-right" : "text-left"}`}>
          <div className="text-xs font-display font-bold uppercase tracking-[0.25em] text-gold">Contact</div>
          <h1 className="mt-6 font-display font-black text-5xl sm:text-6xl md:text-7xl leading-[0.95]">{hero.headline || <>Get in <span className="text-gold">Touch</span></>}</h1>
          <p className="mt-6 max-w-2xl text-xl text-white/90 font-display font-medium leading-snug">{hero.subhead || "A real person will reply. WhatsApp is fastest."}</p>
        </div>
      </section>

      <section className="py-20 bg-paper">
        <div className="max-w-[1200px] mx-auto px-4 sm:px-6 grid grid-cols-1 lg:grid-cols-12 gap-8">
          {/* Form */}
          <div className="lg:col-span-7">
            {done ? (
              <div className="rounded-3xl bg-white shadow-card p-12 text-center">
                <div className="mx-auto w-16 h-16 rounded-full bg-gold text-navy flex items-center justify-center">
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5L20 7" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" /></svg>
                </div>
                <h3 className="mt-6 font-display font-black text-2xl text-navy">Asante! Message received.</h3>
                <p className="mt-3 text-ink/65">A real person will reply within two business days.</p>
              </div>
            ) : (
              <form onSubmit={submitContact} className="rounded-3xl bg-white shadow-card p-8 md:p-10 space-y-5">
                <h2 className="font-display font-black text-3xl text-navy">Send us a message</h2>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <Field label="Name" id="c-name"><Input id="c-name" required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></Field>
                  <Field label="Email" id="c-email"><Input id="c-email" type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></Field>
                </div>
                <Field label="Phone" id="c-phone"><Input id="c-phone" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="+256 …" /></Field>
                <Field label="Subject" id="c-subject">
                  <Select id="c-subject" value={form.subject} onChange={(e) => setForm({ ...form, subject: e.target.value })}>
                    {["General", "Partnership", "Be A Man Chapter", "Forge Group", "Media", "Other"].map((t) => <option key={t}>{t}</option>)}
                  </Select>
                </Field>
                <Field label="Message" id="c-msg"><Textarea id="c-msg" rows="6" required value={form.msg} onChange={(e) => setForm({ ...form, msg: e.target.value })} placeholder="Tell us what's on your heart…" /></Field>
                {error && (
                  <div className="rounded-xl bg-red-50 border border-red-200 text-red-700 text-sm p-3">{error}</div>
                )}
                <button disabled={submitting} className="btn-gold rounded-full px-8 py-3.5 font-display font-black uppercase tracking-wider disabled:opacity-60 disabled:cursor-not-allowed">
                  {submitting ? "Sending…" : "Submit"}
                </button>
              </form>
            )}
          </div>

          {/* Direct Contact */}
          <aside className="lg:col-span-5 space-y-4">
            {[
              { ic: "phone", label: "Phone / WhatsApp", val: "+256 700 669 586", note: "Mon–Sat · 9am–6pm EAT" },
              { ic: "mail", label: "Email", val: "hello@fathersarize.org", note: "We reply within 2 business days" },
              { ic: "pin", label: "Location", val: "Kampala, Uganda", note: "By appointment" },
            ].map((c, i) => (
              <div key={i} className="rounded-3xl bg-white shadow-card p-6 flex items-start gap-4">
                <span className="w-12 h-12 rounded-2xl bg-navy text-gold flex items-center justify-center shrink-0"><ContactIcon name={c.ic} /></span>
                <div>
                  <div className="text-[10px] uppercase tracking-[0.2em] font-display font-bold text-sky">{c.label}</div>
                  <div className="mt-1 font-display font-bold text-navy text-lg">{c.val}</div>
                  <div className="mt-0.5 text-xs text-ink/55">{c.note}</div>
                </div>
              </div>
            ))}

            {/* Social */}
            <div className="rounded-3xl bg-navy text-white p-7 relative overflow-hidden">
              <div className="absolute inset-0 grid-bg opacity-10" />
              <div className="relative">
                <div className="text-xs font-display font-bold uppercase tracking-[0.2em] text-gold">Follow the Movement</div>
                <div className="mt-5 flex flex-wrap gap-3">
                  {[
                    { name: "Instagram", href: "https://www.instagram.com/fathersariseofficial/?__pwa=1#", svg: <path d="M7 3h10a4 4 0 0 1 4 4v10a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V7a4 4 0 0 1 4-4zm5 5a4 4 0 1 0 0 8 4 4 0 0 0 0-8zm5.5-1.5a1 1 0 1 0 0-2 1 1 0 0 0 0 2z" /> },
                    { name: "Facebook", href: "#", svg: <path d="M13 22v-9h3l1-4h-4V6.5c0-1 .3-1.7 1.8-1.7H17V1.2C16.5 1.1 15.2 1 13.9 1 11.3 1 9.5 2.6 9.5 5.5V9H6.5v4h3v9h3.5z" /> },
                    { name: "TikTok", href: "#", svg: <path d="M16 3v3.5a3.5 3.5 0 0 0 3.5 3.5V13a6.5 6.5 0 0 1-3.5-1v6.5a5.5 5.5 0 1 1-5.5-5.5v3a2.5 2.5 0 1 0 2.5 2.5V3h3z" /> },
                    { name: "X", href: "#", svg: <path d="M3 3l8 10L3 21h2.5L12.5 14.5 17 21h4l-8-10 8-10h-2.5L13 9.5 8 3H3z" /> },
                    { name: "YouTube", href: "https://www.youtube.com/@FathersArse", svg: <path d="M22 12s0-3.5-.5-5a2.5 2.5 0 0 0-1.8-1.8C18 5 12 5 12 5s-6 0-7.7.2A2.5 2.5 0 0 0 2.5 7C2 8.5 2 12 2 12s0 3.5.5 5a2.5 2.5 0 0 0 1.8 1.8C6 19 12 19 12 19s6 0 7.7-.2A2.5 2.5 0 0 0 21.5 17c.5-1.5.5-5 .5-5zM10 15V9l5 3-5 3z" /> },
                  ].map((s) => (
                    <a key={s.name} href={s.href} target={s.href.startsWith("http") ? "_blank" : undefined} rel={s.href.startsWith("http") ? "noopener noreferrer" : undefined} className="flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 hover:bg-gold hover:text-navy text-sm font-display font-bold transition-colors">
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">{s.svg}</svg>
                      {s.name}
                    </a>
                  ))}
                </div>
              </div>
            </div>

            {/* Map */}
            <div className="rounded-3xl overflow-hidden shadow-card">
              <div className="aspect-[4/3] bg-[#E8EFFB] grid-bg relative">
                <div className="absolute inset-0 flex flex-col items-center justify-center text-navy">
                  <svg width="40" height="40" viewBox="0 0 24 24" fill="none"><path d="M12 21s-7-6.5-7-12a7 7 0 1 1 14 0c0 5.5-7 12-7 12z" stroke="currentColor" strokeWidth="2" /><circle cx="12" cy="9" r="3" fill="#E8B830" stroke="currentColor" strokeWidth="2" /></svg>
                  <div className="mt-3 font-display font-bold text-navy">Kampala, Uganda</div>
                  <div className="mt-1 text-[10px] font-mono uppercase tracking-widest text-navy/60">Google Map embed</div>
                </div>
              </div>
            </div>
          </aside>
        </div>
      </section>
    </div>
  );
}

function ContactIcon({ name }) {
  const p = { width: 20, height: 20, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "phone": return <svg {...p}><path d="M22 16.92V21a1 1 0 0 1-1.09 1A19.79 19.79 0 0 1 2 4.09 1 1 0 0 1 3 3h4.09a1 1 0 0 1 1 .75l1 4a1 1 0 0 1-.27 1L7 10.5a16 16 0 0 0 6.5 6.5l1.75-1.82a1 1 0 0 1 1-.27l4 1a1 1 0 0 1 .75 1z"/></svg>;
    case "mail": return <svg {...p}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>;
    case "pin": return <svg {...p}><path d="M12 21s-7-6.5-7-12a7 7 0 1 1 14 0c0 5.5-7 12-7 12z"/><circle cx="12" cy="9" r="2.5"/></svg>;
    default: return null;
  }
}

/* ---------- Events ---------- */
function EventsPage() {
  const [view, setView] = useState("list");
  const [filter, setFilter] = useState("All");
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);
  // Phase 3.7: editable site content
  const [cms, setCms] = useState({});

  useEffect(() => {
    window.cms.getEvents().then((e) => { setEvents(e); setLoading(false); });
    if (window.cms && typeof window.cms.getSiteContent === "function") {
      window.cms.getSiteContent("events").then(setCms);
    }
  }, []);
  const hero = cms.hero || {};

  const types = ["All", ...Array.from(new Set(events.map((e) => e.type)))];
  const filtered = filter === "All" ? events : events.filter((e) => e.type === filter);

  return (
    <div data-screen-label="09 Events">
      <section data-cms-section="hero" data-cms-page="events" className="relative overflow-hidden bg-navy text-white">
        <div className="absolute inset-0">
          <img src={hero.image || "uploads/TRG_Father_sBreakfast19.jpg"} alt="" className="w-full h-full object-cover" />
          <div className="absolute inset-0 bg-gradient-to-b from-black/40 via-black/30 to-black/60" />
        </div>

        <div className="relative max-w-[1280px] mx-auto px-4 sm:px-6 py-32">
          <div className={`max-w-3xl ${hero.align === "center" ? "mx-auto text-center" : hero.align === "right" ? "ml-auto text-right" : "text-left"}`}>
            <div className="text-xs font-display font-bold uppercase tracking-[0.15em] text-gold">Upcoming Events</div>
            <h1 className="mt-3 font-display font-extrabold text-4xl md:text-6xl leading-[1.02]">{hero.headline || "Join Us in Action"}</h1>
            <p className="mt-4 text-lg text-white/90 max-w-2xl leading-relaxed">
              {hero.subhead || "From Forge gatherings to community celebrations, these are the moments where fatherhood is celebrated, strengthened, and passed forward."}
            </p>
          </div>
        </div>
      </section>

      <section className="py-10 border-b border-navy/8 bg-white">
        <div className="max-w-[1280px] mx-auto px-4 sm:px-6 flex items-center justify-between flex-wrap gap-4">
          <div className="flex flex-wrap gap-2">
            {types.map((t) => (
              <button key={t} onClick={() => setFilter(t)}
                className={`px-3 py-1.5 rounded-full text-xs font-display font-bold uppercase tracking-widest ${filter === t ? "bg-navy text-white" : "bg-paper text-ink/65 border border-navy/10 hover:border-navy/30"}`}>{t}</button>
            ))}
          </div>
          <div className="inline-flex p-1 bg-paper rounded-full border border-navy/10">
            {[["list", "List"], ["calendar", "Calendar"]].map(([k, l]) => (
              <button key={k} onClick={() => setView(k)}
                className={`px-4 py-1.5 rounded-full text-sm font-display font-bold ${view === k ? "bg-navy text-white" : "text-ink/55"}`}>{l}</button>
            ))}
          </div>
        </div>
      </section>

      <section className="py-12">
        <div className="max-w-[1280px] mx-auto px-4 sm:px-6">
          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
              {Array.from({ length: 4 }).map((_, i) => (
                <div key={i} className="rounded-2xl bg-white border border-navy/8 animate-pulse h-72" />
              ))}
            </div>
          ) : view === "list" ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
              {filtered.map((e) => <EventListCard key={e.id} event={e} />)}
            </div>
          ) : (
            <CalendarView events={filtered} />
          )}
        </div>
      </section>
    </div>
  );
}

function EventListCard({ event }) {
  const date = new Date(event.date);
  return (
    <article className="rounded-2xl bg-white border border-navy/8 shadow-card overflow-hidden lift">
      {event.image ? (
        <img src={event.image} alt={event.title} className="w-full h-auto object-cover" style={{ aspectRatio: "16/9" }} />
      ) : (
        <Placeholder label={`${event.type} photo`} tone="sky" ratio="16/9" />
      )}
      <div className="p-6">
        <div className="flex items-center gap-2 text-[10px] font-display font-bold uppercase tracking-widest">
          <span className="px-2 py-0.5 bg-gold/20 text-[#7C5800] rounded-full">{event.type}</span>
          <span className="text-ink/55">{date.toLocaleDateString("en", { day: "numeric", month: "long", year: "numeric" })}</span>
        </div>
        <h3 className="mt-2 font-display font-extrabold text-xl text-navy leading-snug">{event.title}</h3>
        <div className="mt-2 text-sm text-ink/60 flex items-center gap-1.5">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M12 21s-7-6.5-7-12a7 7 0 1 1 14 0c0 5.5-7 12-7 12z" stroke="currentColor" strokeWidth="2"/><circle cx="12" cy="9" r="2.5" stroke="currentColor" strokeWidth="2"/></svg>
          {event.location}
        </div>
        <p className="mt-3 text-ink/70 text-sm">{event.summary}</p>
        <div className="mt-5 flex items-center justify-between">
          <button className="btn-navy rounded-full px-5 py-2 text-xs font-display font-bold uppercase tracking-wider">{event.cta}</button>
          <button className="text-xs font-display font-bold uppercase tracking-wider text-ink/55 hover:text-navy">Add to calendar</button>
        </div>
      </div>
    </article>
  );
}

function CalendarView({ events }) {
  // Simple month grid for May/June/July 2026 with event chips
  const months = [
    { name: "May 2026", year: 2026, month: 4, days: 31, startDay: 5 },
    { name: "June 2026", year: 2026, month: 5, days: 30, startDay: 1 },
    { name: "July 2026", year: 2026, month: 6, days: 31, startDay: 3 },
  ];
  const lookup = (year, month, day) => events.filter((e) => {
    const d = new Date(e.date);
    return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day;
  });
  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
      {months.map((m) => (
        <div key={m.name} className="rounded-2xl bg-white border border-navy/8 overflow-hidden">
          <div className="p-4 border-b border-navy/8 font-display font-bold text-navy">{m.name}</div>
          <div className="grid grid-cols-7 text-center text-[10px] uppercase tracking-widest font-display font-bold text-ink/45 p-2">
            {["S", "M", "T", "W", "T", "F", "S"].map((d, i) => <div key={i} className="py-1">{d}</div>)}
          </div>
          <div className="grid grid-cols-7 gap-px bg-navy/5">
            {Array.from({ length: m.startDay }).map((_, i) => <div key={"e" + i} className="bg-white aspect-square" />)}
            {Array.from({ length: m.days }).map((_, i) => {
              const day = i + 1;
              const evs = lookup(m.year, m.month, day);
              return (
                <div key={day} className="bg-white aspect-square p-1.5 text-[11px] relative">
                  <div className={`text-ink/55 ${evs.length ? "font-bold text-navy" : ""}`}>{day}</div>
                  {evs.length > 0 && (
                    <div className="absolute left-1 right-1 bottom-1 truncate rounded bg-gold text-navy px-1 py-0.5 text-[9px] font-display font-bold">{evs[0].type}</div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- Team Login — doorway to the Fathers Arise OS ---------- */
// Same-origin: works on the temp Hostinger preview AND on the real domain
// when it goes live. One config, no edits later.
const FA_OS_URL = "/os/";

function TeamLoginPage() {
  return (
    <div data-screen-label="10 Team Login" className="min-h-[70vh] py-20 bg-paper">
      <div className="max-w-lg mx-auto px-4 sm:px-6">
        <div className="rounded-3xl bg-white border border-navy/8 shadow-card p-10 relative overflow-hidden">
          <div className="absolute inset-0 grid-bg opacity-5 pointer-events-none" />
          <div className="relative">
            <div className="flex items-center gap-4">
              <div className="w-14 h-14 rounded-2xl bg-navy text-gold flex items-center justify-center shrink-0">
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none"><rect x="3" y="3" width="7" height="7" rx="1" stroke="currentColor" strokeWidth="2"/><rect x="14" y="3" width="7" height="7" rx="1" stroke="currentColor" strokeWidth="2"/><rect x="3" y="14" width="7" height="7" rx="1" stroke="currentColor" strokeWidth="2"/><rect x="14" y="14" width="7" height="7" rx="1" stroke="currentColor" strokeWidth="2"/></svg>
              </div>
              <div>
                <div className="text-[10px] font-display font-bold uppercase tracking-[0.2em] text-sky">Internal Tool</div>
                <h1 className="font-display font-extrabold text-2xl text-navy mt-1">Fathers Arise OS</h1>
              </div>
            </div>

            <p className="mt-6 text-ink/75 leading-relaxed">
              The internal Operating System for the Fathers Arise team. Sign in to access tasks, finance, monthly reports, the website editor, and live form submissions.
            </p>

            <div className="mt-8">
              <a
                href={FA_OS_URL}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center justify-center gap-2 w-full btn-navy rounded-full px-8 py-4 font-display font-bold uppercase tracking-wider text-sm"
              >
                Open OS
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M7 17L17 7M17 7H7M17 7v10" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </a>
              <div className="mt-3 text-xs text-ink/55 text-center font-mono">
                fathersarize.org/os
              </div>
            </div>

            <div className="mt-8 pt-6 border-t border-navy/8">
              <p className="text-xs text-ink/55 leading-relaxed text-center">
                For Fathers Arise staff, program leads, and Forge captains only.<br />
                Not a team member?{" "}
                <Link to="get-involved" className="text-sky hover:underline font-display font-bold">
                  Get involved →
                </Link>
              </p>
            </div>
          </div>
        </div>

        <div className="mt-4 text-center text-[10px] font-mono text-ink/40 uppercase tracking-widest">
          The OS lives at a separate, secure address.
        </div>
      </div>
    </div>
  );
}

window.DonatePage = DonatePage;
window.GetInvolvedPage = GetInvolvedPage;
window.ContactPage = ContactPage;
window.EventsPage = EventsPage;
window.TeamLoginPage = TeamLoginPage;
