// Candidate detail drawer
const { useState: useStateD } = React;

function CandidateDrawer({ candidate, job, onClose, onUpdate, onSchedule, onPapi }) {
  const [tab, setTab] = useStateD('profil');
  const [status, setStatus] = useStateD(candidate.status);
  const [notes, setNotes] = useStateD('');
  const [showAsg, setShowAsg] = useStateD(false);

  // Real WhatsApp conversation for this candidate (null = still loading,
  // [] = no messages, [...] = list). Powers both the tab badge count and
  // the Chat tab itself — no more dummy WA_DEMO.
  const [waLogs, setWaLogs] = useStateD(null);
  const reloadWaLogs = React.useCallback(async () => {
    try {
      const r = await window.TalentirAPI.get('/api/candidates/' + candidate.id + '/wa-logs');
      setWaLogs(Array.isArray(r) ? r : []);
    } catch (e) { console.error('Gagal memuat chat WA:', e); setWaLogs([]); }
  }, [candidate.id]);
  React.useEffect(() => { reloadWaLogs(); }, [reloadWaLogs]);
  // If the chat tab was active and the conversation just disappeared (e.g.
  // wiped from the WhatsApp view), bounce the user back to Profil so they
  // don't sit on a tab that no longer exists.
  React.useEffect(() => {
    if (tab === 'chat' && waLogs !== null && waLogs.length === 0) setTab('profil');
  }, [tab, waLogs]);

  const cls = candidate.score >= 80 ? 'good' : candidate.score >= 60 ? '' : candidate.score >= 40 ? 'warn' : 'danger';
  const STATUSES = window.TalentirData.STATUSES;
  const HR_USERS = window.TalentirData.HR_USERS;
  const assignedHR = HR_USERS.find(h => h.id === candidate.assignedTo);

  const setStat = (s) => { setStatus(s); onUpdate({ ...candidate, status: s }); };
  const setAsg = (hrId) => { onUpdate({ ...candidate, assignedTo: hrId }); setShowAsg(false); };

  const [emailMsg, setEmailMsg] = useStateD(null);
  const sendEmail = async () => {
    if (!candidate.email) { setEmailMsg('Kandidat tidak punya email.'); setTimeout(() => setEmailMsg(null), 4000); return; }
    setEmailMsg('Mengirim…');
    try {
      const r = await window.TalentirAPI.post('/api/email', {
        to: candidate.email,
        subject: `Update lamaran — ${job?.title || 'Talentir'}`,
        text: `Halo ${candidate.name.split(' ')[0]},\n\nTerima kasih telah melamar posisi ${job?.title || ''}. Tim kami akan menghubungi Anda untuk langkah selanjutnya.\n\nSalam,\nTim Rekrutmen`,
      });
      setEmailMsg(r.mode === 'smtp' ? `✓ Email terkirim ke ${candidate.email}` : `Mode dev: email belum dikirim sungguhan (atur SMTP di server).`);
    } catch (e) { console.error(e); setEmailMsg('Gagal mengirim email.'); }
    setTimeout(() => setEmailMsg(null), 5000);
  };

  const sendWa = async () => {
    if (!candidate.phone) { setEmailMsg('Kandidat tidak punya nomor WhatsApp.'); setTimeout(() => setEmailMsg(null), 4000); return; }
    setEmailMsg('Menambahkan ke antrian WhatsApp…');
    try {
      await window.TalentirAPI.post('/api/candidates/' + candidate.id + '/wa-send', {
        content: `Halo ${candidate.name.split(' ')[0]}, ini dari tim rekrutmen ${job?.title ? 'untuk posisi ' + job.title : ''}. Boleh kami lanjutkan proses Anda?`,
      });
      setEmailMsg('✓ Masuk antrian WhatsApp — terkirim saat WhatsApp Bot terhubung.');
    } catch (e) { console.error(e); setEmailMsg('Gagal menambahkan ke antrian WhatsApp.'); }
    setTimeout(() => setEmailMsg(null), 6000);
  };

  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="drawer">
        {/* Header */}
        <div className="drawer-head">
          <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
            <Avatar name={candidate.name} size="lg"/>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <h2 style={{ margin: 0, fontSize: 20, letterSpacing: '-0.02em' }}>{candidate.name}</h2>
                <Source src={candidate.source}/>
                <Badge>{(window.TalentirData.SOURCES[candidate.source] || {}).label || candidate.source}</Badge>
              </div>
              <div style={{ color: 'var(--muted)', fontSize: 13, marginTop: 3 }}>
                Melamar untuk <strong style={{ color: 'var(--ink-2)' }}>{job?.title || '—'}</strong> · {candidate.appliedAt}
              </div>
              <div style={{ display: 'flex', gap: 18, marginTop: 14, alignItems: 'center' }}>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 120 }}>
                  <div style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--muted)', textTransform: 'uppercase', fontWeight: 700 }}>AI Match Score</div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                    <span className={'mono v ' + cls} style={{ fontSize: 30, fontWeight: 700, color: cls === 'good' ? 'oklch(0.45 0.13 155)' : cls === 'warn' ? 'oklch(0.5 0.13 70)' : cls === 'danger' ? 'oklch(0.5 0.17 25)' : 'var(--ink)' }}>{candidate.score}</span>
                    <span className="mono" style={{ color: 'var(--faint)', fontSize: 14 }}>/ 100</span>
                  </div>
                  <ScoreBar value={candidate.score}/>
                </div>
                <div style={{ height: 50, width: 1, background: 'var(--border)' }}/>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                  <div style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--muted)', textTransform: 'uppercase', fontWeight: 700 }}>Stage</div>
                  <select className="select" style={{ width: 'auto' }} value={status} onChange={(e) => setStat(e.target.value)}>
                    {STATUSES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                  </select>
                </div>
                <div style={{ height: 50, width: 1, background: 'var(--border)' }}/>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 5, position: 'relative' }}>
                  <div style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--muted)', textTransform: 'uppercase', fontWeight: 700 }}>Ditugaskan ke</div>
                  <button className="btn sm" onClick={() => setShowAsg(!showAsg)} style={{ minWidth: 150, justifyContent: 'flex-start' }}>
                    {assignedHR ? <>
                      <HRAvatar hr={assignedHR} size={18}/>
                      <span style={{ flex: 1, textAlign: 'left' }}>{assignedHR.name.split(' ')[0]} {assignedHR.name.split(' ')[1] ? assignedHR.name.split(' ')[1][0] + '.' : ''}</span>
                    </> : <>
                      <span style={{ width: 18, height: 18, borderRadius: 99, background: 'oklch(0.97 0.02 30)', color: 'oklch(0.5 0.13 30)', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 11 }}>?</span>
                      <span style={{ flex: 1, textAlign: 'left' }}>Belum dibagi</span>
                    </>}
                    <Icon name="chevronD" size={11}/>
                  </button>
                  {showAsg && (
                    <div style={{
                      position: 'absolute', top: '100%', left: 0, marginTop: 4,
                      background: 'var(--surface)', border: '1px solid var(--border)',
                      borderRadius: 8, boxShadow: 'var(--shadow-lg)',
                      minWidth: 240, zIndex: 5, padding: 4,
                    }}>
                      <button className="btn ghost sm" style={{ width: '100%', justifyContent: 'flex-start', padding: '8px 10px' }} onClick={() => setAsg(null)}>
                        <span style={{ width: 18, height: 18, borderRadius: 99, background: 'oklch(0.97 0.02 30)', color: 'oklch(0.5 0.13 30)', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 11 }}>?</span>
                        Belum dibagi
                      </button>
                      <div style={{ height: 1, background: 'var(--border)', margin: '4px 0' }}/>
                      {HR_USERS.filter(h => !h.isOwner).map(hr => (
                        <button key={hr.id} className="btn ghost sm" style={{ width: '100%', justifyContent: 'flex-start', padding: '8px 10px', textAlign: 'left' }} onClick={() => setAsg(hr.id)}>
                          <HRAvatar hr={hr} size={20}/>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontWeight: 600, fontSize: 12.5 }}>{hr.name}</div>
                            <div style={{ fontSize: 10.5, color: 'var(--muted)' }}>{hr.branch}</div>
                          </div>
                          {candidate.assignedTo === hr.id && <Icon name="check" size={12} stroke={2.5} style={{ color: 'var(--accent)' }}/>}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
            <button className="btn icon ghost" onClick={onClose} aria-label="Tutup">
              <Icon name="x" size={16}/>
            </button>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <Btn kind="primary" icon="clock" size="sm" onClick={() => onSchedule && onSchedule(candidate)}>Undang Wawancara</Btn>
            <Btn kind="wa" icon="message" size="sm" onClick={sendWa}>Pesan WhatsApp</Btn>
            <Btn icon="mail" size="sm" onClick={sendEmail}>Kirim Email</Btn>
            <Btn icon="file" size="sm" onClick={() => onPapi && onPapi(candidate)}>Tes PAPI</Btn>
            <div style={{ flex: 1 }}/>
            <Btn icon="download" size="sm" kind="ghost">Export PDF</Btn>
          </div>
          {emailMsg && <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 6 }}>{emailMsg}</div>}
        </div>

        {/* Tabs — Chat WhatsApp only appears when this candidate has actual
            messages, so we don't show an empty thread or any dummy content. */}
        <div className="drawer-tabs">
          {[
            ['profil', 'Profil'],
            ['ai',     'Analisa AI'],
            ['cv',     'CV & Lamaran'],
            ['form',   'Jawaban Form'],
            ...(waLogs && waLogs.length > 0 ? [['chat', 'Chat WhatsApp', waLogs.length]] : []),
          ].map(([id, label, ct]) => (
            <button key={id} className={'tab ' + (tab === id ? 'active' : '')} onClick={() => setTab(id)}>
              {label}{ct ? <span className="ct">{ct}</span> : null}
            </button>
          ))}
        </div>

        {/* Body */}
        <div className="drawer-body">
          {tab === 'profil' && <ProfilTab c={candidate}/>}
          {tab === 'ai'     && <AITab c={candidate} onUpdate={onUpdate}/>}
          {tab === 'cv'     && <CVTab c={candidate} onUpdate={onUpdate}/>}
          {tab === 'form'   && <FormTab c={candidate}/>}
          {tab === 'chat'   && <ChatTab c={candidate} logs={waLogs} onReload={reloadWaLogs}/>}
        </div>
      </div>
    </>
  );
}

