// search.jsx — global command palette (⌘K). Exports SearchPalette.
// Live: debounced GET /api/search?q=… → grouped results across leads,
// conversations, campaigns, agents, knowledge, escalations, custom requests
// and queue jobs. Selecting a result opens the right drawer or route.
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

const SEARCH_GROUPS = {
  leads: { label: "Leads", icon: "user" },
  conversations: { label: "Conversations", icon: "message" },
  campaigns: { label: "Campaigns", icon: "megaphone" },
  agents: { label: "Agents", icon: "bot" },
  knowledge: { label: "Knowledge Base", icon: "fileText" },
  escalations: { label: "Escalations", icon: "alert" },
  customRequests: { label: "Custom Requests", icon: "tag" },
  queue: { label: "Queue Jobs", icon: "layers" },
};

function loadRecent() { try { return JSON.parse(localStorage.getItem("maxab.recentSearches") || "[]"); } catch { return []; } }
function saveRecent(list) { try { localStorage.setItem("maxab.recentSearches", JSON.stringify(list.slice(0, 5))); } catch {} }

function SearchPalette({ go, openContact, openAgent, onClose }) {
  const [q, setQ] = useStateP("");
  const [active, setActive] = useStateP(0);
  const [recent, setRecent] = useStateP(loadRecent);
  const [state, setState] = useStateP({ loading: false, error: null, groups: {}, total: 0 });
  const inputRef = useRefP(null);
  const reqSeq = useRefP(0);

  useEffectP(() => { inputRef.current && inputRef.current.focus(); }, []);

  // debounced live search
  useEffectP(() => {
    const term = q.trim();
    if (term.length < 2) { setState({ loading: false, error: null, groups: {}, total: 0 }); return; }
    setState((s) => ({ ...s, loading: true, error: null }));
    const seq = ++reqSeq.current;
    const h = setTimeout(() => {
      API.search(term)
        .then((r) => { if (seq === reqSeq.current) setState({ loading: false, error: null, groups: r.groups || {}, total: r.total || 0 }); })
        .catch((e) => { if (seq === reqSeq.current) setState({ loading: false, error: e.message || "Search failed", groups: {}, total: 0 }); });
    }, 180);
    return () => clearTimeout(h);
  }, [q]);

  useEffectP(() => { setActive(0); }, [q, state.total]);

  // flatten grouped results (server group order) for keyboard nav
  const flat = [];
  const ordered = [];
  Object.keys(SEARCH_GROUPS).forEach((gk) => {
    const rows = state.groups[gk] || [];
    if (!rows.length) return;
    ordered.push([gk, rows]);
    rows.forEach((row) => flat.push({ ...row, group: gk }));
  });

  const choose = (item) => {
    if (!item) return;
    const next = [item.label, ...recent.filter((x) => x !== item.label)].slice(0, 5);
    setRecent(next); saveRecent(next);
    if (item.route === "contacts") {
      const c = (window.DATA?.CONTACTS || []).find((x) => x.id === item.id);
      if (c) openContact(c); else go("contacts");
    } else if (item.route === "agents") {
      const a = (window.DATA?.AGENTS || []).find((x) => x.id === item.id);
      if (a) openAgent(a); else go("agents");
    } else {
      go(item.route);
    }
    onClose();
  };

  useEffectP(() => {
    const h = (e) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowDown") { e.preventDefault(); setActive((a) => Math.min(a + 1, flat.length - 1)); }
      else if (e.key === "ArrowUp") { e.preventDefault(); setActive((a) => Math.max(a - 1, 0)); }
      else if (e.key === "Enter") { e.preventDefault(); choose(flat[active]); }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [flat, active]); // eslint-disable-line

  let runningIndex = -1;
  const term = q.trim();

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "var(--color-overlay)", zIndex: 70, display: "flex", justifyContent: "center", alignItems: "flex-start", paddingTop: "12vh" }}>
      <div onClick={(e) => e.stopPropagation()} className="fade-up" style={{ width: 620, maxWidth: "92vw", background: "#fff", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xl)", overflow: "hidden" }}>
        <div className="row" style={{ gap: 12, padding: "16px 18px", borderBottom: "1px solid var(--border-1)" }}>
          <Icon name="search" size={20} style={{ color: "var(--fg-3)" }} />
          <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search leads, campaigns, agents, queue, requests…"
            style={{ flex: 1, border: "none", outline: "none", fontSize: 16, color: "var(--fg-1)", background: "transparent" }} />
          {state.loading && <span className="spin" style={{ width: 16, height: 16 }} />}
          <span className="kbd">Esc</span>
        </div>

        <div style={{ maxHeight: "52vh", overflowY: "auto", padding: 8 }}>
          {term.length < 2 ? (
            <div style={{ padding: 8 }}>
              {recent.length > 0 && <>
                <div className="sidebar__section-label" style={{ padding: "6px 8px" }}>Recent searches</div>
                {recent.map((r) => (
                  <button key={r} onClick={() => setQ(r)} style={{ display: "flex", alignItems: "center", gap: 12, width: "100%", textAlign: "start", padding: "10px 10px", borderRadius: "var(--radius-sm)", background: "transparent", cursor: "pointer" }}
                    onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-2)"} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                    <Icon name="clock" size={16} style={{ color: "var(--fg-disabled)" }} /><span style={{ fontSize: 14, color: "var(--fg-2)" }}>{r}</span>
                  </button>
                ))}
              </>}
              <div className="sidebar__section-label" style={{ padding: "12px 8px 6px" }}>Jump to</div>
              {[["Messaging Queue", "layers", "queue"], ["Escalations", "alert", "escalations"], ["Custom Requests", "tag", "requests"]].map(([label, icon, r]) => (
                <button key={r} onClick={() => { go(r); onClose(); }} style={{ display: "flex", alignItems: "center", gap: 12, width: "100%", textAlign: "start", padding: "10px 10px", borderRadius: "var(--radius-sm)", background: "transparent", cursor: "pointer" }}
                  onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-2)"} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                  <Icon name={icon} size={16} style={{ color: "var(--fg-3)" }} /><span style={{ fontSize: 14, color: "var(--fg-1)", fontWeight: 600 }}>{label}</span>
                </button>
              ))}
            </div>
          ) : state.error ? (
            <div style={{ textAlign: "center", padding: "40px 16px", color: "var(--color-danger)" }}>
              <Icon name="alert" size={26} /><div style={{ fontSize: 13.5, fontWeight: 600, marginTop: 8 }}>{state.error}</div>
            </div>
          ) : flat.length === 0 ? (
            <div style={{ textAlign: "center", padding: "40px 16px", color: "var(--fg-4)" }}>
              <Icon name="search" size={28} style={{ color: "var(--fg-disabled)" }} />
              <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-2)", marginTop: 10 }}>{state.loading ? "Searching…" : `No results for "${term}"`}</div>
              <div style={{ fontSize: 12.5, marginTop: 2 }}>Try a lead, company, campaign or agent name.</div>
            </div>
          ) : (
            ordered.map(([gk, rows]) => (
              <div key={gk} style={{ marginBottom: 4 }}>
                <div className="sidebar__section-label" style={{ padding: "8px 10px 4px" }}>{SEARCH_GROUPS[gk].label}</div>
                {rows.map((r) => {
                  runningIndex++;
                  const idx = runningIndex;
                  const isActive = idx === active;
                  return (
                    <button key={gk + (r.id || idx)} onClick={() => choose({ ...r, group: gk })} onMouseEnter={() => setActive(idx)}
                      style={{ display: "flex", alignItems: "center", gap: 12, width: "100%", textAlign: "start", padding: "10px 10px", borderRadius: "var(--radius-sm)", background: isActive ? "var(--color-primary-tint-soft)" : "transparent", cursor: "pointer" }}>
                      <span className="opp" style={{ width: 32, height: 32, borderRadius: 8, background: "var(--bg-2)", color: "var(--color-secondary)", flexShrink: 0 }}><Icon name={SEARCH_GROUPS[gk].icon} size={16} /></span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 14, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</div>
                        <div style={{ fontSize: 12, color: "var(--fg-4)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.sub}</div>
                      </div>
                      {isActive && <Icon name="arrowRight" size={16} style={{ color: "var(--fg-disabled)" }} />}
                    </button>
                  );
                })}
              </div>
            ))
          )}
        </div>

        <div className="row" style={{ gap: 16, padding: "10px 16px", borderTop: "1px solid var(--border-1)", background: "var(--bg-2)", fontSize: 11.5, color: "var(--fg-4)" }}>
          <span className="row" style={{ gap: 5 }}><span className="kbd">↑</span><span className="kbd">↓</span>navigate</span>
          <span className="row" style={{ gap: 5 }}><span className="kbd">↵</span>open</span>
          <span className="row" style={{ gap: 5 }}><span className="kbd">Esc</span>close</span>
        </div>
      </div>
    </div>
  );
}

window.SearchPalette = SearchPalette;
