/* ════════════════════════════════════════════════
   Halaman Toko Buku — katalog + detail buku
   ════════════════════════════════════════════════ */
function TokoPage({ navigate }) {
  const [books, setBooks] = useState(((window.MQA || {}).buku || []).filter(b => b.active !== false));
  const [cat, setCat] = useState('Semua');
  const [detail, setDetail] = useState(null);

  useEffect(() => {
    const b = window.__openBuku;
    if (b && b.id) { window.__openBuku = null; setTimeout(() => setDetail(b), 120); }
  }, []);

  useEffect(() => {
    api.get('content.php?action=get_section&section=buku').then(r => {
      const arr = (r.ok && r.data && Array.isArray(r.data.items)) ? r.data.items : null;
      if (arr && arr.length) setBooks(arr.filter(b => b.active !== false));
    }).catch(() => {});
  }, []);

  const allCats = ['Semua', ...new Set(books.flatMap(b => b.categories || []))];
  const list = cat === 'Semua' ? books : books.filter(b => (b.categories || []).includes(cat));

  return (
    <div style={{ background: 'var(--bg)', minHeight: '70vh' }}>
      <PageBand pageKey="toko" kicker="Toko Buku" title="Pustaka Islami" sub="Buku-buku pilihan seputar tahfidz, tajwid, bahasa Arab, fiqih, dan akhlaq." />
      <div className="container" style={{ padding: '28px 20px 60px' }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 24 }}>
          {allCats.map(c => {
            const active = c === cat;
            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 ? 'var(--navy)' : 'var(--border)'}`, background: active ? 'var(--navy)' : 'var(--surface)', color: active ? '#fff' : 'var(--ink)' }}>{c}</button>;
          })}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 20 }}>
          {list.map(b => {
            const disc = b.originalPrice && b.originalPrice > b.price;
            const bslug = b.slug || (window.slugify ? slugify(b.title) : b.id);
            const handle = (e) => { if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return; e.preventDefault(); setDetail(b); };
            return (
              <a key={b.id} href={'/buku/' + bslug} onClick={handle} className="fade-up toko-card" style={{ textDecoration: 'none', 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: '3/4', background: b.color || 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
                  {b.cover_url ? <img src={b.cover_url} alt="" loading="lazy" decoding="async" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} /> : <GlyphMark name="book" size={56} />}
                  {b.featured ? <span style={{ position: 'absolute', top: 10, left: 10, padding: '3px 10px', borderRadius: 999, background: 'var(--orange)', color: '#fff', fontSize: 10.5, fontWeight: 800 }}>UNGGULAN</span> : null}
                  {disc ? <span style={{ position: 'absolute', top: 10, right: 10, padding: '3px 9px', borderRadius: 999, background: '#DC2626', color: '#fff', fontSize: 10.5, fontWeight: 800 }}>HEMAT</span> : null}
                </div>
                <div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', flex: 1 }}>
                  <h3 style={{ fontFamily: 'var(--font-d)', fontSize: 16, fontWeight: 800, color: 'var(--ink-deep)', margin: '0 0 4px', lineHeight: 1.25, textWrap: 'pretty' }}>{b.title}</h3>
                  <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 12 }}>{b.author}</div>
                  <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 16.5, fontWeight: 900, color: 'var(--sage)' }}>{fmtRp(b.price)}</span>
                    {disc ? <span style={{ fontSize: 12.5, color: 'var(--muted)', textDecoration: 'line-through' }}>{fmtRp(b.originalPrice)}</span> : null}
                  </div>
                </div>
              </a>
            );
          })}
        </div>
        {list.length === 0 && <div style={{ padding: 50, textAlign: 'center', color: 'var(--muted)' }}>Belum ada buku di kategori ini.</div>}
      </div>

      {detail && <BukuModal b={detail} onClose={() => setDetail(null)} />}
    </div>
  );
}

function BukuModal({ b, onClose }) {
  const disc = b.originalPrice && b.originalPrice > b.price;
  const pesanWA = () => window.open('https://wa.me/628123456789?text=' + encodeURIComponent(`Assalamu'alaikum, saya ingin memesan buku "${b.title}" (${fmtRp(b.price)}).`), '_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: 560, maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 30px 80px rgba(0,0,0,.35)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: 0 }} className="buku-modal-grid">
          <div style={{ position: 'relative', background: b.color || 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 220, overflow: 'hidden' }}>
            {b.cover_url ? <img src={b.cover_url} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} /> : <GlyphMark name='book' size={60} />}
          </div>
          <div style={{ padding: '24px 26px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
              <div>
                <h2 style={{ fontFamily: 'var(--font-d)', fontSize: 22, fontWeight: 900, color: 'var(--ink-deep)', margin: '0 0 4px', lineHeight: 1.2 }}>{b.title}</h2>
                <div style={{ fontSize: 13, color: 'var(--muted)' }}>oleh {b.author}</div>
              </div>
              <button onClick={onClose} style={{ background: 'var(--bg2)', border: 'none', borderRadius: 8, width: 32, height: 32, cursor: 'pointer', color: 'var(--ink-deep)', fontSize: 16, flexShrink: 0 }}>✕</button>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, margin: '14px 0' }}>
              <span style={{ fontSize: 24, fontWeight: 900, color: 'var(--sage)' }}>{fmtRp(b.price)}</span>
              {disc ? <span style={{ fontSize: 14, color: 'var(--muted)', textDecoration: 'line-through' }}>{fmtRp(b.originalPrice)}</span> : null}
            </div>
            <p style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--ink)', margin: '0 0 16px' }}>{b.desc}</p>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 14, fontSize: 12.5, color: 'var(--muted)', marginBottom: 18 }}>
              {b.pages ? <span>{b.pages} halaman</span> : null}
              {b.weight ? <span>· {b.weight}</span> : null}
              {typeof b.stock === 'number' ? <span>· Stok {b.stock}</span> : null}
            </div>
            <button onClick={pesanWA} style={{ width: '100%', padding: '13px', borderRadius: 12, border: 'none', background: '#25D366', color: '#fff', fontSize: 15, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit', marginBottom: 10 }}>💬 Pesan via WhatsApp</button>
            <div style={{ display: 'flex', gap: 10 }}>
              {b.tokopedia_url ? <a href={b.tokopedia_url} target="_blank" rel="noopener" style={{ flex: 1, textAlign: 'center', padding: '11px', borderRadius: 10, background: '#42b549', color: '#fff', fontSize: 13, fontWeight: 700, textDecoration: 'none' }}>Tokopedia</a> : null}
              {b.shopee_url ? <a href={b.shopee_url} target="_blank" rel="noopener" style={{ flex: 1, textAlign: 'center', padding: '11px', borderRadius: 10, background: '#ee4d2d', color: '#fff', fontSize: 13, fontWeight: 700, textDecoration: 'none' }}>Shopee</a> : null}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.TokoPage = TokoPage;
