/* ════════════════════════════════════════════════
   Dashboard — shell + modul
   ════════════════════════════════════════════════ */
const _di = (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{p}</svg>;
const DICON = {
  overview:      _di(<><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></>),
  banner:        _di(<><rect x="3" y="4" width="18" height="14" rx="2"/><circle cx="8.5" cy="9" r="1.5"/><path d="M21 15l-5-5L5 21"/></>),
  pageheaders:   _di(<><rect x="3" y="4" width="18" height="5" rx="1"/><path d="M3 13h12M3 17h8"/></>),
  articles:      _di(<><path d="M4 4h11l5 5v11a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z"/><path d="M14 4v5h5M8 13h8M8 17h6"/></>),
  registrations: _di(<><path d="M9 4h6a1 1 0 0 1 1 1v1h2a1 1 0 0 1 1 1v13H5V7a1 1 0 0 1 1-1h2V5a1 1 0 0 1 1-1z"/><path d="M9 12l1.5 1.5L13 11M9 17h6"/></>),
  donasi:        _di(<path d="M12 21s-7-4.5-9.5-9.5C.5 7 4 3 7.5 3c1.7 0 3.4 1 4.5 2.5C13.1 4 14.8 3 16.5 3 20 3 23.5 7 21.5 11.5 19 16.5 12 21 12 21z"/>),
  toko:          _di(<><path d="M5 7h14l-1 13H6L5 7z"/><path d="M9 7a3 3 0 0 1 6 0"/></>),
  programs:      _di(<><path d="M22 9L12 4 2 9l10 5 10-5z"/><path d="M6 11v5c0 1 2.5 3 6 3s6-2 6-3v-5"/></>),
  teachers:      _di(<><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 3.5-6 8-6s8 2 8 6"/></>),
  testimonials:  _di(<path d="M12 3l2.6 5.3 5.8.8-4.2 4.1 1 5.8L12 16.8 6.8 19l1-5.8L3.6 9.1l5.8-.8L12 3z"/>),
  fasilitas:     _di(<><path d="M3 21V8l9-5 9 5v13"/><path d="M9 21v-6h6v6"/></>),
  kegiatan:      _di(<><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 9h18M8 3v4M16 3v4"/></>),
  settings:      _di(<><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.6 1.6 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.6 1.6 0 0 0-2.7 1.1V21a2 2 0 0 1-4 0v-.1A1.6 1.6 0 0 0 7 19.4a1.6 1.6 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.6 1.6 0 0 0-1.1-2.7H1a2 2 0 0 1 0-4h.1A1.6 1.6 0 0 0 2.6 7a1.6 1.6 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.6 1.6 0 0 0 7 2.6 1.6 1.6 0 0 0 8 1.1V1a2 2 0 0 1 4 0v.1A1.6 1.6 0 0 0 14 2.6a1.6 1.6 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.6 1.6 0 0 0 1.1 2.7H21a2 2 0 0 1 0 4h-.1a1.6 1.6 0 0 0-1.5 1z"/></>),
  users:         _di(<><circle cx="9" cy="8" r="3.5"/><path d="M2.5 20c0-3.3 2.9-5 6.5-5s6.5 1.7 6.5 5"/><path d="M17 8.5a3 3 0 0 1 0 5M19 20c0-2.2-1-3.7-2.5-4.5"/></>),
  globe:         _di(<><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.5 2.7 2.5 15.3 0 18M12 3c-2.5 2.7-2.5 15.3 0 18"/></>),
  questions:     _di(<><path d="M21 11.5a8.38 8.38 0 0 1-8.5 8.5 8.5 8.5 0 0 1-3.8-.9L3 21l1.9-5.7a8.5 8.5 0 0 1-.9-3.8 8.38 8.38 0 0 1 8.5-8.5 8.38 8.38 0 0 1 8.5 8.5z"/><path d="M9.5 9.5a2.5 2.5 0 0 1 4.6 1.3c0 1.7-2.5 2.2-2.5 2.2" strokeWidth="1.6"/><path d="M11.6 16h.01" strokeWidth="2"/></>),
  logout:        _di(<><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5M21 12H9"/></>),
};

function Dashboard({ user, navigate, onLogout }) {
  const [tab, setTab] = useState('overview');
  const [toastNode, toast] = useToast();
  const [mobileNav, setMobileNav] = useState(false);
  const [pwModal, setPwModal] = useState(false);
  const roleLabelTop = user.role === 'admin' ? 'Administrator' : (user.role === 'writer' ? 'Penulis' : user.role);

  const isAdmin = user.role === 'admin';
  const menu = [
    { key: 'overview', label: 'Ringkasan', icon: DICON.overview, admin: false },
    { key: 'profile', label: 'Profil Saya', icon: DICON.teachers, admin: false },
    { key: 'banner', label: 'Banner Beranda', icon: DICON.banner, admin: true },
    { key: 'pageheaders', label: 'Header Halaman', icon: DICON.pageheaders, admin: true },
    { key: 'articles', label: 'Artikel', icon: DICON.articles, admin: false },
    { key: 'questions', label: 'Pertanyaan', icon: DICON.questions, admin: false },
    { key: 'registrations', label: 'Pendaftar', icon: DICON.registrations, admin: true },
    { key: 'donasi', label: 'Donasi', icon: DICON.donasi, admin: true },
    { key: 'toko', label: 'Toko Buku', icon: DICON.toko, admin: true },
    { key: 'programs', label: 'Program', icon: DICON.programs, admin: true },
    { key: 'teachers', label: 'Pengajar', icon: DICON.teachers, admin: true },
    { key: 'testimonials', label: 'Testimoni', icon: DICON.testimonials, admin: true },
    { key: 'fasilitas', label: 'Fasilitas', icon: DICON.fasilitas, admin: true },
    { key: 'kegiatan', label: 'Kegiatan', icon: DICON.kegiatan, admin: true },
    { key: 'settings', label: 'Pengaturan', icon: DICON.settings, admin: true },
    { key: 'smtp', label: 'Pengaturan Email', icon: DICON.globe, admin: true },
    { key: 'users', label: 'Pengguna', icon: DICON.users, admin: true },
  ].filter(m => !m.admin || isAdmin);

  const Module = {
    overview: <OverviewModule user={user} setTab={setTab} />,
    banner: <ContentListModule section="banners" toast={toast} kind="banner" />,
    articles: <ArticlesModule user={user} toast={toast} />,
    registrations: <RegistrationsModule toast={toast} />,
    donasi: <DonasiModule toast={toast} />,
    toko: <ContentListModule section="buku" toast={toast} kind="buku" />,
    programs: <ContentListModule section="programs" toast={toast} kind="program" />,
    teachers: <ContentListModule section="teachers" toast={toast} kind="teacher" />,
    testimonials: <ContentListModule section="testimonials" toast={toast} kind="testimonial" />,
    fasilitas: <ContentListModule section="fasilitas" toast={toast} kind="fasilitas" />,
    kegiatan: <ContentListModule section="kegiatan" toast={toast} kind="kegiatan" />,
    settings: <SettingsModule toast={toast} />,
    pageheaders: <PageHeadersModule toast={toast} />,
    users: <UsersModule user={user} toast={toast} />,
    smtp: <SmtpModule toast={toast} />,
    profile: <ProfileModule user={user} toast={toast} />,
    questions: <QuestionsModule user={user} toast={toast} />,
  }[tab];

  const sidebar = (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '18px 20px', borderBottom: '1px solid rgba(255,255,255,.08)' }}>
        <img src="logo.jpg" alt="" style={{ height: 34, borderRadius: 7 }} /><img src="logo-rq.png" alt="" style={{ height: 32, marginLeft: 7 }} />
        <div style={{ color: '#fff', fontWeight: 800, fontSize: 14.5, lineHeight: 1.1 }}>Dashboard<br /><span style={{ fontSize: 11, opacity: .6, fontWeight: 600 }}>Qurrota A'yun</span></div>
      </div>
      <nav style={{ flex: 1, padding: '12px 10px', overflowY: 'auto' }}>
        {menu.map(m => (
          <button key={m.key} onClick={() => { setTab(m.key); setMobileNav(false); }} style={{
            display: 'flex', alignItems: 'center', gap: 11, width: '100%', padding: '10px 13px', marginBottom: 3, borderRadius: 10,
            background: tab === m.key ? 'rgba(232,145,42,.18)' : 'transparent', color: tab === m.key ? '#F0A93E' : 'rgba(255,255,255,.72)',
            border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13.5, fontWeight: 700, textAlign: 'left',
          }}><span style={{ display: 'flex', flexShrink: 0 }}>{m.icon}</span>{m.label}</button>
        ))}
      </nav>
      <div style={{ padding: '12px 14px', borderTop: '1px solid rgba(255,255,255,.08)' }}>
        <button onClick={() => navigate('home')} style={{ display: 'flex', alignItems: 'center', gap: 9, width: '100%', padding: '9px 12px', borderRadius: 9, background: 'transparent', color: 'rgba(255,255,255,.6)', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, marginBottom: 4 }}><span style={{ display: 'flex', flexShrink: 0 }}>{DICON.globe}</span> Lihat Situs</button>
        <button onClick={onLogout} style={{ display: 'flex', alignItems: 'center', gap: 9, width: '100%', padding: '9px 12px', borderRadius: 9, background: 'rgba(255,255,255,.06)', color: 'rgba(255,255,255,.85)', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700 }}><span style={{ display: 'flex', flexShrink: 0 }}>{DICON.logout}</span> Keluar</button>
      </div>
    </div>
  );

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', display: 'flex' }}>
      {/* Sidebar desktop */}
      <aside className="dash-sidebar" style={{ width: 240, flexShrink: 0, background: 'var(--brand-deep)', position: 'sticky', top: 0, height: '100vh' }}>{sidebar}</aside>

      {/* Sidebar mobile (drawer) */}
      {mobileNav && (
        <div onClick={() => setMobileNav(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 200 }}>
          <div onClick={e => e.stopPropagation()} style={{ width: 250, height: '100%', background: 'var(--brand-deep)' }}>{sidebar}</div>
        </div>
      )}

      {/* Main */}
      <main style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <header style={{ background: 'var(--surface)', borderBottom: '1px solid var(--border-soft)', padding: '14px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'sticky', top: 0, zIndex: 100 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <button className="dash-burger" onClick={() => setMobileNav(true)} style={{ display: 'none', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-deep)' }}>{IC.menu}</button>
            <div style={{ fontFamily: 'var(--font-d)', fontSize: 19, fontWeight: 900, color: 'var(--ink-deep)' }}>{menu.find(m => m.key === tab)?.label}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <ThemeToggle />
            <button onClick={() => setPwModal(true)} title="Ubah Password" style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
              <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--navy)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13 }}>{user.name[0]}</div>
              <div className="dash-user" style={{ lineHeight: 1.15, textAlign: 'left' }}>
                <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--ink-deep)' }}>{user.name}</div>
                <div style={{ fontSize: 11, color: 'var(--muted)' }}>{roleLabelTop} · Ubah sandi</div>
              </div>
            </button>
          </div>
        </header>
        <div style={{ padding: '24px', flex: 1 }}>{Module}</div>
      </main>
      {pwModal && <ChangePasswordModal onClose={() => setPwModal(false)} toast={toast} />}
      {toastNode}
    </div>
  );
}

