/* Slideshow artikel unggulan (beberapa, berputar otomatis) */
function FeaturedSlider({ items, openArticle }) {
  const [i, setI] = useState(0);
  const n = items.length;
  useEffect(() => {
    if (n <= 1) return;
    const t = setInterval(() => setI(p => (p + 1) % n), 6000);
    return () => clearInterval(t);
  }, [n]);
  if (!n) return null;
  const go = (d) => setI(p => (p + d + n) % n);
  const sw = React.useRef(null);
  const onTouchStart = (e) => { sw.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => { if (sw.current == null) return; const dx = e.changedTouches[0].clientX - sw.current; if (Math.abs(dx) > 45) go(dx < 0 ? 1 : -1); sw.current = null; };
  return (
    <div style={{ position: 'relative', minWidth: 0, maxWidth: '100%' }}>
      <div style={{ overflow: 'hidden', borderRadius: 20, touchAction: 'pan-y' }} onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
        <div style={{ display: 'flex', transform: `translateX(-${i * 100}%)`, transition: 'transform .55s cubic-bezier(.5,.05,.1,1)' }}>
          {items.map(a => (
            <div key={a.id} style={{ flex: '0 0 100%', minWidth: '100%' }}>
              <ArticleCard a={a} featured onClick={() => openArticle(a)} />
            </div>
          ))}
        </div>
      </div>
      {n > 1 && <>
        <button onClick={() => go(-1)} aria-label="Sebelumnya" style={{ position: 'absolute', left: 12, top: '38%', width: 38, height: 38, borderRadius: '50%', border: 'none', background: 'rgba(255,255,255,.92)', color: 'var(--ink-deep)', cursor: 'pointer', fontSize: 18, fontWeight: 700, boxShadow: '0 3px 10px rgba(0,0,0,.2)' }}>‹</button>
        <button onClick={() => go(1)} aria-label="Berikutnya" style={{ position: 'absolute', right: 12, top: '38%', width: 38, height: 38, borderRadius: '50%', border: 'none', background: 'rgba(255,255,255,.92)', color: 'var(--ink-deep)', cursor: 'pointer', fontSize: 18, fontWeight: 700, boxShadow: '0 3px 10px rgba(0,0,0,.2)' }}>›</button>
        <div style={{ display: 'flex', gap: 7, justifyContent: 'center', marginTop: 12 }}>
          {items.map((_, idx) => <button key={idx} onClick={() => setI(idx)} aria-label={`Slide ${idx + 1}`} style={{ width: idx === i ? 24 : 8, height: 8, borderRadius: 999, border: 'none', background: idx === i ? 'var(--sage)' : 'var(--border)', cursor: 'pointer', transition: 'all .3s', padding: 0 }} />)}
        </div>
      </>}
    </div>
  );
}

/* Baris artikel kompak (daftar "Semua Artikel") */
function ArticleRow({ a, onClick }) {
  const na = normArticle(a);
  const s = catStyle(a.category);
  return (
    <button onClick={onClick} className="art-row" style={{ display: 'flex', gap: 14, width: '100%', textAlign: 'left', background: 'var(--surface)', border: '1px solid var(--border-soft)', borderRadius: 12, padding: 10, cursor: 'pointer', fontFamily: 'inherit', alignItems: 'center' }}>
      <span style={{ flexShrink: 0, width: 84, height: 64, borderRadius: 9, overflow: 'hidden', background: s.color, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
        {na.cover_url ? <img src={na.cover_url} alt="" loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <GlyphMark name={CAT_GLYPH[a.category] || 'scroll'} size={26} />}
      </span>
      <span style={{ minWidth: 0, flex: 1 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 4 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: s.color, flexShrink: 0 }} />
          <span style={{ fontSize: 11, fontWeight: 700, color: s.color }}>{a.category}</span>
          <span style={{ fontSize: 11, color: 'var(--muted)' }}>· {na.date} · {na.readTime}</span>
        </span>
        <span style={{ display: 'block', fontFamily: 'var(--font-d)', fontSize: 15.5, fontWeight: 800, color: 'var(--ink-deep)', lineHeight: 1.3, textWrap: 'pretty', marginBottom: 3, display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{a.title}</span>
        <span style={{ display: 'block', fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.45, display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{a.excerpt}</span>
      </span>
    </button>
  );
}

/* ── Halaman Daftar Artikel — discovery + daftar kompak ── */
function ArticlesPage({ navigate, openArticle }) {
  const M = window.MQA || {};
  const [articles, setArticles] = useState(M.articles || []);
  const [loading, setLoading] = useState(true);
  const [cat, setCat] = useState('Semua');
  const [q, setQ] = useState('');
  const [sort, setSort] = useState('terbaru');
  const [limit, setLimit] = useState(12);

  useEffect(() => {
    api.get('articles.php?action=list').then(r => { if (r.ok && Array.isArray(r.articles) && r.articles.length) setArticles(r.articles); }).finally(() => setLoading(false));
  }, []);

  const present = [...new Set(articles.map(a => a.category).filter(Boolean))];
  const base = ['Tahfidz', 'Bahasa Arab', 'Fiqih', 'Akhlaq'];
  const cats = ['Semua', ...base, ...present.filter(c => !base.includes(c))];
  const view = (cat === 'Semua' && !q.trim()) ? 'discovery' : 'filtered';

  // data untuk discovery
  const byDate = [...articles].sort((a, b) => new Date(b.published_at || b.date || 0) - new Date(a.published_at || a.date || 0));
  const byViews = [...articles].sort((a, b) => (b.views || b.view_count || 0) - (a.views || a.view_count || 0));
  const featured = articles.filter(a => a.featured);
  const editorPick = featured.length ? featured.slice(0, 6) : byViews.slice(0, 3);
  const latest = byDate.slice(0, 6);
  const popular = byViews.slice(0, 5);
  const catGroups = present.length ? present : base;

  // data untuk filtered (kategori/cari)
  let list = cat === 'Semua' ? articles : articles.filter(a => a.category === cat);
  if (q.trim()) { const t = q.toLowerCase(); list = list.filter(a => ((a.title || '') + (a.excerpt || '') + (a.category || '') + (a.body || '')).toLowerCase().includes(t)); }
  list = [...list].sort((a, b) => sort === 'populer'
    ? (b.views || b.view_count || 0) - (a.views || a.view_count || 0)
    : new Date(b.published_at || b.date || 0) - new Date(a.published_at || a.date || 0));
  const shown = list.slice(0, limit);

  const SectionTitle = ({ label, title, action }) => (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: 16 }}>
      <div>
        <div className="sec-label">{label}</div>
        <h2 style={{ fontFamily: 'var(--font-d)', fontSize: 22, fontWeight: 900, color: 'var(--ink-deep)', margin: 0 }}>{title}</h2>
      </div>
      {action}
    </div>
  );

  return (
    <div style={{ background: 'var(--bg)', minHeight: '70vh' }}>
      <PageBand pageKey="articles" arabic="اقرأ وتعلّم" title="Kumpulan Artikel" sub="Bacaan ilmu agama seputar Al-Qur'an, tahfidz, bahasa Arab, fiqih, dan akhlaq." />

      {/* toolbar STICKY */}
      <div className="art-toolbar">
        <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', padding: '12px 20px' }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', flex: 1, minWidth: 0 }}>
            {cats.map(c => {
              const active = c === cat;
              const s = c === 'Semua' ? { color: 'var(--ink-deep)' } : catStyle(c);
              return <button key={c} onClick={() => { setCat(c); setLimit(12); }} style={{ padding: '7px 14px', borderRadius: 999, fontSize: 12.5, 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)', whiteSpace: 'nowrap' }}>{c}</button>;
            })}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            {view === 'filtered' && <select value={sort} onChange={e => setSort(e.target.value)} style={{ padding: '9px 12px', borderRadius: 10, border: '1.5px solid var(--border)', fontSize: 12.5, fontWeight: 700, fontFamily: 'inherit', background: 'var(--surface)', color: 'var(--ink-deep)', cursor: 'pointer' }}>
              <option value="terbaru">Terbaru</option>
              <option value="populer">Terpopuler</option>
            </select>}
            <input value={q} onChange={e => { setQ(e.target.value); setLimit(12); }} placeholder="🔍 Cari…"
              style={{ padding: '9px 14px', borderRadius: 999, border: '1.5px solid var(--border)', fontSize: 13, fontFamily: 'inherit', width: 150, background: 'var(--surface)', color: 'var(--ink-deep)' }} />
          </div>
        </div>
      </div>

      <div className="container" style={{ padding: '24px 20px 60px' }}>
        {loading ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 20 }}>
            {[0,1,2,3].map(i => (
              <div key={i} style={{ borderRadius: 16, overflow: 'hidden', border: '1px solid var(--border-soft)', background: 'var(--surface)' }}>
                <div className="skeleton" style={{ aspectRatio: '16/9', borderRadius: 0 }} />
                <div style={{ padding: '16px 18px' }}><div className="skeleton" style={{ height: 14, width: '40%', marginBottom: 12 }} /><div className="skeleton" style={{ height: 16, width: '90%' }} /></div>
              </div>
            ))}
          </div>
        ) : view === 'discovery' ? (
          <>
            {/* UNGGULAN */}
            {editorPick.length > 0 && (
              <section style={{ marginBottom: 44 }}>
                <SectionTitle label="Pilihan Redaksi" title="Artikel Unggulan" />
                <FeaturedSlider items={editorPick} openArticle={openArticle} />
              </section>
            )}

            {/* TERBARU + POPULER */}
            <div className="art-two-col" style={{ display: 'grid', gridTemplateColumns: '1.7fr 1fr', gap: 32, marginBottom: 44, alignItems: 'start' }}>
              <section style={{ marginTop: 28 }}>
                <SectionTitle label="Baru Terbit" title="Artikel Terbaru" />
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 16 }}>
                  {latest.slice(0, 4).map(a => <ArticleCard key={a.id} a={a} onClick={() => openArticle(a)} />)}
                </div>
              </section>
              <section>
                <div className="sec-label" style={{ marginBottom: 14 }}>Paling Banyak Dibaca</div>
                <div style={{ background: 'var(--surface)', borderRadius: 16, padding: '8px 18px', border: '1px solid var(--border-soft)' }}>
                  {popular.map((a, i) => {
                    const na = normArticle(a);
                    return (
                      <button key={a.id} onClick={() => openArticle(a)} style={{ display: 'flex', gap: 13, alignItems: 'center', width: '100%', textAlign: 'left', background: 'none', border: 'none', borderTop: i ? '1px solid var(--border-soft)' : 'none', padding: '13px 0', cursor: 'pointer', fontFamily: 'inherit' }}>
                        <span style={{ flexShrink: 0, width: 26, height: 26, borderRadius: '50%', background: i === 0 ? 'var(--orange)' : 'var(--navy)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13 }}>{i + 1}</span>
                        <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink-deep)', lineHeight: 1.35, textWrap: 'pretty' }}>{a.title}</span>
                      </button>
                    );
                  })}
                </div>
              </section>
            </div>

            {/* PER KATEGORI */}
            {catGroups.map(c => {
              const items = articles.filter(a => a.category === c).slice(0, 4);
              if (!items.length) return null;
              const s = catStyle(c);
              return (
                <section key={c} style={{ marginBottom: 40 }}>
                  <SectionTitle label="Topik" title={c}
                    action={<button onClick={() => { setCat(c); setLimit(12); window.scrollTo(0, 0); }} style={{ padding: '7px 14px', borderRadius: 999, border: `1.5px solid ${s.color}`, background: 'var(--surface)', color: s.color, fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>Lihat semua →</button>} />
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 16 }}>
                    {items.map(a => <ArticleCard key={a.id} a={a} onClick={() => openArticle(a)} />)}
                  </div>
                </section>
              );
            })}
          </>
        ) : (
          <>
            <div style={{ fontSize: 13.5, color: 'var(--muted)', marginBottom: 16, fontWeight: 600 }}>
              {q.trim() ? `${list.length} hasil untuk “${q.trim()}”` : `${list.length} artikel · ${cat}`}
            </div>
            {list.length === 0 ? (
              <div style={{ padding: '60px 20px', textAlign: 'center', color: 'var(--muted)' }}>
                <div style={{ fontFamily: 'var(--font-d)', fontSize: 20, fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 8 }}>Tidak ada artikel yang cocok</div>
                <p style={{ margin: '0 0 18px' }}>Coba kata kunci lain atau pilih kategori berbeda.</p>
                <button className="btn-hero-secondary" onClick={() => { setQ(''); setCat('Semua'); }}>Atur Ulang Filter</button>
              </div>
            ) : (
              <>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {shown.map(a => <ArticleRow key={a.id} a={a} onClick={() => openArticle(a)} />)}
                </div>
                {limit < list.length && (
                  <div style={{ textAlign: 'center', marginTop: 26 }}>
                    <button className="btn-hero-secondary" onClick={() => setLimit(l => l + 12)}>Muat Lebih Banyak ({list.length - limit} lagi)</button>
                  </div>
                )}
              </>
            )}
          </>
        )}
      </div>
    </div>
  );
}

