/* ════════════════════════════════════════════════
   Dashboard — modul Konten generik + Donasi + Pengaturan
   ════════════════════════════════════════════════ */

/* Skema field per jenis konten */
const PAGE_OPTS = [
  { value: 'articles', label: 'Halaman Artikel' },
  { value: 'donasi', label: 'Halaman Donasi' },
  { value: 'register', label: 'Pendaftaran Santri' },
  { value: 'programs', label: 'Halaman Program' },
  { value: 'kegiatan', label: 'Halaman Kegiatan' },
  { value: 'toko', label: 'Toko Buku' },
  { value: 'about', label: 'Tentang Kami' },
  { value: 'contact', label: 'Kontak' },
];
const ACCENT_OPTS = [
  { value: '#1F6B47', label: 'Hijau (Sage)' },
  { value: '#1B2F6E', label: 'Biru (Navy)' },
  { value: '#C26F12', label: 'Oranye' },
  { value: '#8B5A2B', label: 'Coklat' },
];
const KIND_GLYPH = { banner: 'scroll', program: 'cap', teacher: 'mosque', testimonial: 'scroll', fasilitas: 'mosque', kegiatan: 'calendar', buku: 'book' };
const KIND_SCHEMA = {
  banner: {
    title: 'Banner Beranda', singular: 'Banner', icon: '🖼️',
    fields: [
      { key: 'title', label: 'Judul Banner', type: 'text', primary: true },
      { key: 'subtitle', label: 'Subjudul / Deskripsi', type: 'textarea' },
      { key: 'tag', label: 'Label kecil (mis. Artikel Baru)', type: 'text' },
      { key: 'image_url', label: 'Gambar Latar', type: 'image' },
      { key: 'cta_label', label: 'Teks Tombol (mis. Baca Selengkapnya)', type: 'text' },
      { key: 'cta_target', label: 'Tombol Menuju Halaman', type: 'select', options: PAGE_OPTS },
      { key: 'accent', label: 'Warna Aksen', type: 'select', options: ACCENT_OPTS },
    ],
  },
  program: {
    title: 'Program', singular: 'Program', icon: '🎓',
    fields: [
      { key: 'name', label: 'Nama Program', type: 'text', primary: true },
      { key: 'icon', label: 'Ikon (emoji)', type: 'text' },
      { key: 'desc', label: 'Deskripsi', type: 'textarea' },
      { key: 'schedule', label: 'Jadwal', type: 'text' },
      { key: 'levels', label: 'Level (pisahkan koma)', type: 'list' },
      { key: 'banner_url', label: 'Gambar Banner (opsional)', type: 'image' },
      { key: 'youtube_url', label: 'Link Video YouTube (opsional)', type: 'text' },
      { key: 'featured', label: 'Tampilkan di Beranda?', type: 'toggle' },
      { key: 'banner_home', label: 'Jadikan Banner Slideshow Beranda?', type: 'toggle' },
    ],
  },
  teacher: {
    title: 'Pengajar', singular: 'Pengajar', icon: '👤',
    fields: [
      { key: 'name', label: 'Nama', type: 'text', primary: true },
      { key: 'title', label: 'Jabatan / Keahlian', type: 'text' },
      { key: 'bio', label: 'Bio singkat', type: 'textarea' },
      { key: 'photo_url', label: 'Foto', type: 'image' },
      { key: 'tags', label: 'Keahlian (pisahkan koma)', type: 'list' },
    ],
  },
  testimonial: {
    title: 'Testimoni', singular: 'Testimoni', icon: '⭐',
    fields: [
      { key: 'name', label: 'Nama', type: 'text', primary: true },
      { key: 'role', label: 'Peran (mis. Wali Santri)', type: 'text' },
      { key: 'text', label: 'Isi Testimoni', type: 'textarea' },
      { key: 'stars', label: 'Bintang (1-5)', type: 'number' },
    ],
  },
  fasilitas: {
    title: 'Fasilitas', singular: 'Fasilitas', icon: '🏫',
    fields: [
      { key: 'caption', label: 'Nama Fasilitas', type: 'text', primary: true },
      { key: 'img_url', label: 'Foto', type: 'image' },
      { key: 'emoji', label: 'Ikon (emoji)', type: 'text' },
    ],
  },
  kegiatan: {
    title: 'Kegiatan', singular: 'Kegiatan', icon: '📅',
    fields: [
      { key: 'title', label: 'Judul Kegiatan', type: 'text', primary: true },
      { key: 'date', label: 'Tanggal', type: 'text' },
      { key: 'time', label: 'Waktu (opsional)', type: 'text' },
      { key: 'location', label: 'Lokasi (opsional)', type: 'text' },
      { key: 'desc', label: 'Deskripsi', type: 'textarea' },
      { key: 'img_url', label: 'Foto', type: 'image' },
      { key: 'youtube_url', label: 'Link Video YouTube (opsional)', type: 'text' },
      { key: 'featured', label: 'Tampilkan di Beranda?', type: 'toggle' },
      { key: 'banner_home', label: 'Jadikan Banner Slideshow Beranda?', type: 'toggle' },
    ],
  },
  buku: {
    title: 'Toko Buku', singular: 'Buku', icon: '🛒',
    fields: [
      { key: 'title', label: 'Judul Buku', type: 'text', primary: true },
      { key: 'author', label: 'Penulis', type: 'text' },
      { key: 'price', label: 'Harga (Rp)', type: 'number' },
      { key: 'originalPrice', label: 'Harga Coret (opsional)', type: 'number' },
      { key: 'desc', label: 'Deskripsi', type: 'textarea' },
      { key: 'cover_url', label: 'Sampul', type: 'image' },
      { key: 'emoji', label: 'Ikon (emoji)', type: 'text' },
      { key: 'stock', label: 'Stok', type: 'number' },
      { key: 'categories', label: 'Kategori (pisahkan koma)', type: 'list' },
      { key: 'featured', label: 'Unggulan (badge)?', type: 'toggle' },
      { key: 'banner_home', label: 'Jadikan Banner Slideshow Beranda?', type: 'toggle' },
    ],
  },
};