// Format an expected-salary string ("1000000") as "Rp 1.000.000".
const fmtRupiah = (v) => {
  const n = Number(String(v).replace(/[^\d]/g, ''));
  return Number.isFinite(n) && n > 0 ? 'Rp ' + n.toLocaleString('id-ID') : v;
};

const ProfilTab = ({ c }) => {
  const edu = [c.educationLevel, c.educationMajor].filter(Boolean).join(' · ');
  const hasCareer = c.currentPosition || c.currentCompany || (c.previousPositions && c.previousPositions.length) || c.expectedSalary;
  const hasEducation = edu || c.educationInstitution;
  return (
    <div className="col-flex" style={{ gap: 20 }}>
      <div className="card card-pad">
        <div className="section-title" style={{ marginBottom: 12 }}>Kontak & Data Diri</div>
        <dl className="kv">
          <dt>Email</dt><dd>{c.email}</dd>
          <dt>WhatsApp</dt><dd>{c.phone} {c.hasWA && <Badge kind="wa" style={{marginLeft: 6}}><Icon name="message" size={10}/>Terhubung</Badge>}</dd>
          <dt>Domisili</dt><dd>{c.location}</dd>
          {c.distanceFromOfficeKm != null && (
            <><dt>Jarak ke kantor</dt><dd>{c.distanceFromOfficeKm} km {c.willingToRelocate && <Badge kind="good" style={{ marginLeft: 6 }}>Bersedia relokasi</Badge>}</dd></>
          )}
          {c.gender && <><dt>Jenis kelamin</dt><dd>{c.gender}</dd></>}
          <dt>Usia</dt><dd>{c.age} tahun</dd>
          <dt>Pengalaman</dt><dd>{c.experience}</dd>
          {c.sourceStatus && <><dt>Status sumber</dt><dd><Badge>{c.sourceStatus}</Badge> {c.source && <span style={{ color: 'var(--muted)', fontSize: 12 }}>via {c.source}</span>}</dd></>}
          <dt>Tagged</dt>
          <dd style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {c.tags.map(t => <Badge key={t}>{t}</Badge>)}
          </dd>
        </dl>
      </div>

      {(hasEducation || hasCareer) && (
        <div className="card card-pad">
          <div className="section-title" style={{ marginBottom: 12 }}>Pendidikan & Karier</div>
          <dl className="kv">
            {hasEducation && <><dt>Pendidikan</dt><dd>{[edu, c.educationInstitution].filter(Boolean).join(' — ')}</dd></>}
            {(c.currentPosition || c.currentCompany) && (
              <><dt>Posisi sekarang</dt><dd>{[c.currentPosition, c.currentCompany].filter(Boolean).join(' di ')}</dd></>
            )}
            {c.previousPositions && c.previousPositions.length > 0 && (
              <><dt>Posisi sebelumnya</dt>
                <dd style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>{c.previousPositions.map((p, i) => <Badge key={i}>{p}</Badge>)}</dd></>
            )}
            {c.expectedSalary && <><dt>Ekspektasi gaji</dt><dd>{fmtRupiah(c.expectedSalary)}<span style={{ color: 'var(--muted)', fontSize: 12 }}> / bulan</span></dd></>}
          </dl>
        </div>
      )}

      <NotesCard c={c}/>
    </div>
  );
};

