const { Tag } = window.BecoDesignSystem_7188f3;

const RECENT_SEARCHES = ["pastel", "chopp gelado", "nordestina", "açaí"];
const FAVOURITES = ["Beco Bar", "Pastel do Zé", "Açúcar Bruto"];
const RECENT_ORDERS = [
  { where: "Pastel do Zé", when: "24/07", total: "R$ 31,50", what: "2× Pastel de queijo" },
  { where: "Forno da Vila", when: "19/07", total: "R$ 78,00", what: "1× Marguerita, 1× Chopp" },
  { where: "Beco Bar", when: "12/07", total: "R$ 46,90", what: "1× Calabresa, 2× Chopp" }
];

/** Full-screen search on paper. Opens as a wave: a circle grows out of the pill until it
 *  floods the screen, so the black feed is replaced rather than covered. */
function SearchOverlay({ open, origin, value, onChange, onClose, onPickRestaurant }) {
  const [flooded, setFlooded] = React.useState(false);
  const input = React.useRef(null);

  React.useEffect(() => {
    if (!open) { setFlooded(false); return; }
    const r = requestAnimationFrame(() => setFlooded(true));
    const t = setTimeout(() => input.current && input.current.focus(), 320);
    return () => { cancelAnimationFrame(r); clearTimeout(t); };
  }, [open]);

  if (!open) return null;

  const ox = origin ? origin.x : 40, oy = origin ? origin.y : 68;
  const hits = value.trim()
    ? PLACES.filter(r =>
        r.name.toLowerCase().includes(value.toLowerCase()) ||
        r.cuisine.toLowerCase().includes(value.toLowerCase()) ||
        (r.producer && r.producer.kind.toLowerCase().includes(value.toLowerCase())))
    : [];

  const heading = (t) => (
    <div style={{
      fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9, letterSpacing: "0.16em",
      textTransform: "uppercase", color: "var(--ink-400)", marginBottom: 10
    }}>{t}</div>
  );

  const bigRow = (main, meta, onClick, key) => (
    <button key={key || main} type="button" onClick={onClick}
      style={{
        display: "flex", alignItems: "baseline", gap: 10, width: "100%", textAlign: "left",
        padding: "11px 0", background: "none", border: "none", borderBottom: "1px solid var(--ink-100)",
        cursor: "pointer"
      }}>
      <span style={{
        flex: 1, minWidth: 0, fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%",
        textTransform: "uppercase", fontSize: 17, letterSpacing: "-0.02em", color: "var(--black)",
        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"
      }}>{main}</span>
      {meta && (
        <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-400)", whiteSpace: "nowrap" }}>{meta}</span>
      )}
    </button>
  );

  return (
    <div className="beco-light" style={{
      position: "absolute", inset: 0, zIndex: 360, background: "var(--paper)", color: "var(--black)",
      clipPath: "circle(" + (flooded ? "150%" : "22px") + " at " + ox + "px " + oy + "px)",
      transition: "clip-path 520ms cubic-bezier(0.22, 1, 0.28, 1)",
      display: "flex", flexDirection: "column"
    }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 10, padding: "46px 16px 14px",
        opacity: flooded ? 1 : 0, transition: "opacity 200ms var(--ease-out) 160ms"
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, flex: 1, minWidth: 0, height: 42, padding: "0 14px", border: "1.5px solid var(--black)", borderRadius: "var(--radius-pill)" }}>
          <Icon d={P.search} size={17} stroke={2.25} style={{ color: "var(--black)" }} />
          <input ref={input} value={value} onChange={e => onChange(e.target.value)}
            placeholder="restaurante, prato ou cozinha"
            style={{
              flex: 1, minWidth: 0, border: "none", outline: "none", background: "transparent",
              fontFamily: "var(--font-body)", fontSize: 14, color: "var(--black)"
            }} />
          {value && (
            <button type="button" onClick={() => onChange("")} aria-label="Limpar"
              style={{ background: "none", border: "none", padding: 0, cursor: "pointer", color: "var(--ink-400)" }}>
              <Icon d={P.x} size={15} />
            </button>
          )}
        </div>
        <button type="button" onClick={onClose}
          style={{
            flex: "0 0 auto", background: "none", border: "none", padding: "0 2px", cursor: "pointer",
            fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 10, letterSpacing: "0.14em",
            textTransform: "uppercase", color: "var(--ink-500)"
          }}>Fechar</button>
      </div>

      <div style={{
        flex: 1, overflowY: "auto", padding: "8px 16px 28px", scrollbarWidth: "none",
        opacity: flooded ? 1 : 0, transition: "opacity 240ms var(--ease-out) 220ms"
      }}>
        {value.trim() ? (
          <div>
            {heading(plural(hits.length, "resultado", "resultados"))}
            {hits.map(r => bigRow(r.name, r.producer ? "banca · " + r.producer.next : r.cuisine + " · " + r.eta, () => onPickRestaurant(r)))}
            {!hits.length && (
              <div style={{ fontSize: 14, color: "var(--ink-400)" }}>Nada com esse nome por aqui.</div>
            )}
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 26 }}>
            <div>
              {heading("Buscas recentes")}
              <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
                {RECENT_SEARCHES.map(s => (
                  <Tag key={s} onClick={() => onChange(s)}>{s}</Tag>
                ))}
              </div>
            </div>

            <div>
              {heading("Favoritos")}
              {FAVOURITES.map(n => {
                const r = RESTAURANTS.find(x => x.name === n);
                return bigRow(n, r ? r.eta : null, () => r && onPickRestaurant(r), n);
              })}
            </div>

            <div>
              {heading("Pedidos recentes")}
              {RECENT_ORDERS.map(o => {
                const r = RESTAURANTS.find(x => x.name === o.where);
                return (
                  <button key={o.where + o.when} type="button" onClick={() => r && onPickRestaurant(r)}
                    style={{
                      display: "flex", alignItems: "flex-start", gap: 10, width: "100%", textAlign: "left",
                      padding: "12px 0", background: "none", border: "none", borderBottom: "1px solid var(--ink-100)", cursor: "pointer"
                    }}>
                    <span style={{ flex: 1, minWidth: 0 }}>
                      <span style={{
                        display: "block", fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%",
                        textTransform: "uppercase", fontSize: 16, letterSpacing: "-0.02em", color: "var(--black)"
                      }}>{o.where}</span>
                      <span style={{ display: "block", fontSize: 12.5, color: "var(--ink-400)", marginTop: 2 }}>{o.what}</span>
                    </span>
                    <span style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                      <span style={{ display: "block", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 11, color: "var(--black)" }}>{o.total}</span>
                      <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.12em", color: "var(--ink-400)", marginTop: 3 }}>{o.when}</span>
                    </span>
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
Object.assign(window, { SearchOverlay });