function ContentListModule({ section, kind, toast }) {
  const schema = KIND_SCHEMA[kind];
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState(null);
  const [form, setForm] = useState({});
  const [saving, setSaving] = useState(false);

  const load = () => {
    setLoading(true);
    // mula-mula dari data lokal sebagai fallback
    const seed = (window.MQA || {})[section] || [];
    api.get(`content.php?action=get_section&section=${section}`).then(r => {
      const arr = (r.ok && r.data && Array.isArray(r.data.items)) ? r.data.items : seed;
      setItems(arr);
    }).catch(() => setItems(seed)).finally(() => setLoading(false));
  };
  useEffect(load, [section]);

  const persist = async (next) => {
    setItems(next);
    const r = await api.post('content.php?action=save', { section, data: { items: next } });
    if (r.ok) toast('Tersimpan'); else toast('Gagal menyimpan');
  };

  const primaryKey = schema.fields.find(f => f.primary).key;
  const blank = () => { const o = {}; schema.fields.forEach(f => o[f.key] = f.type === 'list' ? [] : f.type === 'toggle' ? false : ''); return o; };
  const openAdd = () => { setForm(blank()); setModal({}); };
  const openEdit = (it, i) => { setForm({ ...it }); setModal({ i }); };

  const save = async () => {
    if (!form[primaryKey]) return;
    setSaving(true);
    // normalisasi number/list
    const clean = { ...form };
    schema.fields.forEach(f => {
      if (f.type === 'number') clean[f.key] = clean[f.key] === '' || clean[f.key] == null ? null : Number(clean[f.key]);
    });
    let next;
    if (modal.i != null) next = items.map((x, i) => i === modal.i ? { ...x, ...clean } : x);
    else next = [{ id: Date.now(), ...clean }, ...items];
    await persist(next);
    setSaving(false); setModal(null);
  };
  const del = async (i) => {
    if (!window.confirm('Hapus item ini?')) return;
    await persist(items.filter((_, j) => j !== i));
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, gap: 12, flexWrap: 'wrap' }}>
        <p style={{ color: 'var(--muted)', fontSize: 13.5, margin: 0 }}>Kelola {schema.title.toLowerCase()} yang tampil di situs.</p>
        <DBtn variant="orange" onClick={openAdd}>+ Tambah {schema.singular}</DBtn>
      </div>

      {loading ? <DCard><div style={{ padding: 30, textAlign: 'center', color: 'var(--muted)' }}>Memuat…</div></DCard>
      : items.length === 0 ? <DCard><div style={{ padding: 40, textAlign: 'center', color: 'var(--muted)' }}>Belum ada {schema.title.toLowerCase()}.</div></DCard>
      : <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 14 }}>
          {items.map((it, i) => {
            const img = it.cover_url || it.img_url || it.photo_url;
            return (
              <DCard key={it.id || i} pad="0" style={{ overflow: 'hidden' }}>
                <div style={{ height: 110, background: it.color || 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden' }}>
                  {img ? <img src={img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <GlyphMark name={KIND_GLYPH[kind] || 'scroll'} size={38} />}
                </div>
                <div style={{ padding: '14px 16px' }}>
                  <div style={{ fontWeight: 800, color: 'var(--ink-deep)', fontSize: 14.5, marginBottom: 3 }}>{it[primaryKey]}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.desc || it.text || it.title || it.role || it.author || it.schedule || ''}</div>
                  <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
                    <DBtn size="sm" onClick={() => openEdit(it, i)} style={{ flex: 1 }}>Edit</DBtn>
                    <DBtn size="sm" variant="danger" onClick={() => del(i)}>Hapus</DBtn>
                  </div>
                </div>
              </DCard>
            );
          })}
        </div>}

      <Modal open={!!modal} onClose={() => setModal(null)} title={modal && modal.i != null ? `Edit ${schema.singular}` : `Tambah ${schema.singular}`} width="560px">
        {modal && schema.fields.map(f => {
          const val = form[f.key];
          if (f.type === 'image') return <ImageUpload key={f.key} label={f.label} value={val} onChange={v => setForm(s => ({ ...s, [f.key]: v }))} ratio={kind === 'buku' || kind === 'teacher' ? '3/4' : '16/9'} />;
          if (f.type === 'textarea') return <DField key={f.key} label={f.label}><textarea value={val || ''} onChange={e => setForm(s => ({ ...s, [f.key]: e.target.value }))} rows="3" style={{ ...dInp, resize: 'vertical' }} /></DField>;
          if (f.type === 'list') return <DField key={f.key} label={f.label}><input value={Array.isArray(val) ? val.join(', ') : (val || '')} onChange={e => setForm(s => ({ ...s, [f.key]: e.target.value.split(',').map(x => x.trim()).filter(Boolean) }))} style={dInp} /></DField>;
          if (f.type === 'number') return <DField key={f.key} label={f.label}><input type="number" value={val ?? ''} onChange={e => setForm(s => ({ ...s, [f.key]: e.target.value }))} style={dInp} /></DField>;
          if (f.type === 'select') return <DField key={f.key} label={f.label}><select value={val || ''} onChange={e => setForm(s => ({ ...s, [f.key]: e.target.value }))} style={dInp}>{(f.options || []).map(o => <option key={o.value} value={o.value}>{o.label}</option>)}</select></DField>;
          if (f.type === 'toggle') return <DField key={f.key} label={f.label}><label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 14, color: 'var(--ink-deep)' }}><input type="checkbox" checked={!!val} onChange={e => setForm(s => ({ ...s, [f.key]: e.target.checked }))} style={{ width: 18, height: 18, accentColor: 'var(--sage)' }} />{val ? 'Ya, tampilkan' : 'Tidak'}</label></DField>;
          return <DField key={f.key} label={f.label}><input value={val || ''} onChange={e => setForm(s => ({ ...s, [f.key]: e.target.value }))} style={dInp} /></DField>;
        })}
        <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
          <DBtn variant="orange" size="lg" onClick={save} disabled={saving || !form[primaryKey]} style={{ flex: 1 }}>{saving ? 'Menyimpan…' : 'Simpan'}</DBtn>
          <DBtn size="lg" onClick={() => setModal(null)}>Batal</DBtn>
        </div>
      </Modal>
    </div>
  );
}