// Internal recruiter notes — persisted to the candidate via PATCH.
function NotesCard({ c }) {
  const [notes, setNotes] = useStateD(c.notes || '');
  const [saving, setSaving] = useStateD(false);
  const [saved, setSaved] = useStateD(false);
  const dirty = notes !== (c.notes || '');
  const save = async () => {
    setSaving(true); setSaved(false);
    try {
      await window.TalentirAPI.patch('/api/candidates/' + c.id, { notes });
      c.notes = notes; // reflect into the in-memory candidate
      setSaved(true); setTimeout(() => setSaved(false), 2000);
    } catch (e) { console.error('Gagal menyimpan catatan:', e); }
    setSaving(false);
  };
  return (
    <div className="card card-pad">
      <div className="section-title" style={{ marginBottom: 10 }}>Catatan Internal Rekruter</div>
      <textarea className="textarea" placeholder="Tulis catatan tim soal kandidat ini…"
        value={notes} onChange={(e) => setNotes(e.target.value)}/>
      <div style={{ marginTop: 10, display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 8 }}>
        {saved && <span style={{ fontSize: 12, color: 'oklch(0.55 0.13 155)', fontWeight: 600 }}><Icon name="check" size={12} stroke={2.5}/> Tersimpan</span>}
        <Btn size="sm" kind="accent" onClick={save} disabled={saving || !dirty}>{saving ? 'Menyimpan…' : 'Simpan Catatan'}</Btn>
      </div>
    </div>
  );
}

