// mb-storekinds.jsx — Agenda (booking) & Vitrine (showcase) stores + sheets

function StoreHero({ p, onBack, badge, isFav, onToggleFav, onReview }) {
  return (
    <>
      <div style={{ position: "relative" }}>
        {p.coverUrl
          ? <img src={p.coverUrl} alt={p.name} className="mb-store-cover" style={{ width: "100%", height: 188, objectFit: "cover", display: "block" }} />
          : <Ph label={p.cat} h={188} r={0} className="mb-store-cover" />}
        <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={onToggleFav} />
          </div>
        </div>
      </div>
      <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, overflow: "hidden", flexShrink: 0 }}>
            {p.logoUrl
              ? <img src={p.logoUrl} alt={p.name} style={{ width: 52, height: 52, objectFit: "cover" }} />
              : <Icon name={segIcon(p.seg) || "store"} size={26} color="var(--accent)" />}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 8 }}>
              <h2 style={{ margin: 0, font: "800 20px var(--ui)", color: "var(--text)", flex: 1, minWidth: 0 }}>{p.name}</h2>
              {badge && <div style={{ flexShrink: 0, marginTop: 2 }}>{badge}</div>}
            </div>
            <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", marginTop: 2 }}>{p.cat} · {p.area}</div>
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 13, font: "600 12.5px var(--ui)", 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.area}</span>
          {onReview && (
            <button onClick={onReview} 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>
    </>
  );
}

// ── Barra de contato rápido — canais de comunicação (WhatsApp, Ligar, Instagram) ──
function ContactBar({ p }) {
  const hasAny = p.whatsapp || p.phone || p.instagram;
  if (!hasAny) return null;

  const tileLink = (icon, label, href) => (
    <a key={label} href={href} target="_blank" rel="noopener noreferrer"
      style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
        textDecoration: "none", flexShrink: 0, minWidth: 60 }}>
      <div style={{ width: 54, height: 54, borderRadius: 16, background: "transparent",
        border: "1.5px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        {icon}
      </div>
      <span style={{ font: "600 11px var(--ui)", color: "var(--muted)", whiteSpace: "nowrap" }}>{label}</span>
    </a>
  );

  return (
    <div style={{ display: "flex", gap: 14, margin: "18px 16px 0", justifyContent: "center", flexWrap: "wrap" }}>
      {p.whatsapp && tileLink(
        <svg width="24" height="24" 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>,
        "WhatsApp", "https://wa.me/55" + p.whatsapp.replace(/\D/g, "")
      )}
      {p.phone && !p.whatsapp && tileLink(
        <Icon name="phone" size={24} color="#EA580C" sw={2} />,
        "Ligar", "tel:" + p.phone.replace(/\D/g, "")
      )}
      {p.instagram && tileLink(
        <svg width="24" height="24" 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"/><path d="M16 11.37A4 4 0 1112.63 8 4 4 0 0116 11.37z"/><circle cx="17.5" cy="6.5" r=".5" fill="#C026D3" stroke="none"/></svg>,
        "Instagram", "https://instagram.com/" + p.instagram.replace(/^@/, "")
      )}
    </div>
  );
}