/* ── Donasi: kelola campaign ── */
function DonasiModule({ toast }) {
  const [camps, setCamps] = useState([]);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState(null);
  const [form, setForm] = useState({});
  const [saving, setSaving] = useState(false);

  const load = () => { setLoading(true); api.get('donations.php?action=list_campaigns').then(r => { if (r.ok && r.campaigns) setCamps(r.campaigns); }).finally(() => setLoading(false)); };
  useEffect(load, []);

  const openAdd = () => { setForm({ title: '', description: '', target: 10000000, collected: 0, urgent: 0, status: 'aktif', image_url: '' }); setModal({}); };
  const openEdit = (c) => { setForm({ ...c }); setModal({ id: c.id }); };

  const save = async () => {
    if (!form.title) return;
    setSaving(true);
    const action = modal.id ? 'update_campaign' : 'create_campaign';
    const r = await api.post('donations.php?action=' + action, modal.id ? { ...form, id: modal.id } : form);
    // mock belum punya endpoint ini → fallback: simpan via list lokal
    if (r.ok) { toast('Tersimpan'); setModal(null); load(); }
    else {
      // fallback lokal supaya tetap terasa di preview
      setCamps(p => modal.id ? p.map(c => c.id === modal.id ? { ...c, ...form } : c) : [{ ...form, id: Date.now(), donor_count: 0 }, ...p]);
      toast('Tersimpan'); setModal(null);
    }
    setSaving(false);
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, gap: 12, flexWrap: 'wrap' }}>
        <p style={{ color: 'var(--muted)', fontSize: 13.5, margin: 0 }}>Kelola program donasi & pantau perolehan.</p>
        <DBtn variant="orange" onClick={openAdd}>+ Program Donasi</DBtn>
      </div>
      {loading ? <DCard><div style={{ padding: 30, textAlign: 'center', color: 'var(--muted)' }}>Memuat…</div></DCard>
      : <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
          {camps.map(c => {
            const pct = c.target ? Math.min(100, Math.round((c.collected / c.target) * 100)) : 0;
            return (
              <DCard key={c.id} pad="18px">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8, marginBottom: 10 }}>
                  <div style={{ fontWeight: 800, color: 'var(--ink-deep)', fontSize: 15, lineHeight: 1.3 }}>{c.title}</div>
                  {c.urgent ? <Pill color="red">Mendesak</Pill> : <Pill color={c.status === 'selesai' ? 'green' : 'blue'}>{c.status === 'selesai' ? 'Selesai' : 'Aktif'}</Pill>}
                </div>
                <div style={{ height: 7, borderRadius: 999, background: 'var(--bg2)', overflow: 'hidden', marginBottom: 7 }}>
                  <div style={{ width: pct + '%', height: '100%', background: 'var(--orange)' }} />
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 14 }}>
                  <span style={{ fontWeight: 800, color: 'var(--ink-deep)' }}>{fmtRp(c.collected)}</span>
                  <span style={{ color: 'var(--muted)' }}>{pct}% dari {fmtRp(c.target)}</span>
                </div>
                <DBtn size="sm" onClick={() => openEdit(c)} style={{ width: '100%' }}>Edit Program</DBtn>
              </DCard>
            );
          })}
        </div>}

      <Modal open={!!modal} onClose={() => setModal(null)} title={modal && modal.id ? 'Edit Program Donasi' : 'Program Donasi Baru'}>
        {modal && (
          <>
            <ImageUpload label="Gambar Program" value={form.image_url} onChange={v => setForm(f => ({ ...f, image_url: v }))} />
            <DField label="Judul Program *"><input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} style={dInp} /></DField>
            <DField label="Deskripsi"><textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} rows="3" style={{ ...dInp, resize: 'vertical' }} /></DField>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <DField label="Target (Rp)"><input type="number" value={form.target} onChange={e => setForm(f => ({ ...f, target: Number(e.target.value) }))} style={dInp} /></DField>
              <DField label="Terkumpul (Rp)"><input type="number" value={form.collected} onChange={e => setForm(f => ({ ...f, collected: Number(e.target.value) }))} style={dInp} /></DField>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <DField label="Status"><select value={form.status} onChange={e => setForm(f => ({ ...f, status: e.target.value }))} style={dInp}><option value="aktif">Aktif</option><option value="selesai">Selesai</option></select></DField>
              <DField label="Mendesak?"><select value={form.urgent ? '1' : '0'} onChange={e => setForm(f => ({ ...f, urgent: e.target.value === '1' ? 1 : 0 }))} style={dInp}><option value="0">Tidak</option><option value="1">Ya</option></select></DField>
            </div>
            <DField label="Jadikan Banner Beranda?" hint="Tampil di slideshow atas beranda">
              <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 14, color: 'var(--ink-deep)' }}>
                <input type="checkbox" checked={!!form.banner_home} onChange={e => setForm(f => ({ ...f, banner_home: e.target.checked }))} style={{ width: 18, height: 18, accentColor: 'var(--sage)' }} />
                {form.banner_home ? 'Ya, tampilkan di banner' : 'Tidak'}
              </label>
            </DField>
            <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
              <DBtn variant="orange" size="lg" onClick={save} disabled={saving || !form.title} style={{ flex: 1 }}>{saving ? 'Menyimpan…' : 'Simpan'}</DBtn>
              <DBtn size="lg" onClick={() => setModal(null)}>Batal</DBtn>
            </div>
          </>
        )}
      </Modal>

      <DonasiSettingsCard toast={toast} />
    </div>
  );
}

