/** Search opens a dedicated full-screen view. Beside it: filter and sort, each dropping a small
 *  black panel. No pills, no bell — the only chrome up here is what changes the list. */
function SearchPill({ value, onChange, filters, onFilters, sort, onSort, onOpenSearch, botDismissed, onRestoreBot }) {
  const [panel, setPanel] = React.useState(null);
  const btn = React.useRef(null);

  const activeCount = Object.values(filters).filter(Boolean).length;

  const circle = (active) => ({
    width: 40, height: 40, borderRadius: "var(--radius-pill)",
    background: active ? "var(--white)" : "transparent",
    color: active ? "var(--black)" : "var(--white)",
    border: "1px solid " + (active ? "var(--white)" : "var(--ink-600)"),
    cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
    padding: 0, position: "relative",
    transition: "background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out)"
  });

  const row = (label, meta, on, onClick, mark) => (
    <button key={label} type="button" onClick={onClick}
      style={{
        display: "flex", alignItems: "center", gap: 10, width: "100%",
        background: "none", border: "none", padding: "11px 14px", cursor: "pointer", textAlign: "left"
      }}>
      <span style={{
        width: 14, height: 14, flex: "0 0 auto",
        borderRadius: mark === "dot" ? "var(--radius-pill)" : 3,
        border: "1px solid var(--white)",
        background: on ? "var(--white)" : "transparent"
      }} />
      <span style={{
        flex: 1, fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%",
        textTransform: "uppercase", fontSize: 13, letterSpacing: "-0.01em",
        color: "var(--white)", opacity: on ? 1 : 0.62
      }}>{label}</span>
      {meta && (
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-400)" }}>{meta}</span>
      )}
    </button>
  );

  const sheet = (children, footer) => (
    <div style={{
      position: "absolute", top: 48, left: 0, width: 244, zIndex: 80,
      background: "var(--black)", border: "1px solid var(--white)",
      borderRadius: "var(--radius-lg)", overflow: "hidden",
      boxShadow: "var(--shadow-float)"
    }}>
      {children}
      {footer}
    </div>
  );

  return (
    <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 6 }}>
      <button ref={btn} type="button" aria-label="Buscar" style={circle(Boolean(value))}
        onClick={() => {
          setPanel(null);
          const r = btn.current.getBoundingClientRect();
          const shell = btn.current.closest(".beco-shell").getBoundingClientRect();
          onOpenSearch({ x: r.left - shell.left + r.width / 2, y: r.top - shell.top + r.height / 2 });
        }}>
        <Icon d={P.search} size={18} />
      </button>

      <button type="button" aria-label="Filtrar" style={circle(panel === "filter" || activeCount > 0)}
        onClick={() => setPanel(p => (p === "filter" ? null : "filter"))}>
        <Icon d={P.filter} size={18} />
        {activeCount > 0 && panel !== "filter" && (
          <span style={{
            position: "absolute", top: -2, right: -2, minWidth: 16, height: 16,
            borderRadius: "var(--radius-pill)", background: "var(--black)", color: "var(--white)",
            border: "1px solid var(--white)", fontFamily: "var(--font-mono)", fontWeight: 700,
            fontSize: 9, lineHeight: "14px", textAlign: "center"
          }}>{activeCount}</span>
        )}
      </button>

      <button type="button" aria-label="Ordenar" style={circle(panel === "sort")}
        onClick={() => setPanel(p => (p === "sort" ? null : "sort"))}>
        <Icon d={P.sort} size={18} />
      </button>

      {botDismissed && (
        <button type="button" aria-label="Trazer o bot de volta" style={circle(false)}
          onClick={onRestoreBot}>
          <Icon d={P.chat} size={18} />
        </button>
      )}

      {panel === "filter" && sheet(
        <div style={{ padding: "6px 0" }}>
          <div style={{ padding: "10px 14px 6px", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-400)" }}>Filtrar</div>
          {[
            ["Entrega grátis", "R$ 0,00", "freeDelivery"],
            ["Até 30 min", "rápido", "fast"],
            ["Nota 4,7+", "★", "topRated"],
            ["Perto de você", "até 2 km", "near"]
          ].map(([label, meta, key]) => row(label, meta, Boolean(filters[key]), () => onFilters({ ...filters, [key]: !filters[key] }), "box"))}
        </div>,
        <button type="button" onClick={() => { onFilters({}); setPanel(null); }}
          style={{
            width: "100%", padding: "12px 14px", background: "none", border: "none", borderTop: "1px solid var(--ink-700)",
            cursor: "pointer", textAlign: "left",
            fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9.5, letterSpacing: "0.14em",
            textTransform: "uppercase", color: "var(--ink-300)"
          }}>Limpar tudo</button>
      )}

      {panel === "sort" && sheet(
        <div style={{ padding: "6px 0" }}>
          <div style={{ padding: "10px 14px 6px", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-400)" }}>Ordenar por</div>
          {[
            ["Mais perto", "km", "distance"],
            ["Mais rápido", "min", "eta"],
            ["Melhor nota", "★", "rating"],
            ["Sem taxa primeiro", "R$ 0,00", "fee"]
          ].map(([label, meta, key]) => row(label, meta, sort === key, () => { onSort(key); setPanel(null); }, "dot"))}
        </div>
      )}
    </div>
  );
}
Object.assign(window, { SearchPill });
