/* ============================================================
   Search — global command palette (⌘K). Targets, contacts,
   threads, campaigns, surfaces. Jumps you to the right place.
   ============================================================ */
function GlobalSearch({ onClose, onTarget, onGo }) {
  const W = window.WTC;
  const [q, setQ] = React.useState("");
  const [sel, setSel] = React.useState(0);
  const inputRef = React.useRef(null);
  React.useEffect(() => { inputRef.current && inputRef.current.focus(); }, []);

  const results = React.useMemo(() => {
    const s = q.trim().toLowerCase();
    const out = [];
    const SURF = [["assistant", "Assistant"], ["inbox", "Inbox"], ["contacts", "Contacts"], ["campaigns", "Campaigns"], ["scouting", "Scouting"], ["stats", "Stats"], ["agents", "Agents"]];
    if (!s) {
      W.todayQueue.slice(0, 4).forEach((t) => out.push({ type: "target", id: t.id, label: t.brand, sub: t.whyNow, mono: t.mono, lane: t.lane }));
      out.push({ type: "go", id: "inbox", label: "Go to Inbox", icon: "inbox" });
      return out;
    }
    W.targets.forEach((t) => { if ((t.brand + " " + t.event).toLowerCase().includes(s)) out.push({ type: "target", id: t.id, label: t.brand, sub: W.LANE_META[t.lane].label + " · " + t.event, mono: t.mono, lane: t.lane }); });
    W.contacts.forEach((c) => { if ((c.name + " " + c.title + " " + c.email).toLowerCase().includes(s)) out.push({ type: "contact", id: c.targetId, label: c.name, sub: c.title + " · " + c.brand, color: c.color, initials: c.initials }); });
    W.threads.forEach((t) => { if (t.subject.toLowerCase().includes(s)) out.push({ type: "thread", id: t.targetId, label: t.subject, sub: t.brand, mono: t.mono, lane: t.lane }); });
    SURF.forEach(([id, label]) => { if (label.toLowerCase().includes(s)) out.push({ type: "go", id, label: "Go to " + label, icon: "chevronRight" }); });
    return out.slice(0, 12);
  }, [q]);

  React.useEffect(() => { setSel(0); }, [q]);
  const pick = (r) => { if (!r) return; if (r.type === "go") onGo(r.id); else if (r.type === "target" || r.type === "thread") onTarget(r.id); else if (r.type === "contact") onTarget(r.id); onClose(); };
  const onKey = (e) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setSel((i) => Math.min(results.length - 1, i + 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setSel((i) => Math.max(0, i - 1)); }
    else if (e.key === "Enter") { e.preventDefault(); pick(results[sel]); }
    else if (e.key === "Escape") onClose();
  };

  return (
    <div className="search-scrim" onClick={onClose}>
      <div className="search-palette" onClick={(e) => e.stopPropagation()}>
        <div className="search-input-row">
          <Icon name="search" size={18} style={{ color: "var(--text-3)" }} />
          <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={onKey}
            placeholder="Search targets, contacts, conversations…" />
          <span className="search-kbd">esc</span>
        </div>
        <div className="search-results">
          {results.length === 0 ? (
            <div className="search-empty">No matches for "{q}"</div>
          ) : results.map((r, i) => (
            <button key={r.type + r.id + i} className="search-row" data-active={sel === i || undefined}
              onMouseEnter={() => setSel(i)} onClick={() => pick(r)}>
              {r.type === "target" || r.type === "thread" ? <Avatar mono={r.mono} size={26} square />
                : r.type === "contact" ? <Avatar initials={r.initials} color={r.color} size={26} />
                : <span className="search-go-ico"><Icon name={r.icon || "chevronRight"} size={15} /></span>}
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.label}</div>
                {r.sub && <div style={{ fontSize: 11.5, color: "var(--text-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.sub}</div>}
              </div>
              {r.lane && <LaneChip lane={r.lane} small />}
              <span className="search-type">{r.type === "go" ? "Page" : r.type === "thread" ? "Thread" : r.type === "contact" ? "Contact" : "Target"}</span>
            </button>
          ))}
        </div>
        <div className="search-foot"><span><span className="search-kbd">↑↓</span> navigate</span><span><span className="search-kbd">↵</span> open</span></div>
      </div>
    </div>
  );
}
Object.assign(window, { GlobalSearch });