/* ── Halaman Baca Artikel ── */
function ArticleReader({ article, navigate, openArticle, openAuthor }) {
  const M = window.MQA || {};
  const [a, setA] = useState(normArticle(article));
  const all = M.articles || [];

  useEffect(() => { setA(normArticle(article)); window.scrollTo(0, 0); if (article && article.id) api.post('articles.php?action=view', { id: article.id }); }, [article]);

  // Konten lintas-jenis untuk sidebar (program/donasi/buku/kegiatan terkait)
  const [aside, setAside] = useState({ programs: [], campaigns: [], buku: [], kegiatan: [] });
  useEffect(() => {
    Promise.all([
      api.get('content.php?action=get_section&section=programs'),
      api.get('donations.php?action=list_campaigns'),
      api.get('content.php?action=get_section&section=buku'),
      api.get('content.php?action=get_section&section=kegiatan'),
    ]).then(([p, c, b, k]) => {
      const items = (r) => (r.ok && r.data && Array.isArray(r.data.items)) ? r.data.items : [];
      setAside({
        programs: items(p).length ? items(p) : ((window.MQA||{}).programs||[]),
        campaigns: (c.ok && c.campaigns) ? c.campaigns : [],
        buku: items(b).length ? items(b) : ((window.MQA||{}).buku||[]),
        kegiatan: items(k).length ? items(k) : ((window.MQA||{}).kegiatan||[]),
      });
    }).catch(() => {});
  }, []);

  if (!a) return null;
  const s = catStyle(a.category);
  const sameCat = all.filter(x => x.id !== a.id && x.category === a.category);
  // Urutkan: artikel SESUDAH yang dibaca dulu (berdasar urutan id), lalu melingkar ke awal
  const ordered = [...sameCat].sort((x, y) => x.id - y.id);
  const after = ordered.filter(x => x.id > a.id);
  const before = ordered.filter(x => x.id < a.id);
  const related = [...after, ...before].slice(0, 3);
  const popular = [...all].filter(x => x.id !== a.id).sort((x, y) => (y.views || y.view_count || 0) - (x.views || x.view_count || 0)).slice(0, 4);
  // Rekomendasi acak — diacak ulang tiap buka/refresh artikel
  const recos = React.useMemo(() => {
    const pool = all.filter(x => x.id !== a.id);
    for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; }
    return pool.slice(0, 4);
  }, [a.id]);
  const bodyHTML = renderMD(a.body || a.excerpt || '');

  // Pencocokan terkait berdasarkan kata di judul/kategori artikel
  const hay = ((a.title || '') + ' ' + (a.category || '') + ' ' + (a.excerpt || '')).toLowerCase();
  const matchProg = aside.programs.find(p => hay.includes((p.name || '').toLowerCase().split(' ')[0]) || (a.category && (p.name || '').toLowerCase().includes(a.category.toLowerCase().split(' ')[0]))) || aside.programs.find(p => p.featured) || aside.programs[0];
  const matchBuku = aside.buku.find(b => { const t = (b.title + ' ' + (b.categories || []).join(' ')).toLowerCase(); return a.category && t.includes(a.category.toLowerCase().split(' ')[0]); }) || aside.buku.find(b => b.featured) || aside.buku[0];
  const matchCamp = aside.campaigns.find(c => c.urgent || c.urgensi === 'tinggi') || aside.campaigns[0];

  const shareURL = () => location.href;
  const shareTxt = () => a.title + ' — ' + location.href;
  const SH = {
    wa: () => window.open('https://wa.me/?text=' + encodeURIComponent(shareTxt()), '_blank'),
    fb: () => window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(shareURL()), '_blank'),
    x:  () => window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(a.title) + '&url=' + encodeURIComponent(shareURL()), '_blank'),
    tg: () => window.open('https://t.me/share/url?url=' + encodeURIComponent(shareURL()) + '&text=' + encodeURIComponent(a.title), '_blank'),
    th: () => window.open('https://www.threads.net/intent/post?text=' + encodeURIComponent(shareTxt()), '_blank'),
    native: async () => { try { if (navigator.share) await navigator.share({ title: a.title, text: a.title, url: shareURL() }); else { navigator.clipboard?.writeText(shareURL()); } } catch {} },
  };
  const [copied, setCopied] = useState(false);
  const doCopy = () => { navigator.clipboard?.writeText(shareURL()); setCopied(true); setTimeout(() => setCopied(false), 1600); };

  return (
    <div style={{ background: 'var(--bg)' }}>
      <CoverArt a={a} ratio="21/9" iconSize={110} />

      <div className="container reader-shell" style={{ maxWidth: 1080, margin: '0 auto', padding: '0 20px 70px', display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 320px', gap: 32, alignItems: 'start' }}>
        {/* KOLOM ARTIKEL */}
        <article style={{ minWidth: 0 }}>
          <div style={{ background: 'var(--surface)', borderRadius: 20, padding: '34px 40px', marginTop: -56, position: 'relative', boxShadow: 'var(--shadow-warm-md)', border: '1px solid var(--border-soft)' }}>
            <button onClick={() => navigate('articles')} style={{ background: 'none', border: 'none', color: 'var(--muted)', fontSize: 13, fontWeight: 700, cursor: 'pointer', padding: 0, marginBottom: 16 }}>← Semua Artikel</button>
            <div style={{ marginBottom: 14 }}><CatBadge cat={a.category} /></div>
            <h1 style={{ fontFamily: 'var(--font-d)', fontSize: 32, fontWeight: 900, lineHeight: 1.2, color: 'var(--ink-deep)', margin: '0 0 18px', textWrap: 'pretty' }}>{a.title}</h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11, paddingBottom: 22, borderBottom: '1px solid var(--border-soft)', marginBottom: 26 }}>
              <button onClick={() => openAuthor && openAuthor(a.author)} style={{ display: 'flex', alignItems: 'center', gap: 11, background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
                <span style={{ width: 42, height: 42, borderRadius: '50%', background: s.color, color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800 }}>{a.authorInitial || (a.author || '?')[0]}</span>
                <div>
                  <div style={{ fontWeight: 800, fontSize: 14.5, color: 'var(--ink-deep)', textDecoration: 'underline', textDecorationColor: 'var(--border)', textUnderlineOffset: 3 }}>{a.author}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>{a.date} · {a.readTime} baca</div>
                </div>
              </button>
            </div>
            <div className="reader-body" style={{ color: 'var(--ink)' }} dangerouslySetInnerHTML={{ __html: bodyHTML }} />

            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 30, paddingTop: 24, borderTop: '1px solid var(--border-soft)', flexWrap: 'wrap' }}>
              <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--muted)', marginRight: 2 }}>Bagikan:</span>
              {[
                ['wa', '💬', 'WhatsApp', '#25D366'],
                ['fb', 'f', 'Facebook', '#1877F2'],
                ['x', '𝕏', 'X', '#000000'],
                ['tg', '✈', 'Telegram', '#229ED9'],
                ['th', '@', 'Threads', '#000000'],
              ].map(([k, ic, label, bg]) => (
                <button key={k} onClick={SH[k]} title={'Bagikan ke ' + label} aria-label={'Bagikan ke ' + label}
                  style={{ width: 38, height: 38, borderRadius: '50%', border: 'none', background: bg, color: '#fff', fontSize: 15, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{ic}</button>
              ))}
              <button onClick={SH.native} title="Bagikan ke aplikasi lain (Instagram, TikTok, dll)" aria-label="Bagikan lainnya"
                style={{ width: 38, height: 38, borderRadius: '50%', border: '1.5px solid var(--border)', background: 'var(--surface)', color: 'var(--ink-deep)', fontSize: 15, cursor: 'pointer', fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>⋯</button>
              <button onClick={doCopy}
                style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '9px 16px', borderRadius: 999, border: '1.5px solid var(--border)', background: copied ? 'var(--sage)' : 'var(--surface)', color: copied ? '#fff' : 'var(--ink-deep)', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>{copied ? '✓ Disalin' : '🔗 Salin Tautan'}</button>
            </div>
          </div>

          <AskQuestion article={a} />

          {related.length > 0 && (
            <div style={{ marginTop: 40 }}>
              <div className="sec-label">Artikel Terkait</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 16, marginTop: 14 }}>
                {related.map(r => <ArticleCard key={r.id} a={r} onClick={() => openArticle(r)} />)}
              </div>
            </div>
          )}
        </article>

        {/* SIDEBAR KANAN */}
        <aside className="reader-aside" style={{ position: 'sticky', top: 16, display: 'flex', flexDirection: 'column', gap: 18, marginTop: -56 }}>
          {/* Populer */}
          {popular.length > 0 && (
            <div style={{ background: 'var(--surface)', borderRadius: 16, padding: '18px 20px', border: '1px solid var(--border-soft)' }}>
              <div style={{ fontFamily: 'var(--font-d)', fontSize: 14, fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 2 }}>Paling Banyak Dibaca</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', marginBottom: 12 }}>Artikel populer pilihan pembaca</div>
              {popular.map((p, i) => { const np = normArticle(p); return (
                <button key={p.id} onClick={() => openArticle(p)} style={{ display: 'flex', gap: 12, alignItems: 'center', width: '100%', textAlign: 'left', background: 'none', border: 'none', borderTop: i ? '1px solid var(--border-soft)' : 'none', padding: '11px 0', cursor: 'pointer', fontFamily: 'inherit' }}>
                  <span style={{ fontSize: 13, fontWeight: 800, color: '#fff', background: i === 0 ? 'var(--orange)' : 'var(--navy)', lineHeight: 1, flexShrink: 0, width: 24, height: 24, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{i + 1}</span>
                  <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink-deep)', lineHeight: 1.35, textWrap: 'pretty' }}>{np.title}</span>
                </button>
              ); })}
            </div>
          )}

          {/* Rekomendasi acak — berubah tiap buka/refresh */}
          {recos.length > 0 && (
            <div style={{ background: 'var(--surface)', borderRadius: 16, padding: '18px 20px', border: '1px solid var(--border-soft)' }}>
              <div style={{ fontFamily: 'var(--font-d)', fontSize: 14, fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 2 }}>Rekomendasi Lainnya</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', marginBottom: 12 }}>Bacaan pilihan untuk Anda</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {recos.map(r => { const nr = normArticle(r); const sc = catStyle(r.category); return (
                  <button key={r.id} onClick={() => openArticle(r)} style={{ display: 'flex', gap: 11, alignItems: 'center', width: '100%', textAlign: 'left', background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: 'inherit' }}>
                    <span style={{ flexShrink: 0, width: 48, height: 48, borderRadius: 10, background: sc.color, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, overflow: 'hidden' }}>
                      {r.cover_url ? <img src={r.cover_url} alt="" loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <GlyphMark name={CAT_GLYPH[r.category] || 'scroll'} size={26} />}
                    </span>
                    <span style={{ minWidth: 0 }}>
                      <span style={{ display: 'block', fontSize: 11, fontWeight: 700, color: sc.color }}>{r.category}</span>
                      <span style={{ display: 'block', fontSize: 13, fontWeight: 700, color: 'var(--ink-deep)', lineHeight: 1.3, textWrap: 'pretty', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{r.title}</span>
                    </span>
                  </button>
                ); })}
              </div>
              <button onClick={() => navigate('articles')} style={{ width: '100%', marginTop: 14, padding: '9px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--surface)', color: 'var(--ink-deep)', fontWeight: 700, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit' }}>Lihat Semua Artikel →</button>
            </div>
          )}

          {/* Kajian / kegiatan mendatang */}
          {(() => {
            const upcoming = (aside.kegiatan || []).filter(k => k.status !== 'past' && k.status !== 'selesai').slice(0, 3);
            if (!upcoming.length) return null;
            return (
              <div style={{ background: 'var(--surface)', borderRadius: 16, padding: '18px 20px', border: '1px solid var(--border-soft)' }}>
                <div style={{ fontFamily: 'var(--font-d)', fontSize: 14, fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 2 }}>Kajian Mendatang</div>
                <div style={{ fontSize: 11.5, color: 'var(--muted)', marginBottom: 12 }}>Agenda kajian &amp; kegiatan terdekat</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {upcoming.map(k => (
                    <a key={k.id} href="#/kegiatan" onClick={(e) => { e.preventDefault(); navigate('kegiatan'); }} style={{ display: 'flex', gap: 11, alignItems: 'flex-start', textDecoration: 'none' }}>
                      <span style={{ flexShrink: 0, width: 40, height: 40, borderRadius: 10, background: 'var(--bg2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>{k.youtube_url ? '▶️' : '📖'}</span>
                      <span style={{ minWidth: 0 }}>
                        <span style={{ display: 'block', fontSize: 13.5, fontWeight: 800, color: 'var(--ink-deep)', lineHeight: 1.3, textWrap: 'pretty' }}>{k.title}</span>
                        {(k.date || k.time) && <span style={{ display: 'block', fontSize: 11.5, color: 'var(--sage)', fontWeight: 700, marginTop: 3 }}>🕐 {k.date}{k.time ? ' · ' + k.time : ''}</span>}
                      </span>
                    </a>
                  ))}
                </div>
                <button onClick={() => navigate('kegiatan')} style={{ width: '100%', marginTop: 14, padding: '9px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--surface)', color: 'var(--ink-deep)', fontWeight: 700, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit' }}>Lihat Semua Kegiatan →</button>
              </div>
            );
          })()}

          {/* Mungkin bermanfaat — lintas konten */}
          {/* Rekomendasi terkait — kartu CTA */}
          {matchProg && (
            <div style={{ background: 'var(--surface)', borderRadius: 16, padding: '18px 20px', border: '1px solid var(--border-soft)' }}>
              <div style={{ fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--sage)', marginBottom: 8 }}>Program Terkait</div>
              <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 14 }}>
                <span style={{ flexShrink: 0, width: 48, height: 48, borderRadius: 10, background: 'var(--sage)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><GlyphMark name={CAT_GLYPH[matchProg.name] || 'cap'} size={26} /></span>
                <div style={{ background: 'var(--sage)', borderRadius: 8, padding: 0 }} hidden></div>
                <div>
                  <div style={{ fontFamily: 'var(--font-d)', fontSize: 16, fontWeight: 800, color: 'var(--ink-deep)', lineHeight: 1.25 }}>{matchProg.name}</div>
                  {matchProg.schedule && <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>🕐 {matchProg.schedule}</div>}
                </div>
              </div>
              <button onClick={() => navigate('register')} className="btn-hero-primary" style={{ width: '100%', justifyContent: 'center', fontSize: 13.5, padding: '10px' }}>Daftar Program</button>
            </div>
          )}

          {matchBuku && (
            <div style={{ background: 'var(--surface)', borderRadius: 16, padding: '0', border: '1px solid var(--border-soft)', overflow: 'hidden' }}>
              <div style={{ display: 'flex', gap: 0 }}>
                <div style={{ width: 92, flexShrink: 0, aspectRatio: '3/4', background: matchBuku.color || 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
                  {matchBuku.cover_url ? <img src={matchBuku.cover_url} alt="" loading="lazy" decoding="async" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <GlyphMark name='book' size={34} />}
                </div>
                <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', minWidth: 0 }}>
                  <div style={{ fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--orange)', marginBottom: 4 }}>Buku Rekomendasi</div>
                  <div style={{ fontFamily: 'var(--font-d)', fontSize: 14.5, fontWeight: 800, color: 'var(--ink-deep)', lineHeight: 1.25, marginBottom: 4 }}>{matchBuku.title}</div>
                  <div style={{ fontSize: 14, fontWeight: 900, color: 'var(--sage)', marginTop: 'auto', marginBottom: 8 }}>{fmtRp(matchBuku.price)}</div>
                  <button onClick={() => navigate('toko')} style={{ background: 'var(--navy)', color: '#fff', border: 'none', borderRadius: 8, padding: '8px', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>Lihat Buku</button>
                </div>
              </div>
            </div>
          )}

          {matchCamp && (
            <div style={{ background: 'linear-gradient(135deg, var(--sage), #0F3D27)', borderRadius: 16, padding: '20px', color: '#fff' }}>
              <div style={{ fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.05em', opacity: .8, marginBottom: 8 }}>Donasi</div>
              <div style={{ fontFamily: 'var(--font-d)', fontSize: 16, fontWeight: 800, lineHeight: 1.3, marginBottom: 12 }}>{matchCamp.title}</div>
              <button onClick={() => navigate('donasi')} style={{ width: '100%', background: '#fff', color: 'var(--sage)', border: 'none', borderRadius: 9, padding: '11px', fontSize: 13.5, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit' }}>Donasi Sekarang</button>
            </div>
          )}

          {/* CTA daftar */}
          <div style={{ background: 'linear-gradient(135deg, var(--brand-deep), var(--brand-navy))', borderRadius: 16, padding: '22px 20px', color: '#fff' }}>
            <div style={{ fontFamily: 'var(--font-d)', fontSize: 17, fontWeight: 800, marginBottom: 6 }}>Belajar Bersama Kami</div>
            <p style={{ fontSize: 13, opacity: .85, margin: '0 0 14px', lineHeight: 1.5 }}>Daftar program tahfidz, bahasa Arab, fiqih &amp; akhlaq.</p>
            <button onClick={() => navigate('register')} style={{ width: '100%', padding: '11px', borderRadius: 10, border: 'none', background: 'var(--orange)', color: '#fff', fontWeight: 800, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit' }}>Daftar Santri</button>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ── Overlay Profil Penulis ── */
function AuthorProfile({ name, navigate, openArticle, onClose }) {
  const M = window.MQA || {};
  const [prof, setProf] = useState(null);
  const [loaded, setLoaded] = useState(false);
  useEffect(() => {
    api.get('auth.php?action=get_profile&email=' + encodeURIComponent(name)).then(r => { setProf(r.ok ? r.profile : null); setLoaded(true); });
  }, [name]);
  const articles = (M.articles || []).filter(a => (a.author || a.author_name) === name);
  const initial = (name || '?')[0];
  return (
    <div onClick={onClose} className="anim-overlay" style={{ position: 'fixed', inset: 0, background: 'rgba(10,20,45,.55)', zIndex: 400, display: 'flex', justifyContent: 'center', alignItems: 'flex-start', padding: '8vh 16px 16px', backdropFilter: 'blur(3px)', overflowY: 'auto' }}>
      <div onClick={e => e.stopPropagation()} className="anim-sheet" style={{ width: '100%', maxWidth: 520, background: 'var(--surface)', borderRadius: 18, boxShadow: '0 30px 80px rgba(0,0,0,.4)', overflow: 'hidden' }}>
        <div style={{ background: 'linear-gradient(135deg, var(--brand-deep), var(--brand-navy))', padding: '28px 26px', color: '#fff', display: 'flex', alignItems: 'center', gap: 16, position: 'relative' }}>
          <button onClick={onClose} style={{ position: 'absolute', top: 14, right: 14, background: 'rgba(255,255,255,.18)', border: 'none', borderRadius: 8, width: 30, height: 30, cursor: 'pointer', color: '#fff', fontSize: 14, fontWeight: 700 }}>✕</button>
          <div style={{ width: 72, height: 72, borderRadius: '50%', overflow: 'hidden', background: 'rgba(255,255,255,.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 30, flexShrink: 0 }}>
            {prof && prof.photo ? <img src={prof.photo} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : initial}
          </div>
          <div>
            <div style={{ fontFamily: 'var(--font-d)', fontSize: 22, fontWeight: 900 }}>{name}</div>
            <div style={{ fontSize: 13, opacity: .85 }}>{(prof && prof.title) || 'Penulis'}</div>
          </div>
        </div>
        <div style={{ padding: '22px 26px' }}>
          {prof && prof.bio
            ? <p style={{ fontSize: 14.5, lineHeight: 1.7, color: 'var(--ink)', margin: '0 0 18px' }}>{prof.bio}</p>
            : <p style={{ fontSize: 13.5, color: 'var(--muted)', fontStyle: 'italic', margin: '0 0 18px' }}>{loaded ? 'Penulis belum mengisi bio.' : 'Memuat…'}</p>}
          {articles.length > 0 && (
            <>
              <div className="sec-label" style={{ marginBottom: 10 }}>Artikel oleh {name.split(' ')[0]}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {articles.slice(0, 5).map(a => {
                  const na = normArticle(a); const sc = catStyle(a.category);
                  return (
                    <button key={a.id} onClick={() => { onClose(); openArticle(a); }} style={{ display: 'flex', gap: 11, alignItems: 'center', width: '100%', textAlign: 'left', background: 'none', border: 'none', borderRadius: 10, padding: '8px', cursor: 'pointer', fontFamily: 'inherit' }}>
                      <span style={{ flexShrink: 0, width: 40, height: 40, borderRadius: 8, background: sc.color, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 17 }}>{na.icon}</span>
                      <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink-deep)', lineHeight: 1.3 }}>{a.title}</span>
                    </button>
                  );
                })}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ArticlesPage, ArticleReader, AuthorProfile });

/* ── Form Tanya Ustadz (bawah artikel) ── */
function AskQuestion({ article }) {
  const [f, setF] = useState({ name: '', email: '', question: '' });
  const [sending, setSending] = useState(false);
  const [done, setDone] = useState(false);
  const submit = async (e) => {
    e.preventDefault();
    if (!f.email || !f.question.trim()) return;
    setSending(true);
    try {
      await api.post('questions.php?action=submit', { ...f, article_id: article.id, article_title: article.title });
      setDone(true);
    } finally { setSending(false); }
  };
  return (
    <div style={{ marginTop: 40, paddingTop: 30, borderTop: '2px solid var(--border-soft)' }}>
      <div className="sec-label">Tanya Ustadz</div>
      <h3 style={{ fontFamily: 'var(--font-d)', fontSize: 20, fontWeight: 800, color: 'var(--ink-deep)', margin: '4px 0 6px' }}>Punya pertanyaan tentang artikel ini?</h3>
      {done ? (
        <div style={{ background: 'rgba(31,107,71,.08)', border: '1px solid rgba(31,107,71,.25)', borderRadius: 14, padding: '20px 22px', marginTop: 12 }}>
          <div style={{ fontWeight: 800, color: 'var(--sage)', marginBottom: 4 }}>✓ Pertanyaan terkirim</div>
          <p style={{ fontSize: 14, color: 'var(--ink)', margin: 0, lineHeight: 1.6 }}>Jazakallahu khairan. Pertanyaan Anda akan dijawab oleh ustadz/admin, dan jawabannya dikirim ke email <strong>{f.email}</strong>.</p>
        </div>
      ) : (
        <form onSubmit={submit} style={{ marginTop: 12 }}>
          <p style={{ fontSize: 13.5, color: 'var(--muted)', margin: '0 0 14px', lineHeight: 1.55 }}>Tim kami akan menjawab dan mengirim balasan ke email Anda. Pertanyaan ini bersifat privat (tidak tampil di situs).</p>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }} className="ask-grid">
            <input value={f.name} onChange={e => setF(s => ({ ...s, name: e.target.value }))} placeholder="Nama (opsional)" style={askInp} />
            <input type="email" value={f.email} onChange={e => setF(s => ({ ...s, email: e.target.value }))} required placeholder="Email Anda *" style={askInp} />
          </div>
          <textarea value={f.question} onChange={e => setF(s => ({ ...s, question: e.target.value }))} required rows="4" placeholder="Tulis pertanyaan Anda…" style={{ ...askInp, width: '100%', resize: 'vertical', marginBottom: 12 }} />
          <button type="submit" disabled={sending || !f.email || !f.question.trim()} className="btn-hero-primary" style={{ opacity: (sending || !f.email || !f.question.trim()) ? .6 : 1 }}>{sending ? 'Mengirim…' : 'Kirim Pertanyaan'}</button>
        </form>
      )}
    </div>
  );
}
const askInp = { 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' };
window.AskQuestion = AskQuestion;