// Command palette — Linear-style ⌘K. Filter applicants, jump to surfaces,
// run actions.

function CommandPalette({ open, onClose, applicants, setSection, openApplicant }) {
  const [q, setQ] = React.useState("");
  const [idx, setIdx] = React.useState(0);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setQ(""); setIdx(0);
      setTimeout(() => inputRef.current?.focus(), 0);
    }
  }, [open]);

  // Build candidate list
  const items = React.useMemo(() => {
    const nav = [
      { kind: "nav",     id: "queue",        label: "Pending Reviews",   icon: IUsers,    hint: "Queue · primary" },
      { kind: "nav",     id: "vitals",       label: "Compliance Ops Vitals", icon: IGraph },
      { kind: "nav",     id: "withdrawals",  label: "Withdrawal Approvals", icon: ICoins },
      { kind: "nav",     id: "coverage",     label: "Coverage Gaps",     icon: IGitMerge },
      { kind: "nav",     id: "docs",         label: "Document Expiration", icon: ICalendar },
      { kind: "nav",     id: "kyt",          label: "KYT Transactions",  icon: IBolt },
      { kind: "nav",     id: "audit",        label: "Audit Trail",       icon: ILock },
      { kind: "nav",     id: "glossary",     label: "Compliance Glossary", icon: IFile,    hint: "Hover any underlined term in the dashboard" },
      { kind: "nav",     id: "settings-thresholds", label: "Risk-Tier Thresholds", icon: ISettings },
    ];
    const apps = applicants.map(a => ({
      kind: "applicant", id: a.id, label: a.name, hint: `${a.id} · ${a.kind.toUpperCase()} · ${a.country} · ${a.action}`, icon: IUsers
    }));
    const actions = [
      { kind: "action", id: "bulk-approve",  label: "Bulk approve low-risk", icon: ICheck,    hint: "Apply to current selection" },
      { kind: "action", id: "rekyc-7d",      label: "Send re-KYC · ≤ 7d expiring", icon: ISend },
      { kind: "action", id: "export-audit",  label: "Export audit trail (CSV)", icon: IDownload },
      { kind: "action", id: "toggle-dark",   label: "Toggle dark mode", icon: ICircle },
    ];
    if (!q.trim()) return [...nav.slice(0, 4), ...actions.slice(0, 3), ...apps.slice(0, 4)];
    const ql = q.toLowerCase();
    const match = (s) => s.toLowerCase().includes(ql);
    return [...nav, ...actions, ...apps].filter(it =>
      match(it.label) || match(it.hint || "") || match(it.id)
    ).slice(0, 24);
  }, [q, applicants]);

  React.useEffect(() => { setIdx(0); }, [q]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") { e.preventDefault(); onClose(); return; }
      if (e.key === "ArrowDown") { e.preventDefault(); setIdx(i => Math.min(i + 1, items.length - 1)); }
      if (e.key === "ArrowUp")   { e.preventDefault(); setIdx(i => Math.max(i - 1, 0)); }
      if (e.key === "Enter") {
        e.preventDefault();
        const it = items[idx]; if (!it) return;
        if (it.kind === "nav")        { setSection(it.id);       onClose(); }
        else if (it.kind === "applicant") { setSection("queue"); openApplicant(it.id); onClose(); }
        else if (it.kind === "action") {
          if (it.id === "toggle-dark") {
            const r = document.documentElement;
            r.dataset.theme = r.dataset.theme === "dark" ? "light" : "dark";
          }
          onClose();
        }
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, items, idx, onClose, setSection, openApplicant]);

  if (!open) return null;

  const sections = {
    nav: items.filter(i => i.kind === "nav"),
    action: items.filter(i => i.kind === "action"),
    applicant: items.filter(i => i.kind === "applicant"),
  };

  return (
    <div className="cmdk-backdrop" onClick={onClose}>
      <div className="cmdk" onClick={e => e.stopPropagation()}>
        <div className="cmdk-search">
          <ISearch size={14} className="fg-4" />
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)}
            placeholder="Jump to applicant, withdrawal, surface, or action…" />
          <Kbd>esc</Kbd>
        </div>
        <div className="cmdk-results">
          {sections.nav.length > 0 && <>
            <div className="cmdk-section">Navigate</div>
            {sections.nav.map(it => <CmdItem key={it.id} it={it} active={items.indexOf(it) === idx} />)}
          </>}
          {sections.action.length > 0 && <>
            <div className="cmdk-section">Actions</div>
            {sections.action.map(it => <CmdItem key={it.id} it={it} active={items.indexOf(it) === idx} />)}
          </>}
          {sections.applicant.length > 0 && <>
            <div className="cmdk-section">Applicants</div>
            {sections.applicant.map(it => <CmdItem key={it.id} it={it} active={items.indexOf(it) === idx} />)}
          </>}
          {items.length === 0 && <div className="cmdk-item fg-4">No matches</div>}
        </div>
        <div className="cmdk-foot">
          <span><Kbd>↑</Kbd><Kbd>↓</Kbd> Navigate</span>
          <span><Kbd>↵</Kbd> Open</span>
          <span><Kbd>esc</Kbd> Close</span>
          <span style={{marginLeft:"auto"}}>{items.length} results</span>
        </div>
      </div>
    </div>
  );
}

function CmdItem({ it, active }) {
  const Icon = it.icon;
  return (
    <div className={`cmdk-item ${active ? "is-active" : ""}`}>
      {Icon ? <Icon size={14} className="fg-3" /> : null}
      <span>{it.label}</span>
      {it.hint ? <span className="fg-4" style={{fontSize:11.5}}> · {it.hint}</span> : null}
      <span className="cmdk-item-r">
        {it.kind === "nav" ? "open" : it.kind === "applicant" ? "review" : "run"}
      </span>
    </div>
  );
}

Object.assign(window, { CommandPalette });