/* ── Kartu pengaturan donasi: QRIS, WA konfirmasi, rekening ── */
function DonasiSettingsCard({ toast }) {
  const [s, setS] = useState({ qris_url: '', donasi_wa_konfirmasi: '' });
  const [rek, setRek] = useState([]);
  const [saving, setSaving] = useState(false);
  useEffect(() => {
    api.get('donations.php?action=get_settings').then(r => { if (r.ok && r.settings) setS(v => ({ ...v, ...r.settings })); });
    api.get('donations.php?action=list_rekening').then(r => { if (r.ok && r.rekening) setRek(r.rekening); });
  }, []);
  const save = async () => { setSaving(true); const r = await api.post('donations.php?action=save_settings', s); if (r.ok) toast('Pengaturan donasi disimpan'); setSaving(false); };
  return (
    <div style={{ marginTop: 28, maxWidth: 560 }}>
      <div style={{ fontWeight: 800, color: 'var(--ink-deep)', fontSize: 15, marginBottom: 12 }}>Metode Pembayaran Donasi</div>
      <DCard>
        <ImageUpload label="Gambar QRIS (donatur scan dengan e-wallet / m-banking apa pun)" value={s.qris_url} onChange={v => setS(f => ({ ...f, qris_url: v }))} ratio="1/1" />
        <DField label="Nomor WhatsApp Konfirmasi Donasi (62…)"><input value={s.donasi_wa_konfirmasi || ''} onChange={e => setS(f => ({ ...f, donasi_wa_konfirmasi: e.target.value }))} style={dInp} placeholder="628xxxxxxxxxx" /></DField>
        <DBtn variant="orange" size="lg" onClick={save} disabled={saving}>{saving ? 'Menyimpan…' : 'Simpan Metode Pembayaran'}</DBtn>
        <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--border-soft)' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink-deep)', marginBottom: 8 }}>Rekening Terdaftar ({rek.length})</div>
          {rek.length === 0
            ? <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>Belum ada rekening. Tambahkan lewat panel rekening (kelola-donasi) di server.</div>
            : rek.map((r, i) => <div key={i} style={{ fontSize: 13, color: 'var(--ink)', padding: '4px 0' }}>• <strong>{r.bank}</strong> {r.nomor || r.number} — a.n. {r.atas_nama || r.name}</div>)}
          <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 8 }}>Pilihan "Metode" di form donasi otomatis mengikuti rekening ini + QRIS (bila gambar diisi).</div>
        </div>
      </DCard>
    </div>
  );
}