// ── Agenda store ─────────────────────────────────────────────
function AgendaStore({ partner, onBack, onBook, onNeedLogin }) {
  const companyId = partner._raw?.id || partner.id;

  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 totalCb = p.cashback + p.turbo;

  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);
    }
  };

  const [apiServices, setApiServices] = React.useState(null);
  const [videoOpen, setVideoOpen] = React.useState(false);
  const [contactOpen, setContactOpen] = React.useState(false);
  React.useEffect(() => {
    API.services(companyId).then(d => {
      const svcs = (d.services || []).filter(s => s.active).map(s => ({
        id: s.id,
        name: s.name,
        desc: s.description || "",
        price: s.price ? parseFloat(s.price) : null,
        dur: s.duration_min ? Math.floor(s.duration_min / 60) + "h" + (s.duration_min % 60 ? (s.duration_min % 60) + "min" : "") : "—",
        _raw: s,
      }));
      if (svcs.length) setApiServices(svcs);
    }).catch(() => {});
  }, [companyId]);

  const services = apiServices || servicesFor(p);
  const [reviewOpen, setReviewOpen] = React.useState(false);
  const handleReview = () => { if (!Auth.isLogged()) { onNeedLogin?.(); return; } setReviewOpen(true); };
  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
      <div style={{ flex: 1, overflow: "auto", paddingBottom: 24 }}>
        <StoreHero p={p} onBack={onBack} isFav={isFav} onToggleFav={toggleFav} onReview={handleReview} badge={<>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 4, background: "var(--accent-50)", color: "var(--accent)", font: "700 12.5px var(--ui)", padding: "3px 9px", borderRadius: 999 }}><Icon name="clock" size={13} sw={2.2} />Agendamento</span>
          {totalCb > 0 && <Cashback pct={p.cashback} />}
          {p.turbo > 0 && <Turbo pct={p.turbo} />}
        </>} />

        {/* botão de vídeo */}
        {p.video && (
          <div style={{ padding: "12px 12px 0" }}>
            <button onClick={() => setVideoOpen(true)} style={{ width: "100%", height: 46, borderRadius: 14, border: "none", cursor: "pointer", background: "#1a1a1a", display: "flex", alignItems: "center", justifyContent: "center", gap: 10 }}>
              <svg width="18" height="18" viewBox="0 0 18 18" fill="#fff"><polygon points="4,2 16,9 4,16" /></svg>
              <span style={{ font: "700 14px var(--ui)", color: "#fff" }}>Ver vídeo institucional</span>
            </button>
          </div>
        )}

        <ContactBar p={p} />

        {/* Botões: Localização + Contato */}
        {(p.address || p.whatsapp || p.phone) && (
          <div style={{ display: "flex", gap: 10, margin: "14px 16px 0" }}>
            {p.address && (
              <a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(p.address)}
                target="_blank" rel="noopener noreferrer"
                style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                  height: 48, borderRadius: 14, background: "#EEF2FF", border: "1.5px solid #C7D2FE",
                  textDecoration: "none" }}>
                <Icon name="pin" size={17} color="#4F46E5" sw={2} />
                <span style={{ font: "700 13.5px var(--ui)", color: "#4F46E5" }}>Localização</span>
              </a>
            )}
            {(p.whatsapp || p.phone) && (
              <button onClick={() => setContactOpen(true)}
                style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                  height: 48, borderRadius: 14, background: "var(--accent)", border: "none", cursor: "pointer" }}>
                <Icon name="headset" size={17} color="#fff" sw={1.8} />
                <span style={{ font: "700 13.5px var(--ui)", color: "#fff" }}>Contato</span>
              </button>
            )}
          </div>
        )}

        {p.horario && (
          <div style={{ display: "flex", alignItems: "center", gap: 8, margin: "10px 16px 0", font: "500 12.5px var(--ui)", color: "var(--muted)" }}>
            <Icon name="clock" size={15} sw={2} />{p.horario}
          </div>
        )}

        <div style={{ display: "flex", alignItems: "center", gap: 8, margin: "12px 16px 0", font: "600 12px var(--ui)", color: "var(--muted)" }}>
          <Icon name="info" size={15} sw={2} />Escolha o serviço, a data e o horário. Você confirma sem pagar agora.
        </div>

        <h3 style={{ margin: 0, padding: "20px 16px 4px", font: "800 16px var(--ui)", color: "var(--text)" }}>Serviços</h3>
        <div className="mb-tablet-2col">
          {services.map(s => (
            <div key={s.id} style={{ display: "flex", gap: 12, alignItems: "center", padding: "14px 16px", borderTop: "1px solid var(--line)" }}>
              <div style={{ flex: 1 }}>
                <div style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{s.name}</div>
                <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", marginTop: 3, lineHeight: 1.4 }}>{s.desc}</div>
                <div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>{s.price == null ? "Sob consulta" : money(s.price)}</span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 4, font: "600 12px var(--ui)", color: "var(--muted)" }}><Icon name="clock" size={13} sw={2} />{s.dur}</span>
                  {totalCb > 0 && s.price != null && <Cashback pct={totalCb} small />}
                </div>
              </div>
              <Btn variant="soft" onClick={() => onBook(s)} style={{ height: 42, padding: "0 16px", borderRadius: 12 }}>Agendar</Btn>
            </div>
          ))}
        </div>
      </div>
      {videoOpen && p.video && <VideoModal url={p.video} title={p.name} onClose={() => setVideoOpen(false)} />}
      {reviewOpen && <CompanyReviewModal companyId={companyId} companyName={p.name} onClose={() => setReviewOpen(false)} onDone={() => API.company(companyId).catch(() => {})} />}

      {contactOpen && (
        <div style={{ position: "fixed", inset: 0, zIndex: 60, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
          <div onClick={() => setContactOpen(false)} style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,.5)", backdropFilter: "blur(3px)" }} />
          <div style={{ position: "relative", background: "var(--surface)", borderRadius: "22px 22px 0 0", padding: "22px 18px 40px" }}>
            <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--line)", margin: "0 auto 20px" }} />
            <div style={{ font: "800 17px var(--ui)", color: "var(--text)", marginBottom: 4 }}>Como quer entrar em contato?</div>
            <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", marginBottom: 20 }}>{p.name}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {p.whatsapp && (
                <a href={"https://wa.me/55" + p.whatsapp.replace(/\D/g, "") + "?text=" + encodeURIComponent(`Olá! Vi a empresa "${p.name}" no Morar Bem e tenho interesse.`)}
                  target="_blank" rel="noopener noreferrer"
                  style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 16px", borderRadius: 15, background: "#F0FDF4", border: "1.5px solid #BBF7D0", textDecoration: "none" }}>
                  <div style={{ width: 44, height: 44, borderRadius: 13, background: "#16A34A", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff"><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>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ font: "700 14.5px var(--ui)", color: "#15803D" }}>Falar pelo WhatsApp</div>
                    <div style={{ font: "500 12px var(--ui)", color: "#16A34A", marginTop: 2 }}>Resposta mais rápida</div>
                  </div>
                  <Icon name="chevR" size={18} color="#16A34A" sw={2.2} />
                </a>
              )}
              {p.phone && (
                <a href={"tel:" + p.phone.replace(/\D/g, "")}
                  style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 16px", borderRadius: 15, background: "#FFF7ED", border: "1.5px solid #FED7AA", textDecoration: "none" }}>
                  <div style={{ width: 44, height: 44, borderRadius: 13, background: "#EA580C", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <Icon name="phone" size={22} color="#fff" sw={2} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ font: "700 14.5px var(--ui)", color: "#9A3412" }}>Ligar agora</div>
                    <div style={{ font: "500 12px var(--ui)", color: "#EA580C", marginTop: 2 }}>{p.phone}</div>
                  </div>
                  <Icon name="chevR" size={18} color="#EA580C" sw={2.2} />
                </a>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Listing detail — fullscreen ───────────────────────────────
function ListingDetailSheet({ item, partner, onClose, onContact }) {
  const specs = (item._specs || item.specs || []).filter(s => s[0] !== "Segmento");
  const segmento = (item._specs || item.specs || []).find(s => s[0] === "Segmento")?.[1] || null;
  const imgs = item.imgs && item.imgs.length ? item.imgs : (item.img && item.img.startsWith("http") ? [item.img] : []);
  const [imgIdx, setImgIdx] = React.useState(0);
  const [videoOpen, setVideoOpen]   = React.useState(false);
  const [mapOpen,   setMapOpen]     = React.useState(false);
  const [contactNowOpen, setContactNowOpen] = React.useState(false);
  const hasImgs   = imgs.length > 0;
  const hasVideo  = !!item.videoUrl;
  const hasMap    = item.lat != null && item.lng != null;
  const p = partner || {};

  // Auto-advance das fotos a cada 3.8s
  React.useEffect(() => {
    if (imgs.length < 2) return;
    const t = setInterval(() => setImgIdx(i => (i + 1) % imgs.length), 3800);
    return () => clearInterval(t);
  }, [imgs.length]);

  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 40, background: "var(--bg)", display: "flex", flexDirection: "column" }}>

      {/* ── Hero: imagens ── */}
      <div style={{ position: "relative", flexShrink: 0, height: hasImgs ? "44%" : 160, overflow: "hidden", background: "var(--brand)" }}>
        {hasImgs
          ? imgs.map((url, i) => (
              <img key={i} src={url} alt={item.title}
                style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: i === imgIdx ? 1 : 0, transition: "opacity .35s" }} />
            ))
          : <Ph label={item.title} h="100%" r={0} style={{ position: "absolute", inset: 0 }} />
        }
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(13,16,46,.72) 0%, rgba(13,16,46,.1) 55%, transparent 100%)" }} />

        {/* botão fechar */}
        <button onClick={onClose} style={{ position: "absolute", top: 48, left: 16, width: 38, height: 38, borderRadius: 12, border: "none", background: "rgba(255,255,255,.18)", backdropFilter: "blur(8px)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="arrowL" size={20} color="#fff" sw={2.2} />
        </button>

        {/* contador de fotos — sempre no mesmo lugar, sem conflito com botão de vídeo */}
        {imgs.length > 1 && (
          <div style={{ position: "absolute", top: 52, right: 16, background: "rgba(16,18,45,.55)", backdropFilter: "blur(6px)", borderRadius: 9, padding: "5px 10px", font: "600 12px var(--ui)", color: "#fff" }}>
            {imgIdx + 1} / {imgs.length}
          </div>
        )}

        {/* setas de navegação */}
        {imgs.length > 1 && (<>
          <button onClick={() => setImgIdx(i => Math.max(0, i - 1))} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", width: 34, height: 34, borderRadius: 999, background: "rgba(255,255,255,.18)", backdropFilter: "blur(6px)", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="arrowL" size={15} color="#fff" sw={2.2} />
          </button>
          <button onClick={() => setImgIdx(i => Math.min(imgs.length - 1, i + 1))} style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", width: 34, height: 34, borderRadius: 999, background: "rgba(255,255,255,.18)", backdropFilter: "blur(6px)", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="chevR" size={15} color="#fff" sw={2.2} />
          </button>
        </>)}

        {/* título + preço + vídeo sobre a imagem */}
        <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, padding: "20px 18px 14px" }}>
          {segmento && (
            <span style={{ display: "inline-block", font: "700 10.5px var(--ui)", color: "rgba(255,255,255,.85)", background: "rgba(255,255,255,.18)", borderRadius: 6, padding: "3px 9px", marginBottom: 6, letterSpacing: ".04em", textTransform: "uppercase" }}>{segmento}</span>
          )}
          <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
            <h2 style={{ margin: 0, font: "800 20px var(--ui)", color: "#fff", lineHeight: 1.2, textShadow: "0 1px 8px rgba(0,0,0,.3)", flex: 1 }}>{item.title}</h2>
            {hasVideo && (
              <button onClick={() => setVideoOpen(true)} style={{
                flexShrink: 0, display: "flex", alignItems: "center", gap: 7,
                background: "rgba(220,38,38,.82)", backdropFilter: "blur(8px)",
                border: "1px solid rgba(255,255,255,.22)",
                borderRadius: 12, padding: "9px 15px", cursor: "pointer",
              }}>
                <svg width="14" height="14" viewBox="0 0 12 12" fill="#fff"><polygon points="2,1 11,6 2,11" /></svg>
                <span style={{ font: "700 13px var(--ui)", color: "#fff", whiteSpace: "nowrap" }}>Ver vídeo</span>
              </button>
            )}
          </div>
          <div style={{ font: "800 17px var(--ui)", color: "#fff", marginTop: 4, opacity: .92 }}>{item.priceLabel}</div>
        </div>

        {/* dots */}
        {imgs.length > 1 && (
          <div style={{ position: "absolute", bottom: -14, left: 0, right: 0, display: "flex", justifyContent: "center", gap: 5, zIndex: 2 }}>
            {imgs.map((_, i) => (
              <div key={i} onClick={() => setImgIdx(i)} style={{ width: i === imgIdx ? 20 : 6, height: 6, borderRadius: 999, background: i === imgIdx ? "var(--accent)" : "var(--line)", transition: "width .25s", cursor: "pointer" }} />
            ))}
          </div>
        )}
      </div>

      {/* ── Conteúdo scrollável ── */}
      <div style={{ flex: 1, overflow: "auto", paddingBottom: 24, paddingTop: imgs.length > 1 ? 22 : 8 }}>

        {/* Specs em grid */}
        {specs.length > 0 && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8, padding: "8px 16px 12px" }}>
            {specs.map(([k, v], i) => (
              <div key={i} style={{ background: "var(--surface)", borderRadius: 12, padding: "10px 12px", boxShadow: "0 2px 8px rgba(16,18,45,.05)" }}>
                <div style={{ font: "600 10px var(--ui)", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 3 }}>{k}</div>
                <div style={{ font: "700 13.5px var(--ui)", color: "var(--text)" }}>{v}</div>
              </div>
            ))}
          </div>
        )}

        {/* Botões: Ver no mapa + Solicitar contato lado a lado */}
        <div style={{ padding: "0 16px 14px", display: "flex", gap: 10 }}>
          {hasMap && (
            <button onClick={() => setMapOpen(true)} style={{
              flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 9,
              background: "linear-gradient(135deg, #0E7C86 0%, #0A5F68 100%)",
              border: "none", borderRadius: 16, padding: "15px 10px", cursor: "pointer",
              boxShadow: "0 6px 18px rgba(14,124,134,.28)",
            }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>
              <span style={{ font: "700 13.5px var(--ui)", color: "#fff" }}>Ver no mapa</span>
            </button>
          )}
          <button onClick={() => setContactNowOpen(true)} style={{
            flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 9,
            background: "var(--accent)", border: "none", borderRadius: 16, padding: "15px 10px", cursor: "pointer",
            boxShadow: "0 6px 18px rgba(24,27,87,.22)",
          }}>
            <Icon name="headset" size={18} color="#fff" sw={1.8} />
            <span style={{ font: "700 13.5px var(--ui)", color: "#fff" }}>Solicitar contato</span>
          </button>
        </div>

        {/* Descrição */}
        {item.desc && (
          <div style={{ padding: "0 16px 16px" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
              <div style={{ font: "700 11px var(--ui)", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".08em" }}>Descrição</div>
              {item.urlAnuncio && (
                <a href={item.urlAnuncio} target="_blank" rel="noopener noreferrer"
                  style={{ display: "inline-flex", alignItems: "center", gap: 4, font: "600 12px var(--ui)", color: "var(--accent)", textDecoration: "none", opacity: .85 }}>
                  <Icon name="eye" size={14} color="var(--accent)" sw={2} />Ver mais
                </a>
              )}
            </div>
            <p style={{ margin: 0, font: "600 14.5px var(--ui)", color: "var(--text)", lineHeight: 1.7, textAlign: "justify", hyphens: "auto" }}>{item.desc}</p>
          </div>
        )}

        {/* "Ver mais informações" sem descrição */}
        {item.urlAnuncio && !item.desc && (
          <div style={{ padding: "0 16px 12px" }}>
            <a href={item.urlAnuncio} target="_blank" rel="noopener noreferrer"
              style={{ display: "inline-flex", alignItems: "center", gap: 5, font: "600 13px var(--ui)", color: "var(--accent)", textDecoration: "none" }}>
              <Icon name="eye" size={15} color="var(--accent)" sw={2} />Ver mais informações
            </a>
          </div>
        )}
      </div>

      {/* ── Modal vídeo fullscreen ── */}
      {videoOpen && <VideoFullscreen url={item.videoUrl} onClose={() => setVideoOpen(false)} />}

      {/* ── Modal mapa localização ── */}
      {mapOpen && <LocationMapModal lat={item.lat} lng={item.lng} title={item.title} onClose={() => setMapOpen(false)} />}

      {/* ── Modal contato rápido ── */}
      {contactNowOpen && (
        <div style={{ position: "fixed", inset: 0, zIndex: 60, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
          <div onClick={() => setContactNowOpen(false)} style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,.5)", backdropFilter: "blur(3px)" }} />
          <div style={{ position: "relative", background: "var(--surface)", borderRadius: "22px 22px 0 0", padding: "22px 18px 40px" }}>
            <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--line)", margin: "0 auto 20px" }} />
            <div style={{ font: "800 17px var(--ui)", color: "var(--text)", marginBottom: 4 }}>Como quer entrar em contato?</div>
            <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", marginBottom: 20 }}>
              {p.name || "Parceiro"} · {item.title}
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {/* WhatsApp — prioritário */}
              {p.whatsapp && (
                <a href={"https://wa.me/55" + p.whatsapp.replace(/\D/g, "") + "?text=" + encodeURIComponent(`Olá! Vi o anúncio "${item.title}" no Morar Bem e tenho interesse.`)}
                  target="_blank" rel="noopener noreferrer"
                  style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 16px", borderRadius: 15, background: "#F0FDF4", border: "1.5px solid #BBF7D0", textDecoration: "none" }}>
                  <div style={{ width: 44, height: 44, borderRadius: 13, background: "#16A34A", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff"><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>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ font: "700 14.5px var(--ui)", color: "#15803D" }}>Falar pelo WhatsApp</div>
                    <div style={{ font: "500 12px var(--ui)", color: "#16A34A", marginTop: 2 }}>Resposta mais rápida</div>
                  </div>
                  <Icon name="chevR" size={18} color="#16A34A" sw={2.2} />
                </a>
              )}
              {/* Ligar */}
              {p.phone && (
                <a href={"tel:" + p.phone.replace(/\D/g, "")}
                  style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 16px", borderRadius: 15, background: "#FFF7ED", border: "1.5px solid #FED7AA", textDecoration: "none" }}>
                  <div style={{ width: 44, height: 44, borderRadius: 13, background: "#EA580C", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <Icon name="phone" size={22} color="#fff" sw={2} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ font: "700 14.5px var(--ui)", color: "#9A3412" }}>Ligar agora</div>
                    <div style={{ font: "500 12px var(--ui)", color: "#EA580C", marginTop: 2 }}>{p.phone}</div>
                  </div>
                  <Icon name="chevR" size={18} color="#EA580C" sw={2.2} />
                </a>
              )}
              {/* Formulário de lead */}
              <button onClick={() => { setContactNowOpen(false); onContact(); }}
                style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 16px", borderRadius: 15, background: "var(--bg)", border: "1.5px solid var(--line)", cursor: "pointer", textAlign: "left" }}>
                <div style={{ width: 44, height: 44, borderRadius: 13, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  <Icon name="headset" size={22} color="var(--accent)" sw={1.8} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ font: "700 14.5px var(--ui)", color: "var(--text)" }}>Deixar mensagem</div>
                  <div style={{ font: "500 12px var(--ui)", color: "var(--muted)", marginTop: 2 }}>A empresa entra em contato com você</div>
                </div>
                <Icon name="chevR" size={18} color="var(--muted)" sw={2} />
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Vitrine store ────────────────────────────────────────────
function VitrineStore({ partner, onBack, onLead, onNeedLogin }) {
  const companyId = partner._raw?.id || partner.id;

  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 [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);  }
  };

  const [apiListings, setApiListings] = React.useState(null);
  React.useEffect(() => {
    API.listings(companyId).then(d => {
      const ls = (d.listings || []).filter(l => l.active).map(l => ({
        id: l.id, title: l.title, desc: l.description || "",
        priceLabel: l.price_label || "Sob consulta", specs: l.specs || [],
        img: (l.image_urls && l.image_urls[0]) || null, imgs: l.image_urls || [],
        urlAnuncio: l.url_anuncio || null, lat: l.lat ?? null, lng: l.lng ?? null,
        videoUrl: l.video_url || null, _raw: l,
      }));
      if (ls.length) setApiListings(ls);
    }).catch(() => {});
  }, [companyId]);

  const items = apiListings || catalogFor(p);
  const [detailItem, setDetailItem] = React.useState(null);
  const [videoOpen, setVideoOpen] = React.useState(false);
  const [contactOpen, setContactOpen] = React.useState(false);
  const [reviewOpen, setReviewOpen] = React.useState(false);
  const handleReview = () => { if (!Auth.isLogged()) { onNeedLogin?.(); return; } setReviewOpen(true); };

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
      <div style={{ flex: 1, overflow: "auto", paddingBottom: TAB_H }}>
        {/* badge: só ícone, sem texto "Divulgação" */}
        <StoreHero p={p} onBack={onBack} isFav={isFav} onToggleFav={toggleFav} onReview={handleReview} badge={
          <span style={{ display: "inline-flex", alignItems: "center", background: "var(--brand)", color: "#fff", padding: "5px 8px", borderRadius: 999 }}>
            <Icon name="store" size={13} color="#fff" sw={2} />
          </span>
        } />

        {p.blurb && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "12px 12px 0", padding: "12px 14px", borderRadius: 14, background: "var(--accent-50)" }}>
            <Icon name="info" size={19} color="var(--accent)" sw={2} />
            <span style={{ font: "600 12.5px var(--ui)", color: "var(--text)" }}>{p.blurb}</span>
          </div>
        )}

        {/* botão de vídeo */}
        {p.video && (
          <div style={{ padding: "12px 12px 0" }}>
            <button onClick={() => setVideoOpen(true)} style={{ width: "100%", height: 46, borderRadius: 14, border: "none", cursor: "pointer", background: "#1a1a1a", display: "flex", alignItems: "center", justifyContent: "center", gap: 10 }}>
              <svg width="18" height="18" viewBox="0 0 18 18" fill="#fff"><polygon points="4,2 16,9 4,16" /></svg>
              <span style={{ font: "700 14px var(--ui)", color: "#fff" }}>Ver vídeo institucional</span>
            </button>
          </div>
        )}

        <ContactBar p={p} />

        {/* Botões: Localização + Contato */}
        <div style={{ display: "flex", gap: 10, margin: "14px 16px 0" }}>
          {p.address && (
            <a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(p.address)}
              target="_blank" rel="noopener noreferrer"
              style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                height: 48, borderRadius: 14, background: "#EEF2FF", border: "1.5px solid #C7D2FE",
                textDecoration: "none" }}>
              <Icon name="pin" size={17} color="#4F46E5" sw={2} />
              <span style={{ font: "700 13.5px var(--ui)", color: "#4F46E5" }}>Localização</span>
            </a>
          )}
          <button onClick={() => setContactOpen(true)}
            style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
              height: 48, borderRadius: 14, background: "var(--accent)", border: "none", cursor: "pointer" }}>
            <Icon name="headset" size={17} color="#fff" sw={1.8} />
            <span style={{ font: "700 13.5px var(--ui)", color: "#fff" }}>Contato</span>
          </button>
        </div>

        {p.horario && (
          <div style={{ display: "flex", alignItems: "center", gap: 8, margin: "10px 16px 0", font: "500 12.5px var(--ui)", color: "var(--muted)" }}>
            <Icon name="clock" size={15} sw={2} />{p.horario}
          </div>
        )}

        {items.length > 0 && <h3 style={{ margin: 0, padding: "20px 16px 8px", font: "800 16px var(--ui)", color: "var(--text)" }}>Em destaque</h3>}
        <div className="mb-tablet-2col" style={{ display: "flex", flexDirection: "column", gap: 14, padding: "0 12px" }}>
          {items.map(it => (
            <button key={it.id} onClick={() => setDetailItem(it)} style={{ textAlign: "left", border: "none", cursor: "pointer", background: "var(--surface)", borderRadius: 18, overflow: "hidden", boxShadow: "0 4px 16px rgba(16,18,45,.07)", padding: 0 }}>
              {it.img && it.img.startsWith("http")
                ? <img src={it.img} alt={it.title} style={{ width: "100%", height: 150, objectFit: "cover", display: "block" }} />
                : <Ph label={it.img || "foto"} h={150} r={0} />}
              <div style={{ padding: "13px 15px 15px" }}>
                <div style={{ font: "700 15.5px var(--ui)", color: "var(--text)" }}>{it.title}</div>
                <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", marginTop: 4, lineHeight: 1.45, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{it.desc}</div>
                {(it.specs || it._specs || []).filter(s => s[0] !== "Segmento").length > 0 && (
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 10 }}>
                    {(it.specs || it._specs || []).filter(s => s[0] !== "Segmento").slice(0, 3).map(([k, v], i) => (
                      <span key={i} style={{ font: "600 11.5px var(--ui)", color: "var(--muted)", background: "var(--bg)", borderRadius: 6, padding: "3px 8px" }}>{k}: {v}</span>
                    ))}
                  </div>
                )}
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 12 }}>
                  <span style={{ font: "800 16px var(--ui)", color: "var(--brand)" }}>{it.priceLabel}</span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5, font: "700 13px var(--ui)", color: "var(--accent)" }}>Ver detalhes <Icon name="chevR" size={15} sw={2.4} color="var(--accent)" /></span>
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Listing detail bottom sheet */}
      {detailItem && (
        <ListingDetailSheet item={detailItem} partner={p} onClose={() => setDetailItem(null)} onContact={() => { setDetailItem(null); onLead(detailItem); }} />
      )}
      {videoOpen && p.video && <VideoModal url={p.video} title={p.name} onClose={() => setVideoOpen(false)} />}
      {reviewOpen && <CompanyReviewModal companyId={companyId} companyName={p.name} onClose={() => setReviewOpen(false)} />}

      {/* Modal contato rápido */}
      {contactOpen && (
        <div style={{ position: "fixed", inset: 0, zIndex: 60, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
          <div onClick={() => setContactOpen(false)} style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,.5)", backdropFilter: "blur(3px)" }} />
          <div style={{ position: "relative", background: "var(--surface)", borderRadius: "22px 22px 0 0", padding: "22px 18px 40px" }}>
            <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--line)", margin: "0 auto 20px" }} />
            <div style={{ font: "800 17px var(--ui)", color: "var(--text)", marginBottom: 4 }}>Como quer entrar em contato?</div>
            <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", marginBottom: 20 }}>{p.name}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {p.whatsapp && (
                <a href={"https://wa.me/55" + p.whatsapp.replace(/\D/g, "") + "?text=" + encodeURIComponent(`Olá! Vi a empresa "${p.name}" no Morar Bem e tenho interesse.`)}
                  target="_blank" rel="noopener noreferrer"
                  style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 16px", borderRadius: 15, background: "#F0FDF4", border: "1.5px solid #BBF7D0", textDecoration: "none" }}>
                  <div style={{ width: 44, height: 44, borderRadius: 13, background: "#16A34A", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff"><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>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ font: "700 14.5px var(--ui)", color: "#15803D" }}>Falar pelo WhatsApp</div>
                    <div style={{ font: "500 12px var(--ui)", color: "#16A34A", marginTop: 2 }}>Resposta mais rápida</div>
                  </div>
                  <Icon name="chevR" size={18} color="#16A34A" sw={2.2} />
                </a>
              )}
              {p.phone && (
                <a href={"tel:" + p.phone.replace(/\D/g, "")}
                  style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 16px", borderRadius: 15, background: "#FFF7ED", border: "1.5px solid #FED7AA", textDecoration: "none" }}>
                  <div style={{ width: 44, height: 44, borderRadius: 13, background: "#EA580C", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <Icon name="phone" size={22} color="#fff" sw={2} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ font: "700 14.5px var(--ui)", color: "#9A3412" }}>Ligar agora</div>
                    <div style={{ font: "500 12px var(--ui)", color: "#EA580C", marginTop: 2 }}>{p.phone}</div>
                  </div>
                  <Icon name="chevR" size={18} color="#EA580C" sw={2.2} />
                </a>
              )}
              <button onClick={() => { setContactOpen(false); onLead(null); }}
                style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 16px", borderRadius: 15, background: "var(--bg)", border: "1.5px solid var(--line)", cursor: "pointer", textAlign: "left" }}>
                <div style={{ width: 44, height: 44, borderRadius: 13, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  <Icon name="headset" size={22} color="var(--accent)" sw={1.8} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ font: "700 14.5px var(--ui)", color: "var(--text)" }}>Deixar mensagem</div>
                  <div style={{ font: "500 12px var(--ui)", color: "var(--muted)", marginTop: 2 }}>A empresa entra em contato com você</div>
                </div>
                <Icon name="chevR" size={18} color="var(--muted)" sw={2} />
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Booking sheet ────────────────────────────────────────────
const WD = ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"];
const MO = ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"];
function nextDays(n) {
  const out = []; const d = new Date();
  for (let i = 0; i < n; i++) { const x = new Date(d); x.setDate(d.getDate() + i); out.push(x); }
  return out;
}
function BookingSheet({ partner, service, onConfirm }) {
  const days = React.useMemo(() => nextDays(7), []);
  const [di, setDi] = React.useState(1);
  const [time, setTime] = React.useState(null);
  const [local, setLocal] = React.useState("domicilio");
  const slots = ["08:00", "10:00", "13:00", "15:00", "17:00"];
  const d = days[di];
  const dateLabel = `${WD[d.getDay()]}, ${d.getDate()} ${MO[d.getMonth()]}`;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={segIcon(partner.seg)} size={22} color="var(--accent)" /></div>
        <div><div style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{service.name}</div><div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)" }}>{partner.name} · {service.price == null ? "Sob consulta" : money(service.price)}</div></div>
      </div>

      <div>
        <div style={{ font: "700 13.5px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Data</div>
        <div className="mb-noscroll" style={{ display: "flex", gap: 8, overflowX: "auto" }}>
          {days.map((x, i) => (
            <button key={i} onClick={() => setDi(i)} style={{ flexShrink: 0, width: 54, padding: "9px 0", borderRadius: 13, cursor: "pointer", border: di === i ? "1.5px solid var(--accent)" : "1.5px solid var(--line)", background: di === i ? "var(--accent)" : "var(--surface)", color: di === i ? "var(--accent-ink)" : "var(--text)" }}>
              <div style={{ font: "600 11px var(--ui)", opacity: .8 }}>{i === 0 ? "Hoje" : WD[x.getDay()]}</div>
              <div style={{ font: "800 17px var(--ui)", marginTop: 2 }}>{x.getDate()}</div>
            </button>
          ))}
        </div>
      </div>

      <div>
        <div style={{ font: "700 13.5px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Horário</div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {slots.map(s => <Chip key={s} active={time === s} onClick={() => setTime(s)}>{s}</Chip>)}
        </div>
      </div>

      <div>
        <div style={{ font: "700 13.5px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Onde</div>
        <div style={{ display: "flex", gap: 8 }}>
          <Chip icon="home" active={local === "domicilio"} onClick={() => setLocal("domicilio")}>Na minha casa</Chip>
          <Chip icon="store" active={local === "loja"} onClick={() => setLocal("loja")}>No estabelecimento</Chip>
        </div>
      </div>

      <Btn full disabled={!time} onClick={() => {
        const iso = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
        onConfirm({ dateISO: iso, dateLabel, time, local });
      }}>
        {time ? `Confirmar · ${dateLabel} às ${time}` : "Escolha um horário"}
      </Btn>
    </div>
  );
}

// ── Lead sheet (vitrine) ─────────────────────────────────────
function LeadSheet({ partner, listing, onConfirm, user }) {
  const [pref, setPref] = React.useState("whats");
  const [msg, setMsg] = React.useState(listing ? `Tenho interesse em: ${listing.title}` : "Tenho interesse e gostaria de mais informações.");
  const u = user || USER;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={segIcon(partner.seg)} size={22} color="var(--accent)" /></div>
        <div><div style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{partner.name}</div><div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)" }}>Solicitar contato</div></div>
      </div>

      {listing && (
        <div style={{ display: "flex", gap: 11, background: "var(--bg)", borderRadius: 14, padding: 10 }}>
          {listing.img && listing.img.startsWith("http")
            ? <img src={listing.img} alt={listing.title} style={{ width: 64, height: 52, objectFit: "cover", borderRadius: 10, flexShrink: 0 }} />
            : <Ph label={listing.img || "foto"} h={52} style={{ width: 64, flexShrink: 0 }} r={10} />}
          <div><div style={{ font: "700 13px var(--ui)", color: "var(--text)" }}>{listing.title}</div><div style={{ font: "700 13px var(--ui)", color: "var(--brand)", marginTop: 3 }}>{listing.priceLabel}</div></div>
        </div>
      )}

      <Field label="Seu nome" value={u.name} />
      <Field label="Telefone / WhatsApp" value={u.phone} />
      <div>
        <div style={{ font: "700 13px var(--ui)", color: "var(--text)", marginBottom: 7 }}>Mensagem</div>
        <textarea value={msg} onChange={e => setMsg(e.target.value)} rows={3} style={{ width: "100%", boxSizing: "border-box", border: "1.5px solid var(--line)", borderRadius: 12, padding: "11px 13px", font: "500 14px var(--ui)", color: "var(--text)", resize: "none", outline: "none", background: "var(--bg)" }} />
      </div>
      <div>
        <div style={{ font: "700 13px var(--ui)", color: "var(--text)", marginBottom: 8 }}>Prefere ser contatado por</div>
        <div style={{ display: "flex", gap: 8 }}>
          <Chip icon="headset" active={pref === "whats"} onClick={() => setPref("whats")}>WhatsApp</Chip>
          <Chip icon="bell" active={pref === "call"} onClick={() => setPref("call")}>Ligação</Chip>
        </div>
      </div>
      <Btn full onClick={() => onConfirm({ pref, msg })}>Enviar solicitação</Btn>
    </div>
  );
}
function Field({ label, value }) {
  return (
    <div>
      <div style={{ font: "700 13px var(--ui)", color: "var(--text)", marginBottom: 7 }}>{label}</div>
      <div style={{ border: "1.5px solid var(--line)", borderRadius: 12, padding: "12px 13px", font: "600 14px var(--ui)", color: "var(--text)", background: "var(--bg)" }}>{value}</div>
    </div>
  );
}

// ── Vídeo fullscreen ──────────────────────────────────────────
function VideoFullscreen({ url, onClose }) {
  const isYT    = /youtu(be\.com|\.be)/i.test(url);
  const isVimeo = /vimeo\.com/i.test(url);

  const embedUrl = React.useMemo(() => {
    if (isYT) {
      const id = url.match(/(?:v=|youtu\.be\/|embed\/)([A-Za-z0-9_-]{11})/)?.[1];
      return id ? `https://www.youtube.com/embed/${id}?autoplay=1&rel=0` : null;
    }
    if (isVimeo) {
      const id = url.match(/vimeo\.com\/(\d+)/)?.[1];
      return id ? `https://player.vimeo.com/video/${id}?autoplay=1` : null;
    }
    return null;
  }, [url]);

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 200, background: "#000", display: "flex", flexDirection: "column" }}>
      <button onClick={onClose} style={{ position: "absolute", top: 48, left: 16, zIndex: 10, width: 40, height: 40, borderRadius: 12, border: "none", background: "rgba(255,255,255,.18)", backdropFilter: "blur(8px)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>
      </button>
      {embedUrl
        ? <iframe src={embedUrl} style={{ flex: 1, border: "none", width: "100%", height: "100%" }} allow="autoplay; fullscreen" allowFullScreen />
        : <video src={url} controls autoPlay playsInline style={{ flex: 1, width: "100%", height: "100%", objectFit: "contain", background: "#000" }} />
      }
    </div>
  );
}

// ── Mapa localização exclusivo ────────────────────────────────
function LocationMapModal({ lat, lng, title, onClose }) {
  const mapRef = React.useRef(null);
  const mapInst = React.useRef(null);

  React.useEffect(() => {
    if (!mapRef.current || mapInst.current) return;
    const map = window.L.map(mapRef.current, { zoomControl: false, attributionControl: false }).setView([lat, lng], 16);
    window.L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19 }).addTo(map);
    window.L.control.zoom({ position: "bottomright" }).addTo(map);

    const icon = window.L.divIcon({
      className: "",
      html: `<div style="width:44px;height:44px;border-radius:50%;background:var(--accent,#181B57);display:flex;align-items:center;justify-content:center;box-shadow:0 4px 18px rgba(24,27,87,.5);border:3px solid #fff">
               <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>
             </div>`,
      iconSize: [44, 44], iconAnchor: [22, 44],
    });
    window.L.marker([lat, lng], { icon }).addTo(map);
    mapInst.current = map;
    return () => { map.remove(); mapInst.current = null; };
  }, [lat, lng]);

  const gmUrl = `https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`;
  const wazeUrl = `https://waze.com/ul?ll=${lat},${lng}&navigate=yes`;

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 200, display: "flex", flexDirection: "column" }}>
      {/* mapa — position:relative + zIndex:1 isola os z-indexes internos do Leaflet (400-700)
          para que o header/footer possam ficar acima sem conflito */}
      <div ref={mapRef} style={{ position: "relative", zIndex: 1, flex: 1, width: "100%", height: "100%" }} />

      {/* header com botão voltar — zIndex alto para ficar acima do mapa */}
      <div style={{ position: "absolute", top: 0, left: 0, right: 0, zIndex: 20, display: "flex", alignItems: "center", gap: 10, padding: "48px 14px 12px", background: "linear-gradient(to bottom, rgba(255,255,255,.96) 70%, transparent)", backdropFilter: "blur(1px)" }}>
        <button onClick={onClose} style={{ display: "flex", alignItems: "center", gap: 6, height: 42, paddingLeft: 10, paddingRight: 14, borderRadius: 13, border: "1.5px solid var(--line)", background: "var(--surface)", cursor: "pointer", boxShadow: "0 2px 10px rgba(16,18,45,.10)" }}>
          <Icon name="arrowL" size={19} color="var(--text)" sw={2.3} />
          <span style={{ font: "700 13.5px var(--ui)", color: "var(--text)" }}>Voltar</span>
        </button>
        <div style={{ flex: 1, font: "700 14px var(--ui)", color: "var(--text)", lineHeight: 1.3, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{title || "Localização"}</div>
      </div>

      {/* painel de rota na base */}
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, zIndex: 20, padding: "14px 14px 36px", background: "linear-gradient(to top, rgba(255,255,255,.98) 70%, transparent)" }}>
        <div style={{ font: "700 12px var(--ui)", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 10 }}>Traçar rota</div>
        <div style={{ display: "flex", gap: 10 }}>
          <a href={gmUrl} target="_blank" rel="noopener noreferrer" style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 8, height: 50, borderRadius: 14, background: "#E8F0FE", textDecoration: "none" }}>
            <svg width="22" height="22" 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={{ font: "700 13.5px var(--ui)", color: "#1a73e8" }}>Google Maps</span>
          </a>
          <a href={wazeUrl} target="_blank" rel="noopener noreferrer" style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 8, height: 50, borderRadius: 14, background: "#E6F9FF", textDecoration: "none" }}>
            <svg width="22" height="22" 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={{ font: "700 13.5px var(--ui)", color: "#06a3c7" }}>Waze</span>
          </a>
        </div>
      </div>
    </div>
  );
}

