/* ════════════════════════════════════════════════
   Dashboard — Kelola Pengguna, Role & Kewenangan (dinamis)
   ════════════════════════════════════════════════ */
const PERM_LIST = [
  ['articles', 'Kelola Artikel'],
  ['registrations', 'Lihat Pendaftar'],
  ['donasi', 'Kelola Donasi'],
  ['content', 'Edit Konten Halaman'],
  ['users', 'Kelola Pengguna'],
  ['settings', 'Pengaturan Situs'],
];

function UsersModule({ user, toast }) {
  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [perms, setPerms] = useState({});
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState(null);      // form pengguna
  const [roleModal, setRoleModal] = useState(null); // form role baru
  const [form, setForm] = useState({});
  const [roleForm, setRoleForm] = useState({ label: '', permissions: {} });
  const [saving, setSaving] = useState(false);

  const roleLabel = (id) => (roles.find(r => r.id === id) || {}).label || id;

  const load = () => {
    setLoading(true);
    Promise.all([
      api.get('auth.php?action=users'),
      api.get('auth.php?action=get_permissions'),
      api.get('auth.php?action=get_roles'),
    ]).then(([u, p, r]) => {
      if (u.ok && u.users) setUsers(u.users);
      if (p.ok && p.permissions) setPerms(p.permissions);
      if (r.ok && r.roles) setRoles(r.roles);
    }).finally(() => setLoading(false));
  };
  useEffect(load, []);

  const firstRole = roles[0] ? roles[0].id : 'writer';
  const openAdd = () => { setForm({ name: '', email: '', role: roles.find(r => !r.system)?.id || firstRole, password: '' }); setModal({}); };
  const openEdit = (u) => { setForm({ ...u, password: '' }); setModal({ id: u.id }); };

  const save = async () => {
    if (!form.name || !form.email) return;
    setSaving(true);
    const action = modal.id ? 'update_user' : 'create_user';
    const r = await api.post(`auth.php?action=${action}`, modal.id ? { ...form, id: modal.id } : form);
    setSaving(false);
    if (r.ok) { toast(modal.id ? '✅ Pengguna diperbarui' : '✅ Pengguna ditambahkan'); setModal(null); load(); }
    else toast('⚠️ ' + (r.error || 'Gagal menyimpan'));
  };
  const del = async (u) => {
    if (u.id === user.id) { toast('⚠️ Tidak bisa menghapus akun sendiri'); return; }
    if (!window.confirm(`Hapus pengguna "${u.name}"?`)) return;
    const r = await api.post('auth.php?action=delete_user', { id: u.id });
    if (r.ok) { toast('Pengguna dihapus'); load(); } else toast('⚠️ Gagal menghapus');
  };

  const togglePerm = (role, key) => setPerms(p => ({ ...p, [role]: { ...p[role], [key]: !p[role]?.[key] } }));
  const savePerms = async () => {
    const r = await api.post('auth.php?action=save_permissions', { permissions: perms });
    if (r.ok) toast('✅ Kewenangan role disimpan'); else toast('⚠️ Gagal');
  };

  const saveRole = async () => {
    if (!roleForm.label.trim()) return;
    setSaving(true);
    const r = await api.post('auth.php?action=create_role', { label: roleForm.label.trim(), permissions: roleForm.permissions });
    setSaving(false);
    if (r.ok) { toast('✅ Role baru dibuat'); setRoleModal(null); setRoleForm({ label: '', permissions: {} }); load(); }
    else toast('⚠️ ' + (r.error || 'Gagal'));
  };
  const delRole = async (role) => {
    if (!window.confirm(`Hapus role "${role.label}"?`)) return;
    const r = await api.post('auth.php?action=delete_role', { id: role.id });
    if (r.ok) { toast('Role dihapus'); load(); } else toast('⚠️ ' + (r.error || 'Gagal menghapus'));
  };

  const accent = (id, i) => id === 'admin' ? 'var(--navy)' : ['var(--sage)', 'var(--orange)', '#7A4E8C', '#0E7C86'][i % 4];

  return (
    <div style={{ display: 'grid', gap: 24, maxWidth: 820 }}>
      {/* Daftar pengguna */}
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ fontWeight: 800, color: 'var(--ink-deep)', fontSize: 15 }}>Pengguna ({users.length})</div>
          <DBtn variant="orange" onClick={openAdd}>+ Tambah Pengguna</DBtn>
        </div>
        <DCard p="0">
          {loading ? <div style={{ padding: 30, textAlign: 'center', color: 'var(--muted)' }}>Memuat…</div> : (
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <tbody>
                {users.map((u, i) => (
                  <tr key={u.id} style={{ borderTop: i ? '1px solid var(--border-soft)' : 'none' }}>
                    <DTd>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                        <span style={{ width: 38, height: 38, borderRadius: '50%', background: u.role === 'admin' ? 'var(--navy)' : 'var(--sage)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800 }}>{(u.name || '?')[0]}</span>
                        <div>
                          <div style={{ fontWeight: 700, color: 'var(--ink-deep)' }}>{u.name}{u.id === user.id ? ' (Anda)' : ''}</div>
                          <div style={{ fontSize: 12, color: 'var(--muted)' }}>{u.email}</div>
                        </div>
                      </div>
                    </DTd>
                    <DTd><Pill color={u.role === 'admin' ? 'blue' : 'green'}>{roleLabel(u.role)}</Pill></DTd>
                    <DTd>
                      <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                        <DBtn size="sm" onClick={() => openEdit(u)}>Edit</DBtn>
                        <DBtn size="sm" variant="danger" onClick={() => del(u)}>Hapus</DBtn>
                      </div>
                    </DTd>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </DCard>
      </div>

      {/* Kewenangan role (dinamis) */}
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
          <div style={{ fontWeight: 800, color: 'var(--ink-deep)', fontSize: 15 }}>Role &amp; Kewenangan</div>
          <DBtn onClick={() => { setRoleForm({ label: '', permissions: {} }); setRoleModal({}); }}>+ Role Baru</DBtn>
        </div>
        <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '0 0 14px' }}>Centang akses tiap role. Administrator selalu penuh &amp; tak bisa diubah.</p>
        <DCard style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14, minWidth: 460 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--border-soft)' }}>
                <th style={{ textAlign: 'left', padding: '8px 4px', color: 'var(--muted)', fontSize: 12.5 }}>Kewenangan</th>
                {roles.map((role, i) => (
                  <th key={role.id} style={{ padding: '8px 6px', color: accent(role.id, i), fontSize: 12.5, whiteSpace: 'nowrap' }}>
                    {role.label}
                    {!role.system && <button onClick={() => delRole(role)} title="Hapus role" style={{ marginLeft: 5, border: 'none', background: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 12 }}>✕</button>}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {PERM_LIST.map(([key, label]) => (
                <tr key={key} style={{ borderTop: '1px solid var(--border-soft)' }}>
                  <td style={{ padding: '10px 4px', color: 'var(--ink-deep)', fontWeight: 600 }}>{label}</td>
                  {roles.map(role => {
                    const isAdmin = role.id === 'admin';
                    return (
                      <td key={role.id} style={{ textAlign: 'center' }}>
                        <input type="checkbox" disabled={isAdmin} checked={isAdmin ? true : !!perms[role.id]?.[key]} onChange={() => togglePerm(role.id, key)} style={{ width: 17, height: 17, accentColor: 'var(--sage)', cursor: isAdmin ? 'not-allowed' : 'pointer' }} />
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
          <DBtn variant="orange" size="lg" onClick={savePerms} style={{ marginTop: 14 }}>Simpan Kewenangan</DBtn>
        </DCard>
      </div>

      {/* Modal pengguna */}
      <Modal open={!!modal} onClose={() => setModal(null)} title={modal && modal.id ? 'Edit Pengguna' : 'Tambah Pengguna'} width="440px">
        {modal && (
          <>
            <DField label="Nama Lengkap *"><input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} style={dInp} /></DField>
            <DField label="Email *"><input type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} style={dInp} /></DField>
            <DField label="Role"><select value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value }))} style={dInp}>{roles.map(r => <option key={r.id} value={r.id}>{r.label}</option>)}</select></DField>
            <DField label={modal.id ? 'Password Baru (kosongkan jika tetap)' : 'Password *'}><input type="password" value={form.password} onChange={e => setForm(f => ({ ...f, password: e.target.value }))} style={dInp} placeholder="••••••••" /></DField>
            <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
              <DBtn variant="orange" size="lg" onClick={save} disabled={saving || !form.name || !form.email} style={{ flex: 1 }}>{saving ? 'Menyimpan…' : 'Simpan'}</DBtn>
              <DBtn size="lg" onClick={() => setModal(null)}>Batal</DBtn>
            </div>
          </>
        )}
      </Modal>

      {/* Modal role baru */}
      <Modal open={!!roleModal} onClose={() => setRoleModal(null)} title="Buat Role Baru" width="440px">
        {roleModal && (
          <>
            <DField label="Nama Role *"><input value={roleForm.label} onChange={e => setRoleForm(f => ({ ...f, label: e.target.value }))} style={dInp} placeholder="mis. Editor, Bendahara, Humas" /></DField>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-deep)', margin: '6px 0 8px' }}>Kewenangan</div>
            <div style={{ display: 'grid', gap: 8, marginBottom: 8 }}>
              {PERM_LIST.map(([key, label]) => (
                <label key={key} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, color: 'var(--ink-deep)', cursor: 'pointer' }}>
                  <input type="checkbox" checked={!!roleForm.permissions[key]} onChange={() => setRoleForm(f => ({ ...f, permissions: { ...f.permissions, [key]: !f.permissions[key] } }))} style={{ width: 17, height: 17, accentColor: 'var(--sage)' }} />
                  {label}
                </label>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
              <DBtn variant="orange" size="lg" onClick={saveRole} disabled={saving || !roleForm.label.trim()} style={{ flex: 1 }}>{saving ? 'Menyimpan…' : 'Buat Role'}</DBtn>
              <DBtn size="lg" onClick={() => setRoleModal(null)}>Batal</DBtn>
            </div>
          </>
        )}
      </Modal>
    </div>
  );
}

window.UsersModule = UsersModule;

/* ── Profil Saya: semua pengguna isi foto, bio, gelar ── */
function ProfileModule({ user, toast, onUpdated }) {
  const [f, setF] = useState({ name: user.name || '', title: '', bio: '', photo: '' });
  const [saving, setSaving] = useState(false);
  useEffect(() => { api.get('auth.php?action=me').then(r => { if (r.ok && r.user) setF(s => ({ ...s, name: r.user.name || '', title: r.user.title || '', bio: r.user.bio || '', photo: r.user.photo || '' })); }); }, []);
  const save = async () => {
    setSaving(true);
    const r = await api.post('auth.php?action=update_profile', f);
    setSaving(false);
    if (r.ok) { toast('✅ Profil disimpan'); if (onUpdated) onUpdated(); } else toast('⚠️ ' + (r.error || 'Gagal'));
  };
  return (
    <div style={{ maxWidth: 560 }}>
      <div style={{ fontWeight: 800, color: 'var(--ink-deep)', fontSize: 15, marginBottom: 4 }}>Profil Saya</div>
      <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '0 0 16px' }}>Foto, gelar, dan bio ini tampil saat pengunjung mengeklik nama Anda di artikel.</p>
      <DCard>
        <div style={{ display: 'flex', gap: 18, alignItems: 'center', marginBottom: 18 }}>
          <div style={{ width: 76, height: 76, borderRadius: '50%', overflow: 'hidden', background: 'var(--navy)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 30, flexShrink: 0 }}>
            {f.photo ? <img src={f.photo} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : (f.name[0] || '?')}
          </div>
          <div style={{ flex: 1 }}><ImageUpload label="Foto Profil" value={f.photo} onChange={v => setF(s => ({ ...s, photo: v }))} ratio="1/1" /></div>
        </div>
        <DField label="Nama"><input value={f.name} onChange={e => setF(s => ({ ...s, name: e.target.value }))} style={dInp} /></DField>
        <DField label="Gelar / Jabatan (mis. Pengajar Tahfidz)"><input value={f.title} onChange={e => setF(s => ({ ...s, title: e.target.value }))} style={dInp} placeholder="Pengajar / Penulis" /></DField>
        <DField label="Bio Singkat"><textarea value={f.bio} onChange={e => setF(s => ({ ...s, bio: e.target.value }))} rows="3" style={{ ...dInp, resize: 'vertical' }} placeholder="Ceritakan sedikit tentang Anda…" /></DField>
        <DBtn variant="orange" size="lg" onClick={save} disabled={saving}>{saving ? 'Menyimpan…' : 'Simpan Profil'}</DBtn>
      </DCard>
    </div>
  );
}
window.ProfileModule = ProfileModule;

/* ── Pengaturan Email (SMTP) — admin only ── */
function SmtpModule({ toast }) {
  const [f, setF] = useState({ host: 'smtp.hostinger.com', port: '587', user: '', pass: '', from_name: "Markaz Qurrota A'yun" });
  const [saving, setSaving] = useState(false);
  useEffect(() => { api.get('auth.php?action=get_smtp').then(r => { if (r.ok && r.smtp) setF(s => ({ ...s, ...r.smtp, pass: '' })); }); }, []);
  const save = async () => { setSaving(true); const r = await api.post('auth.php?action=save_smtp', f); setSaving(false); if (r.ok) toast('✅ Pengaturan email disimpan'); else toast('⚠️ Gagal'); };
  const F = (k) => (e) => setF(s => ({ ...s, [k]: e.target.value }));
  return (
    <div style={{ maxWidth: 560 }}>
      <div style={{ fontWeight: 800, color: 'var(--ink-deep)', fontSize: 15, marginBottom: 4 }}>Pengaturan Email (SMTP)</div>
      <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '0 0 16px', lineHeight: 1.55 }}>Dipakai untuk mengirim jawaban Tanya Ustadz, notifikasi donasi &amp; pendaftaran. Buat akun email di hPanel Hostinger → Emails, lalu isi di sini.</p>
      <DCard>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
          <DField label="SMTP Host"><input value={f.host} onChange={F('host')} style={dInp} placeholder="smtp.hostinger.com" /></DField>
          <DField label="Port"><input value={f.port} onChange={F('port')} style={dInp} placeholder="587" /></DField>
        </div>
        <DField label="Email Pengirim (SMTP User)"><input value={f.user} onChange={F('user')} style={dInp} placeholder="info@qurrotaayun.com" /></DField>
        <DField label="Password Email"><input type="password" value={f.pass} onChange={F('pass')} style={dInp} placeholder="••••••••" /></DField>
        <DField label="Nama Pengirim"><input value={f.from_name} onChange={F('from_name')} style={dInp} /></DField>
        <DBtn variant="orange" size="lg" onClick={save} disabled={saving}>{saving ? 'Menyimpan…' : 'Simpan Pengaturan Email'}</DBtn>
      </DCard>
      <p style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 10, lineHeight: 1.5 }}>Catatan: Password email disimpan terenkripsi di server &amp; tidak ditampilkan kembali. Kosongkan kolom password bila tak ingin mengubahnya.</p>
    </div>
  );
}
window.SmtpModule = SmtpModule;