const AITab = ({ c, onUpdate }) => {
  const cls = c.score >= 80 ? 'good' : c.score >= 60 ? '' : 'warn';
  const [busy, setBusy] = useStateD(false);
  const [info, setInfo] = useStateD(null);

  const rescreen = async () => {
    setBusy(true); setInfo(null);
    try {
      const r = await window.TalentirAPI.post('/api/candidates/' + c.id + '/rescreen', {});
      // Use r.candidate as the source of truth — backend may have auto-staged
      // the candidate (e.g. score crossed passThreshold → wawancara-hr).
      onUpdate && onUpdate({ ...c, ...(r.candidate || {}), score: r.score, aiSummary: r.summary });
      setInfo({ provider: r.provider, model: r.model, score: r.score, autoStaged: r.autoStaged });
    } catch (e) { console.error(e); setInfo({ error: true }); }
    setBusy(false);
  };

  return (
    <div className="col-flex" style={{ gap: 16 }}>
      <div className="ai-block">
        <div className="lbl" style={{ display: 'flex', alignItems: 'center' }}>
          <Icon name="sparkles" size={12}/>Ringkasan AI
          <span style={{ flex: 1 }}/>
          <button className="btn ghost sm" style={{ padding: '3px 8px' }} onClick={rescreen} disabled={busy}>
            <Icon name="sparkles" size={11}/> {busy ? 'Menilai…' : 'Nilai ulang dengan AI'}
          </button>
        </div>
        <div className="body">
          {c.aiSummary
            ? c.aiSummary
            : <>{c.name.split(' ')[0]} menunjukkan profil yang <strong>{c.score >= 75 ? 'sangat relevan' : c.score >= 55 ? 'cukup relevan' : 'kurang sesuai'}</strong> untuk posisi ini.
                Berdasarkan analisa CV{c.hasWA ? ', jawaban form, dan interview WhatsApp' : ' dan jawaban form'},
                AI menemukan kecocokan kuat di kemampuan komunikasi dan domain knowledge, dengan beberapa gap di area teknis tertentu.</>}
        </div>
        {info && !info.error && (
          <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 8 }}>
            Skor diperbarui ke <strong>{info.score}</strong> · sumber: {info.provider === 'heuristic' ? 'heuristik (set API key di Pengaturan untuk AI penuh)' : `${info.provider} ${info.model || ''}`}
            {info.autoStaged && <> · auto-pindah ke <strong>{(window.TalentirData.STATUSES.find(s => s.id === info.autoStaged)?.name) || info.autoStaged}</strong></>}
          </div>
        )}
        {info && info.error && <div style={{ fontSize: 11.5, color: 'oklch(0.55 0.18 25)', marginTop: 8 }}>Gagal menilai ulang. Coba lagi.</div>}
      </div>

      <div className="card card-pad">
        <div className="section-title" style={{ marginBottom: 12 }}>Breakdown Skor</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            ['Relevansi pengalaman', Math.min(98, c.score + 6)],
            ['Skill match (teknis)', Math.max(20, c.score - 8)],
            ['Komunikasi & soft skill', Math.min(96, c.score + 12)],
            ['Kelengkapan & responsivitas', Math.min(99, c.score + 18)],
          ].map(([k, v]) => (
            <div key={k} style={{ display: 'grid', gridTemplateColumns: '180px 1fr 36px', gap: 12, alignItems: 'center', fontSize: 13 }}>
              <div style={{ color: 'var(--ink-2)' }}>{k}</div>
              <ScoreBar value={v}/>
              <div className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>{v}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="card card-pad">
        <div className="section-title" style={{ marginBottom: 10 }}>Keunggulan terdeteksi</div>
        <ul style={{ margin: 0, paddingLeft: 18, color: 'var(--ink-2)' }}>
          <li>Pengalaman {c.experience} di industri terkait, sesuai requirement minimum.</li>
          <li>Menggunakan terminologi profesional yang konsisten saat menjawab pertanyaan studi kasus.</li>
          {c.hasWA && <li>Responsif via WhatsApp (rata-rata reply 2 menit), menunjukkan kebiasaan komunikasi proaktif.</li>}
          <li>Tagged: {c.tags.join(', ')}.</li>
        </ul>
      </div>

      <div className="card card-pad">
        <div className="section-title" style={{ marginBottom: 10 }}>Area yang perlu diklarifikasi</div>
        <ul style={{ margin: 0, paddingLeft: 18, color: 'var(--ink-2)' }}>
          <li>Tidak ada penjelasan eksplisit terkait pengalaman dengan tooling spesifik (lihat requirement #3).</li>
          <li>Notice period kandidat {c.score % 2 ? '1 bulan' : '2 minggu'} — perlu konfirmasi timeline onboarding.</li>
          <li>Salary expectation belum dieksplorasi dalam interview otomatis.</li>
        </ul>
      </div>
    </div>
  );
};

const CVTab = ({ c, onUpdate }) => {
  const [uploading, setUploading] = useStateD(false);
  const fileUrl = c.cvUrl ? window.TalentirAPI.base + c.cvUrl : null;

  const uploadCv = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const r = await fetch(window.TalentirAPI.base + '/api/candidates/' + c.id + '/cv', {
        method: 'POST', credentials: 'include', body: fd,
      }).then((res) => res.json());
      if (r.url) onUpdate && onUpdate({ ...c, cvUrl: r.url, hasCV: true });
    } catch (err) { console.error('Gagal unggah CV:', err); }
    setUploading(false);
  };

  return (
  <div className="col-flex" style={{ gap: 14 }}>
    {!fileUrl && (
      <div className="card card-pad" style={{ textAlign: 'center', padding: 32 }}>
        <Icon name="cv" size={28}/>
        <div style={{ fontWeight: 700, marginTop: 10 }}>Belum ada file CV</div>
        <div style={{ color: 'var(--muted)', fontSize: 13, marginTop: 4, marginBottom: 14 }}>
          {c.hasWA ? 'Kandidat lamar via WhatsApp/chat — data diekstrak ke profil.' : 'Unggah CV (PDF) untuk disimpan di profil kandidat.'}
        </div>
        <label className="btn accent" style={{ cursor: 'pointer' }}>
          <Icon name="download" size={14}/> {uploading ? 'Mengunggah…' : 'Unggah CV'}
          <input type="file" accept=".pdf,.doc,.docx,.txt" style={{ display: 'none' }} onChange={uploadCv} disabled={uploading}/>
        </label>
      </div>
    )}
    {fileUrl && <>
      <div className="row-flex" style={{ justifyContent: 'space-between' }}>
        <div className="row-flex">
          <Icon name="cv" size={16}/>
          <strong>CV {c.name.split(' ')[0]}</strong>
          <span style={{ color: 'var(--muted)', fontSize: 12 }}>· diunggah</span>
        </div>
        <div className="row-flex">
          <a className="btn sm" href={fileUrl} download><Icon name="download" size={13}/>Unduh</a>
          <a className="btn sm" href={fileUrl} target="_blank" rel="noopener"><Icon name="eye" size={13}/>Lihat asli</a>
        </div>
      </div>
      <div className="card card-pad">
        <div className="section-title" style={{ marginBottom: 12 }}>Hasil Ekstraksi AI</div>
        <dl className="kv">
          <dt>Posisi terakhir</dt><dd>{['Senior Coordinator', 'Team Lead', 'Specialist', 'Officer'][c.id.length % 4]}</dd>
          <dt>Perusahaan</dt><dd>{['PT Sinar Jaya', 'Tokopedia', 'Astra International', 'Bank Mandiri'][c.id.length % 4]}</dd>
          <dt>Durasi</dt><dd>{c.experience} pengalaman terhitung</dd>
          <dt>Pendidikan</dt><dd>S1 {['Manajemen', 'Komunikasi', 'Sistem Informasi', 'Desain'][c.id.length % 4]} · Universitas Indonesia</dd>
          <dt>Lokasi tinggal</dt><dd>{c.location}</dd>
          <dt>Skill kunci</dt>
          <dd style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {c.tags.map(t => <Badge key={t}>{t}</Badge>)}
            <Badge>Bahasa Indonesia (native)</Badge>
            <Badge>English (intermediate)</Badge>
          </dd>
        </dl>
      </div>
    </>}
  </div>
  );
};

