// Database Kandidat — a single sortable/filterable table of every candidate
// registered in the workspace (across all jobs & sources).

function CandidatesView({ candidates, openCandidate, go }) {
  const { JOBS, HR_USERS, STATUSES, SOURCES } = window.TalentirData;

  const [query, setQuery] = useState('');
  const [fStatus, setFStatus] = useState('all');
  const [fJob, setFJob] = useState('all');
  const [fSource, setFSource] = useState('all');
  const [sortKey, setSortKey] = useState('score'); // score | name | appliedAt | status
  const [sortDir, setSortDir] = useState('desc');   // asc | desc

  const jobTitle = (id) => (JOBS.find(j => j.id === id) || {}).title || '—';
  const hrName = (id) => (HR_USERS.find(h => h.id === id) || {}).name || null;

  const toggleSort = (key) => {
    if (sortKey === key) setSortDir(d => (d === 'asc' ? 'desc' : 'asc'));
    else { setSortKey(key); setSortDir(key === 'name' ? 'asc' : 'desc'); }
  };

  const rows = useMemo(() => {
    const q = query.trim().toLowerCase();
    let list = candidates.filter(c => {
      if (fStatus !== 'all' && c.status !== fStatus) return false;
      if (fJob !== 'all' && c.jobId !== fJob) return false;
      if (fSource !== 'all' && c.source !== fSource) return false;
      if (q) {
        const hay = [c.name, c.email, c.phone, c.location, jobTitle(c.jobId)].filter(Boolean).join(' ').toLowerCase();
        if (!hay.includes(q)) return false;
      }
      return true;
    });
    const dir = sortDir === 'asc' ? 1 : -1;
    list = [...list].sort((a, b) => {
      let av, bv;
      if (sortKey === 'name') { av = (a.name || '').toLowerCase(); bv = (b.name || '').toLowerCase(); }
      else if (sortKey === 'appliedAt') { av = a.appliedAt || ''; bv = b.appliedAt || ''; }
      else if (sortKey === 'status') { av = a.status || ''; bv = b.status || ''; }
      else { av = a.score ?? 0; bv = b.score ?? 0; }
      return av < bv ? -dir : av > bv ? dir : 0;
    });
    return list;
  }, [candidates, query, fStatus, fJob, fSource, sortKey, sortDir]);

  const exportCsv = () => {
    const cols = ['Nama', 'Email', 'WhatsApp', 'Posisi', 'Sumber', 'Status', 'Skor AI', 'Lokasi', 'Usia', 'Pengalaman', 'HR', 'Tanggal Daftar'];
    const esc = (v) => {
      const s = v == null ? '' : String(v);
      return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
    };
    const lines = [cols.join(',')];
    for (const c of rows) {
      lines.push([
        c.name, c.email, c.phone, jobTitle(c.jobId),
        (SOURCES[c.source] || {}).label || c.source,
        (STATUSES.find(s => s.id === c.status) || {}).name || c.status,
        c.score, c.location, c.age, c.experience, hrName(c.assignedTo) || 'Belum dibagi', c.appliedAt,
      ].map(esc).join(','));
    }
    const blob = new Blob(['﻿' + lines.join('\n')], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `kandidat-talentir-${new Date().toISOString().slice(0, 10)}.csv`;
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  const SortTh = ({ k, children, style }) => (
    <th style={{ cursor: 'pointer', userSelect: 'none', ...style }} onClick={() => toggleSort(k)}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
        {children}
        {sortKey === k && <Icon name={sortDir === 'asc' ? 'chevronD' : 'chevron'} size={11} style={{ transform: sortDir === 'asc' ? 'rotate(180deg)' : 'rotate(90deg)' }}/>}
      </span>
    </th>
  );

  return (
    <div className="view">
      <div className="view-head">
        <div>
          <div className="title">Database Kandidat</div>
          <div className="subtitle">Seluruh kandidat yang terdaftar di workspace — dari semua lowongan & sumber. Klik baris untuk membuka profil.</div>
        </div>
        <div className="row-flex">
          <Btn icon="download" onClick={exportCsv} disabled={rows.length === 0}>Export CSV</Btn>
          <Btn kind="accent" icon="download" onClick={() => go({ view: 'import' })}>Import Kandidat</Btn>
        </div>
      </div>

      {/* Toolbar: search + filters */}
      <div className="row-flex" style={{ gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
        <div className="row-flex" style={{ gap: 6, flex: 1, minWidth: 220, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: '6px 10px' }}>
          <Icon name="search" size={14}/>
          <input style={{ border: 0, outline: 0, background: 'transparent', flex: 1, fontSize: 13 }}
                 placeholder="Cari nama, email, telepon, lokasi…" value={query} onChange={(e) => setQuery(e.target.value)}/>
          {query && <button className="btn icon ghost" style={{ padding: 2 }} onClick={() => setQuery('')}><Icon name="x" size={12}/></button>}
        </div>
        <select className="select" style={{ width: 'auto' }} value={fStatus} onChange={(e) => setFStatus(e.target.value)}>
          <option value="all">Semua status</option>
          {STATUSES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
        </select>
        <select className="select" style={{ width: 'auto' }} value={fJob} onChange={(e) => setFJob(e.target.value)}>
          <option value="all">Semua posisi</option>
          {JOBS.map(j => <option key={j.id} value={j.id}>{j.title}</option>)}
        </select>
        <select className="select" style={{ width: 'auto' }} value={fSource} onChange={(e) => setFSource(e.target.value)}>
          <option value="all">Semua sumber</option>
          {Object.entries(SOURCES).map(([k, s]) => <option key={k} value={k}>{s.label}</option>)}
        </select>
      </div>

      <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 8 }}>
        Menampilkan <b style={{ color: 'var(--ink-2)' }}>{rows.length}</b> dari {candidates.length} kandidat
      </div>

      <div className="card" style={{ overflow: 'auto' }}>
        <table className="tbl">
          <thead>
            <tr>
              <SortTh k="name" style={{ width: '24%' }}>Kandidat</SortTh>
              <th>Posisi</th>
              <th style={{ width: 90 }}>Sumber</th>
              <SortTh k="status" style={{ width: 110 }}>Status</SortTh>
              <SortTh k="score" style={{ width: 130 }}>Skor AI</SortTh>
              <th>Lokasi</th>
              <th style={{ width: 90 }}>HR</th>
              <SortTh k="appliedAt" style={{ width: 110 }}>Daftar</SortTh>
              <th style={{ width: 70 }}>Berkas</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && (
              <tr><td colSpan={9} style={{ textAlign: 'center', color: 'var(--muted)', padding: '28px 0' }}>Tidak ada kandidat yang cocok dengan filter.</td></tr>
            )}
            {rows.map(c => {
              const hr = HR_USERS.find(h => h.id === c.assignedTo);
              return (
                <tr key={c.id} style={{ cursor: 'pointer' }} onClick={() => openCandidate(c)}>
                  <td>
                    <div className="row-flex">
                      <Avatar name={c.name}/>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.name}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.email || c.phone || '—'}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ fontSize: 13 }}>{jobTitle(c.jobId)}</td>
                  <td><Source src={c.source}/></td>
                  <td><StatusBadge status={c.status}/></td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span className="mono" style={{ fontWeight: 700, fontSize: 13, width: 24 }}>{c.score}</span>
                      <div style={{ flex: 1 }}><ScoreBar value={c.score}/></div>
                    </div>
                  </td>
                  <td style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{c.location || '—'}</td>
                  <td>{hr ? <HRAvatar hr={hr} size={22}/> : <span style={{ fontSize: 11.5, color: 'var(--muted)' }}>Belum dibagi</span>}</td>
                  <td className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>{c.appliedAt || '—'}</td>
                  <td>
                    <div style={{ display: 'flex', gap: 4 }}>
                      {c.hasWA && <span title="WhatsApp terhubung" style={{ color: 'var(--wa)' }}><Icon name="message" size={13}/></span>}
                      {c.hasCV && <span title="CV tersedia" style={{ color: 'var(--accent)' }}><Icon name="file" size={13}/></span>}
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.CandidatesView = CandidatesView;
