// Command palette (⌘K / Ctrl+K). Jump to any page, run a quick action, or open
// a candidate by name. Rendered by <App/>; opened via the topbar search box or
// the global ⌘K listener. Theme-aware (uses CSS tokens, works in dark mode).

const CMD_DESTINATIONS = [
  { label: 'Dashboard', icon: 'home', view: 'dashboard' },
  { label: 'Inbox', icon: 'message', view: 'inbox' },
  { label: 'Lowongan', icon: 'briefcase', view: 'jobs' },
  { label: 'Kandidat', icon: 'layout', view: 'candidates' },
  { label: 'Kalender', icon: 'clock', view: 'calendar' },
  { label: 'Tim HR', icon: 'users', view: 'team' },
  { label: 'Import Kandidat', icon: 'download', view: 'import' },
  { label: 'Pencarian AI', icon: 'sparkles', view: 'search' },
  { label: 'Psikotes', icon: 'file', view: 'papi' },
  { label: 'WhatsApp Bot', icon: 'message', view: 'whatsapp' },
  { label: 'Halaman Publik', icon: 'globe', view: 'public' },
  { label: 'Pengaturan', icon: 'settings', view: 'settings' },
];

function toggleTheme() {
  const next = !document.documentElement.classList.contains('dark');
  document.documentElement.classList.toggle('dark', next);
  try { localStorage.setItem('talentir_theme', next ? 'dark' : 'light'); } catch (_) {}
}

function CmdPalette({ open, onClose, go, candidates, openCandidate }) {
  const [q, setQ] = useState('');
  const [sel, setSel] = useState(0);
  const inputRef = useRef(null);

  useEffect(() => {
    if (open) { setQ(''); setSel(0); setTimeout(() => inputRef.current && inputRef.current.focus(), 20); }
  }, [open]);

  if (!open) return null;
  const ql = q.trim().toLowerCase();

  const actions = [
    { label: 'Buat Posisi Baru', icon: 'plus', run: () => go({ view: 'jobs', subview: 'new' }) },
    { label: 'Ganti mode terang / gelap', icon: 'moon', run: toggleTheme },
  ];

  const dest = CMD_DESTINATIONS
    .filter(d => !ql || d.label.toLowerCase().includes(ql))
    .map(d => ({ ...d, kind: 'Navigasi', onRun: () => { go({ view: d.view }); onClose(); } }));
  const acts = actions
    .filter(a => !ql || a.label.toLowerCase().includes(ql))
    .map(a => ({ ...a, kind: 'Aksi', onRun: () => { a.run(); onClose(); } }));
  const cands = ql.length >= 2
    ? (candidates || []).filter(c => (c.name || '').toLowerCase().includes(ql)).slice(0, 6)
        .map(c => ({ label: c.name, sub: c.jobTitle || c.position || c.location || '', icon: 'user', kind: 'Kandidat',
                     onRun: () => { onClose(); openCandidate && openCandidate(c); } }))
    : [];

  const items = [...dest, ...acts, ...cands];
  const cur = Math.min(sel, Math.max(0, items.length - 1));

  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setSel(s => Math.min(s + 1, items.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setSel(s => Math.max(s - 1, 0)); }
    else if (e.key === 'Enter') { e.preventDefault(); if (items[cur]) items[cur].onRun(); }
    else if (e.key === 'Escape') { e.preventDefault(); onClose(); }
  };

  let lastKind = null;
  return (
    <div className="cmdk-scrim" onClick={onClose}>
      <div className="cmdk" onClick={(e) => e.stopPropagation()} onKeyDown={onKey}>
        <div className="cmdk-head">
          <Icon name="search" size={16}/>
          <input ref={inputRef} className="cmdk-input" placeholder="Cari halaman, aksi, atau kandidat…"
                 value={q} onChange={(e) => { setQ(e.target.value); setSel(0); }}/>
          <kbd className="cmdk-esc">ESC</kbd>
        </div>
        <div className="cmdk-list">
          {items.length === 0 && <div className="cmdk-empty">Tidak ada hasil untuk “{q}”.</div>}
          {items.map((it, i) => {
            const showHead = it.kind !== lastKind;
            lastKind = it.kind;
            return (
              <React.Fragment key={i}>
                {showHead && <div className="cmdk-group">{it.kind}</div>}
                <div className={'cmdk-item' + (i === cur ? ' active' : '')}
                     onMouseEnter={() => setSel(i)} onClick={() => it.onRun()}>
                  <Icon name={it.icon} size={15}/>
                  <span className="cmdk-label">{it.label}</span>
                  {it.sub && <span className="cmdk-sub">{it.sub}</span>}
                  {i === cur && <kbd className="cmdk-enter">↵</kbd>}
                </div>
              </React.Fragment>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.CmdPalette = CmdPalette;
