/* ════════════════════════════════════════════════
   Dashboard — Pertanyaan (Tanya Ustadz)
   Penulis lihat pertanyaan untuk artikelnya; admin lihat semua.
   ════════════════════════════════════════════════ */
function QuestionsModule({ user, toast }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState('baru');
  const [answering, setAnswering] = useState(null);
  const [answer, setAnswer] = useState('');
  const [saving, setSaving] = useState(false);
  const isAdmin = user.role === 'admin';

  const load = () => {
    setLoading(true);
    api.get('questions.php?action=list').then(r => { if (r.ok && r.questions) setItems(r.questions); }).finally(() => setLoading(false));
  };
  useEffect(load, []);

  const list = items.filter(q => filter === 'semua' ? true : filter === 'baru' ? q.status !== 'terjawab' : q.status === 'terjawab');

  const openAnswer = (q) => { setAnswering(q); setAnswer(q.answer || ''); };
  const sendAnswer = async () => {
    if (!answer.trim()) return;
    setSaving(true);
    const r = await api.post('questions.php?action=answer', { id: answering.id, answer });
    setSaving(false);
    if (r.ok) { toast('✅ Jawaban terkirim ke email penanya'); setAnswering(null); load(); }
    else toast('⚠️ ' + (r.error || 'Gagal'));
  };
  const del = async (q) => {
    if (!window.confirm('Hapus pertanyaan ini?')) return;
    const r = await api.post('questions.php?action=delete', { id: q.id });
    if (r.ok) { toast('🗑 Dihapus'); load(); }
  };

  const counts = { baru: items.filter(q => q.status !== 'terjawab').length, terjawab: items.filter(q => q.status === 'terjawab').length };

  return (
    <div style={{ maxWidth: 760 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14, flexWrap: 'wrap', gap: 10 }}>
        <div style={{ fontWeight: 800, color: 'var(--ink-deep)', fontSize: 15 }}>Pertanyaan Pembaca</div>
        <div style={{ display: 'flex', gap: 6 }}>
          {[['baru', `Belum dijawab (${counts.baru})`], ['terjawab', `Terjawab (${counts.terjawab})`], ['semua', 'Semua']].map(([k, l]) => (
            <button key={k} onClick={() => setFilter(k)} style={{ padding: '7px 13px', borderRadius: 999, fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', border: `1.5px solid ${filter === k ? 'var(--navy)' : 'var(--border)'}`, background: filter === k ? 'var(--navy)' : 'var(--surface)', color: filter === k ? '#fff' : 'var(--ink)' }}>{l}</button>
          ))}
        </div>
      </div>
      {!isAdmin && <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '0 0 14px' }}>Menampilkan pertanyaan untuk artikel yang Anda tulis.</p>}

      {loading ? <DCard><div style={{ padding: 24, textAlign: 'center', color: 'var(--muted)' }}>Memuat…</div></DCard>
        : list.length === 0 ? <DCard><div style={{ padding: 30, textAlign: 'center', color: 'var(--muted)' }}>Tidak ada pertanyaan.</div></DCard>
        : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {list.map(q => (
              <DCard key={q.id}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10, marginBottom: 8 }}>
                  <div>
                    <span style={{ fontWeight: 800, color: 'var(--ink-deep)' }}>{q.name || 'Anonim'}</span>
                    <span style={{ fontSize: 12, color: 'var(--muted)', marginLeft: 8 }}>{q.email}</span>
                  </div>
                  <Pill color={q.status === 'terjawab' ? 'green' : 'orange'}>{q.status === 'terjawab' ? 'Terjawab' : 'Baru'}</Pill>
                </div>
                {q.article_title && <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 8 }}>📄 {q.article_title}</div>}
                <p style={{ fontSize: 14.5, color: 'var(--ink)', lineHeight: 1.6, margin: '0 0 12px', background: 'var(--bg2)', padding: '12px 14px', borderRadius: 10 }}>{q.question}</p>
                {q.answer && <p style={{ fontSize: 14, color: 'var(--ink)', lineHeight: 1.6, margin: '0 0 12px', borderLeft: '3px solid var(--sage)', paddingLeft: 12 }}><strong style={{ color: 'var(--sage)' }}>Jawaban:</strong> {q.answer}</p>}
                <div style={{ display: 'flex', gap: 8 }}>
                  <DBtn size="sm" variant="orange" onClick={() => openAnswer(q)}>{q.status === 'terjawab' ? '✏️ Edit Jawaban' : '✉️ Jawab'}</DBtn>
                  <DBtn size="sm" variant="danger" onClick={() => del(q)}>🗑</DBtn>
                </div>
              </DCard>
            ))}
          </div>
        )}

      <Modal open={!!answering} onClose={() => setAnswering(null)} title="Jawab Pertanyaan" width="480px">
        {answering && (
          <>
            <div style={{ fontSize: 12.5, color: 'var(--muted)', marginBottom: 6 }}>Dari {answering.name || 'Anonim'} · {answering.email}</div>
            <p style={{ fontSize: 14, color: 'var(--ink)', background: 'var(--bg2)', padding: '12px 14px', borderRadius: 10, margin: '0 0 14px' }}>{answering.question}</p>
            <DField label="Jawaban (akan dikirim ke email penanya)"><textarea value={answer} onChange={e => setAnswer(e.target.value)} rows="6" style={{ ...dInp, resize: 'vertical' }} placeholder="Tulis jawaban…" /></DField>
            <div style={{ display: 'flex', gap: 10 }}>
              <DBtn variant="orange" size="lg" onClick={sendAnswer} disabled={saving || !answer.trim()} style={{ flex: 1 }}>{saving ? 'Mengirim…' : '✉️ Kirim Jawaban'}</DBtn>
              <DBtn size="lg" onClick={() => setAnswering(null)}>Batal</DBtn>
            </div>
          </>
        )}
      </Modal>
    </div>
  );
}
window.QuestionsModule = QuestionsModule;
