/* ════════════════════════════════════════════════
   Halaman Donasi — campaign + progress + rekening + form
   ════════════════════════════════════════════════ */
const NOMINALS = [50000, 100000, 250000, 500000, 1000000, 2500000];
const rpShort = (n) => n >= 1000000 ? (n / 1000000).toFixed(n % 1000000 ? 1 : 0) + ' jt' : n >= 1000 ? (n / 1000) + ' rb' : n;

function DonasiPage({ navigate }) {
  const [campaigns, setCampaigns] = useState([]);
  const [rekening, setRekening] = useState([]);
  const [settings, setSettings] = useState({});
  const [stats, setStats] = useState({ total_masuk: 0, total_donatur: 0, total_campaign: 0 });
  const [loading, setLoading] = useState(true);
  const [nominal, setNominal] = useState(250000);
  const [custom, setCustom] = useState('');
  const [modal, setModal] = useState(null); // { campaign, amount }

  useEffect(() => {
    const f = window.__openDonasiForm;
    if (f) { window.__openDonasiForm = false; setTimeout(() => setModal({ campaign: (f && f.id) ? f : null, amount: 250000 }), 120); }
  }, []);

  useEffect(() => {
    Promise.all([
      api.get('donations.php?action=list_campaigns'),
      api.get('donations.php?action=list_rekening'),
      api.get('donations.php?action=public_stats'),
      api.get('donations.php?action=get_settings'),
    ]).then(([c, r, s, st]) => {
      if (c.ok && c.campaigns) setCampaigns(c.campaigns);
      if (r.ok && r.rekening) setRekening(r.rekening);
      if (s.ok) setStats({ total_masuk: s.total_masuk || 0, total_donatur: s.total_donatur || 0, total_campaign: s.kampanye_aktif ?? s.total_campaign ?? 0 });
      if (st.ok && st.settings) setSettings(st.settings);
    }).finally(() => setLoading(false));
  }, []);

  const finalNominal = custom ? (parseInt(custom) || 0) : nominal;

  return (
    <div style={{ background: 'var(--bg)' }}>
      <PageBand pageKey="donasi" kicker="Sedekah · Wakaf · Infaq" title="Salurkan Amal Jariyah Anda" sub="Setiap rupiah yang Anda berikan menjadi bekal pendidikan santri dan dakwah yang terus mengalir pahalanya." />

      {/* Statistik */}
      <section className="container" style={{ padding: '24px 20px 0' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 14 }}>
          {[[fmtRpShort(stats.total_masuk), 'Terkumpul'], [stats.total_donatur, 'Donatur'], [stats.total_campaign, 'Program Donasi']].map(([n, l]) => (
            <div key={l} style={{ background: 'var(--surface)', borderRadius: 16, padding: '20px 14px', textAlign: 'center', border: '1px solid var(--border-soft)' }}>
              <div style={{ fontFamily: 'var(--font-d)', fontSize: 23, fontWeight: 900, color: 'var(--orange)', whiteSpace: 'nowrap' }}>{n}</div>
              <div style={{ fontSize: 12.5, color: 'var(--muted)', fontWeight: 600, marginTop: 3 }}>{l}</div>
            </div>
          ))}
        </div>
      </section>

      {/* QUICK DONATE */}
      <section className="container" style={{ padding: '34px 20px 10px' }}>
        <div style={{ background: 'var(--surface)', borderRadius: 20, padding: '28px 28px', border: '1px solid var(--border-soft)', boxShadow: 'var(--shadow-warm-md)' }}>
          <div style={{ fontFamily: 'var(--font-d)', fontSize: 20, fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 16 }}>Donasi Cepat</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(96px, 1fr))', gap: 10, marginBottom: 14 }}>
            {NOMINALS.map(n => {
              const active = nominal === n && !custom;
              return <button key={n} onClick={() => { setNominal(n); setCustom(''); }} style={{ padding: '13px 8px', borderRadius: 12, border: `1.5px solid ${active ? 'var(--orange)' : 'var(--border)'}`, background: active ? 'rgba(232,145,42,.1)' : 'var(--surface)', color: active ? '#C26F12' : 'var(--ink-deep)', fontWeight: 800, fontSize: 14.5, cursor: 'pointer', fontFamily: 'inherit' }}>Rp {rpShort(n)}</button>;
            })}
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <input value={custom} onChange={e => setCustom(e.target.value.replace(/\D/g, ''))} placeholder="Nominal lain (Rp)" inputMode="numeric"
              style={{ flex: 1, minWidth: 160, padding: '13px 16px', borderRadius: 12, border: '1.5px solid var(--border)', fontSize: 14.5, fontFamily: 'inherit', background: 'var(--surface)', color: 'var(--ink-deep)' }} />
            <button className="btn-donasi-cta" onClick={() => finalNominal >= 1000 && setModal({ campaign: null, amount: finalNominal })} style={{ padding: '13px 26px' }}>{IC.heart} Donasi {finalNominal >= 1000 ? fmtRp(finalNominal) : ''}</button>
          </div>
        </div>
      </section>

      {/* CAMPAIGNS */}
      <section className="container" style={{ padding: '34px 20px 50px' }}>
        <SectionHeader label="Program Donasi" title="Pilih Program untuk Didukung" />
        {loading ? <div style={{ padding: 40, textAlign: 'center', color: 'var(--muted)' }}>Memuat…</div> : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 20 }}>
            {campaigns.map(c => {
              // Normalisasi: PHP asli pakai nama Indonesia, mock pakai Inggris
              const collected = c.terkumpul ?? c.collected ?? 0;
              const target = c.target ?? 0;
              const desc = c.deskripsi || c.description || '';
              const cover = c.cover_url || c.image_url;
              const urgent = c.urgensi === 'tinggi' || c.urgent;
              const pct = c.percent != null ? c.percent : (target ? Math.min(100, Math.round((collected / target) * 100)) : 0);
              const done = c.urgensi === 'selesai' || c.status === 'arsip' || c.status === 'selesai' || pct >= 100;
              const cslug = c.slug || (window.slugify ? slugify(c.title) : c.id);
              const openCard = (e) => { if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return; e.preventDefault(); setModal({ campaign: c, amount: finalNominal }); };
              return (
                <a key={c.id} href={'/donasi/' + cslug} onClick={openCard} className="fade-up donasi-card" style={{ textDecoration: 'none', background: 'var(--surface)', borderRadius: 18, overflow: 'hidden', border: '1px solid var(--border-soft)', boxShadow: 'var(--shadow-warm-sm, 0 4px 14px rgba(120,80,30,.06))', display: 'flex', flexDirection: 'column' }}>
                  <div style={{ position: 'relative', aspectRatio: '16/9', background: 'linear-gradient(135deg, var(--sage), #0F3D27)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
                    {cover ? <img src={cover} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} /> : <GlyphMark name='hands' size={52} />}
                    {urgent ? <span style={{ position: 'absolute', top: 12, left: 12, padding: '4px 11px', borderRadius: 999, background: '#DC2626', color: '#fff', fontSize: 11.5, fontWeight: 800 }}>MENDESAK</span> : null}
                  </div>
                  <div style={{ padding: '20px 22px', display: 'flex', flexDirection: 'column', flex: 1 }}>
                    <h3 style={{ fontFamily: 'var(--font-d)', fontSize: 19, fontWeight: 800, color: 'var(--ink-deep)', margin: '0 0 8px', textWrap: 'pretty' }}>{c.title}</h3>
                    <p style={{ fontSize: 13.5, lineHeight: 1.55, color: 'var(--muted)', margin: '0 0 16px', flex: 1 }}>{desc}</p>
                    <div style={{ height: 8, borderRadius: 999, background: 'var(--bg2)', overflow: 'hidden', marginBottom: 8 }}>
                      <div style={{ width: pct + '%', height: '100%', background: done ? 'var(--sage)' : 'var(--orange)', borderRadius: 999 }} />
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 16 }}>
                      <span style={{ fontWeight: 800, color: 'var(--ink-deep)' }}>{fmtRp(collected)}</span>
                      <span style={{ color: 'var(--muted)' }}>dari {fmtRp(target)} · {pct}%</span>
                    </div>
                    <span className={done ? 'btn-hero-secondary' : 'btn-donasi-cta'} style={{ width: '100%', justifyContent: 'center', opacity: done ? .7 : 1, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                      {done ? '✓ Target Tercapai' : <>{IC.heart} Donasi Sekarang</>}
                    </span>
                  </div>
                </a>
              );
            })}
          </div>
        )}
      </section>

      {/* REKENING */}
      <section className="container" style={{ padding: '0 20px 60px' }}>
        <SectionHeader label="Rekening Donasi" title="Transfer ke Rekening Resmi" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14 }}>
          {rekening.map((r, i) => <RekeningCard key={i} r={r} />)}
        </div>
        {settings.qris_url && (
          <div style={{ marginTop: 20, display: 'flex', justifyContent: 'center' }}>
            <div style={{ background: 'var(--surface)', borderRadius: 16, padding: '22px', border: '1px solid var(--border-soft)', textAlign: 'center', maxWidth: 320 }}>
              <div style={{ fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 4 }}>Scan QRIS</div>
              <div style={{ fontSize: 12.5, color: 'var(--muted)', marginBottom: 14 }}>Bayar pakai e-wallet (GoPay, OVO, Dana, ShopeePay) atau m-banking apa pun</div>
              <img src={settings.qris_url} alt="QRIS Donasi" style={{ width: '100%', maxWidth: 240, borderRadius: 10, display: 'block', margin: '0 auto' }} />
            </div>
          </div>
        )}
      </section>

      {modal && <DonasiModal modal={modal} rekening={rekening} settings={settings} onClose={() => setModal(null)} />}
    </div>
  );
}

