// mb-shop.jsx — Lojas feed + Loja do parceiro (iFood style)

const money = (n) => "R$ " + n.toFixed(2).replace(".", ",");

// ── Video helpers ─────────────────────────────────────────────
function getVideoEmbed(url) {
  if (!url) return null;
  const yt = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/);
  if (yt) return { type: "iframe", src: `https://www.youtube.com/embed/${yt[1]}?autoplay=1&rel=0` };
  const vm = url.match(/vimeo\.com\/(\d+)/);
  if (vm) return { type: "iframe", src: `https://player.vimeo.com/video/${vm[1]}?autoplay=1` };
  if (/\.(mp4|webm|mov)(\?|$)/i.test(url)) return { type: "video", src: url };
  return { type: "external", src: url };
}

function VideoModal({ url, title, onClose }) {
  const embed = getVideoEmbed(url);
  React.useEffect(() => {
    const handler = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, []);
  if (!embed) return null;
  if (embed.type === "external") {
    window.open(embed.src, "_blank", "noopener,noreferrer");
    onClose();
    return null;
  }
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 999, background: "rgba(0,0,0,.95)", display: "flex", flexDirection: "column" }} onClick={onClose}>
      {/* header */}
      <div onClick={e => e.stopPropagation()} style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 16px", paddingTop: "max(20px, env(safe-area-inset-top, 20px))", flexShrink: 0 }}>
        <div style={{ width: 34, height: 34, borderRadius: 10, background: "#DC2626", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="#fff"><polygon points="3,1 13,7 3,13" /></svg>
        </div>
        <span style={{ flex: 1, font: "700 15px var(--ui)", color: "#fff", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{title}</span>
        <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: 10, background: "rgba(255,255,255,.12)", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
          <Icon name="close" size={18} color="#fff" sw={2.2} />
        </button>
      </div>
      {/* player */}
      <div onClick={e => e.stopPropagation()} style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "0 0 max(24px, env(safe-area-inset-bottom, 24px))" }}>
        {embed.type === "iframe"
          ? <iframe src={embed.src} style={{ width: "100%", aspectRatio: "16/9", border: "none" }} allow="autoplay; encrypted-media; fullscreen" allowFullScreen />
          : <video src={embed.src} controls autoPlay playsInline style={{ width: "100%", maxHeight: "70vh", outline: "none" }} />
        }
      </div>
    </div>
  );
}

