const { Button, QuantityStepper } = window.BecoDesignSystem_7188f3;

/** Loja no molde do Plutão: hero (logo, claim, lede + saiba mais) e cardápio com
 *  tabs sticky, busca rápida e cards-alavanca de três zonas. Nada abaixo do cardápio.
 *  A entrada segue sendo a porta do beco; o pagamento segue no balcão de papel. */
function RestaurantView({ restaurant, rect, cart, onAdd, onQty, onClose, onConfirm, onCheckout }) {
  const root = React.useRef(null);
  const [box, setBox] = React.useState(null);
  const [phase, setPhase] = React.useState(0); // 0 porta · 1 corredor · 2 dentro
  const [leaving, setLeaving] = React.useState(false);
  const [checkout, setCheckout] = React.useState(false);
  const [paid, setPaid] = React.useState(false);
  const [pay, setPay] = React.useState("pix");
  const [about, setAbout] = React.useState(false);
  const [search, setSearch] = React.useState("");
  const [tool, setTool] = React.useState(null); // "search" | "filter" | "sort"
  const [only, setOnly] = React.useState({});
  const [order, setOrder] = React.useState("menu");
  const [expanded, setExpanded] = React.useState(null);
  const [favs, setFavs] = React.useState([]);
  const [press, setPress] = React.useState(null); // {name, zone, empty}
  const [stuck, setStuck] = React.useState(false);
  // BANCA (Feira do Beco): a mesma loja, lida no eixo do produtor — fornada em vez
  // de ETA, retirada/entrega em vez de taxa, e assinatura no balcão.
  const PR = restaurant.producer || null;
  const [recur, setRecur] = React.useState("once"); // "once" | "sub"
  const menu = MENUS[restaurant.menuKey] || MENUS.default;
  const sections = Object.keys(menu);
  const HERO = "\u0000hero"; // the store's own name, first stop on the rail
  const [section, setSection] = React.useState(HERO);
  const scroller = React.useRef(null);
  const heads = React.useRef({});
  const lockUntil = React.useRef(0);
  const zone = React.useRef(null);
  const hero = restaurant.hero || {};

  React.useEffect(() => {
    const el = root.current;
    if (el) setBox({ w: el.offsetWidth, h: el.offsetHeight });
    if (!rect) { setPhase(2); return; }
    const r = requestAnimationFrame(() => setPhase(1));
    const t = setTimeout(() => setPhase(2), 300);
    return () => { cancelAnimationFrame(r); clearTimeout(t); };
  }, [rect]);

  React.useEffect(() => { if (onCheckout) onCheckout(checkout); }, [checkout]);
  React.useEffect(() => { if (checkout && !paid && !cart.length) setCheckout(false); }, [checkout, paid, cart.length]);

  const close = () => { setLeaving(true); setTimeout(onClose, 260); };

  const goSection = (s) => {
    setSection(s);
    const b = scroller.current;
    if (!b) return;
    lockUntil.current = performance.now() + 700;
    if (s === HERO) { b.scrollTo({ top: 0, behavior: "smooth" }); return; }
    const el = heads.current[s];
    if (el) b.scrollTo({ top: el.offsetTop - 52, behavior: "smooth" });
  };
  const onScroll = () => {
    const b = scroller.current;
    if (!b) return;
    setStuck(b.scrollTop > 320);
    if (performance.now() < lockUntil.current) { lockUntil.current = performance.now() + 160; return; }
    const first = heads.current[sections[0]];
    let cur = first && first.offsetTop - 92 > b.scrollTop ? HERO : sections[0];
    sections.forEach(s => { const el = heads.current[s]; if (el && el.offsetTop - 92 <= b.scrollTop) cur = s; });
    if (b.scrollTop >= b.scrollHeight - b.clientHeight - 6) cur = sections[sections.length - 1];
    setSection(c => (c === cur ? c : cur));
  };

  const qtyOf = (d) => cart.filter(i => i.name === d.name).reduce((a, i) => a + i.qty, 0);
  const addItem = (d, n) => { for (let k = 0; k < (n || 1); k++) onAdd(d); };
  const openOptions = (d) => setExpanded(e => (e === d.name ? null : d.name));
  const plus = (d) => { if (d.options && d.options.length) openOptions(d); else onAdd(d); };
  const minus = (d) => { const q = qtyOf(d); if (q > 0) onQty(d.name, q - 1); };

  // card-alavanca: a zona é decidida no pointerdown, com o transform neutralizado
  const zoneAt = (el, clientX) => {
    const prev = el.style.transform;
    el.style.transform = "none";
    const r = el.getBoundingClientRect();
    el.style.transform = prev;
    const x = clientX - r.left;
    const media = el.querySelector("[data-media]");
    const mw = (media && media.offsetWidth) || 108;
    if (x >= r.width - (mw + 12)) return "plus";
    if (x <= Math.min(84, r.width * 0.26)) return "minus";
    return "open";
  };
  const down = (e, d) => {
    if (e.target.closest("[data-own]")) return;
    const z = zoneAt(e.currentTarget, e.clientX);
    zone.current = z;
    setPress({ name: d.name, zone: z, empty: z === "minus" && qtyOf(d) === 0 });
  };
  const up = (d) => {
    const z = zone.current;
    zone.current = null;
    setPress(null);
    if (!z) return;
    if (z === "plus") plus(d);
    else if (z === "minus") minus(d);
    else openOptions(d);
  };

  const count = cart.reduce((a, i) => a + i.qty, 0);
  const subtotal = cart.reduce((a, i) => a + parse(i.price) * i.qty, 0);
  const delivery = parse(restaurant.deliveryFee);
  const total = subtotal + delivery;
  const here = ADDRESSES[0];
  const initials = (n) => n.split(/\s+/).slice(0, 2).map(w => w[0]).join("").toUpperCase();
  const q = search.trim().toLowerCase();

  const door = box && rect
    ? "inset(" + rect.top + "px " + (box.w - rect.left - rect.width) + "px " + (box.h - rect.top - rect.height) + "px " + rect.left + "px round 14px)"
    : "inset(0px)";
  const slit = box && rect
    ? "inset(0px " + (box.w - rect.left - rect.width) + "px 0px " + rect.left + "px round 0px)"
    : "inset(0px)";
  const clip = leaving ? door : phase === 0 ? door : phase === 1 ? slit : "inset(0px)";
  const inside = phase === 2 && !leaving;

  const circle = (on) => ({
    flex: "0 0 auto", width: 40, height: 40, borderRadius: "var(--radius-pill)",
    background: on ? "var(--white)" : "var(--ink-900)",
    color: on ? "var(--black)" : "var(--white)",
    border: "1px solid " + (on ? "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 toolRow = (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={{
        flex: "0 0 auto", width: 14, height: 14, 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: 8,
      background: "var(--black)", border: "1px solid var(--white)", borderRadius: "var(--radius-lg)",
      overflow: "hidden", boxShadow: "var(--shadow-float)"
    }}>{children}{footer}</div>
  );

  const lever = (p) => {
    if (!p) return { transform: "perspective(760px)", boxShadow: "none" };
    if (p.zone === "plus") return { transform: "perspective(760px) rotateY(10deg) scale(0.985)", boxShadow: "-16px 12px 30px -16px rgb(0 0 0 / 0.9)" };
    if (p.zone === "minus") return p.empty
      ? { transform: "perspective(760px) rotateY(-4deg)", boxShadow: "7px 5px 16px -14px rgb(0 0 0 / 0.7)" }
      : { transform: "perspective(760px) rotateY(-10deg) scale(0.985)", boxShadow: "16px 12px 30px -16px rgb(0 0 0 / 0.9)" };
    return { transform: "perspective(760px) scale(0.955) translateZ(-10px)", boxShadow: "inset 0 2px 10px rgb(0 0 0 / 0.6)" };
  };

  const B = restaurant.brand || null;
  const theme = B ? {
    "--black": B.bg, "--white": B.fg, "--paper": B.paper,
    "--ink-900": B.surfaceDeep, "--ink-800": B.surface, "--ink-700": B.line, "--ink-600": B.line2,
    "--ink-500": B.faint, "--ink-400": B.dimmer, "--ink-300": B.dim, "--ink-200": B.fg,
    "--ink-100": "rgb(0 0 0 / 0.12)", "--ink-050": "rgb(0 0 0 / 0.06)",
    "--font-display": B.display
  } : null;
  const brandStretch = B ? "normal" : "125%";

  const fadeEnd = count && !checkout ? 206 : 152;
  const fadeStart = count && !checkout ? 158 : 104;
  const storeMask = "linear-gradient(to bottom, transparent 0, transparent 28px, #000 98px, #000 calc(100% - " +
    fadeEnd + "px), transparent calc(100% - " + fadeStart + "px))";

  return (
    <div ref={root} style={{
      ...(theme || {}),
      position: "absolute", inset: 0, zIndex: 300, overflow: "hidden", background: "var(--black)",
      clipPath: clip, WebkitClipPath: clip,
      transition: "clip-path " + (leaving ? "240ms" : "380ms") + " cubic-bezier(0.22, 1, 0.28, 1)"
    }}>
      {!inside && [0, 1].map(side => (
        <div key={side} aria-hidden="true" style={{
          position: "absolute", top: 0, bottom: 0, [side ? "right" : "left"]: 0, zIndex: 6,
          width: phase === 2 ? 0 : "52%",
          background: "linear-gradient(" + (side ? 270 : 90) + "deg, var(--black) 0%, var(--ink-900) 62%, var(--ink-800) 100%)",
          [side ? "borderLeft" : "borderRight"]: "1px solid var(--ink-700)",
          transition: "width 560ms cubic-bezier(0.22, 1, 0.28, 1)"
        }} />
      ))}

      <div ref={scroller} onScroll={onScroll} style={{
        position: "absolute", inset: 0, zIndex: 1, overflowY: "auto", scrollbarWidth: "none",
        opacity: leaving ? 0 : phase === 2 ? 1 : 0,
        transform: inside ? "translateY(0) scale(1)" : "translateY(26px) scale(1.09)",
        transformOrigin: "50% 38%",
        transition: "opacity 300ms var(--ease-out), transform 640ms cubic-bezier(0.16, 1, 0.3, 1)",
        maskImage: storeMask, WebkitMaskImage: storeMask
      }}>
        {/* HERO — logo, claim, lede com saiba mais. Sem canais, sem promo. */}
        <div style={{ padding: "104px 20px 30px", textAlign: "center" }}>
          {/* LOGO-MOEDA — clicar foca e vira o círculo; o verso guarda o saiba mais. */}
          <div style={{
            width: about ? 296 : 116, height: about ? 296 : 116, margin: "0 auto 16px",
            perspective: 1100, cursor: "pointer",
            opacity: inside ? 1 : 0, transform: inside ? "scale(1)" : "scale(0.92)",
            transition: "opacity 420ms var(--ease-out) 60ms, transform 520ms cubic-bezier(0.16, 1, 0.3, 1) 60ms, width 620ms cubic-bezier(0.16, 1, 0.3, 1), height 620ms cubic-bezier(0.16, 1, 0.3, 1)"
          }} onClick={() => setAbout(a => !a)} role="button" tabIndex={0} aria-expanded={about}
            aria-label={about ? "fechar detalhes da loja" : "ver detalhes da loja"}>
            <div style={{
              position: "relative", width: "100%", height: "100%", transformStyle: "preserve-3d",
              transform: "rotateY(" + (about ? 180 : 0) + "deg)",
              transition: "transform 760ms cubic-bezier(0.62, 0.02, 0.3, 1)"
            }}>
              <div style={{
                position: "absolute", inset: 0, borderRadius: "50%", backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden",
                border: B ? "3px solid " + B.accent : "1px solid var(--ink-700)",
                background: B ? B.paper : "var(--ink-900)",
                boxShadow: B ? "0 0 0 5px " + B.gold : "none",
                display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 1,
                fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: brandStretch,
                fontSize: B ? 34 : 40, letterSpacing: B ? "0.01em" : "-0.04em",
                color: B ? B.accent : "var(--ink-400)"
              }}>
                {B && B.logo ? (
                  /* marca com logo próprio: a logo ocupa o selo inteiro */
                  <img src={B.logo} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", borderRadius: "50%" }} />
                ) : (<>
                {B && (
                  <span style={{
                    fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 8, letterSpacing: "0.22em",
                    textTransform: "uppercase", color: B.faint
                  }}>{B.kicker}</span>
                )}
                <span style={{ lineHeight: 0.9 }}>{B ? B.mark : initials(restaurant.name)}</span>
                {B && (
                  <span style={{
                    maxWidth: 84, fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 7,
                    letterSpacing: "0.12em", textTransform: "uppercase", color: B.faint,
                    whiteSpace: "nowrap", overflow: "hidden", textOverflow: "clip"
                  }}>{B.sub}</span>
                )}
                </>)}
              </div>

              <div style={{
                position: "absolute", inset: 0, borderRadius: "50%", overflow: "hidden",
                backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden", transform: "rotateY(180deg)",
                border: B ? "3px solid " + B.accent : "1px solid var(--ink-700)",
                background: B ? B.paper : "var(--ink-900)",
                boxShadow: B ? "0 0 0 5px " + B.gold : "none",
                display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
                gap: 9, padding: "30px 46px", textAlign: "center"
              }}>
                <span style={{
                  fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 8, letterSpacing: "0.22em",
                  textTransform: "uppercase", color: B ? B.faint : "var(--ink-500)"
                }}>o verso</span>
                <p style={{
                  margin: 0, maxWidth: "26ch", fontSize: 11.5, lineHeight: 1.5, textWrap: "pretty",
                  color: B ? B.bg : "var(--ink-300)",
                  display: "-webkit-box", WebkitLineClamp: 7, WebkitBoxOrient: "vertical", overflow: "hidden"
                }}>{hero.about}</p>
                <div style={{
                  display: "flex", flexWrap: "wrap", justifyContent: "center", gap: "3px 9px", maxWidth: "24ch",
                  paddingTop: 8, borderTop: "1px solid " + (B ? B.line : "var(--ink-700)"),
                  fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 8, letterSpacing: "0.1em",
                  textTransform: "uppercase", color: B ? B.accent : "var(--ink-500)"
                }}>
                  <span>★ {restaurant.rating}</span>
                  <span>{PR ? PR.kind : restaurant.cuisine}</span>
                  <span>{restaurant.distance}</span>
                  <span>{PR ? PR.cadence : restaurant.eta}</span>
                  <span>{PR ? PR.fulfil : "entrega " + restaurant.deliveryFee}</span>
                </div>
              </div>
            </div>
          </div>

          <h1 style={{
            fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%", textTransform: "uppercase",
            fontStretch: brandStretch,
            fontSize: B ? 34 : 40, lineHeight: B ? 1.02 : 0.94,
            letterSpacing: B ? "-0.01em" : "-0.045em", color: "var(--white)", margin: "0 0 16px"
          }}>
            {(hero.claim || [restaurant.name]).map((line, i) => (
              <span key={line} style={{
                display: "block",
                color: i === hero.accent ? (B ? B.gold : "transparent") : "var(--white)",
                WebkitTextStroke: i === hero.accent && !B ? "1.2px var(--white)" : "0"
              }}>{line}</span>
            ))}
          </h1>

          <div style={{ maxWidth: "42ch", margin: "0 auto" }}>
            <p style={{
              display: "inline", margin: 0, fontSize: 14.5, lineHeight: 1.55, color: "var(--ink-300)", textWrap: "pretty"
            }}>{hero.lede}{" "}
              <button type="button" onClick={() => setAbout(a => !a)} style={{
                display: "inline", padding: 0, background: "none", border: "none", cursor: "pointer",
                fontStyle: "italic", fontSize: "inherit", lineHeight: "inherit", color: "var(--ink-200)",
                borderBottom: "1px solid var(--ink-600)", whiteSpace: "nowrap"
              }}>{about ? "fechar" : "saiba mais"} <span style={{ fontStyle: "normal" }}>↻</span></button>
            </p>
          </div>

          {/* o carimbo da banca: a próxima fornada, estampada como carimbo de caixote */}
          {PR && (
            <div style={{
              display: "inline-block", marginTop: 18, padding: "7px 12px",
              border: "2px solid " + (B ? B.gold : "var(--white)"), borderRadius: 6,
              transform: "rotate(-2deg)",
              fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 10.5,
              letterSpacing: "0.16em", textTransform: "uppercase",
              color: B ? B.gold : "var(--white)"
            }}>{PR.nextLabel || "próxima fornada"} · {PR.next}</div>
          )}
        </div>

        <div style={{ padding: "26px 20px " + (count ? "420px" : "330px") }}>
          {sections.map(s => {
            let items = menu[s].filter(d => !q || (d.name + " " + (d.description || "")).toLowerCase().includes(q));
            if (only.fav) items = items.filter(d => favs.includes(d.name));
            if (only.options) items = items.filter(d => d.options && d.options.length);
            if (only.tagged) items = items.filter(d => d.tag);
            if (order === "cheap") items = [...items].sort((a, b) => parse(a.price) - parse(b.price));
            if (order === "pricey") items = [...items].sort((a, b) => parse(b.price) - parse(a.price));
            if (order === "az") items = [...items].sort((a, b) => a.name.localeCompare(b.name, "pt-BR"));
            if (!items.length) return null;
            return (
              <div key={s} ref={el => { heads.current[s] = el; }} style={{ paddingTop: 26 }}>
                <div style={{
                  fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%", textTransform: "uppercase",
                  fontSize: 19, letterSpacing: "-0.03em", color: "var(--white)", marginBottom: 12
                }}>{s}</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {items.map(d => {
                    const p = press && press.name === d.name ? press : null;
                    const qty = qtyOf(d);
                    const fav = favs.includes(d.name);
                    const lv = lever(p);
                    return (
                      <div key={d.name} style={{
                        border: "1px solid " + (expanded === d.name ? "var(--ink-400)" : "var(--ink-700)"),
                        borderRadius: 14, background: "var(--ink-900)", overflow: "hidden"
                      }}>
                        <div role="button" tabIndex={0}
                          onPointerDown={e => down(e, d)} onPointerUp={() => up(d)}
                          onPointerLeave={() => { zone.current = null; setPress(null); }}
                          style={{
                            position: "relative", display: "grid", gridTemplateColumns: "minmax(0, 1fr) 108px",
                            gap: 14, padding: 12, cursor: "pointer", userSelect: "none", touchAction: "manipulation",
                            transition: "transform 160ms var(--ease-out), box-shadow 160ms var(--ease-out)",
                            ...lv
                          }}>
                          <div style={{ minWidth: 0, display: "flex", flexDirection: "column" }}>
                            <div style={{ display: "flex", alignItems: "flex-start", gap: 6, fontSize: 16, fontWeight: 600, lineHeight: 1.2, color: "var(--white)" }}>
                              <span style={{ minWidth: 0, textWrap: "pretty" }}>{d.name}</span>
                              <button type="button" data-own aria-label="Favorito"
                                onClick={() => setFavs(f => f.includes(d.name) ? f.filter(x => x !== d.name) : [...f, d.name])}
                                style={{
                                  flex: "0 0 auto", marginTop: 2, padding: 0, width: 15, height: 15, background: "none",
                                  border: "none", cursor: "pointer", color: fav ? "var(--white)" : "var(--ink-600)"
                                }}>
                                <svg viewBox="0 0 24 24" fill="currentColor" width="15" height="15" aria-hidden="true"><polygon points="12,2.5 14.8,9.2 22,9.9 16.5,14.6 18.3,21.5 12,17.9 5.7,21.5 7.5,14.6 2,9.9 9.2,9.2" /></svg>
                              </button>
                            </div>
                            {d.description && (
                              <div style={{
                                marginTop: 4, fontSize: 12.5, lineHeight: 1.4, color: "var(--ink-400)",
                                display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden"
                              }}>{d.description}</div>
                            )}
                            <div style={{ marginTop: "auto", paddingTop: 8, minHeight: 30, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                              <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 14.5, color: B ? B.gold : "var(--white)", whiteSpace: "nowrap" }}>{d.price}</span>
                              {qty > 0 && (
                                <span style={{
                                  margin: "0 auto", width: 30, height: 30, borderRadius: "50%",
                                  display: "flex", alignItems: "center", justifyContent: "center",
                                  background: "rgb(255 255 255 / 0.14)", border: "1px solid rgb(255 255 255 / 0.3)",
                                  color: "var(--white)", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 12
                                }}>{qty}</span>
                              )}
                            </div>
                          </div>

                          <div data-media style={{ position: "relative", width: 108, alignSelf: "stretch" }}>
                            <div style={{
                              position: "absolute", inset: 0, borderRadius: 10, background: "var(--ink-800)",
                              border: "1px solid var(--ink-700)", display: "flex", alignItems: "center", justifyContent: "center",
                              fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%",
                              fontSize: 34, letterSpacing: "-0.04em", color: "var(--ink-600)"
                            }}>{initials(d.name)}</div>
                            {d.tag && (
                              <span style={{
                                position: "absolute", top: 6, left: 6, padding: "3px 6px",
                                background: B ? B.accent : "var(--white)", color: B ? B.paper : "var(--black)", borderRadius: 4, fontFamily: "var(--font-mono)", fontWeight: 700,
                                fontSize: 8, letterSpacing: "0.1em", textTransform: "uppercase"
                              }}>{d.tag}</span>
                            )}
                          </div>

                          {/* zonas: o glifo acende no lado que afundou */}
                          {["minus", "plus"].map(z => (
                            <span key={z} aria-hidden="true" style={{
                              position: "absolute", top: 0, bottom: 0, [z === "minus" ? "left" : "right"]: 0, width: "46%",
                              display: "flex", alignItems: "center", justifyContent: "center",
                              fontFamily: "var(--font-mono)", fontSize: 44, fontWeight: 300, color: "var(--white)",
                              background: "linear-gradient(to " + (z === "minus" ? "right" : "left") + ", rgb(0 0 0 / 0.55), transparent 92%)",
                              opacity: p && p.zone === z ? (p.empty ? 0.35 : 1) : 0,
                              transition: p && p.zone === z ? "opacity 70ms ease" : "opacity 550ms ease",
                              pointerEvents: "none"
                            }}>{z === "minus" ? "−" : "+"}</span>
                          ))}
                        </div>

                        {expanded === d.name && (
                          <div style={{ padding: "0 12px 6px" }}>
                            <ItemOptions item={d} onAdd={addItem} onClose={() => setExpanded(null)} />
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
          {q && !sections.some(s => menu[s].some(d => (d.name + " " + (d.description || "")).toLowerCase().includes(q))) && (
            <div style={{ padding: "28px 0", fontSize: 14, color: "var(--ink-400)" }}>Nada com esse nome no cardápio.</div>
          )}
        </div>
      </div>

      {/* busca · filtro · ordem — flutuantes, alinhados ao endereço */}
      <div style={{
        position: "absolute", top: 48, left: 16, zIndex: 7,
        display: "flex", alignItems: "center", gap: 6,
        opacity: inside && !checkout ? 1 : 0, pointerEvents: inside && !checkout ? "auto" : "none",
        transition: "opacity 260ms var(--ease-out) 80ms"
      }}>
        <button type="button" onClick={close} aria-label="Voltar" style={circle(false)}>
          <Icon d={P.chevronLeft} size={18} stroke={2.25} />
        </button>
        <button type="button" aria-label="Buscar no cardápio" style={circle(tool === "search" || Boolean(q))}
          onClick={() => setTool(t => (t === "search" ? null : "search"))}>
          <Icon d={P.search} size={18} />
        </button>
        {tool === "search" ? (
          <input autoFocus value={search} onChange={e => setSearch(e.target.value)} placeholder="Pastel, chopp…"
            style={{
              width: 132, height: 40, padding: "0 12px", boxSizing: "border-box",
              background: "var(--ink-900)", border: "1px solid var(--ink-600)", borderRadius: "var(--radius-pill)",
              color: "var(--white)", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 11,
              letterSpacing: "0.08em", textTransform: "uppercase", outline: "none"
            }} />
        ) : (
          <>
            <button type="button" aria-label="Filtrar" style={circle(tool === "filter" || Object.values(only).some(Boolean))}
              onClick={() => setTool(t => (t === "filter" ? null : "filter"))}>
              <Icon d={P.filter} size={18} />
            </button>
            <button type="button" aria-label="Ordenar" style={circle(tool === "sort" || order !== "menu")}
              onClick={() => setTool(t => (t === "sort" ? null : "sort"))}>
              <Icon d={P.sort} size={18} />
            </button>
          </>
        )}

        {tool === "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>
            {[["Favoritos", "★", "fav"], ["Com adicionais", "opções", "options"], ["Destaques", "novo · popular", "tagged"]]
              .map(([l, m, k]) => toolRow(l, m, Boolean(only[k]), () => setOnly(o => ({ ...o, [k]: !o[k] })), "box"))}
          </div>,
          <button type="button" onClick={() => { setOnly({}); setTool(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>
        )}

        {tool === "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>
            {[["Do cardápio", "casa", "menu"], ["Menor preço", "R$", "cheap"], ["Maior preço", "R$", "pricey"], ["A–Z", "nome", "az"]]
              .map(([l, m, k]) => toolRow(l, m, order === k, () => { setOrder(k); setTool(null); }, "dot"))}
          </div>
        )}
      </div>

      {/* categorias do cardápio, mesmo tratamento das categorias do feed */}
      <div style={{
        position: "absolute", inset: 0, zIndex: 2, pointerEvents: "none",
        opacity: inside && !checkout ? 1 : 0, transition: "opacity 260ms var(--ease-out)"
      }}>
        <CategoryRail items={[restaurant.name, ...sections]}
          index={section === HERO ? 0 : sections.indexOf(section) + 1}
          onIndex={i => goSection(i === 0 ? HERO : sections[i - 1])} active={false} progress={0}
          bottom={count && !checkout ? 94 : 26} />
      </div>

      {/* Sacola */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0, zIndex: 2,
        transform: count && !checkout ? "translateY(0)" : "translateY(110%)",
        transition: "transform var(--dur-base) var(--ease-out)",
        background: "var(--black)", borderTop: "1px solid var(--ink-600)",
        padding: "14px 16px 20px", display: "flex", alignItems: "center", gap: 14
      }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-300)" }}>Sacola · {plural(count, "item", "itens")}</div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%", fontSize: 22, color: "var(--white)", lineHeight: 1.1 }}>{brl(subtotal)}</div>
        </div>
        <Button onClick={() => setCheckout(true)}>Ir ao balcão</Button>
      </div>

      {/* Balcão */}
      <div className="beco-light" style={{
        position: "absolute", left: 0, right: 0, bottom: 0, top: 56, zIndex: 3, overflow: "hidden",
        transform: checkout ? "translateY(0)" : "translateY(101%)",
        transition: "transform 420ms cubic-bezier(0.16, 1, 0.3, 1)",
        background: "var(--paper)", color: "var(--black)",
        borderTopLeftRadius: 18, borderTopRightRadius: 18,
        boxShadow: "0 -20px 44px rgb(0 0 0 / 0.6)",
        display: "flex", flexDirection: "column"
      }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: "16px 16px 12px", borderBottom: "1px solid var(--ink-100)" }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-400)" }}>Balcão</div>
            <div style={{
              fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%", textTransform: "uppercase",
              fontSize: 20, letterSpacing: "-0.03em", color: "var(--black)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"
            }}>{restaurant.name}</div>
          </div>
          <button type="button" onClick={() => setCheckout(false)} aria-label="Voltar à loja"
            style={{
              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)"
            }}>Voltar</button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: "16px", scrollbarWidth: "none", display: "flex", flexDirection: "column", gap: 22 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {cart.map(i => (
              <div key={i.name} style={{ display: "flex", alignItems: "center", gap: 11 }}>
                <QuantityStepper size="sm" value={i.qty} min={0} onChange={n => onQty(i.name, n)} />
                <span style={{ flex: 1, minWidth: 0, fontSize: 13.5, color: "var(--black)" }}>{i.name}</span>
                <span style={{ flex: 1, height: 1, borderBottom: "1px dotted var(--ink-200)" }} />
                <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 12.5, color: "var(--black)" }}>{brl(parse(i.price) * i.qty)}</span>
              </div>
            ))}
          </div>

          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-400)", marginBottom: 8 }}>{PR ? "Receber" : "Entrega"}</div>
            <div style={{ fontSize: 13.5, color: "var(--black)" }}>{here.line}</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-400)", marginTop: 4 }}>{PR ? (PR.nextWord || "fornada") + " " + PR.next : restaurant.eta} · {here.district}</div>
          </div>

          {/* ASSINATURA — a recorrência da Feira decide-se aqui, no balcão */}
          {PR && PR.sub && (
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-400)", marginBottom: 8 }}>Frequência</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                {[
                  { id: "once", label: "Só desta vez", note: (PR.nextWord || "fornada") + " " + PR.next },
                  { id: "sub", label: "Assinar · " + PR.sub.label, note: PR.sub.desc + " — pausa quando quiser" }
                ].map(o => {
                  const on = recur === o.id;
                  return (
                    <button key={o.id} type="button" onClick={() => setRecur(o.id)} style={{
                      display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, width: "100%",
                      textAlign: "left", padding: "11px 13px", cursor: "pointer", borderRadius: 10,
                      border: "1.5px solid " + (on ? "var(--black)" : "var(--ink-200)"),
                      background: on ? "var(--black)" : "transparent",
                      color: on ? "var(--paper)" : "var(--black)",
                      transition: "background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out)"
                    }}>
                      <span>
                        <span style={{ display: "block", fontSize: 13.5, fontWeight: 600 }}>{o.label}</span>
                        <span style={{ display: "block", fontSize: 11.5, marginTop: 2, opacity: 0.62 }}>{o.note}</span>
                      </span>
                      <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9.5, letterSpacing: "0.14em", textTransform: "uppercase", opacity: on ? 1 : 0 }}>ok</span>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-400)", marginBottom: 8 }}>Pagamento</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
              {[{ id: "pix", label: "Pix", note: "Aprovação na hora" }, { id: "cartao", label: "Cartão na entrega", note: "Crédito ou débito" }].map(o => {
                const on = pay === o.id;
                return (
                  <button key={o.id} type="button" onClick={() => setPay(o.id)} style={{
                    display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, width: "100%",
                    textAlign: "left", padding: "11px 13px", cursor: "pointer", borderRadius: 10,
                    border: "1.5px solid " + (on ? "var(--black)" : "var(--ink-200)"),
                    background: on ? "var(--black)" : "transparent",
                    color: on ? "var(--paper)" : "var(--black)",
                    transition: "background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out)"
                  }}>
                    <span>
                      <span style={{ display: "block", fontSize: 13.5, fontWeight: 600 }}>{o.label}</span>
                      <span style={{ display: "block", fontSize: 11.5, marginTop: 2, opacity: 0.62 }}>{o.note}</span>
                    </span>
                    <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9.5, letterSpacing: "0.14em", textTransform: "uppercase", opacity: on ? 1 : 0 }}>ok</span>
                  </button>
                );
              })}
            </div>
          </div>

          <div style={{ borderTop: "1px dashed var(--ink-300)", paddingTop: 12, display: "flex", flexDirection: "column", gap: 6 }}>
            {[["Subtotal", brl(subtotal)], ["Entrega", brl(delivery)], ["Taxa de serviço", "R$ 0,00"]].map(([k, v]) => (
              <div key={k} style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.04em", color: "var(--ink-500)" }}>
                <span style={{ textTransform: "uppercase" }}>{k}</span>
                <span style={{ flex: 1, borderBottom: "1px dotted var(--ink-200)" }} />
                <span style={{ fontWeight: 700, color: "var(--black)" }}>{v}</span>
              </div>
            ))}
            <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 10, marginTop: 8 }}>
              <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-400)" }}>Total</span>
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%", fontSize: 32, letterSpacing: "-0.04em", color: "var(--black)", lineHeight: 1 }}>{brl(total)}</span>
            </div>
          </div>
        </div>

        <div style={{ padding: "0 16px 22px" }}>
          <button type="button" onClick={() => { setPaid(true); setTimeout(() => { setPaid(false); setCheckout(false); onConfirm({ sub: Boolean(PR && PR.sub && recur === "sub") }); }, 1500); }}
            style={{
              width: "100%", height: 52, background: "var(--black)", color: "var(--paper)", border: "none",
              borderRadius: 12, cursor: "pointer", fontFamily: "var(--font-display)", fontWeight: 900,
              fontStretch: "125%", textTransform: "uppercase", fontSize: 14, letterSpacing: "0.02em"
            }}>{PR && recur === "sub" ? "Assinar e pagar " : "Pagar "}{brl(total)}</button>
        </div>

        {paid && (
          <div style={{
            position: "absolute", inset: 0, background: "var(--paper)", display: "flex",
            flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 10
          }}>
            <div style={{
              padding: "12px 20px", border: "3px solid var(--black)", borderRadius: 8,
              transform: "rotate(-6deg)", animation: "beco-stamp 420ms cubic-bezier(0.16, 1, 0.3, 1) both",
              fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%", textTransform: "uppercase",
              fontSize: 26, letterSpacing: "-0.02em", color: "var(--black)"
            }}>{PR && recur === "sub" ? "Assinatura feita" : "Pedido feito"}</div>
            <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-400)" }}>{PR ? (PR.nextWord || "fornada") + " " + PR.next : "chega em " + restaurant.eta}</div>
          </div>
        )}
      </div>
    </div>
  );
}
Object.assign(window, { RestaurantView });
