/* ── Beranda: fokus pada ARTIKEL (ramping, foto asli) ── */
function HomePage({ navigate, openArticle }) {
  const M = window.MQA || {};
  const [articles, setArticles] = useState(M.articles || []);
  const [cat, setCat] = useState('Semua');
  const [campaigns, setCampaigns] = useState([]);
  const [donStats, setDonStats] = useState(null);
  const [banners, setBanners] = useState([]);
  const [programs, setPrograms] = useState(M.programs || []);
  const [kegiatan, setKegiatan] = useState(M.kegiatan || []);
  const [buku, setBuku] = useState((M.buku || []));

  useEffect(() => {
    api.get('articles.php?action=list').then(r => { if (r.ok && Array.isArray(r.articles) && r.articles.length) setArticles(r.articles); });
    api.get('donations.php?action=list_campaigns').then(r => { if (r.ok && r.campaigns) setCampaigns(r.campaigns); });
    api.get('donations.php?action=public_stats').then(r => { if (r.ok) setDonStats(r); });
    api.get('content.php?action=get_section&section=banners').then(r => { if (r.ok && r.data && Array.isArray(r.data.items)) setBanners(r.data.items); });
    api.get('content.php?action=get_section&section=programs').then(r => { if (r.ok && r.data && Array.isArray(r.data.items) && r.data.items.length) setPrograms(r.data.items); });
    api.get('content.php?action=get_section&section=kegiatan').then(r => { if (r.ok && r.data && Array.isArray(r.data.items) && r.data.items.length) setKegiatan(r.data.items); });
    api.get('content.php?action=get_section&section=buku').then(r => { if (r.ok && r.data && Array.isArray(r.data.items) && r.data.items.length) setBuku(r.data.items); });
  }, []);

  const cats = ['Semua', ...new Set([...Object.keys(window.CATS), ...articles.map(a => a.category).filter(Boolean)])];
  const featured = articles[0];
  const recent = articles.slice(0, 4);
  const filtered = cat === 'Semua' ? articles : articles.filter(a => a.category === cat);
  // Paling banyak dibaca (berdasar jumlah views, fallback urutan asli)
  const popular = [...articles].sort((a, b) => (b.views || 0) - (a.views || 0)).slice(0, 5);
  // Program donasi aktif untuk ditonjolkan di beranda (mini-dashboard)
  const activeCampaigns = campaigns
    .filter(c => !(c.urgensi === 'selesai' || c.status === 'arsip' || c.status === 'selesai'))
    .slice(0, 3);

  // ── Slide banner: pakai banner dari dashboard bila ada, jika tidak auto dari konten ──
  const featuredPrograms = programs.filter(p => p.featured).slice(0, 3);
  const featuredKegiatan = kegiatan.filter(k => k.featured).slice(0, 3);
  const prog = (M.programs || [])[0];
  const keg = (M.kegiatan || [])[0];

  const SCRIM = { '#1F6B47': ['rgba(15,61,39,.86)', 'rgba(15,61,39,.35)'], '#1B2F6E': ['rgba(14,26,69,.86)', 'rgba(14,26,69,.4)'], '#C26F12': ['rgba(150,90,15,.85)', 'rgba(150,90,15,.4)'], '#8B5A2B': ['rgba(90,56,24,.84)', 'rgba(90,56,24,.38)'] };
  let slides = [];
  // 1) Banner kustom dari menu "Banner Beranda"
  banners.forEach(b => { const sc = SCRIM[b.accent] || SCRIM['#1B2F6E']; slides.push({ tag: b.tag || '', image: b.image_url, overlay: sc[0], overlay2: sc[1], accent: b.accent || '#1B2F6E', title: b.title, subtitle: b.subtitle, cta: b.cta_label || 'Selengkapnya', onClick: () => navigate(b.cta_target || 'articles') }); });
  // 2) Item yang ditandai "Jadikan Banner" (banner_home) dari konten
  articles.filter(a => a.banner_home).forEach(a => { const na = normArticle(a); slides.push({ tag: 'Artikel', image: a.cover_url, overlay: SCRIM['#1F6B47'][0], overlay2: SCRIM['#1F6B47'][1], accent: '#1F6B47', title: a.title, subtitle: a.excerpt, cta: 'Baca Selengkapnya', onClick: () => openArticle(a) }); });
  programs.filter(p => p.banner_home).forEach(p => slides.push({ tag: 'Program', image: p.banner_url || 'img/grup-besar.jpg', overlay: SCRIM['#1B2F6E'][0], overlay2: SCRIM['#1B2F6E'][1], accent: '#1B2F6E', title: p.name, subtitle: p.desc, cta: 'Daftar Sekarang', onClick: () => navigate('register') }));
  kegiatan.filter(k => k.banner_home).forEach(k => slides.push({ tag: 'Kegiatan', image: k.img_url || 'img/grup-santri.jpg', overlay: SCRIM['#8B5A2B'][0], overlay2: SCRIM['#8B5A2B'][1], accent: '#8B5A2B', title: k.title, subtitle: k.desc, cta: 'Lihat Kegiatan', onClick: () => navigate('kegiatan') }));
  campaigns.filter(c => c.banner_home).forEach(c => slides.push({ tag: 'Donasi', image: c.cover_url || c.image_url || 'img/gedung.jpg', overlay: SCRIM['#C26F12'][0], overlay2: SCRIM['#C26F12'][1], accent: '#C26F12', title: c.title, subtitle: c.deskripsi || c.description, cta: 'Donasi Sekarang', onClick: () => { window.__openDonasiForm = c; navigate('donasi'); } }));
  buku.filter(b => b.banner_home).forEach(b => slides.push({ tag: 'Toko Buku', image: b.cover_url, overlay: SCRIM['#1B2F6E'][0], overlay2: SCRIM['#1B2F6E'][1], accent: '#1B2F6E', title: b.title, subtitle: b.desc, cta: 'Lihat Buku', onClick: () => { window.__openBuku = b; navigate('toko'); } }));

  // 3) Fallback otomatis bila admin belum menandai apa pun
  if (slides.length === 0) {
    if (featured) slides.push({ tag: 'Artikel Pilihan', image: featured.cover_url, overlay: 'rgba(15,61,39,.86)', overlay2: 'rgba(15,61,39,.35)', accent: '#1F6B47', title: featured.title, subtitle: featured.excerpt, cta: 'Baca Selengkapnya', onClick: () => openArticle(featured) });
    if (prog) slides.push({ tag: 'Program', image: 'img/grup-besar.jpg', overlay: 'rgba(14,26,69,.86)', overlay2: 'rgba(14,26,69,.4)', accent: '#1B2F6E', title: prog.name, subtitle: prog.desc, cta: 'Daftar Sekarang', onClick: () => navigate('register') });
    if (keg) slides.push({ tag: 'Kegiatan', image: 'img/grup-santri.jpg', overlay: 'rgba(90,56,24,.84)', overlay2: 'rgba(90,56,24,.38)', accent: '#8B5A2B', title: keg.title, subtitle: keg.desc, cta: 'Lihat Kegiatan', onClick: () => navigate('kegiatan') });
    slides.push({ tag: 'Donasi', image: 'img/gedung.jpg', overlay: 'rgba(150,90,15,.85)', overlay2: 'rgba(150,90,15,.4)', accent: '#C26F12', title: 'Wujudkan Amal Jariyah Bersama Kami', subtitle: 'Dukung pendidikan santri yatim & dhuafa melalui sedekah dan wakaf Anda.', cta: 'Donasi Sekarang', onClick: () => { window.__openDonasiForm = true; navigate('donasi'); } });
  }

  return (
    <div style={{ background: 'var(--bg)', paddingBottom: 50 }}>
      {/* ── BANNER SLIDESHOW (hero tunggal) ── */}
      <section className="container" style={{ paddingTop: 22 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20, flexWrap: 'wrap' }}>
          <div className="hero-v10-arabic" style={{ fontSize: 21, margin: 0, lineHeight: 1.9, whiteSpace: 'nowrap' }}>مَرْكَزُ قُرَّةِ أَعْيُن</div>
          <span style={{ color: 'var(--border)' }}>·</span>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--muted)' }}>Rumah Ilmu &amp; Kajian Al-Qur'an</div>
        </div>
        <HeroSlider slides={slides} />
      </section>

      {/* ── ARTIKEL TERBARU (strip ringkas) ── */}
      <section className="container" style={{ paddingTop: 40, paddingBottom: 8 }}>
        <div className="sec-label">Terbaru</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 18 }}>
          {recent.map(a => <ArticleCard key={a.id} a={a} onClick={() => openArticle(a)} />)}
        </div>
      </section>

      {/* ── PALING BANYAK DIBACA ── */}
      <section className="container" style={{ paddingTop: 40, paddingBottom: 8 }}>
        <div className="home-popular-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 30, alignItems: 'start' }}>
          <div>
            <div className="sec-label">Paling Banyak Dibaca</div>
            <h2 className="sec-title" style={{ margin: '0 0 8px' }}>Artikel Populer</h2>
            <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.6, margin: 0 }}>Bacaan yang paling sering dibuka oleh pengunjung.</p>
          </div>
          <ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>
            {popular.map((a, i) => {
              const na = normArticle(a);
              const sc = catStyle(a.category);
              return (
                <li key={a.id}>
                  <button onClick={() => openArticle(a)} style={{ width: '100%', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 14, padding: '12px 10px', background: 'none', border: 'none', borderBottom: i < popular.length - 1 ? '1px solid var(--border-soft)' : 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
                    <span style={{ fontFamily: 'var(--font-d)', fontSize: 28, fontWeight: 900, lineHeight: 1, color: i === 0 ? 'var(--orange)' : 'var(--border)', width: 26, flexShrink: 0, textAlign: 'center' }}>{i + 1}</span>
                    <span style={{ width: 64, height: 64, borderRadius: 12, flexShrink: 0, overflow: 'hidden', background: sc.color, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
                      {na.cover_url
                        ? <img src={na.cover_url} alt="" loading="lazy" decoding="async" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                        : <GlyphMark name={CAT_GLYPH[a.category] || 'scroll'} size={30} />}
                    </span>
                    <span style={{ minWidth: 0, flex: 1 }}>
                      <span style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 4 }}>
                        <span style={{ width: 7, height: 7, borderRadius: '50%', background: sc.color, flexShrink: 0 }} />
                        <span style={{ fontSize: 11.5, fontWeight: 700, color: sc.color }}>{a.category}</span>
                      </span>
                      <span style={{ display: 'block', fontFamily: 'var(--font-d)', fontSize: 15.5, fontWeight: 800, color: 'var(--ink-deep)', lineHeight: 1.3, textWrap: 'pretty', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{a.title}</span>
                      <span style={{ display: 'block', fontSize: 11.5, color: 'var(--muted)', marginTop: 4 }}>{(a.views || 0).toLocaleString('id-ID')}× dibaca · {na.readTime}</span>
                    </span>
                  </button>
                </li>
              );
            })}
          </ol>
        </div>
      </section>

      {/* ── KUMPULAN ARTIKEL (konten utama, dengan filter) ── */}
      <section className="container" style={{ paddingTop: 44, paddingBottom: 50 }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: 22 }}>
          <div>
            <div className="sec-label">Kumpulan Artikel</div>
            <h2 className="sec-title" style={{ margin: 0 }}>Jelajahi Berdasarkan Topik</h2>
          </div>
          <div className="cat-pills" style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {cats.map(c => {
              const active = c === cat;
              const s = c === 'Semua' ? { color: 'var(--ink-deep)' } : catStyle(c);
              return (
                <button key={c} onClick={() => setCat(c)} style={{
                  padding: '8px 15px', borderRadius: 999, fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
                  border: `1.5px solid ${active ? s.color : 'var(--border)'}`,
                  background: active ? s.color : 'var(--surface)', color: active ? '#fff' : 'var(--ink)', transition: 'all .15s',
                }}>{c}</button>
              );
            })}
          </div>
        </div>

        <div className="art-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 20 }}>
          {filtered.map(a => <ArticleCard key={a.id} a={a} onClick={() => openArticle(a)} />)}
        </div>
        {filtered.length === 0 && <div style={{ padding: 50, textAlign: 'center', color: 'var(--muted)' }}>Belum ada artikel di kategori ini.</div>}

        <div style={{ textAlign: 'center', marginTop: 34 }}>
          <button className="btn-hero-secondary" onClick={() => navigate('articles')}>Lihat Semua Artikel →</button>
        </div>
      </section>

      {/* ── PROGRAM DONASI (mini-dashboard) ── */}
      {activeCampaigns.length > 0 && (
        <section className="container" style={{ paddingTop: 44, paddingBottom: 8 }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: 20 }}>
            <div>
              <div className="sec-label">Program Donasi</div>
              <h2 className="sec-title" style={{ margin: 0 }}>Salurkan Amal Jariyah</h2>
            </div>
            {donStats && (
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontFamily: 'var(--font-d)', fontSize: 22, fontWeight: 900, color: 'var(--sage)' }}>{fmtRpShort(donStats.total_masuk || 0)}</div>
                <div style={{ fontSize: 12, color: 'var(--muted)' }}>terkumpul · {donStats.total_donatur || 0} donatur</div>
              </div>
            )}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 18 }}>
            {activeCampaigns.map(c => {
              const collected = c.terkumpul ?? c.collected ?? 0;
              const target = c.target ?? 0;
              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);
              return (
                <div key={c.id} className="fade-up" onClick={() => navigate('donasi')} style={{ cursor: 'pointer', background: 'var(--surface)', borderRadius: 16, 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="" loading="lazy" decoding="async" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} /> : <span style={{ fontSize: 46 }}>🤲</span>}
                    {urgent ? <span style={{ position: 'absolute', top: 12, left: 12, padding: '4px 11px', borderRadius: 999, background: '#DC2626', color: '#fff', fontSize: 11, fontWeight: 800 }}>MENDESAK</span> : null}
                  </div>
                  <div style={{ padding: '16px 18px 18px', display: 'flex', flexDirection: 'column', flex: 1 }}>
                    <h3 style={{ fontFamily: 'var(--font-d)', fontSize: 17, fontWeight: 800, color: 'var(--ink-deep)', margin: '0 0 12px', lineHeight: 1.3, textWrap: 'pretty' }}>{c.title}</h3>
                    <div style={{ marginTop: 'auto' }}>
                      <div style={{ height: 7, borderRadius: 999, background: 'var(--bg2)', overflow: 'hidden', marginBottom: 7 }}>
                        <div style={{ width: pct + '%', height: '100%', background: 'var(--orange)', borderRadius: 999 }} />
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                        <span style={{ fontWeight: 800, color: 'var(--ink-deep)' }}>{fmtRp(collected)}</span>
                        <span style={{ color: 'var(--muted)' }}>{pct}%</span>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ textAlign: 'center', marginTop: 26 }}>
            <button className="btn-donasi-cta" onClick={() => navigate('donasi')}>{IC.heart} Lihat Semua Program Donasi</button>
          </div>
        </section>
      )}

      {/* ── PROGRAM UNGGULAN ── */}
      {featuredPrograms.length > 0 && (
        <section className="container" style={{ paddingTop: 44, paddingBottom: 8 }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: 20 }}>
            <div>
              <div className="sec-label">Program Unggulan</div>
              <h2 className="sec-title" style={{ margin: 0 }}>Belajar Bersama Kami</h2>
            </div>
            <button className="btn-hero-secondary" onClick={() => navigate('programs')}>Semua Program →</button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 18 }}>
            {featuredPrograms.map(p => (
              <div key={p.id} className="fade-up" onClick={() => navigate('programs')} style={{ cursor: 'pointer', background: 'var(--surface)', borderRadius: 16, padding: '22px 22px', border: '1px solid var(--border-soft)', boxShadow: 'var(--shadow-warm-sm, 0 4px 14px rgba(120,80,30,.06))' }}>
                <div style={{ fontSize: 34, marginBottom: 12 }}>{p.icon || '📗'}</div>
                <h3 style={{ fontFamily: 'var(--font-d)', fontSize: 18, fontWeight: 800, color: 'var(--ink-deep)', margin: '0 0 6px', textWrap: 'pretty' }}>{p.name}</h3>
                <p style={{ fontSize: 13.5, lineHeight: 1.55, color: 'var(--muted)', margin: 0, display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.desc}</p>
                {p.schedule && <div style={{ marginTop: 12, fontSize: 12.5, fontWeight: 700, color: 'var(--sage)' }}>🕐 {p.schedule}</div>}
              </div>
            ))}
          </div>
        </section>
      )}

      {/* ── KEGIATAN UNGGULAN ── */}
      {featuredKegiatan.length > 0 && (
        <section className="container" style={{ paddingTop: 44, paddingBottom: 8 }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: 20 }}>
            <div>
              <div className="sec-label">Kegiatan Unggulan</div>
              <h2 className="sec-title" style={{ margin: 0 }}>Agenda &amp; Kajian</h2>
            </div>
            <button className="btn-hero-secondary" onClick={() => navigate('kegiatan')}>Semua Kegiatan →</button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 18 }}>
            {featuredKegiatan.map(k => (
              <div key={k.id} className="fade-up" onClick={() => navigate('kegiatan')} style={{ cursor: 'pointer', background: 'var(--surface)', borderRadius: 16, 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(--brand-navy), var(--brand-deep))', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
                  {k.img_url ? <img src={k.img_url} alt="" loading="lazy" decoding="async" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} /> : <GlyphMark name='calendar' size={44} />}
                  {k.date && <span style={{ position: 'absolute', top: 12, left: 12, padding: '4px 11px', borderRadius: 999, background: 'rgba(255,255,255,.92)', color: 'var(--navy)', fontSize: 11.5, fontWeight: 800 }}>{k.date}</span>}
                </div>
                <div style={{ padding: '16px 18px 18px' }}>
                  <h3 style={{ fontFamily: 'var(--font-d)', fontSize: 17, fontWeight: 800, color: 'var(--ink-deep)', margin: '0 0 6px', lineHeight: 1.3, textWrap: 'pretty' }}>{k.title}</h3>
                  <p style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--muted)', margin: 0, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{k.desc}</p>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}

window.HomePage = HomePage;
