// mb-discover.jsx — Descobrir (map + filters + radius + list)

// ── Centros de cada região (lat, lng) ────────────────────────
const REGION_CENTERS = {
  "Todas":               [-10.9472, -37.0731],
  "Aracaju":             [-10.9472, -37.0731],
  "Barra dos Coqueiros": [-10.9098, -37.0395],
  "Zona de Expansão":    [-11.0500, -37.1200],
};

// ── Mapa Leaflet real ────────────────────────────────────────
function MapCanvas({ partners, radiusKm, regionFilter, userPos, selectedId, onSelect }) {
  const mapDiv  = React.useRef(null);
  const mapInst = React.useRef(null);
  const markers = React.useRef({});
  const circle  = React.useRef(null);
  const userMk  = React.useRef(null);

  // Inicializa o mapa uma única vez
  React.useEffect(() => {
    if (!window.L || !mapDiv.current || mapInst.current) return;
    const center = REGION_CENTERS[regionFilter || "Todas"] || REGION_CENTERS["Aracaju"];
    const map = L.map(mapDiv.current, {
      center, zoom: 14,
      zoomControl: false,
      attributionControl: false,
    });
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19 }).addTo(map);
    mapInst.current = map;
    return () => { map.remove(); mapInst.current = null; };
  }, []);

  // Navega quando muda região (explícita)
  React.useEffect(() => {
    if (!mapInst.current) return;
    const c = REGION_CENTERS[regionFilter || "Todas"] || REGION_CENTERS["Aracaju"];
    mapInst.current.flyTo(c, 14, { duration: 1 });
  }, [regionFilter]);

  // Voa para posição do usuário quando GPS resolve e nenhuma região está fixada
  React.useEffect(() => {
    if (!mapInst.current || !userPos || (regionFilter && regionFilter !== "Todas")) return;
    mapInst.current.flyTo([userPos.lat, userPos.lng], 13, { duration: 1.2 });
  }, [userPos?.lat, userPos?.lng]);

  // Atualiza marcadores quando parceiros mudam
  React.useEffect(() => {
    if (!mapInst.current || !window.L) return;
    const map = mapInst.current;
    Object.values(markers.current).forEach(m => map.removeLayer(m));
    markers.current = {};

    partners.forEach(p => {
      const lat = p._raw?.latitude  || p.latitude;
      const lng = p._raw?.longitude || p.longitude;
      if (!lat || !lng) return;
      const sel   = p.id === selectedId;
      const color = p.color || "#1E63C8";
      const icon  = L.divIcon({
        className: "",
        html: `<div style="width:38px;height:46px;position:relative;filter:drop-shadow(0 3px 6px rgba(16,18,45,.28))">
          <svg width="38" height="46" viewBox="0 0 40 48">
            <path d="M20 47C20 47 36 30 36 18A16 16 0 1 0 4 18C4 30 20 47 20 47Z"
              fill="${sel ? "#181B57" : "#fff"}" stroke="${color}" stroke-width="2.5"/>
            <circle cx="20" cy="18" r="6" fill="${sel ? "#fff" : color}"/>
          </svg>
          ${sel ? `<div style="position:absolute;top:-30px;left:50%;transform:translateX(-50%);background:#181B57;color:#fff;white-space:nowrap;font:700 11px sans-serif;padding:4px 9px;border-radius:8px">${p.name}</div>` : ""}
        </div>`,
        iconSize: [38, 46],
        iconAnchor: [19, 46],
      });
      const mk = L.marker([lat, lng], { icon }).addTo(map).on("click", () => onSelect(p.id));
      markers.current[p.id] = mk;
    });
  }, [partners, selectedId]);

  // Círculo de raio
  React.useEffect(() => {
    if (!mapInst.current || !window.L) return;
    if (circle.current) mapInst.current.removeLayer(circle.current);
    const c  = REGION_CENTERS[regionFilter || "Todas"] || REGION_CENTERS["Aracaju"];
    const lat = userPos?.lat || c[0];
    const lng = userPos?.lng || c[1];
    circle.current = L.circle([lat, lng], {
      radius: radiusKm * 1000,
      color: "#1E63C8", fillColor: "#1E63C8",
      fillOpacity: 0.07, weight: 1.5, dashArray: "6 4",
      interactive: false, // não intercepta eventos de ponteiro
    }).addTo(mapInst.current);
  }, [radiusKm, regionFilter, userPos]);

  // Marcador do usuário
  React.useEffect(() => {
    if (!mapInst.current || !window.L || !userPos) return;
    if (userMk.current) mapInst.current.removeLayer(userMk.current);
    const icon = L.divIcon({
      className: "",
      html: `<div style="width:18px;height:18px;border-radius:50%;background:var(--accent,#1E63C8);border:3px solid #fff;box-shadow:0 2px 8px rgba(0,0,0,.35)"></div>`,
      iconSize: [18, 18], iconAnchor: [9, 9],
    });
    userMk.current = L.marker([userPos.lat, userPos.lng], { icon }).addTo(mapInst.current);
  }, [userPos]);

  return <div ref={mapDiv} style={{ position: "absolute", inset: 0 }} />;
}