/* ── Pengaturan situs: info, profil (Tentang), kontak ── */
function SettingsModule({ toast }) {
  const [form, setForm] = useState({
    site_name: "Markaz Qurrota A'yun", tagline: '', tahun: '2015',
    profil: '', profil2: '', stat_santri: '500+', stat_pengajar: '25+', stat_program: '8',
    phone: '0812-3456-7890', wa: '628123456789', email: 'info@qurrotaayun.com',
    address: '', jam: 'Senin–Sabtu, 08.00–20.00 WIB',
    ig: '', yt: '', fb: '', tiktok: '', maps_embed: '',
  });
  const [saving, setSaving] = useState(false);
  useEffect(() => { api.get('content.php?action=get_section&section=settings').then(r => { if (r.ok && r.data) setForm(f => ({ ...f, ...r.data })); }); }, []);
  const save = async () => { setSaving(true); const r = await api.post('content.php?action=save', { section: 'settings', data: form }); if (r.ok) toast('Pengaturan disimpan'); setSaving(false); };
  const F = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  return (
    <div style={{ maxWidth: 640, display: 'grid', gap: 18 }}>
      <DCard>
        <div style={{ fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 16, fontSize: 15 }}>Informasi Situs</div>
        <DField label="Nama Situs"><input value={form.site_name} onChange={F('site_name')} style={dInp} /></DField>
        <DField label="Tagline / Slogan"><input value={form.tagline} onChange={F('tagline')} style={dInp} /></DField>
        <DField label="Berdiri Sejak (tahun)"><input value={form.tahun} onChange={F('tahun')} style={dInp} /></DField>
      </DCard>

      <DCard>
        <div style={{ fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 16, fontSize: 15 }}>Halaman Tentang</div>
        <DField label="Profil — paragraf 1"><textarea value={form.profil} onChange={F('profil')} rows="3" style={{ ...dInp, resize: 'vertical' }} placeholder="Sejarah / visi lembaga…" /></DField>
        <DField label="Profil — paragraf 2"><textarea value={form.profil2} onChange={F('profil2')} rows="3" style={{ ...dInp, resize: 'vertical' }} /></DField>
        <DField label="Visi"><textarea value={form.visi || ''} onChange={F('visi')} rows="2" style={{ ...dInp, resize: 'vertical' }} placeholder="Visi lembaga…" /></DField>
        <DField label="Misi (satu poin per baris)"><textarea value={form.misi || ''} onChange={F('misi')} rows="4" style={{ ...dInp, resize: 'vertical' }} placeholder={"Membentuk generasi penghafal Al-Qur'an\nMengajarkan bahasa Arab…"} /></DField>
        <DField label="Nilai (satu per baris, format: Judul — penjelasan)"><textarea value={form.nilai || ''} onChange={F('nilai')} rows="4" style={{ ...dInp, resize: 'vertical' }} placeholder={"Ikhlas — meniatkan amal karena Allah\nAmanah — menjaga kepercayaan umat"} /></DField>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <DField label="Statistik: Santri"><input value={form.stat_santri} onChange={F('stat_santri')} style={dInp} /></DField>
          <DField label="Statistik: Pengajar"><input value={form.stat_pengajar} onChange={F('stat_pengajar')} style={dInp} /></DField>
          <DField label="Statistik: Program"><input value={form.stat_program} onChange={F('stat_program')} style={dInp} /></DField>
        </div>
        <ImageUpload label="Foto Tentang (opsional)" value={form.about_image} onChange={v => setForm(f => ({ ...f, about_image: v }))} />
      </DCard>

      <DCard>
        <div style={{ fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 16, fontSize: 15 }}>Sambutan Pimpinan (Mudir)</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <DField label="Nama Mudir"><input value={form.mudir_name || ''} onChange={F('mudir_name')} style={dInp} /></DField>
          <DField label="Jabatan"><input value={form.mudir_title || ''} onChange={F('mudir_title')} style={dInp} placeholder="Mudir / Pimpinan" /></DField>
        </div>
        <ImageUpload label="Foto Mudir" value={form.mudir_photo} onChange={v => setForm(f => ({ ...f, mudir_photo: v }))} ratio="1/1" />
        <DField label="Isi Sambutan"><textarea value={form.mudir_text || ''} onChange={F('mudir_text')} rows="4" style={{ ...dInp, resize: 'vertical' }} placeholder="Assalamu'alaikum… kata sambutan pimpinan…" /></DField>
      </DCard>

      <DCard>
        <div style={{ fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 16, fontSize: 15 }}>Kontak</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <DField label="Telepon (tampil)"><input value={form.phone} onChange={F('phone')} style={dInp} /></DField>
          <DField label="WhatsApp (62…)"><input value={form.wa} onChange={F('wa')} style={dInp} /></DField>
        </div>
        <DField label="Email"><input value={form.email} onChange={F('email')} style={dInp} /></DField>
        <DField label="Alamat lengkap"><textarea value={form.address} onChange={F('address')} rows="2" style={{ ...dInp, resize: 'vertical' }} /></DField>
        <DField label="Jam Operasional"><input value={form.jam} onChange={F('jam')} style={dInp} /></DField>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <DField label="Instagram (URL)"><input value={form.ig} onChange={F('ig')} style={dInp} placeholder="instagram.com/…" /></DField>
          <DField label="YouTube (URL)"><input value={form.yt} onChange={F('yt')} style={dInp} /></DField>
          <DField label="Facebook (URL)"><input value={form.fb} onChange={F('fb')} style={dInp} /></DField>
          <DField label="TikTok (URL)"><input value={form.tiktok} onChange={F('tiktok')} style={dInp} /></DField>
        </div>
        <DField label="Kode Sematan Peta (Google Maps → Bagikan → Sematkan peta)"><textarea value={form.maps_embed} onChange={F('maps_embed')} rows="2" style={{ ...dInp, resize: 'vertical', fontFamily: 'monospace', fontSize: 12 }} placeholder="<iframe …></iframe>" /></DField>
        <DField label="atau Link Google Maps (jika tak pakai sematan)"><input value={form.maps_link || ''} onChange={F('maps_link')} style={dInp} placeholder="https://maps.app.goo.gl/…" /></DField>
      </DCard>

      <DBtn variant="orange" size="lg" onClick={save} disabled={saving}>{saving ? 'Menyimpan…' : 'Simpan Semua Pengaturan'}</DBtn>
    </div>
  );
}