function ShopScreen({ segments, onOpenStore, wallet, onNovoLar, onServices, onGastro, onOpenNotifs, unread }) {
  const segs = segments || SEGMENTS;
  const [apiPartners, setApiPartners] = React.useState(null);
  const [apiLoaded, setApiLoaded] = React.useState(false);
  const [addrPickerOpen, setAddrPickerOpen] = React.useState(false);
  const [savedAddresses, setSavedAddresses] = React.useState([]);
  const [defaultAddr, setDefaultAddr] = React.useState(null);
  const [userPos, setUserPos] = React.useState(null);
  const [searchQuery, setSearchQuery] = React.useState("");
  const [shopSeg, setShopSeg] = React.useState(null);
  const [moreSegsOpen, setMoreSegsOpen] = React.useState(false);
  const searchRef = React.useRef(null);

  React.useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        pos => setUserPos({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
        () => {}
      );
    }
  }, []);

  React.useEffect(() => {
    const params = {};
    if (userPos?.lat != null) { params.lat = userPos.lat; params.lng = userPos.lng; }
    API.discover(params)
      .then(d => {
        let mapped = (d.companies || []).map(apiCompanyToPartner);
        if (userPos?.lat) mapped = recalcDistances(mapped, userPos.lat, userPos.lng);
        setApiPartners(mapped);
        setApiLoaded(true);
      })
      .catch(() => setApiLoaded(true));
    if (Auth.isLogged()) {
      API.me.addresses().then(d => {
        const list = d.addresses || [];
        setSavedAddresses(list);
        setDefaultAddr(list.find(a => a.is_default) || list[0] || null);
      }).catch(() => {});
    }
  }, [userPos?.lat, userPos?.lng]);

  const partners = apiLoaded ? (apiPartners || []) : PARTNERS;

  // Filter by active segment + search query, sort Diamante first
  const filtered = React.useMemo(() => {
    return partners
      .filter(p => {
        if (p.hub) return false;
        if (shopSeg && p.seg !== shopSeg) return false;
        if (searchQuery) {
          const q = searchQuery.toLowerCase();
          return (p.name || "").toLowerCase().includes(q) || (p.cat || "").toLowerCase().includes(q);
        }
        return true;
      })
      .sort((a, b) => planRank(b) - planRank(a) || b.rating - a.rating);
  }, [partners, shopSeg, searchQuery]);

  const turbo = React.useMemo(() =>
    filtered.filter(p => p.turbo > 0).sort((a, b) => planRank(b) - planRank(a) || b.turbo - a.turbo),
    [filtered]);

  const isFiltering = !!searchQuery || !!shopSeg;

  const addrLabel = defaultAddr
    ? `${defaultAddr.label} · ${defaultAddr.neighborhood}, ${defaultAddr.city}`
    : "Adicionar endereço";

  return (
    <div style={{ position: "absolute", inset: 0, overflow: "auto", paddingBottom: TAB_H2 }}>
      {/* header */}
      <div style={{ background: "var(--brand)", padding: "28px 16px 20px", borderRadius: "0 0 24px 24px" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <button onClick={() => setAddrPickerOpen(true)} style={{ background: "none", border: "none", cursor: "pointer", padding: 0, textAlign: "left" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 5, color: "rgba(255,255,255,.7)", font: "600 12px var(--ui)" }}>
              <Icon name="pin" size={14} color="rgba(255,255,255,.7)" sw={2} />ENTREGAR EM
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 5, color: "#fff", font: "700 16px var(--ui)", marginTop: 2 }}>
              {addrLabel} <Icon name="chevD" size={16} color="#fff" sw={2.4} />
            </div>
          </button>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <button onClick={onOpenNotifs} style={{ width: 40, height: 40, borderRadius: 999, border: "none", cursor: "pointer", background: "rgba(255,255,255,.14)", display: "flex", alignItems: "center", justifyContent: "center", position: "relative" }}>
              <Icon name="bell" size={20} color="#fff" />
              {unread > 0 && <span style={{ position: "absolute", top: 6, right: 7, minWidth: 16, height: 16, padding: "0 4px", borderRadius: 999, background: "var(--turbo-grad)", color: "#fff", font: "700 10px var(--ui)", display: "flex", alignItems: "center", justifyContent: "center", border: "2px solid var(--brand)" }}>{unread}</span>}
            </button>
            {Auth.isLogged() && wallet?.balance != null && (
              <button style={{ display: "flex", alignItems: "center", gap: 7, background: "rgba(255,255,255,.14)", border: "none", cursor: "pointer", borderRadius: 999, padding: "7px 12px 7px 9px" }}>
                <Icon name="wallet" size={17} color="#fff" /><span style={{ font: "700 13px var(--ui)", color: "#fff" }}>{money(wallet.balance)}</span>
              </button>
            )}
          </div>
        </div>
        {/* search input */}
        <div style={{ marginTop: 16, height: 46, borderRadius: 13, background: "var(--surface)", display: "flex", alignItems: "center", gap: 10, padding: "0 14px" }}>
          <Icon name="search" size={20} color="var(--muted)" />
          <input
            ref={searchRef}
            type="text"
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            placeholder="Buscar lojas e produtos"
            style={{ flex: 1, border: "none", background: "none", outline: "none", font: "500 14.5px var(--ui)", color: "var(--text)" }}
          />
          {searchQuery && (
            <button onClick={() => setSearchQuery("")} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--muted)", font: "700 18px var(--ui)", lineHeight: 1, padding: "0 2px" }}>×</button>
          )}
        </div>
      </div>

      {/* Segmentos — 9 visíveis + 10° é "Ver mais" que abre bottom sheet */}
      {(() => {
        const LIMIT = 9;
        const visibleSegs = segs.slice(0, LIMIT);
        const extraSegs = segs.slice(LIMIT);
        const hasMore = extraSegs.length > 0;
        const activeInExtra = shopSeg && extraSegs.some(s => s.id === shopSeg);
        const segBtn = (s, onClick) => {
          const active = shopSeg === s.id;
          const label = (s.question || s.q || "").replace(/^Onde /i, "").replace(/\?$/, "");
          return (
            <button key={s.id} onClick={onClick} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 5, background: "none", border: "none", cursor: "pointer", padding: 0 }}>
              <div style={{ width: 46, height: 46, borderRadius: 14, background: active ? "var(--accent)" : "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: active ? "0 4px 12px var(--accent-shadow)" : "none", transition: "background .15s, box-shadow .15s" }}>
                <Icon name={s.icon || segIcon(s.id)} size={22} color={active ? "#fff" : "var(--accent)"} sw={1.9} />
              </div>
              <span style={{ font: `${active ? 700 : 600} 9.5px var(--ui)`, color: active ? "var(--accent)" : "var(--text)", textAlign: "center", lineHeight: 1.2, maxWidth: 58 }}>{label}</span>
            </button>
          );
        };
        return (
          <>
            <div style={{ padding: "14px 16px 4px" }}>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: "10px 4px" }}>
                {visibleSegs.map(s => segBtn(s, () => setShopSeg(shopSeg === s.id ? null : s.id)))}
                {hasMore && (() => {
                  const activeSeg = activeInExtra ? segs.find(s => s.id === shopSeg) : null;
                  const iconName = activeSeg ? (activeSeg.icon || segIcon(activeSeg.id)) : "grid";
                  const label = activeSeg
                    ? (activeSeg.question || activeSeg.q || "").replace(/^Onde /i,"").replace(/\?$/,"")
                    : "Ver mais";
                  return (
                    <button onClick={() => setMoreSegsOpen(true)} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 5, background: "none", border: "none", cursor: "pointer", padding: 0 }}>
                      <div style={{ width: 46, height: 46, borderRadius: 14, background: activeInExtra ? "var(--accent)" : "var(--bg)", border: activeInExtra ? "none" : "1.5px dashed var(--line)", display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden" }}>
                        <Icon name={iconName} size={20} color={activeInExtra ? "#fff" : "var(--muted)"} sw={1.9} />
                      </div>
                      <span style={{ font: `${activeInExtra ? 700 : 600} 9.5px var(--ui)`, color: activeInExtra ? "var(--accent)" : "var(--muted)", textAlign: "center", lineHeight: 1.2, maxWidth: 52, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {label}
                      </span>
                    </button>
                  );
                })()}
              </div>
            </div>
            {/* Bottom sheet — segmentos extras */}
            {moreSegsOpen && (
              <div style={{ position: "fixed", inset: 0, zIndex: 900, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
                <div onClick={() => setMoreSegsOpen(false)} style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,.45)", backdropFilter: "blur(3px)" }} />
                <div style={{ position: "relative", background: "var(--bg)", borderRadius: "22px 22px 0 0", padding: "20px 18px 44px", maxHeight: "70vh", display: "flex", flexDirection: "column" }}>
                  <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--line)", margin: "0 auto 18px" }} />
                  <div style={{ font: "800 17px var(--ui)", color: "var(--text)", marginBottom: 16 }}>Mais segmentos</div>
                  <div style={{ flex: 1, overflowY: "auto" }}>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: "14px 4px" }}>
                      {extraSegs.map(s => segBtn(s, () => { setShopSeg(shopSeg === s.id ? null : s.id); setMoreSegsOpen(false); }))}
                    </div>
                  </div>
                  {activeInExtra && (
                    <button onClick={() => { setShopSeg(null); setMoreSegsOpen(false); }}
                      style={{ marginTop: 14, background: "none", border: "none", cursor: "pointer", font: "700 13.5px var(--ui)", color: "var(--muted)", textDecoration: "underline" }}>
                      Limpar filtro
                    </button>
                  )}
                </div>
              </div>
            )}
          </>
        );
      })()}

      {/* Jornadas — layout horizontal compacto */}
      <div style={{ display: "flex", gap: 8, padding: "12px 16px 2px" }}>
        {[
          { fn: onNovoLar,  bg: "var(--brand)",                             ic: "home",   t: "Novo Lar",    s: "Terreno ao décor" },
          { fn: onServices, bg: "var(--accent)",                            ic: "health", t: "Serviços",    s: "Limpeza, chaveiro…" },
          { fn: onGastro,   bg: "linear-gradient(135deg,#E8552D,#C98A1B)", ic: "food",   t: "Gastronômico", s: "Gastronomia local" },
        ].map(f => (
          <button key={f.t} onClick={f.fn} style={{ flex: 1, textAlign: "left", cursor: "pointer", border: "none", borderRadius: 14, padding: "11px 12px", background: f.bg, color: "#fff", position: "relative", overflow: "hidden", minHeight: 76 }}>
            <Icon name={f.ic} size={44} color="rgba(255,255,255,.12)" sw={1.4} style={{ position: "absolute", right: -4, bottom: -6 }} />
            <div style={{ width: 28, height: 28, borderRadius: 8, background: "rgba(255,255,255,.18)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 6 }}>
              <Icon name={f.ic} size={15} color="#fff" />
            </div>
            <div style={{ font: "800 12px var(--ui)", lineHeight: 1.2 }}>{f.t}</div>
            <div style={{ font: "500 9.5px var(--ui)", color: "rgba(255,255,255,.78)", marginTop: 1, lineHeight: 1.3 }}>{f.s}</div>
          </button>
        ))}
      </div>

      {/* Resultados filtrados (busca ou segmento ativo) */}
      {isFiltering ? (
        <Section title={shopSeg ? SEGMENTS.find(s => s.id === shopSeg)?.q || "Resultados" : `Resultados para "${searchQuery}"`}>
          {filtered.length === 0
            ? <div style={{ padding: "4px 16px 8px", font: "500 13.5px var(--ui)", color: "var(--muted)" }}>Nenhum parceiro encontrado.</div>
            : <div className="mb-tablet-2col" style={{ display: "flex", flexDirection: "column", gap: 14, padding: "0 16px" }}>
                {filtered.map(p => <PartnerCard key={p.id} p={p} onOpen={onOpenStore} />)}
              </div>
          }
        </Section>
      ) : (
        <>
          {/* turbo rail */}
          {turbo.length > 0 && (
            <Section title="BemCash Turbo" sub="Mais dinheiro de volta">
              <div className="mb-noscroll" style={{ display: "flex", gap: 12, overflowX: "auto", padding: "0 16px 4px" }}>
                {turbo.map(p => <PartnerCard key={p.id} p={p} onOpen={onOpenStore} variant="carousel" />)}
              </div>
            </Section>
          )}

          {/* best rated list */}
          <Section title="Bem avaliados perto de você">
            <div className="mb-tablet-2col" style={{ display: "flex", flexDirection: "column", gap: 14, padding: "0 16px" }}>
              {filtered.slice(0, 8).map(p => <PartnerCard key={p.id} p={p} onOpen={onOpenStore} />)}
            </div>
          </Section>
        </>
      )}

      {/* ── Seletor de endereço ── */}
      {addrPickerOpen && (
        <div style={{ position: "fixed", inset: 0, zIndex: 900, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
          <div onClick={() => setAddrPickerOpen(false)} style={{ position: "absolute", inset: 0, background: "rgba(16,18,45,.45)" }} />
          <div style={{ position: "relative", background: "var(--surface)", borderRadius: "22px 22px 0 0", padding: "20px 16px 40px", maxHeight: "70vh", overflow: "auto" }}>
            <div style={{ width: 36, height: 4, borderRadius: 999, background: "var(--line)", margin: "0 auto 18px" }} />
            <div style={{ font: "800 17px var(--ui)", color: "var(--text)", marginBottom: 16 }}>Entregar em</div>

            {savedAddresses.length === 0 ? (
              <div style={{ font: "500 14px var(--ui)", color: "var(--muted)", textAlign: "center", padding: "16px 0" }}>
                Nenhum endereço cadastrado.<br />Adicione em Perfil → Endereços.
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {savedAddresses.map(addr => {
                  const active = defaultAddr?.id === addr.id;
                  return (
                    <button key={addr.id} onClick={() => { setDefaultAddr(addr); setAddrPickerOpen(false); }}
                      style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 16px", borderRadius: 16,
                        background: active ? "var(--accent-50)" : "var(--bg)",
                        border: active ? "1.5px solid var(--accent)" : "1.5px solid var(--line)",
                        cursor: "pointer" }}>
                      <div style={{ width: 40, height: 40, borderRadius: 12, background: active ? "var(--accent)" : "var(--line)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                        <Icon name="pin" size={20} color={active ? "var(--accent-ink)" : "var(--muted)"} sw={2} />
                      </div>
                      <div style={{ flex: 1, textAlign: "left" }}>
                        <div style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>{addr.label || "Endereço"}</div>
                        <div style={{ font: "500 12px var(--ui)", color: "var(--muted)", marginTop: 2 }}>
                          {[addr.street, addr.number, addr.neighborhood, addr.city].filter(Boolean).join(", ")}
                        </div>
                      </div>
                      {active && <Icon name="check" size={18} color="var(--accent)" sw={2.5} />}
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function Section({ title, sub, children }) {
  return (
    <div style={{ marginTop: 20 }}>
      <div style={{ padding: "0 16px 12px" }}>
        <h3 style={{ margin: 0, font: "800 18px var(--ui)", color: "var(--text)" }}>{title}</h3>
        {sub && <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", marginTop: 2 }}>{sub}</div>}
      </div>
      {children}
    </div>
  );
}

// ── Loja do parceiro ─────────────────────────────────────────
function StoreScreen({ partner, mode, setMode, onBack, onPick, getQty, cartCount, cartTotal, onOpenCart, onNeedLogin }) {
  const companyId = partner._raw?.id || partner.id;

  // Busca detalhe completo (garante phone/whatsapp/instagram/video mesmo
  // quando o partner veio do listing sem todos os campos)
  const [detail, setDetail] = React.useState(null);
  React.useEffect(() => {
    if (!companyId) return;
    API.company(companyId).then(c => setDetail(apiCompanyToPartner(c))).catch(() => {});
  }, [companyId]);
  const p = detail || partner;

  const [showMapSheet, setShowMapSheet] = React.useState(false);
  const [videoOpen, setVideoOpen] = React.useState(false);
  const [reviewOpen, setReviewOpen] = React.useState(false);
  const handleReview = () => { if (!Auth.isLogged()) { onNeedLogin?.(); return; } setReviewOpen(true); };
  const [isFav, setIsFav] = React.useState(false);
  React.useEffect(() => {
    if (!companyId || !Auth.isLogged()) return;
    API.me.favorites().then(d => {
      setIsFav((d.favorites || []).some(f => f.id === companyId));
    }).catch(() => {});
  }, [companyId]);
  const toggleFav = () => {
    if (!Auth.isLogged()) { onNeedLogin?.(); return; }
    if (isFav) { API.me.removeFavorite(companyId).catch(() => {}); setIsFav(false); }
    else        { API.me.addFavorite(companyId).catch(() => {});    setIsFav(true);  }
  };

  // Carrega produtos reais da API
  const [apiMenu, setApiMenu] = React.useState(null);
  React.useEffect(() => {
    API.products(companyId).then(d => {
      const prods = d.products || [];
      // Agrupa por category_name (igual ao formato de menu do mock)
      const groups = {};
      prods.filter(pr => pr.active).forEach(pr => {
        const grp = pr.category_name || "Cardápio";
        if (!groups[grp]) groups[grp] = [];
        groups[grp].push({
          id: pr.id,
          name: pr.name,
          desc: pr.description || "",
          price: parseFloat(pr.price) || 0,
          img: pr.image_url || null,
        });
      });
      const sections = Object.entries(groups).map(([title, items]) => ({ title, items }));
      setApiMenu(sections.length ? sections : null);
    }).catch(() => {});
  }, [companyId]);

  const menu = apiMenu || menuFor(p.id);
  const totalCb = p.cashback + p.turbo;
  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
      <div style={{ flex: 1, overflow: "auto", paddingBottom: cartCount > 0 ? 92 : 24 }}>
        {/* hero */}
        <div style={{ position: "relative" }}>
          {p.coverUrl
            ? <img src={p.coverUrl} alt={p.name} style={{ width: "100%", height: 188, objectFit: "cover", display: "block" }} />
            : <Ph label={p.cat} h={188} r={0} />}
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to bottom, rgba(16,18,45,.28), transparent 40%)" }} />
          <div style={{ position: "absolute", top: 50, left: 14, right: 14, display: "flex", justifyContent: "space-between" }}>
            <IconBtn name="arrowL" onClick={onBack} size={40} bg="rgba(255,255,255,.95)" />
            <div style={{ display: "flex", gap: 8 }}>
              <IconBtn name="share" size={40} bg="rgba(255,255,255,.95)" onClick={() => {
                const url = window.location.href.split('?')[0] + '?loja=' + (p._raw?.slug || p.id);
                if (navigator.share) {
                  navigator.share({ title: p.name, text: p.blurb || 'Confira no Morar Bem!', url });
                } else {
                  navigator.clipboard?.writeText(url).then(() => {});
                }
              }} />
              <IconBtn name="heart" size={40} bg="rgba(255,255,255,.95)" color={isFav ? "#E55" : undefined} fill={isFav ? "#E55" : "none"} onClick={toggleFav} />
            </div>
          </div>
        </div>

        {/* store card */}
        <div style={{ background: "var(--surface)", margin: "-26px 12px 0", borderRadius: 20, padding: 16, position: "relative", boxShadow: "0 6px 20px rgba(16,18,45,.08)" }}>
          <div style={{ display: "flex", gap: 12 }}>
            <div style={{ width: 52, height: 52, borderRadius: 14, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name={segIcon(p.seg)} size={26} color="var(--accent)" />
            </div>
            <div style={{ flex: 1 }}>
              <h2 style={{ margin: 0, font: "800 20px var(--ui)", color: "var(--text)" }}>{p.name}</h2>
              <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", marginTop: 2 }}>{p.cat} · {p.area} · {p.price}</div>
            </div>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 13, font: "600 12.5px var(--ui)", color: "var(--text)", flexWrap: "wrap" }}>
            {p.reviews > 0 && (
              <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "#C77E12" }}>
                <Icon name="star" size={15} color="#F5A524" fill="#F5A524" sw={1.4} />
                {parseFloat(p.rating).toFixed(1)} <span style={{ color: "var(--muted)", fontWeight: 500 }}>({p.reviews})</span>
              </span>
            )}
            <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--muted)" }}><Icon name="pin" size={15} sw={2} />{p.dist > 0 ? p.dist + " km" : "—"}</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--muted)" }}><Icon name="clock" size={15} sw={2} />{p.time}</span>
            <button onClick={handleReview} style={{ display: "inline-flex", alignItems: "center", gap: 4, background: "var(--accent-50)", border: "none", borderRadius: 999, padding: "3px 10px", cursor: "pointer", font: "600 12px var(--ui)", color: "var(--accent)" }}>
              <Icon name="star" size={13} color="var(--accent)" fill="none" sw={2} />Avaliar
            </button>
          </div>

          <div style={{ display: "flex", gap: 7, marginTop: 13 }}>
            <Cashback pct={p.cashback} />
            {p.turbo > 0 && <Turbo pct={p.turbo} />}
            {p.turbo > 0 && <span style={{ font: "700 12px var(--ui)", color: "var(--cb)", alignSelf: "center" }}>= {totalCb}% de volta</span>}
          </div>
        </div>

        {/* mode toggle */}
        <div style={{ display: "flex", gap: 8, background: "var(--surface)", margin: "12px 12px 0", padding: 5, borderRadius: 14, boxShadow: "0 4px 14px rgba(16,18,45,.05)" }}>
          {[["delivery", "Entrega", "bike", p.delivery], ["pickup", "Retirada na loja", "store", p.pickup]].map(([id, lbl, ic, ok]) => (
            <button key={id} disabled={!ok} onClick={() => setMode(id)} style={{
              flex: 1, height: 50, borderRadius: 11, border: "none", cursor: ok ? "pointer" : "not-allowed",
              background: mode === id ? "var(--brand)" : "transparent", opacity: ok ? 1 : .4,
              display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 1,
            }}>
              <span style={{ display: "flex", alignItems: "center", gap: 6, font: "700 13.5px var(--ui)", color: mode === id ? "#fff" : "var(--text)" }}>
                <Icon name={ic} size={17} color={mode === id ? "#fff" : "var(--text)"} sw={2} />{lbl}
              </span>
              <span style={{ font: "600 11px var(--ui)", color: mode === id ? "rgba(255,255,255,.8)" : "var(--muted)" }}>
                {id === "delivery" ? (p.fee === 0 ? "Grátis · " + p.time : money(p.fee) + " · " + p.time) : "Grátis · pronto em 15 min"}
              </span>
            </button>
          ))}
        </div>

        {p.turbo > 0 && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "12px 12px 0", padding: "12px 14px", borderRadius: 14, background: "var(--cb-bg)" }}>
            <Icon name="bolt" size={20} color="var(--cb)" fill="var(--cb)" sw={1.5} />
            <span style={{ font: "600 12.5px var(--ui)", color: "var(--cb-ink)" }}>Esta loja turbinou o cashback. Você recebe <b>{totalCb}% de volta</b> em BemCash a cada compra.</span>
          </div>
        )}

        {/* one-purchase rule note */}
        <div style={{ display: "flex", alignItems: "center", gap: 8, margin: "10px 16px 0", font: "500 11.5px var(--ui)", color: "var(--muted)" }}>
          <Icon name="info" size={15} sw={2} />Cashback válido em 1 compra por parceiro a cada pedido.
        </div>

        {/* quick-action bar */}
        {(p.address || p.whatsapp || p.phone || p.instagram || p.video) && (
          <div style={{ display: "flex", gap: 8, margin: "14px 12px 0", overflowX: "auto" }} className="mb-noscroll">
            {p.video && (
              <button onClick={() => setVideoOpen(true)} style={qaBtn("#FEF2F2", "#DC2626")}>
                <svg width="16" height="16" viewBox="0 0 16 16" fill="#DC2626"><polygon points="4,2 14,8 4,14" /></svg>
                <span>Ver vídeo</span>
              </button>
            )}
            {p.address && (
              <button onClick={() => setShowMapSheet(true)} style={qaBtn("#EEF2FF", "#4F46E5")}>
                <Icon name="pin" size={17} color="#4F46E5" sw={2} />
                <span>Localização</span>
              </button>
            )}
            {p.phone && (
              <a href={"tel:" + p.phone.replace(/\D/g, "")} style={qaBtn("#FFF7ED", "#EA580C")}>
                <Icon name="phone" size={17} color="#EA580C" sw={2} />
                <span>Ligar agora</span>
              </a>
            )}
            {p.whatsapp && (
              <a href={"https://wa.me/55" + p.whatsapp.replace(/\D/g, "")} target="_blank" rel="noopener noreferrer" style={qaBtn("#F0FDF4", "#16A34A")}>
                <svg width="17" height="17" viewBox="0 0 24 24" fill="#16A34A"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/><path d="M12 0C5.373 0 0 5.373 0 12c0 2.09.536 4.057 1.475 5.776L.057 23.012a.5.5 0 00.637.608l5.398-1.734C7.846 23.247 9.876 24 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 22c-1.969 0-3.826-.536-5.426-1.474l-.388-.228-4.017 1.29 1.235-4.125-.238-.393A9.937 9.937 0 012 12C2 6.477 6.477 2 12 2s10 4.477 10 10-4.477 10-10 10z"/></svg>
                <span>WhatsApp</span>
              </a>
            )}
            {p.instagram && (
              <a href={"https://instagram.com/" + p.instagram.replace(/^@/, "")} target="_blank" rel="noopener noreferrer" style={qaBtn("#FDF2F8", "#C026D3")}>
                <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#C026D3" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="5" ry="5"/><path d="M16 11.37A4 4 0 1112.63 8 4 4 0 0116 11.37z"/><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/></svg>
                <span>Instagram</span>
              </a>
            )}
          </div>
        )}

        {/* video modal */}
        {videoOpen && p.video && (
          <VideoModal url={p.video} title={p.name} onClose={() => setVideoOpen(false)} />
        )}
        {/* avaliação geral */}
        {reviewOpen && <CompanyReviewModal companyId={companyId} companyName={p.name} onClose={() => setReviewOpen(false)} />}

        {/* map options sheet */}
        {showMapSheet && (
          <div style={{ position: "fixed", inset: 0, zIndex: 999, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
            <div onClick={() => setShowMapSheet(false)} style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,.45)" }} />
            <div style={{ position: "relative", background: "var(--surface)", borderRadius: "20px 20px 0 0", padding: "20px 16px 36px" }}>
              <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--line)", margin: "0 auto 18px" }} />
              <div style={{ font: "800 16px var(--ui)", color: "var(--text)", marginBottom: 6 }}>Localização</div>
              {p.address && <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", marginBottom: 16, lineHeight: 1.4 }}>{p.address}</div>}
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {(() => {
                  const lat = p._raw?.latitude, lng = p._raw?.longitude;
                  const gmUrl = lat && lng
                    ? `https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`
                    : `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(p.address || p.name)}`;
                  const wazeUrl = lat && lng
                    ? `https://waze.com/ul?ll=${lat},${lng}&navigate=yes`
                    : `https://waze.com/ul?q=${encodeURIComponent(p.address || p.name)}`;
                  return (<>
                    <a href={gmUrl} target="_blank" rel="noopener noreferrer" style={mapOptionBtn("#4285F4")}>
                      <svg width="20" height="20" viewBox="0 0 48 48"><path fill="#4285F4" d="M24 4C13.51 4 5 12.51 5 23c0 11.92 16.15 27.53 18.08 29.34a1.5 1.5 0 002.84 0C27.85 50.53 43 34.92 43 23c0-10.49-8.51-19-19-19z"/><circle fill="#fff" cx="24" cy="23" r="7"/></svg>
                      <span style={{ flex: 1, font: "700 14px var(--ui)", color: "#1a1a2e" }}>Abrir no Google Maps</span>
                      <Icon name="chevR" size={16} color="var(--muted)" sw={2} />
                    </a>
                    <a href={wazeUrl} target="_blank" rel="noopener noreferrer" style={mapOptionBtn("#33CCFF")}>
                      <svg width="20" height="20" viewBox="0 0 48 48"><ellipse cx="24" cy="26" rx="19" ry="17" fill="#33CCFF"/><circle cx="17" cy="35" r="4" fill="#fff"/><circle cx="31" cy="35" r="4" fill="#fff"/><ellipse cx="18" cy="20" rx="3" ry="3.5" fill="#fff"/><ellipse cx="30" cy="20" rx="3" ry="3.5" fill="#fff"/><ellipse cx="18" cy="21" rx="1.5" ry="2" fill="#333"/><ellipse cx="30" cy="21" rx="1.5" ry="2" fill="#333"/><path d="M20 27 q4 4 8 0" stroke="#333" strokeWidth="1.5" fill="none" strokeLinecap="round"/></svg>
                      <span style={{ flex: 1, font: "700 14px var(--ui)", color: "#1a1a2e" }}>Abrir no Waze</span>
                      <Icon name="chevR" size={16} color="var(--muted)" sw={2} />
                    </a>
                    {p.phone && (
                      <a href={"tel:" + p.phone.replace(/\D/g, "")} style={mapOptionBtn("#F3F4F6")}>
                        <Icon name="phone" size={20} color="#374151" sw={2} />
                        <span style={{ flex: 1, font: "700 14px var(--ui)", color: "#1a1a2e" }}>{p.phone}</span>
                        <Icon name="chevR" size={16} color="var(--muted)" sw={2} />
                      </a>
                    )}
                  </>);
                })()}
              </div>
              <button onClick={() => setShowMapSheet(false)} style={{ marginTop: 14, width: "100%", height: 46, borderRadius: 13, border: "none", cursor: "pointer", background: "var(--line)", font: "700 14px var(--ui)", color: "var(--text)" }}>Fechar</button>
            </div>
          </div>
        )}

        {/* menu */}
        {menu.map(sec => (
          <div key={sec.title} style={{ marginTop: 22 }}>
            <h3 style={{ margin: 0, padding: "0 16px 8px", font: "800 16px var(--ui)", color: "var(--text)" }}>{sec.title}</h3>
            <div className="mb-tablet-2col" style={{ display: "flex", flexDirection: "column" }}>
              {sec.items.map(it => {
                const q = getQty(it.id);
                return (
                  <button key={it.id} onClick={() => onPick(it)} style={{
                    display: "flex", gap: 12, alignItems: "stretch", textAlign: "left", cursor: "pointer",
                    background: "none", border: "none", borderTop: "1px solid var(--line)", padding: "14px 16px",
                  }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <span style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{it.name}</span>
                        {it.tag && <span style={{ font: "700 9.5px var(--ui)", color: "var(--accent)", background: "var(--accent-50)", padding: "1px 6px", borderRadius: 5 }}>{it.tag.toUpperCase()}</span>}
                      </div>
                      <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", marginTop: 4, lineHeight: 1.4, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{it.desc}</div>
                      <div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 8 }}>
                        <span style={{ font: "700 14.5px var(--ui)", color: "var(--text)" }}>{money(it.price)}</span>
                        <Cashback pct={totalCb} small />
                      </div>
                    </div>
                    <div style={{ position: "relative", width: 96, flexShrink: 0 }}>
                      {it.img && it.img.startsWith("http")
                        ? <img src={it.img} alt={it.name} style={{ width: 96, height: 96, objectFit: "cover", borderRadius: 12, display: "block" }} />
                        : <Ph label={it.img || "item"} h={96} r={12} />}
                      <div style={{ position: "absolute", right: 6, bottom: 6, width: 32, height: 32, borderRadius: 10, background: "var(--surface)", boxShadow: "0 3px 10px rgba(16,18,45,.16)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--accent)" }}>
                        {q > 0 ? <span style={{ font: "800 14px var(--ui)", color: "var(--accent)" }}>{q}</span> : <Icon name="plus" size={18} color="var(--accent)" sw={2.4} />}
                      </div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>

      {/* cart bar */}
      {cartCount > 0 && (
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, padding: "10px 14px 26px", background: "linear-gradient(to top, var(--surface) 70%, transparent)" }}>
          <button onClick={onOpenCart} style={{
            width: "100%", height: 54, borderRadius: 15, border: "none", cursor: "pointer",
            background: "var(--accent)", color: "var(--accent-ink)", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 18px",
            boxShadow: "0 8px 22px var(--accent-shadow)",
          }}>
            <span style={{ display: "flex", alignItems: "center", gap: 9, font: "700 15px var(--ui)" }}>
              <span style={{ width: 26, height: 26, borderRadius: 8, background: "rgba(255,255,255,.25)", display: "flex", alignItems: "center", justifyContent: "center", font: "800 13px var(--ui)" }}>{cartCount}</span>
              Ver sacola
            </span>
            <span style={{ font: "800 15px var(--ui)" }}>{money(cartTotal)}</span>
          </button>
        </div>
      )}
    </div>
  );
}

function qaBtn(bg, color) {
  return {
    display: "inline-flex", alignItems: "center", gap: 6, flexShrink: 0,
    padding: "9px 14px", borderRadius: 12, border: "none", cursor: "pointer",
    background: bg, font: "600 13px var(--ui)", color, textDecoration: "none",
    whiteSpace: "nowrap",
  };
}

function mapOptionBtn(bg) {
  return {
    display: "flex", alignItems: "center", gap: 12, padding: "14px 16px",
    borderRadius: 14, background: bg, textDecoration: "none", border: "none", cursor: "pointer",
  };
}

Object.assign(window, { money, ShopScreen, Section, StoreScreen, VideoModal, getVideoEmbed });