// ── Partner card (compact carousel + full list) ──────────────
function PartnerCard({ p, onOpen, variant = "list" }) {
  const compact = variant === "carousel";
  return (
    <button onClick={() => onOpen(p.id, p)} style={{
      textAlign: "left", border: "none", cursor: "pointer", background: "var(--surface)",
      borderRadius: 18, overflow: "hidden", width: compact ? 248 : "100%",
      boxShadow: "0 4px 16px rgba(16,18,45,.07)", flexShrink: 0, display: "block",
      padding: 0,
    }}>
      <div style={{ position: "relative" }}>
        {p.coverUrl
          ? <img src={p.coverUrl} alt={p.name} style={{ width: "100%", height: compact ? 92 : 120, objectFit: "cover", display: "block" }} />
          : <Ph label={p.cat} h={compact ? 92 : 120} r={0} />}
        <div style={{ position: "absolute", top: 8, left: 8, display: "flex", gap: 6 }}>
          {p.type === "vitrine"
            ? <span style={{ display: "inline-flex", alignItems: "center", background: "var(--brand)", color: "#fff", padding: "4px 6px", borderRadius: 999 }}><Icon name="store" size={12} color="#fff" sw={2} /></span>
            : <>{p.cashback > 0 && <Cashback pct={p.cashback} small />}{p.turbo > 0 && <Turbo pct={p.turbo} small />}{p.type === "agenda" && p.cashback === 0 && <span style={{ background: "var(--accent-50)", color: "var(--accent)", font: "700 11px var(--ui)", padding: "2px 8px", borderRadius: 999 }}>Agendamento</span>}</>}
        </div>
        {!p.open && <span style={{ position: "absolute", top: 8, right: 8, background: "rgba(16,18,45,.78)", color: "#fff", font: "600 10.5px var(--ui)", padding: "2px 8px", borderRadius: 999 }}>Fechado</span>}
      </div>
      <div style={{ padding: compact ? "9px 12px 12px" : "12px 14px 14px" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
          <span style={{ font: `700 ${compact ? 14.5 : 16}px var(--ui)`, color: "var(--text)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</span>
          {p.reviews > 0 && (
            <span style={{ display: "inline-flex", alignItems: "center", gap: 2, font: "700 12.5px var(--ui)", color: "#C77E12" }}>
              <Icon name="star" size={13} color="#F5A524" fill="#F5A524" sw={1.5} />{parseFloat(p.rating).toFixed(1)}
            </span>
          )}
        </div>
        <div style={{ marginTop: 3, font: "500 12.5px var(--ui)", color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {p.cat} · {p.area}
        </div>
        <div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 12, rowGap: 4, flexWrap: "wrap", font: "600 12px var(--ui)", color: "var(--muted)" }}>
          {p.type === "vitrine" ? (
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5, font: "700 12px var(--ui)", color: "var(--accent)" }}><Icon name="chevR" size={14} sw={2.4} color="var(--accent)" />Ver catálogo</span>
          ) : p.type === "agenda" ? (
            <>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="pin" size={14} sw={2} />{p.dist > 0 ? p.dist + " km" : "—"}</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 5, font: "700 12px var(--ui)", color: "var(--accent)" }}><Icon name="clock" size={14} sw={2} color="var(--accent)" />Agendar</span>
            </>
          ) : (
            <>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="pin" size={14} sw={2} />{p.dist > 0 ? p.dist + " km" : "—"}</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="clock" size={14} sw={2} />{p.time}</span>
              {p.delivery && <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="bike" size={15} sw={2} />{p.fee === 0 ? "Grátis" : "R$ " + p.fee.toFixed(2).replace(".", ",")}</span>}
            </>
          )}
        </div>
      </div>
    </button>
  );
}