const FormTab = ({ c }) => {
  const answers = [
    { q: 'Berapa tahun pengalaman Anda di bidang ini?', a: c.experience + ' (dengan pengalaman bertahap di 2 perusahaan)' },
    { q: 'Kapan Anda bisa mulai bekerja?', a: c.score % 2 === 0 ? 'Segera (immediate)' : 'Setelah 1 bulan notice period' },
    { q: 'Ekspektasi gaji bulanan?', a: 'Rp ' + (5 + c.score % 5) + ',5 jt — Rp ' + (7 + c.score % 4) + ' jt (negotiable)' },
    { q: 'Pilih tools yang Anda kuasai (multi):', a: ['Excel', 'Google Workspace', 'Notion', 'Slack', 'Zendesk'].slice(0, 3 + c.score % 3).join(', ') },
    { q: 'Ceritakan situasi tersulit yang pernah Anda tangani.', a: 'Saat handle eskalasi customer dengan volume tiket tinggi pasca system outage. Saya koordinasi dengan tim teknis untuk update status realtime, sambil menjaga ekspektasi customer lewat broadcast & 1-on-1 follow up.' },
  ];
  return (
    <div className="col-flex" style={{ gap: 12 }}>
      <div style={{ color: 'var(--muted)', fontSize: 13 }}>5 dari 5 pertanyaan terjawab · disubmit {c.appliedAt}</div>
      {answers.map((it, i) => (
        <div key={i} className="card card-pad">
          <div style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 700, marginBottom: 5 }}>Q{i+1}</div>
          <div style={{ fontWeight: 700, marginBottom: 8 }}>{it.q}</div>
          <div style={{ color: 'var(--ink-2)', fontSize: 13.5 }}>{it.a}</div>
        </div>
      ))}
    </div>
  );
};