/* ── Header Halaman: edit banner tiap halaman (teks Arab, judul, deskripsi, foto) ── */
const PAGE_LIST = [
  ['articles', 'Artikel'], ['programs', 'Program'], ['teachers', 'Pengajar'],
  ['gallery', 'Fasilitas'], ['kegiatan', 'Kegiatan'], ['toko', 'Toko Buku'],
  ['donasi', 'Donasi'], ['register', 'Pendaftaran'], ['about', 'Tentang'], ['contact', 'Kontak'],
];
function PageHeadersModule({ toast }) {
  const [data, setData] = useState({});
  const [active, setActive] = useState('articles');
  const [saving, setSaving] = useState(false);
  useEffect(() => { api.get('content.php?action=get_section&section=page_headers').then(r => { if (r.ok && r.data) setData(r.data); }); }, []);
  const cur = data[active] || {};
  const upd = (k, v) => setData(d => ({ ...d, [active]: { ...d[active], [k]: v } }));
  const save = async () => { setSaving(true); const r = await api.post('content.php?action=save', { section: 'page_headers', data }); if (r.ok) toast('Header halaman disimpan'); setSaving(false); };
  return (
    <div style={{ maxWidth: 640 }}>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 18 }}>
        {PAGE_LIST.map(([k, label]) => (
          <button key={k} onClick={() => setActive(k)} style={{ padding: '7px 13px', borderRadius: 999, fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', border: `1.5px solid ${active === k ? 'var(--navy)' : 'var(--border)'}`, background: active === k ? 'var(--navy)' : 'var(--surface)', color: active === k ? '#fff' : 'var(--ink)' }}>{label}</button>
        ))}
      </div>
      <DCard>
        <div style={{ fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 4, fontSize: 15 }}>Banner Halaman: {PAGE_LIST.find(p => p[0] === active)[1]}</div>
        <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '0 0 16px' }}>Kosongkan untuk memakai teks bawaan. Tanpa foto, banner otomatis berhias ornamen brand.</p>
        <DField label="Teks Arab (kicker atas, opsional)"><input value={cur.arabic || ''} onChange={e => upd('arabic', e.target.value)} style={dInp} placeholder="mis. اقرأ وتعلّم" /></DField>
        <DField label="Kicker Latin (dipakai bila Arab kosong)"><input value={cur.kicker || ''} onChange={e => upd('kicker', e.target.value)} style={dInp} placeholder="mis. Kumpulan Artikel" /></DField>
        <DField label="Judul Banner"><input value={cur.title || ''} onChange={e => upd('title', e.target.value)} style={dInp} placeholder="Judul besar" /></DField>
        <DField label="Deskripsi"><textarea value={cur.sub || ''} onChange={e => upd('sub', e.target.value)} rows="2" style={{ ...dInp, resize: 'vertical' }} /></DField>
        <ImageUpload label="Foto Latar (opsional)" value={cur.image} onChange={v => upd('image', v)} />
        <DBtn variant="orange" size="lg" onClick={save} disabled={saving} style={{ marginTop: 6 }}>{saving ? 'Menyimpan…' : 'Simpan Header'}</DBtn>
      </DCard>
    </div>
  );
}

Object.assign(window, { ContentListModule, DonasiModule, SettingsModule, PageHeadersModule, KIND_SCHEMA });
