// search.jsx — command palette (⌘K) with ranked results across title / UID /
// alias / description / headings, keyboard-navigable.

const { useState, useEffect, useRef, useMemo } = React;

function scoreDoc(d, q) {
  const t = d.title.toLowerCase(), id = d.id.toLowerCase();
  let s = 0;
  if (t.includes(q)) s += t.startsWith(q) ? 160 : 100;
  if (id.includes(q)) s += id.startsWith(q) ? 90 : 60;
  if ((d.aliases || []).some((a) => a.toLowerCase().includes(q))) s += 55;
  if ((d.description || "").toLowerCase().includes(q)) s += 30;
  if ((d.searchText || "").includes(q)) s += 12;
  return s;
}

function CommandPalette({ index, open, onClose, onOpenDoc }) {
  const [q, setQ] = useState("");
  const [sel, setSel] = useState(0);
  const inputRef = useRef(null);
  const listRef = useRef(null);

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

  const results = useMemo(() => {
    const qq = q.trim().toLowerCase();
    if (!qq) {
      return [...(index.documents || [])].sort((a, b) => String(b.lastUpdated || "").localeCompare(String(a.lastUpdated || ""))).slice(0, 8).map((d) => ({ d, s: 0 }));
    }
    return (index.documents || []).map((d) => ({ d, s: scoreDoc(d, qq) })).filter((x) => x.s > 0)
      .sort((a, b) => b.s - a.s).slice(0, 40);
  }, [q, index]);

  useEffect(() => { setSel(0); }, [q]);
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") { onClose(); }
      else if (e.key === "ArrowDown") { e.preventDefault(); setSel((s) => Math.min(results.length - 1, s + 1)); }
      else if (e.key === "ArrowUp") { e.preventDefault(); setSel((s) => Math.max(0, s - 1)); }
      else if (e.key === "Enter") { e.preventDefault(); const r = results[sel]; if (r) { onOpenDoc(r.d); onClose(); } }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, results, sel, onClose, onOpenDoc]);

  useEffect(() => {
    if (listRef.current) { const el = listRef.current.querySelector(".palette__item.sel"); if (el) el.scrollIntoView({ block: "nearest" }); }
  }, [sel]);

  if (!open) return null;
  const grouped = {};
  results.forEach((r) => { (grouped[r.d.collection] = grouped[r.d.collection] || []).push(r); });
  let flatIndex = -1;

  return (
    <div className="palette-scrim" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="palette" role="dialog" aria-modal="true" aria-label="Search the library">
        <div className="palette__input">
          <I.Search />
          <input ref={inputRef} type="text" value={q} placeholder="Search specs and runbooks…" aria-label="Search query"
                 onChange={(e) => setQ(e.target.value)} />
          <button className="iconbtn" onClick={onClose} aria-label="Close"><I.Close /></button>
        </div>
        <div className="palette__results" ref={listRef}>
          {results.length === 0
            ? <div className="state" style={{ padding: "var(--uk-space-32)" }}><div className="state__msg">No documents match “{q}”.</div></div>
            : Object.keys(grouped).map((coll) => {
                const collLabel = (index.collections || []).find((c) => c.id === coll);
                return (
                  <div key={coll}>
                    <div className="palette__group">{collLabel ? collLabel.label : coll}{!q && " · recently updated"}</div>
                    {grouped[coll].map((r) => {
                      flatIndex++;
                      const cur = flatIndex;
                      return (
                        <button key={r.d.id} className={cx("palette__item", sel === cur && "sel")}
                                onMouseEnter={() => setSel(cur)} onClick={() => { onOpenDoc(r.d); onClose(); }}>
                          {collectionIcon(r.d.collection)}
                          <span style={{ flex: 1, minWidth: 0 }}>
                            <span className="t">{r.d.title}</span>
                            <div className="s">{r.d.id}</div>
                          </span>
                          <StatusChip stage={r.d.statusStage} status={r.d.status} />
                        </button>
                      );
                    })}
                  </div>
                );
              })}
        </div>
        <div className="palette__foot">
          <span><kbd>↑↓</kbd> navigate</span><span><kbd>↵</kbd> open</span><span><kbd>esc</kbd> close</span>
        </div>
      </div>
    </div>
  );
}

window.CommandPalette = CommandPalette;
