/* buscador.jsx — buscador global del topbar (F2 punto 15).
   Antes el input era decorativo. Ahora busca sobre los datos reales ya cargados
   en memoria (pedidos, repartidores, restaurantes) y muestra un dropdown de
   resultados clicables que navegan al detalle. Uso:
     <BuscadorGlobal placeholder="…" buscar={(q) => [{tipo, clave, titulo, sub, icono, data}]} onPick={(r) => …} />
   Registra window.BuscadorGlobal. */
const { useState: bgState, useEffect: bgEffect, useRef: bgRef } = React;

function BuscadorGlobal({ placeholder, buscar, onPick }) {
  const [q, setQ] = bgState("");
  const [abierto, setAbierto] = bgState(false);
  const [idx, setIdx] = bgState(0);
  const wrapRef = bgRef(null);

  const resultados = q.trim().length >= 2 ? (buscar(q.trim().toLowerCase()) || []).slice(0, 8) : [];

  bgEffect(() => {
    const fuera = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setAbierto(false); };
    document.addEventListener("mousedown", fuera);
    return () => document.removeEventListener("mousedown", fuera);
  }, []);

  const elegir = (r) => { setAbierto(false); setQ(""); onPick(r); };

  const teclas = (e) => {
    if (!resultados.length) return;
    if (e.key === "ArrowDown") { e.preventDefault(); setIdx((i) => Math.min(i + 1, resultados.length - 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setIdx((i) => Math.max(i - 1, 0)); }
    else if (e.key === "Enter") { e.preventDefault(); if (resultados[idx]) elegir(resultados[idx]); }
    else if (e.key === "Escape") setAbierto(false);
  };

  return (
    <div className="search" ref={wrapRef} style={{ position: "relative" }} role="search">
      <Icon name="search" />
      <input
        placeholder={placeholder}
        value={q}
        aria-label={placeholder}
        aria-expanded={abierto && resultados.length > 0}
        onChange={(e) => { setQ(e.target.value); setAbierto(true); setIdx(0); }}
        onFocus={() => setAbierto(true)}
        onKeyDown={teclas}
      />
      {abierto && q.trim().length >= 2 && (
        <div role="listbox" aria-label="Resultados de búsqueda"
          style={{ position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0, zIndex: 80,
            background: "var(--panel)", border: "1px solid var(--line)", borderRadius: 12,
            boxShadow: "0 12px 32px rgba(0,0,0,.14)", overflow: "hidden", maxHeight: 340, overflowY: "auto" }}>
          {resultados.length === 0 && (
            <div className="muted" style={{ padding: "12px 14px", fontSize: 13 }}>Sin resultados para “{q}”.</div>
          )}
          {resultados.map((r, i) => (
            <div key={r.tipo + "-" + r.clave} role="option" aria-selected={i === idx}
              onMouseEnter={() => setIdx(i)} onMouseDown={(e) => { e.preventDefault(); elegir(r); }}
              style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 13px", cursor: "pointer",
                background: i === idx ? "var(--panel-2)" : "transparent" }}>
              <span style={{ width: 28, height: 28, borderRadius: 8, display: "grid", placeItems: "center",
                background: "var(--panel-2)", color: "var(--g2)", flex: "none" }}>
                <Icon name={r.icono || "search"} style={{ width: 14, height: 14 }} />
              </span>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.titulo}</div>
                {r.sub && <div className="muted" style={{ fontSize: 11.5 }}>{r.sub}</div>}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* Coincidencia simple: todas las palabras de la consulta en el texto objetivo. */
function bgCoincide(texto, q) {
  const t = String(texto || "").toLowerCase();
  return q.split(/\s+/).every((w) => t.includes(w));
}

Object.assign(window, { BuscadorGlobal, bgCoincide });