// ── Avaliação geral de empresa ────────────────────────────────
function CompanyReviewModal({ companyId, companyName, onClose, onDone }) {
  const [stars, setStars] = React.useState(0);
  const [hovered, setHovered] = React.useState(0);
  const [comment, setComment] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");
  const [existing, setExisting] = React.useState(null);

  React.useEffect(() => {
    if (!Auth.isLogged()) return;
    API.myCompanyReview(companyId).then(d => {
      if (d?.review) {
        setExisting(d.review);
        setStars(d.review.rating);
        setComment(d.review.comment || "");
      }
    }).catch(() => {});
  }, [companyId]);

  const submit = async () => {
    if (stars < 1) { setError("Selecione pelo menos 1 estrela."); return; }
    setLoading(true); setError("");
    try {
      await API.createCompanyReview(companyId, { rating: stars, comment: comment.trim() || null, photo_urls: [] });
      onDone?.();
      onClose();
    } catch (e) { setError(e?.detail || "Erro ao enviar avaliação."); }
    finally { setLoading(false); }
  };

  const starColor = (i) => i <= (hovered || stars) ? "#F5A524" : "var(--line)";

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 900, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,.5)", backdropFilter: "blur(3px)" }} />
      <div style={{ position: "relative", background: "var(--surface)", borderRadius: "22px 22px 0 0", padding: "22px 20px 44px" }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--line)", margin: "0 auto 20px" }} />
        <div style={{ font: "800 17px var(--ui)", color: "var(--text)", marginBottom: 4 }}>
          {existing ? "Editar avaliação" : "Avaliar empresa"}
        </div>
        <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", marginBottom: 20 }}>{companyName}</div>

        {/* Stars */}
        <div style={{ display: "flex", gap: 8, marginBottom: 20 }}>
          {[1,2,3,4,5].map(i => (
            <button key={i}
              onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(0)}
              onClick={() => setStars(i)}
              style={{ background: "none", border: "none", cursor: "pointer", padding: 0, lineHeight: 1 }}>
              <svg width="40" height="40" viewBox="0 0 24 24">
                <path d="M12 2l2.9 5.9L22 9l-5 4.9 1.2 6.9L12 17.7l-6.2 3.2L7 14 2 9l7.1-1.1z"
                  fill={starColor(i)} stroke={starColor(i)} strokeWidth="1.5" strokeLinejoin="round" />
              </svg>
            </button>
          ))}
        </div>

        {/* Labels */}
        <div style={{ font: "600 12.5px var(--ui)", color: "var(--muted)", marginBottom: 16, minHeight: 18 }}>
          {["", "Péssimo", "Ruim", "Regular", "Bom", "Excelente"][hovered || stars] || "Toque em uma estrela"}
        </div>

        {/* Comment */}
        <div style={{ font: "700 13px var(--ui)", color: "var(--text)", marginBottom: 8 }}>Comentário (opcional)</div>
        <textarea value={comment} onChange={e => setComment(e.target.value)} rows={3}
          placeholder="Conte sua experiência com esta empresa…"
          style={{ width: "100%", boxSizing: "border-box", border: "1.5px solid var(--line)", borderRadius: 12, padding: "11px 13px", font: "500 14px var(--ui)", color: "var(--text)", resize: "none", outline: "none", background: "var(--bg)", marginBottom: 12 }} />

        {error && <div style={{ font: "600 12.5px var(--ui)", color: "#D4493A", marginBottom: 10 }}>{error}</div>}

        <Btn full disabled={loading || stars < 1} onClick={submit}>
          <Icon name="star" size={17} color="#fff" fill="#fff" sw={1.5} />
          {loading ? "Enviando…" : existing ? "Salvar avaliação" : "Publicar avaliação"}
        </Btn>
      </div>
    </div>
  );
}

Object.assign(window, { StoreHero, AgendaStore, VitrineStore, ListingDetailSheet, BookingSheet, LeadSheet, Field, VideoFullscreen, LocationMapModal, CompanyReviewModal });