function DescobrirScreen({ filt, setFilt, segments, onOpenStore, openFilters, onNovoLar, onServices, onGastro, onCachePartners }) {
  const segs = segments || SEGMENTS;
  const [view, setView] = React.useState("mapa");
  const [moreSegsOpen, setMoreSegsOpen] = React.useState(false);
  const [sel, setSel] = React.useState(null);
  const [userPos, setUserPos] = React.useState(null);
  const [query, setQuery] = React.useState("");
  const carRef = React.useRef(null);
  const searchRef = React.useRef(null);

  // Geolocalização do usuário
  React.useEffect(() => {
    if (!navigator.geolocation) return;
    navigator.geolocation.getCurrentPosition(
      pos => setUserPos({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
      () => {} // silencia erros de permissão
    );
  }, []);

  // Dados reais da API
  const [apiPartners, setApiPartners] = React.useState(null);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    setLoading(true);
    const params = {};
    if (filt.seg) params.segmentId = filt.seg;
    if (filt.cat) params.categoryId = filt.cat;
    if (filt.mode && filt.mode !== "todos") params.mode = filt.mode;

    const regionFixed = filt.region && filt.region !== "Todas";
    if (regionFixed) {
      // Região escolhida manualmente → centra a busca no centro da região, não no GPS
      const [lat, lng] = REGION_CENTERS[filt.region] || REGION_CENTERS["Aracaju"];
      params.lat = lat; params.lng = lng;
      params.radius = Math.max(filt.radius || 10, 30); // raio mín. 30 km para cobrir a região
    } else if (userPos?.lat != null) {
      // "Todas" + GPS → busca pela posição real do usuário
      params.lat = userPos.lat; params.lng = userPos.lng;
      params.radius = filt.radius || 10;
    } else {
      // Sem GPS e sem região → fallback para Aracaju
      const [lat, lng] = REGION_CENTERS["Aracaju"];
      params.lat = lat; params.lng = lng;
      params.radius = 30;
    }

    API.discover(params)
      .then(d => {
        let mapped = (d.companies || []).map(apiCompanyToPartner);
        // Recalcula distâncias client-side se tiver posição do usuário
        if (userPos?.lat) mapped = recalcDistances(mapped, userPos.lat, userPos.lng);
        setApiPartners(mapped);
        if (onCachePartners) onCachePartners(mapped);
      })
      .catch(() => setApiPartners(null))
      .finally(() => setLoading(false));
  }, [filt.region, filt.seg, filt.cat, filt.mode, filt.radius, userPos?.lat, userPos?.lng]);

  // Quando userPos chega depois dos parceiros já carregados, recalcula client-side
  React.useEffect(() => {
    if (!userPos?.lat || !apiPartners) return;
    setApiPartners(prev => recalcDistances(prev, userPos.lat, userPos.lng));
  }, [userPos?.lat, userPos?.lng]);

  // Fallback para mock enquanto carrega
  const rawList = apiPartners !== null ? apiPartners : PARTNERS;

  const list = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    const base = rawList.filter(p => {
      if (filt.region !== "Todas" && p.region !== filt.region) return false;
      if (p.hub) return false;
      if (q && !p.name.toLowerCase().includes(q) &&
               !(p.cat || "").toLowerCase().includes(q) &&
               !(p.area || "").toLowerCase().includes(q)) return false;
      return true;
    });
    return base.sort((a, b) => planRank(b) - planRank(a) || b.rating - a.rating);
  }, [rawList, filt.region, query]);

  // Detecta usuário fora da área de cobertura — baseado só na distância GPS,
  // não em list.length (que pode estar populado com mock quando API falha)
  const outOfCoverage = React.useMemo(() => {
    if (!userPos?.lat || filt.region !== "Todas") return false;
    const minDist = Math.min(...Object.values(REGION_CENTERS).map(([lat, lng]) =>
      haversineKm(userPos.lat, userPos.lng, lat, lng)
    ));
    return minDist > 50;
  }, [userPos?.lat, userPos?.lng, filt.region]);

  // Quando fora da cobertura, não exibe parceiros (independente de mock/API)
  const displayList = outOfCoverage ? [] : list;

  const select = (id) => {
    setSel(id);
    const car = carRef.current;
    const el = car && car.querySelector(`[data-pid="${id}"]`);
    if (car && el) {
      const cr = car.getBoundingClientRect();
      const er = el.getBoundingClientRect();
      const delta = (er.left + er.width / 2) - (cr.left + cr.width / 2);
      car.scrollBy({ left: delta, behavior: "smooth" });
    }
  };

  const activeChips = (filt.seg ? 1 : 0) + (filt.cat ? 1 : 0) + (filt.mode !== "todos" ? 1 : 0);

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column" }}>
      {view === "mapa"
        ? <MapCanvas partners={displayList} radiusKm={filt.radius} regionFilter={filt.region} userPos={userPos} selectedId={sel} onSelect={select} />
        : <div style={{ position: "absolute", inset: 0, background: "var(--bg)" }} />}

      {/* Top floating controls */}
      <div style={{ position: "relative", zIndex: 700, padding: "26px 14px 0" }}>
        <div style={{ display: "flex", gap: 9, alignItems: "center" }}>
          <div style={{
            flex: 1, height: 48, borderRadius: 14,
            background: "var(--surface)", boxShadow: "0 4px 16px rgba(16,18,45,.1)",
            display: "flex", alignItems: "center", gap: 10, padding: "0 14px",
          }}>
            <Icon name="search" size={20} color="var(--muted)" />
            <input
              ref={searchRef}
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Buscar parceiros e produtos"
              style={{
                flex: 1, border: "none", outline: "none", background: "transparent",
                font: "500 14.5px var(--ui)", color: "var(--text)",
              }}
            />
            {query && (
              <button onClick={() => setQuery("")} style={{ border: "none", background: "none", cursor: "pointer", padding: 0, display: "flex" }}>
                <Icon name="close" size={16} color="var(--muted)" sw={2} />
              </button>
            )}
          </div>
          <IconBtn name="sliders" onClick={openFilters} size={48} style={{ borderRadius: 14, boxShadow: "0 4px 16px rgba(16,18,45,.1)" }}
            badge={activeChips} />
        </div>

        {/* region + segment chips — 9 visíveis + botão "Ver mais" */}
        <div style={{ display: "flex", gap: 8, marginTop: 11, overflowX: "auto", paddingBottom: 4, scrollbarWidth: "none" }} className="mb-noscroll">
          <Chip icon="pin" active={false} onClick={openFilters} style={{ boxShadow: "0 3px 10px rgba(16,18,45,.08)" }}>{filt.region}<Icon name="chevD" size={14} sw={2.2} /></Chip>
          {segs.slice(0, 9).map(s => (
            <Chip key={s.id} icon={s.icon || segIcon(s.id)} active={filt.seg === s.id}
              onClick={() => setFilt(f => ({ ...f, seg: f.seg === s.id ? null : s.id, cat: null }))}
              style={{ boxShadow: "0 3px 10px rgba(16,18,45,.08)" }}>{s.question || s.q}</Chip>
          ))}
          {segs.length > 9 && (() => {
            const extraActive = filt.seg && segs.slice(9).some(s => s.id === filt.seg);
            const activeSeg = extraActive ? segs.find(s => s.id === filt.seg) : null;
            return (
              <Chip active={extraActive} onClick={() => setMoreSegsOpen(true)}
                icon={activeSeg ? (activeSeg.icon || segIcon(activeSeg.id)) : "grid"}
                style={{ boxShadow: "0 3px 10px rgba(16,18,45,.08)", flexShrink: 0 }}>
                {activeSeg ? (activeSeg.question || activeSeg.q || "") : "Ver mais"}
              </Chip>
            );
          })()}
        </div>

        {/* Modal "mais segmentos" */}
        {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 40px", maxHeight: "72vh", 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: "flex", flexWrap: "wrap", gap: 10 }}>
                  {segs.slice(9).map(s => (
                    <Chip key={s.id} icon={s.icon || segIcon(s.id)} active={filt.seg === s.id}
                      onClick={() => {
                        setFilt(f => ({ ...f, seg: f.seg === s.id ? null : s.id, cat: null }));
                        setMoreSegsOpen(false);
                      }}>
                      {s.question || s.q}
                    </Chip>
                  ))}
                </div>
              </div>
              {filt.seg && segs.slice(9).some(s => s.id === filt.seg) && (
                <button onClick={() => { setFilt(f => ({ ...f, seg: null, cat: null })); setMoreSegsOpen(false); }}
                  style={{ marginTop: 16, background: "none", border: "none", cursor: "pointer", font: "700 13.5px var(--ui)", color: "var(--muted)", textDecoration: "underline" }}>
                  Limpar filtro de segmento
                </button>
              )}
            </div>
          </div>
        )}
      </div>

      <div style={{ flex: 1 }} />

      {/* Floating button — only in list mode (back to map) */}
      {view === "lista" && (
        <div style={{ position: "absolute", right: 14, bottom: 96, zIndex: 700 }}>
          <button onClick={() => setView("mapa")} style={{
            height: 44, padding: "0 16px", borderRadius: 999, border: "none", cursor: "pointer",
            background: "var(--brand)", color: "#fff", font: "700 13.5px var(--ui)",
            display: "inline-flex", alignItems: "center", gap: 7, boxShadow: "0 6px 18px rgba(16,18,45,.28)",
          }}>
            <Icon name="map" size={18} sw={2.1} color="#fff" />Mapa
          </button>
        </div>
      )}

      {/* Bottom content */}
      {view === "mapa" ? (
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, zIndex: 700, paddingBottom: TAB_H2,
          background: "linear-gradient(to top, var(--bg) 60%, transparent)" }}>
          {/* control row above the carousel */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, padding: "0 16px 10px" }}>
            <button onClick={openFilters} style={{
              height: 40, padding: "0 13px", borderRadius: 999, border: "none", cursor: "pointer", background: "var(--surface)",
              display: "inline-flex", alignItems: "center", gap: 6, boxShadow: "0 4px 14px rgba(16,18,45,.14)",
              font: "700 12.5px var(--ui)", color: "var(--text)",
            }}>
              <Icon name="target" size={16} color="var(--accent)" sw={2} />Raio {filt.radius} km
            </button>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <IconBtn name="target" onClick={() => select(list[0]?.id)} size={40} color="var(--accent)" />
              <button onClick={() => setView("lista")} style={{
                height: 40, padding: "0 15px", borderRadius: 999, border: "none", cursor: "pointer",
                background: "var(--brand)", color: "#fff", font: "700 12.5px var(--ui)",
                display: "inline-flex", alignItems: "center", gap: 6, boxShadow: "0 6px 18px rgba(16,18,45,.28)",
              }}>
                <Icon name="list" size={17} sw={2.1} color="#fff" />Lista
              </button>
            </div>
          </div>
          <div style={{ padding: "0 16px 8px" }}>
            <span style={{ font: "700 13px var(--ui)", color: "var(--brand)", background: "var(--surface)", padding: "5px 11px", borderRadius: 999, boxShadow: "0 3px 10px rgba(16,18,45,.1)" }}>{displayList.length} parceiros por perto</span>
          </div>
          <div ref={carRef} className="mb-noscroll" style={{ display: "flex", gap: 12, overflowX: "auto", padding: "0 16px", scrollSnapType: "x mandatory" }}>
            {displayList.map(p => (
              <div key={p.id} data-pid={p.id} style={{ scrollSnapAlign: "center" }} onClick={() => setSel(p.id)}>
                <PartnerCard p={p} onOpen={onOpenStore} variant="carousel" />
              </div>
            ))}
            {displayList.length === 0 && (
              outOfCoverage ? (
                <div style={{ background: "var(--surface)", borderRadius: 16, padding: "18px 20px", width: "calc(100vw - 32px)", flexShrink: 0, boxShadow: "0 4px 16px rgba(16,18,45,.07)" }}>
                  <div style={{ font: "700 14px var(--ui)", color: "var(--text)", marginBottom: 5 }}>Você está fora da nossa área</div>
                  <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", lineHeight: 1.5, marginBottom: 14 }}>
                    Ainda não temos parceiros por aí. Nossos parceiros estão em Aracaju, Barra dos Coqueiros e Zona de Expansão.
                  </div>
                  <div style={{ display: "flex", gap: 8 }}>
                    <button onClick={() => setFilt(f => ({ ...f, region: "Aracaju" }))} style={{ flex: 1, height: 38, border: "none", cursor: "pointer", borderRadius: 999, background: "var(--brand)", color: "#fff", font: "700 13px var(--ui)" }}>Ver em Aracaju</button>
                    <button onClick={() => setFilt(f => ({ ...f, region: "Barra dos Coqueiros" }))} style={{ flex: 1, height: 38, border: "1.5px solid var(--line)", cursor: "pointer", borderRadius: 999, background: "var(--surface)", color: "var(--text)", font: "600 12px var(--ui)" }}>Barra dos Coqueiros</button>
                  </div>
                </div>
              ) : (
                <div style={{ background: "var(--surface)", borderRadius: 16, padding: 20, font: "500 14px var(--ui)", color: "var(--muted)", width: "100%", textAlign: "center", boxShadow: "0 4px 16px rgba(16,18,45,.07)" }}>
                  Nenhum parceiro nesse raio. Aumente o raio ou troque os filtros.
                </div>
              )
            )}
          </div>
        </div>
      ) : (
        <div style={{ position: "absolute", inset: 0, top: 150, zIndex: 11, overflow: "auto", padding: "4px 16px 110px" }}>
          <div style={{ font: "700 13px var(--ui)", color: "var(--muted)", padding: "4px 2px 12px" }}>{displayList.length} parceiros encontrados</div>
          <div className="mb-tablet-2col" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {displayList.map(p => <PartnerCard key={p.id} p={p} onOpen={onOpenStore} />)}
            {displayList.length === 0 && (
              outOfCoverage ? (
                <div style={{ background: "var(--surface)", borderRadius: 18, padding: "20px 18px", boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
                  <div style={{ font: "700 15px var(--ui)", color: "var(--text)", marginBottom: 6 }}>Você está fora da nossa área de cobertura</div>
                  <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", lineHeight: 1.55, marginBottom: 16 }}>
                    Ainda não temos parceiros por aí. Atualmente cobrimos Aracaju, Barra dos Coqueiros e Zona de Expansão.
                  </div>
                  <div style={{ display: "flex", gap: 8 }}>
                    <button onClick={() => setFilt(f => ({ ...f, region: "Aracaju" }))} style={{ flex: 1, height: 42, border: "none", cursor: "pointer", borderRadius: 12, background: "var(--brand)", color: "#fff", font: "700 13.5px var(--ui)" }}>Ver em Aracaju</button>
                    <button onClick={() => setFilt(f => ({ ...f, region: "Barra dos Coqueiros" }))} style={{ flex: 1, height: 42, border: "1.5px solid var(--line)", cursor: "pointer", borderRadius: 12, background: "var(--surface)", color: "var(--text)", font: "600 13px var(--ui)" }}>Barra dos Coqueiros</button>
                  </div>
                </div>
              ) : (
                <div style={{ font: "500 14px var(--ui)", color: "var(--muted)", padding: 24, textAlign: "center" }}>Nenhum parceiro encontrado com esses filtros.</div>
              )
            )}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MapCanvas, PartnerCard, DescobrirScreen });