/* ── Ringkasan ── */
function OverviewModule({ user, setTab }) {
  const [stats, setStats] = useState({ articles: 0, regs: 0, campaigns: 0, donasi: 0 });
  useEffect(() => {
    Promise.all([
      api.get('articles.php?action=all'),
      api.get('registrations.php?action=list'),
      api.get('donations.php?action=public_stats'),
    ]).then(([a, r, s]) => {
      setStats({
        articles: a.ok && a.articles ? a.articles.length : 0,
        regs: r.ok && r.registrations ? r.registrations.length : 0,
        campaigns: s.ok ? (s.kampanye_aktif ?? s.total_campaign ?? 0) : 0,
        donasi: s.ok ? (s.total_masuk || 0) : 0,
      });
    });
  }, []);
  return (
    <div>
      <div style={{ marginBottom: 22 }}>
        <div style={{ fontFamily: 'var(--font-d)', fontSize: 24, fontWeight: 900, color: 'var(--ink-deep)' }}>Assalamu'alaikum, {user.name.split(' ')[0]}</div>
        <p style={{ color: 'var(--muted)', fontSize: 14, marginTop: 4 }}>Ringkasan aktivitas situs Markaz Qurrota A'yun.</p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16, marginBottom: 24 }}>
        <StatCard icon={DICON.articles} num={stats.articles} label="Total Artikel" accent="var(--sage)" />
        <StatCard icon={DICON.registrations} num={stats.regs} label="Pendaftar Santri" accent="var(--navy)" />
        <StatCard icon={DICON.donasi} num={stats.campaigns} label="Program Donasi" accent="var(--orange)" />
        <StatCard icon={DICON.toko} num={fmtRp(stats.donasi)} label="Donasi Terkumpul" accent="#8B5A2B" />
      </div>
      <DCard>
        <div style={{ fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 14, fontSize: 15 }}>Akses Cepat</div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <DBtn variant="primary" onClick={() => setTab('articles')}>Tulis Artikel</DBtn>
          <DBtn onClick={() => setTab('registrations')}>Lihat Pendaftar</DBtn>
          <DBtn onClick={() => setTab('donasi')}>Kelola Donasi</DBtn>
        </div>
      </DCard>
    </div>
  );
}