const ChatTab = ({ c, logs, onReload }) => {
  // Still loading the real conversation from the API.
  if (logs === null) {
    return <div className="empty"><div>Memuat percakapan…</div></div>;
  }
  // No messages — hide the chat surface entirely instead of showing dummy
  // bubbles, exactly what the user asked for.
  if (logs.length === 0) {
    return (
      <div className="empty">
        <Icon name="message" size={28}/>
        <div style={{ fontWeight: 700, marginTop: 10, color: 'var(--ink)' }}>Belum ada percakapan WhatsApp</div>
        <div>Kirim pesan pertama dari tombol <b>Pesan WhatsApp</b> di atas, atau dari halaman WhatsApp.</div>
      </div>
    );
  }

  const [draft, setDraft] = useStateD('');
  const [sending, setSending] = useStateD(false);
  const send = async () => {
    const content = draft.trim();
    if (!content) return;
    setSending(true);
    try {
      await window.TalentirAPI.post('/api/candidates/' + c.id + '/wa-send', { content });
      setDraft('');
      if (onReload) await onReload();
    } catch (e) { console.error('Gagal mengirim:', e); }
    setSending(false);
  };

  const fmtTime = (ms) => {
    const d = new Date(ms);
    return d.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' });
  };

  return (
    <div className="card" style={{ overflow: 'hidden' }}>
      <div className="wa-thread" style={{ height: 520 }}>
        <div className="wa-head">
          <Avatar name={c.name}/>
          <div>
            <div style={{ fontWeight: 700, fontSize: 13 }}>{c.name}</div>
            <div style={{ fontSize: 11, color: 'var(--muted)' }}>{c.phone} · {logs.length} pesan</div>
          </div>
          <div style={{ flex: 1 }}/>
          <Badge kind="good"><Icon name="check" size={10}/>Sinkron</Badge>
        </div>
        <div className="wa-msgs">
          {logs.map((m) => (
            <div key={m.id} className={'bubble ' + (m.direction === 'outbound' ? 'out' : 'in')}>
              {m.voice ? (
                <div className="vn">
                  <Icon name="play" size={14}/>
                  <div className="wave"/>
                  <span className="mono" style={{ fontSize: 10 }}>🎤</span>
                </div>
              ) : (
                <span style={{ whiteSpace: 'pre-wrap' }}>{m.content}</span>
              )}
              <span className="ts">{fmtTime(m.createdAt)}</span>
              {m.transcript && <div style={{ borderTop: '1px solid oklch(0 0 0 / 0.07)', marginTop: 6, paddingTop: 6, fontStyle: 'italic', color: 'var(--muted)', fontSize: 11.5 }}>
                <span style={{ fontWeight: 700, color: 'var(--ink-2)' }}>Transkrip AI:</span> "{m.transcript}"
              </div>}
              {m.aiAnalysis?.imageDescription && <div style={{ borderTop: '1px solid oklch(0 0 0 / 0.07)', marginTop: 6, paddingTop: 6, fontStyle: 'italic', color: 'var(--muted)', fontSize: 11.5 }}>
                <span style={{ fontWeight: 700, color: 'var(--ink-2)' }}>Deskripsi AI:</span> {m.aiAnalysis.imageDescription}
              </div>}
              {m.aiAnalysis?.documentText && <div style={{ borderTop: '1px solid oklch(0 0 0 / 0.07)', marginTop: 6, paddingTop: 6, color: 'var(--muted)', fontSize: 11.5, maxHeight: 120, overflow: 'auto' }}>
                <span style={{ fontWeight: 700, color: 'var(--ink-2)' }}>Isi dokumen:</span> {String(m.aiAnalysis.documentText).slice(0, 400)}{String(m.aiAnalysis.documentText).length > 400 ? '…' : ''}
              </div>}
            </div>
          ))}
        </div>
        <div className="wa-compose">
          <input className="input" placeholder="Tulis pesan ke kandidat… (manual override bot)" value={draft}
                 onChange={(e) => setDraft(e.target.value)}
                 onKeyDown={(e) => { if (e.key === 'Enter' && !sending) send(); }}
                 disabled={sending} style={{ flex: 1, border: 'none', background: 'transparent', padding: '0 8px' }}/>
          <Btn kind="wa" icon="message" size="sm" onClick={send} disabled={sending || !draft.trim()}>
            {sending ? '…' : 'Kirim'}
          </Btn>
        </div>
      </div>
    </div>
  );
};

window.CandidateDrawer = CandidateDrawer;