function RekeningCard({ r }) {
  const [copied, setCopied] = useState(false);
  const num = r.number || r.nomor || '';
  const copy = () => { navigator.clipboard?.writeText(num.replace(/[-\s]/g, '')); setCopied(true); setTimeout(() => setCopied(false), 1600); };
  const atasNama = r.atas_nama || r.name || r.nama || '';
  return (
    <div style={{ background: 'var(--surface)', borderRadius: 16, padding: '20px 22px', border: '1px solid var(--border-soft)', display: 'flex', alignItems: 'center', gap: 16 }}>
      <div style={{ width: 52, height: 52, borderRadius: 12, background: 'var(--navy)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13, flexShrink: 0 }}>{r.bank}</div>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--ink-deep)', letterSpacing: '.02em' }}>{num}</div>
        <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>a.n. {atasNama}</div>
      </div>
      <button onClick={copy} style={{ padding: '8px 14px', borderRadius: 9, border: '1.5px solid var(--border)', background: copied ? 'var(--sage)' : 'var(--surface)', color: copied ? '#fff' : 'var(--ink-deep)', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0 }}>{copied ? '✓ Disalin' : 'Salin'}</button>
    </div>
  );
}

function DonasiModal({ modal, rekening, settings, onClose }) {
  const methods = [...rekening.map(r => r.bank), ...(settings && settings.qris_url ? ['QRIS'] : [])];
  const [form, setForm] = useState({ amount: modal.amount || 100000, donor_name: '', donor_phone: '', donor_email: '', metode: methods[0] || 'Transfer', catatan: '' });
  const [sending, setSending] = useState(false);
  const [done, setDone] = useState(false);
  const upd = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const waNum = (settings && settings.donasi_wa_konfirmasi) || '628123456789';

  const submit = async (e) => {
    e.preventDefault();
    if (form.amount < 1000 || !form.donor_phone) return;
    setSending(true);
    try {
      await api.post('donations.php?action=submit', { ...form, campaign_id: modal.campaign ? modal.campaign.id : null });
      setDone(true);
    } finally { setSending(false); }
  };

  const waConfirm = () => {
    const msg = `Assalamu'alaikum, saya ingin konfirmasi donasi:\n\nNama: ${form.donor_name || '-'}\nNominal: ${fmtRp(form.amount)}\nProgram: ${modal.campaign ? modal.campaign.title : 'Donasi Umum'}\nMetode: ${form.metode}`;
    window.open('https://wa.me/' + String(waNum).replace(/\D/g, '').replace(/^0/, '62') + '?text=' + encodeURIComponent(msg), '_blank');
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,20,45,.6)', zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, backdropFilter: 'blur(3px)' }} className="anim-overlay">
      <div onClick={e => e.stopPropagation()} style={{ background: 'var(--surface)', borderRadius: 20, width: '100%', maxWidth: 440, maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 30px 80px rgba(0,0,0,.35)' }}>
        {done ? (
          <div style={{ padding: '40px 32px', textAlign: 'center' }}>
            <div style={{ fontSize: 52, marginBottom: 14 }}>🤲</div>
            <div style={{ fontFamily: 'var(--font-d)', fontSize: 24, fontWeight: 900, color: 'var(--ink-deep)', marginBottom: 10 }}>Jazakumullah Khairan!</div>
            <p style={{ color: 'var(--muted)', fontSize: 14.5, lineHeight: 1.6, marginBottom: 22 }}>Donasi Anda sebesar <strong style={{ color: 'var(--ink-deep)' }}>{fmtRp(form.amount)}</strong> telah dicatat. Mohon transfer & konfirmasi via WhatsApp agar segera kami verifikasi.</p>
            <button onClick={waConfirm} style={{ width: '100%', padding: '13px', borderRadius: 12, border: 'none', background: '#25D366', color: '#fff', fontSize: 15, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit', marginBottom: 10 }}>💬 Konfirmasi via WhatsApp</button>
            <button onClick={onClose} style={{ width: '100%', padding: '12px', borderRadius: 12, border: '1.5px solid var(--border)', background: 'var(--surface)', color: 'var(--ink-deep)', fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>Tutup</button>
          </div>
        ) : (
          <form onSubmit={submit} style={{ padding: '28px 30px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
              <div>
                <div style={{ fontFamily: 'var(--font-d)', fontSize: 21, fontWeight: 900, color: 'var(--ink-deep)' }}>Form Donasi</div>
                <div style={{ fontSize: 13, color: 'var(--muted)' }}>{modal.campaign ? modal.campaign.title : 'Donasi Umum'}</div>
              </div>
              <button type="button" onClick={onClose} style={{ background: 'var(--bg2)', border: 'none', borderRadius: 8, width: 32, height: 32, cursor: 'pointer', color: 'var(--ink-deep)', fontSize: 16 }}>✕</button>
            </div>
            <Field label="Nominal Donasi *">
              <input type="number" value={form.amount} onChange={e => upd('amount', parseInt(e.target.value) || 0)} required min="1000" style={inp} />
            </Field>
            <Field label="Nama (boleh dikosongkan untuk hamba Allah)">
              <input value={form.donor_name} onChange={e => upd('donor_name', e.target.value)} placeholder="Nama Anda" style={inp} />
            </Field>
            <Field label="Nomor WhatsApp *">
              <input value={form.donor_phone} onChange={e => upd('donor_phone', e.target.value.replace(/[^\d+]/g, ''))} required placeholder="08xxxxxxxxxx" style={inp} />
            </Field>
            <Field label="Email (untuk bukti & notifikasi donasi)">
              <input type="email" value={form.donor_email} onChange={e => upd('donor_email', e.target.value)} placeholder="email@contoh.com" style={inp} />
            </Field>
            <Field label="Metode Pembayaran *">
              <select value={form.metode} onChange={e => upd('metode', e.target.value)} style={inp}>
                {methods.length === 0 ? <option>Transfer Bank</option> : methods.map((m, i) => <option key={i} value={m}>{m === 'QRIS' ? 'QRIS (semua e-wallet & m-banking)' : m}</option>)}
              </select>
            </Field>

            {/* Detail pembayaran sesuai metode terpilih — langsung di form */}
            {(() => {
              if (form.metode === 'QRIS' && settings && settings.qris_url) {
                return (
                  <div style={{ background: 'var(--bg2)', borderRadius: 12, padding: '16px', marginBottom: 14, textAlign: 'center' }}>
                    <div style={{ fontSize: 12.5, color: 'var(--muted)', marginBottom: 10 }}>Scan QR ini dengan e-wallet / m-banking apa pun</div>
                    <img src={settings.qris_url} alt="QRIS" style={{ width: '100%', maxWidth: 200, borderRadius: 10, margin: '0 auto', display: 'block' }} />
                  </div>
                );
              }
              const rk = rekening.find(r => r.bank === form.metode);
              if (rk) {
                const num = (rk.nomor || rk.number || '');
                return (
                  <div style={{ background: 'var(--bg2)', borderRadius: 12, padding: '14px 16px', marginBottom: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontSize: 11.5, color: 'var(--muted)', fontWeight: 700 }}>{rk.bank} · a.n. {rk.atas_nama || rk.name || rk.nama}</div>
                      <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--ink-deep)', letterSpacing: '.02em' }}>{num}</div>
                    </div>
                    <button type="button" onClick={() => navigator.clipboard?.writeText(num.replace(/[-\s]/g, ''))} style={{ padding: '8px 13px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--surface)', color: 'var(--ink-deep)', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0 }}>Salin</button>
                  </div>
                );
              }
              return null;
            })()}
            <Field label="Catatan / Doa (opsional)">
              <textarea value={form.catatan} onChange={e => upd('catatan', e.target.value)} rows="2" placeholder="Semoga menjadi amal jariyah…" style={{ ...inp, resize: 'vertical' }} />
            </Field>
            <button type="submit" disabled={sending || form.amount < 1000 || !form.donor_phone} className="btn-donasi-cta" style={{ width: '100%', justifyContent: 'center', marginTop: 6, opacity: (sending || form.amount < 1000 || !form.donor_phone) ? .6 : 1 }}>
              {sending ? 'Memproses…' : `Lanjutkan Donasi ${fmtRp(form.amount)}`}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

const inp = { width: '100%', padding: '11px 14px', borderRadius: 10, border: '1.5px solid var(--border)', fontSize: 14, fontFamily: 'inherit', background: 'var(--surface)', color: 'var(--ink-deep)', boxSizing: 'border-box' };
function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: 'var(--ink-deep)', marginBottom: 6 }}>{label}</label>
      {children}
    </div>
  );
}

Object.assign(window, { DonasiPage, inp, Field });