window.Dashboard = Dashboard;

/* ── Modal ubah password sendiri ── */
function ChangePasswordModal({ onClose, toast }) {
  const [f, setF] = useState({ old_password: '', new_password: '', confirm: '' });
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');
  const submit = async () => {
    if (f.new_password.length < 8) { setErr('Password baru minimal 8 karakter.'); return; }
    if (f.new_password !== f.confirm) { setErr('Konfirmasi password tidak cocok.'); return; }
    setSaving(true); setErr('');
    const r = await api.post('auth.php?action=change_password', { old_password: f.old_password, new_password: f.new_password });
    setSaving(false);
    if (r.ok) { toast('✅ Password berhasil diubah'); onClose(); }
    else setErr(r.error || 'Gagal mengubah password.');
  };
  return (
    <Modal open onClose={onClose} title="Ubah Password" width="400px">
      <DField label="Password Lama"><input type="password" value={f.old_password} onChange={e => setF(s => ({ ...s, old_password: e.target.value }))} style={dInp} placeholder="••••••••" /></DField>
      <DField label="Password Baru (min. 8 karakter)"><input type="password" value={f.new_password} onChange={e => setF(s => ({ ...s, new_password: e.target.value }))} style={dInp} placeholder="••••••••" /></DField>
      <DField label="Ulangi Password Baru"><input type="password" value={f.confirm} onChange={e => setF(s => ({ ...s, confirm: e.target.value }))} style={dInp} placeholder="••••••••" /></DField>
      {err && <div style={{ color: '#DC2626', fontSize: 13, fontWeight: 600, marginBottom: 10 }}>{err}</div>}
      <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
        <DBtn variant="orange" size="lg" onClick={submit} disabled={saving || !f.old_password || !f.new_password} style={{ flex: 1 }}>{saving ? 'Menyimpan…' : '💾 Simpan'}</DBtn>
        <DBtn size="lg" onClick={onClose}>Batal</DBtn>
      </div>
    </Modal>
  );
}
window.ChangePasswordModal = ChangePasswordModal;