// Fallbacks para rodar tanto no app local (com API/TAB_H2) quanto em preview isolado
const MB_API = (typeof API !== "undefined" && API) ? API : null;
const MB_TAB_H = (typeof TAB_H2 !== "undefined") ? TAB_H2 : 96;

// mb-home.jsx — Home tab (tela inicial do app)

const GUIDE_EDITIONS = [
  { n: 14, m: "Jun 2026", c: ["#1B2A6B", "#0E1330"] },
  { n: 13, m: "Mar 2026", c: ["#214E7E", "#0E1B30"] },
  { n: 12, m: "Dez 2025", c: ["#2A4D5E", "#0E1d24"] },
  { n: 11, m: "Set 2025", c: ["#3A3370", "#15122E"] },
  { n: 10, m: "Jun 2025", c: ["#6E3B4E", "#2E1722"] },
];

function GuideCover({ ed, w = 150 }) {
  const h = Math.round(w * 1.4);
  const grad = ed.c || ["#1B2A6B", "#0E1330"];
  return (
    <div style={{ width: w, flexShrink: 0, borderRadius: 12, overflow: "hidden", boxShadow: "0 8px 22px rgba(16,18,45,.18)", position: "relative", height: h, background: `linear-gradient(160deg, ${grad[0]}, ${grad[1]})` }}>
      {ed.coverUrl
        ? <img src={ed.coverUrl} alt={`Edição ${ed.n}`} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
        : <>
            <div style={{ position: "absolute", inset: 0, background: "repeating-linear-gradient(135deg, rgba(255,255,255,.05) 0 12px, rgba(0,0,0,.05) 12px 24px)" }} />
            <img src="uploads/logomorarbem2.png" alt="" style={{ position: "absolute", top: 14, left: 12, right: 12, width: "calc(100% - 24px)", filter: "brightness(0) invert(1)" }} />
            <svg viewBox="0 0 100 30" preserveAspectRatio="none" style={{ position: "absolute", left: 0, right: 0, bottom: 52, width: "100%", height: 30, opacity: .5 }}><path d="M0 18 C 20 6, 40 26, 60 16 S 90 8, 100 16 L100 30 L0 30Z" fill="rgba(255,255,255,.12)" /></svg>
          </>
      }
      <div style={{ position: "absolute", left: 12, bottom: 12, right: 12 }}>
        <div style={{ font: "800 11px var(--mono)", letterSpacing: ".1em", color: "rgba(255,255,255,.7)" }}>EDIÇÃO {ed.n}</div>
        <div style={{ font: "700 13px var(--ui)", color: "#fff", marginTop: 2 }}>{ed.m}</div>
      </div>
    </div>
  );
}

// ── Formulário de Lead para Parceiros ──────────────────────────
function PartnerLeadScreen({ onBack }) {
  const [form, setForm] = React.useState({ name: "", email: "", phone: "", business: "", segment: "", city: "", message: "" });
  const [loading, setLoading] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [error, setError] = React.useState("");

  const up = (k) => (v) => setForm(f => ({ ...f, [k]: v }));

  const valid = form.name.trim() && form.phone.trim() && form.business.trim() && form.email.trim();

  const submit = async () => {
    if (!valid) { setError("Preencha os campos obrigatórios."); return; }
    setError(""); setLoading(true);
    try {
      // Envia para a API de leads quando disponível
      await fetch(`${window.API_BASE || "http://localhost:8080"}/partner-leads`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: form.name, email: form.email, phone: form.phone, business_name: form.business, segment: form.segment, city: form.city, message: form.message }),
      }).catch(() => {});
      setDone(true);
    } finally {
      setLoading(false);
    }
  };

  const inputStyle = {
    width: "100%", boxSizing: "border-box",
    border: "1.5px solid var(--line)", borderRadius: 13,
    padding: "14px 14px", font: "500 14.5px var(--ui)",
    color: "var(--text)", background: "var(--surface)", outline: "none",
  };

  const labelStyle = { font: "700 12px var(--ui)", color: "var(--text)", marginBottom: 6, display: "block" };

  return (
    <div style={{ position: "absolute", inset: 0, background: "var(--bg)", display: "flex", flexDirection: "column", zIndex: 10 }}>
      {/* Header */}
      <div style={{ background: "var(--surface)", borderBottom: "1px solid var(--line)", padding: "max(52px, env(safe-area-inset-top, 52px)) 16px 14px", display: "flex", alignItems: "center", gap: 12, flexShrink: 0 }}>
        <IconBtn name="arrowL" onClick={onBack} size={40} bg="var(--bg)" />
        <div style={{ flex: 1 }}>
          <div style={{ font: "800 17px var(--ui)", color: "var(--text)" }}>Seja um Parceiro</div>
          <div style={{ font: "500 12px var(--ui)", color: "var(--muted)" }}>Preencha o formulário e entraremos em contato</div>
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: "0 0 40px" }}>
        {done ? (
          /* ── Sucesso ── */
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "60px 32px", textAlign: "center" }}>
            <div style={{ width: 72, height: 72, borderRadius: 999, background: "#E6F9F0", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 20 }}>
              <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#0FA968" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 7"/></svg>
            </div>
            <div style={{ font: "800 22px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Solicitação enviada!</div>
            <div style={{ font: "500 14.5px var(--ui)", color: "var(--muted)", lineHeight: 1.6, marginBottom: 32 }}>
              Recebemos seu interesse. Nossa equipe comercial vai entrar em contato em breve pelo telefone ou e-mail informados.
            </div>
            <button onClick={onBack} style={{ height: 50, padding: "0 32px", borderRadius: 14, border: "none", background: "var(--accent)", color: "#fff", font: "800 15px var(--ui)", cursor: "pointer" }}>
              Voltar ao início
            </button>
          </div>
        ) : (
          <>
            {/* ── Hero ── */}
            <div style={{ background: "linear-gradient(135deg, #051E52 0%, #1561B3 100%)", padding: "22px 20px 20px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
                <div style={{ width: 50, height: 50, borderRadius: 14, background: "rgba(255,255,255,.18)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  <Icon name="store" size={26} color="#fff" />
                </div>
                <div>
                  <div style={{ font: "800 17px var(--ui)", color: "#fff", lineHeight: 1.2 }}>Faça parte do Guia Morar Bem</div>
                  <div style={{ font: "500 12px var(--ui)", color: "rgba(255,255,255,.78)", marginTop: 3 }}>Alcance mais clientes na sua região</div>
                </div>
              </div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {["📍 Destaque no mapa", "💰 Receba pelo app", "📊 Dashboard próprio", "✅ Suporte dedicado"].map(t => (
                  <span key={t} style={{ background: "rgba(255,255,255,.14)", color: "#fff", font: "600 11px var(--ui)", padding: "4px 10px", borderRadius: 999 }}>{t}</span>
                ))}
              </div>
            </div>

            {/* ── Formulário ── */}
            <div style={{ padding: "20px 16px", display: "flex", flexDirection: "column", gap: 16 }}>
              <div>
                <label style={labelStyle}>Nome completo <span style={{ color: "var(--accent)" }}>*</span></label>
                <input
                  style={inputStyle}
                  placeholder="Seu nome"
                  value={form.name}
                  onChange={e => up("name")(e.target.value)}
                />
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <div>
                  <label style={labelStyle}>E-mail <span style={{ color: "var(--accent)" }}>*</span></label>
                  <input
                    style={inputStyle}
                    type="email"
                    placeholder="seu@email.com"
                    value={form.email}
                    onChange={e => up("email")(e.target.value)}
                  />
                </div>
                <div>
                  <label style={labelStyle}>Telefone / WhatsApp <span style={{ color: "var(--accent)" }}>*</span></label>
                  <input
                    style={inputStyle}
                    type="tel"
                    placeholder="(79) 9 9999-0000"
                    value={form.phone}
                    onChange={e => up("phone")(e.target.value)}
                  />
                </div>
              </div>

              <div>
                <label style={labelStyle}>Nome do negócio <span style={{ color: "var(--accent)" }}>*</span></label>
                <input
                  style={inputStyle}
                  placeholder="Ex: Restaurante Sabor & Arte"
                  value={form.business}
                  onChange={e => up("business")(e.target.value)}
                />
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <div>
                  <label style={labelStyle}>Segmento</label>
                  <select
                    style={{ ...inputStyle, cursor: "pointer" }}
                    value={form.segment}
                    onChange={e => up("segment")(e.target.value)}
                  >
                    <option value="">Selecione...</option>
                    {SEGMENTS.map(s => (
                      <option key={s.id} value={s.id}>{s.q.replace("Onde ", "").replace("?", "")}</option>
                    ))}
                    <option value="outro">Outro</option>
                  </select>
                </div>
                <div>
                  <label style={labelStyle}>Cidade</label>
                  <select
                    style={{ ...inputStyle, cursor: "pointer" }}
                    value={form.city}
                    onChange={e => up("city")(e.target.value)}
                  >
                    <option value="">Selecione...</option>
                    <option value="Aracaju">Aracaju</option>
                    <option value="Barra dos Coqueiros">Barra dos Coqueiros</option>
                    <option value="Zona de Expansão">Zona de Expansão</option>
                    <option value="Outra">Outra cidade</option>
                  </select>
                </div>
              </div>

              <div>
                <label style={labelStyle}>Mensagem (opcional)</label>
                <textarea
                  style={{ ...inputStyle, minHeight: 90, resize: "vertical", lineHeight: 1.5 }}
                  placeholder="Conte um pouco sobre o seu negócio, dúvidas ou o que espera do guia..."
                  value={form.message}
                  onChange={e => up("message")(e.target.value)}
                />
              </div>

              {error && (
                <div style={{ background: "#FEF2F2", borderRadius: 10, padding: "10px 14px", font: "600 13px var(--ui)", color: "#DC2626", display: "flex", alignItems: "center", gap: 8 }}>
                  <Icon name="info" size={16} color="#DC2626" sw={2} />{error}
                </div>
              )}

              <button
                onClick={submit}
                disabled={loading}
                style={{
                  height: 54, borderRadius: 14, border: "none",
                  background: valid ? "var(--accent)" : "var(--line)",
                  color: valid ? "#fff" : "var(--muted)",
                  font: "800 15px var(--ui)", cursor: valid ? "pointer" : "default",
                  display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
                  transition: "background .2s, color .2s",
                }}
              >
                {loading
                  ? <div style={{ width: 22, height: 22, borderRadius: 999, border: "3px solid rgba(255,255,255,.4)", borderTopColor: "#fff", animation: "spin .7s linear infinite" }} />
                  : <>Enviar solicitação <Icon name="chevR" size={16} color={valid ? "#fff" : "var(--muted)"} sw={2.4} /></>
                }
              </button>

              <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", textAlign: "center", lineHeight: 1.5 }}>
                Suas informações são tratadas com segurança.<br />Entraremos em contato em até 2 dias úteis.
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// Carousel spotlight de edições do guia
function EditionsCarousel({ editions }) {
  const [cur, setCur] = React.useState(0);
  const [isTablet, setIsTablet] = React.useState(() => window.matchMedia("(min-width: 768px)").matches);
  const containerRef = React.useRef(null);
  const [containerW, setContainerW] = React.useState(0);
  const n = editions.length;

  React.useEffect(() => {
    const mq = window.matchMedia("(min-width: 768px)");
    const onMq = e => setIsTablet(e.matches);
    mq.addEventListener("change", onMq);
    return () => mq.removeEventListener("change", onMq);
  }, []);

  React.useEffect(() => {
    if (!containerRef.current) return;
    const ro = new ResizeObserver(([e]) => setContainerW(e.contentRect.width));
    ro.observe(containerRef.current);
    setContainerW(containerRef.current.offsetWidth);
    return () => ro.disconnect();
  }, []);

  React.useEffect(() => {
    if (n < 2 || isTablet) return;
    const t = setInterval(() => setCur(c => (c + 1) % n), 3800);
    return () => clearInterval(t);
  }, [n, isTablet]);

  if (!n) return null;

  const mkEd = ed => ({ n: ed.number, m: ed.month_label, c: ed.cover_gradient || ["#1B2A6B","#0E1330"], coverUrl: ed.cover_url || null });

  /* ── Tablet: linha horizontal 100% ── */
  if (isTablet) {
    const pad = 32, gap = 12;
    const cardW = containerW > 0 ? Math.floor((containerW - pad - gap * (n - 1)) / n) : 160;
    return (
      <div ref={containerRef} style={{ display: "flex", gap, padding: "0 16px 8px" }}>
        {editions.map((ed, i) => <GuideCover key={ed.id || i} ed={mkEd(ed)} w={cardW} />)}
      </div>
    );
  }

  /* ── Mobile: carrossel spotlight 3D ── */
  const cardW = 148, containerH = Math.round(cardW * 1.4) + 32;
  return (
    <div ref={containerRef} style={{ position: "relative", height: containerH, overflow: "hidden", userSelect: "none" }}>
      {editions.map((ed, i) => {
        const dist = ((i - cur + n + Math.floor(n / 2)) % n) - Math.floor(n / 2);
        if (Math.abs(dist) > 1) return null;
        const scale = dist === 0 ? 1 : 0.68;
        const tx    = dist * (cardW * 0.82 + 14);
        return (
          <div key={ed.id || i} onClick={() => dist !== 0 && setCur(i)} style={{
            position: "absolute", left: "50%", top: "50%",
            transform: `translate(calc(-50% + ${tx}px), -50%) scale(${scale})`,
            opacity: dist === 0 ? 1 : 0.55, zIndex: dist === 0 ? 10 : 3,
            transition: "all .42s cubic-bezier(.4,0,.2,1)",
            cursor: dist !== 0 ? "pointer" : "default",
          }}>
            <GuideCover ed={mkEd(ed)} w={cardW} />
          </div>
        );
      })}
      <div style={{ position: "absolute", bottom: 2, left: "50%", transform: "translateX(-50%)", display: "flex", gap: 5 }}>
        {editions.map((_, i) => (
          <div key={i} onClick={() => setCur(i)} style={{ width: i === cur ? 16 : 5, height: 5, borderRadius: 999, background: i === cur ? "var(--accent)" : "var(--line)", transition: "all .3s", cursor: "pointer" }} />
        ))}
      </div>
    </div>
  );
}

// ── Blog preview inline (independente de mb-blog.jsx) ────────
function HomeBlogPreview({ onOpenBlog }) {
  const MB_API_OBJ = (typeof API !== "undefined" && API) ? API : null;
  const [posts, setPosts] = React.useState([]);

  React.useEffect(() => {
    const mock = (typeof BLOG_MOCK_POSTS !== "undefined") ? BLOG_MOCK_POSTS.slice(0, 6) : [];
    if (!MB_API_OBJ) { setPosts(mock); return; }
    const bail = new Promise((_, rej) => setTimeout(() => rej(new Error("timeout")), 7000));
    Promise.race([MB_API_OBJ.blog.posts(), bail])
      .then(d => {
        const list = (d?.posts || []).filter(p => p.published !== false).slice(0, 6);
        setPosts(list.length ? list : mock);
      })
      .catch(() => setPosts(mock));
  }, []);

  if (!posts.length) return null;

  return (
    <div style={{ marginTop: 24 }}>
      {/* Cabeçalho com fundo no título Blog */}
      <div style={{ padding: "0 16px 14px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          {/* Badge "Blog" com fundo */}
          <div style={{ width: 40, height: 40, borderRadius: 13, background: "linear-gradient(135deg, var(--brand) 0%, #2A3599 100%)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, boxShadow: "0 4px 12px rgba(24,27,87,.28)" }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M2 3h6a4 4 0 014 4v14a3 3 0 00-3-3H2z"/><path d="M22 3h-6a4 4 0 00-4 4v14a3 3 0 013-3h7z"/>
            </svg>
          </div>
          <div>
            <div style={{ font: "800 16px var(--ui)", color: "var(--text)", letterSpacing: "-.01em", lineHeight: 1.1 }}>Blog</div>
            <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", marginTop: 2 }}>Inspiração e informação</div>
          </div>
        </div>
        <button onClick={() => onOpenBlog()} style={{ background: "none", border: "none", cursor: "pointer", font: "700 12px var(--ui)", color: "var(--accent)", display: "flex", alignItems: "center", gap: 3, padding: 0 }}>
          Ver todos <Icon name="chevR" size={13} color="var(--accent)" sw={2.6} />
        </button>
      </div>

      {/* Cards menores e mais arredondados */}
      <div style={{ display: "flex", gap: 10, padding: "0 16px 4px", overflowX: "auto" }} className="mb-noscroll">
        {posts.map(p => {
          const grad = p.cover_gradient || ["#1B2A6B", "#0E1330"];
          const catColor = p.category_color || "#051E52";
          return (
            <button key={p.id} onClick={() => onOpenBlog(p)}
              style={{ flexShrink: 0, width: 158, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 20, overflow: "hidden", cursor: "pointer", textAlign: "left", boxShadow: "0 2px 10px rgba(16,18,45,.06)", padding: 0 }}>
              {/* Capa */}
              <div style={{ height: 92, background: `linear-gradient(135deg, ${grad[0]}, ${grad[1]})`, position: "relative", overflow: "hidden" }}>
                {p.cover_url && <img src={p.cover_url} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />}
                <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(0,0,0,.45) 0%, transparent 60%)" }} />
                {/* Chip de categoria */}
                {p.category_name && (
                  <span style={{ position: "absolute", bottom: 7, left: 8, display: "inline-flex", alignItems: "center", gap: 3, font: "700 9px var(--ui)", letterSpacing: ".04em", color: "#fff", background: catColor + "CC", backdropFilter: "blur(4px)", borderRadius: 999, padding: "2px 7px" }}>
                    {p.category_name}
                  </span>
                )}
              </div>
              {/* Corpo */}
              <div style={{ padding: "9px 10px 11px" }}>
                <div style={{ font: "700 12.5px var(--ui)", color: "var(--text)", lineHeight: 1.35, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", marginBottom: 7 }}>
                  {p.title}
                </div>
                <div style={{ font: "500 10.5px var(--ui)", color: "var(--muted)", display: "flex", alignItems: "center", gap: 4 }}>
                  <Icon name="clock" size={11} color="var(--muted)" sw={2} />
                  {p.read_min} min
                  <span style={{ width: 2, height: 2, borderRadius: 999, background: "var(--muted)", flexShrink: 0, margin: "0 1px" }} />
                  {(p.author || "Morar Bem").split(" ")[0]}
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function HomeIntro({ user, onOpenClub, canInstallPwa, onInstallApp, onDescobrir, onNovoLar, onServices, onShop, onOpenBlog, updateReady, updateStatus, onUpdate }) {

  const [homeData, setHomeData]   = React.useState(null);
  const [imgSlides, setImgSlides] = React.useState(null);
  const [slideIdx, setSlideIdx]   = React.useState(0);
  const [partnerFormOpen, setPartnerFormOpen] = React.useState(false);
  const [cardGrad, setCardGrad] = React.useState({ c1: "#3B0764", c2: "#6D28D9" });

  React.useEffect(() => {
    if (!MB_API) { setImgSlides([]); return; }
    MB_API.home().then(d => setHomeData(d)).catch(() => {});
    MB_API.designAssets()
      .then(d => {
        setImgSlides((d.login_slides || []).filter(s => s && s.startsWith("http")));
        if (d.home_card_color1) setCardGrad({ c1: d.home_card_color1, c2: d.home_card_color2 || "#6D28D9" });
      })
      .catch(() => setImgSlides([]));
  }, []);

  const slides = imgSlides && imgSlides.length > 0 ? imgSlides : null;
  React.useEffect(() => {
    const count = slides ? slides.length : 1;
    const t = setInterval(() => setSlideIdx(x => (x + 1) % count), 4500);
    return () => clearInterval(t);
  }, [slides?.length]);

  const title    = homeData?.content?.title    || "O guia impresso que você já conhece — agora também no digital.";
  const subtitle = homeData?.content?.subtitle || "Mapa, gastronomia, imóveis e muito mais na palma da sua mão.";
  const editions = homeData?.editions?.length ? homeData.editions : GUIDE_EDITIONS.map(e => ({
    id: e.id, number: e.n, month_label: e.m, cover_gradient: e.c, status: "publicada",
  }));
  const firstName = user?.first || user?.name?.split(" ")[0];

  // Auto-shrink do título quando a fonte do sistema está aumentada (acessibilidade)
  const titleRef = React.useRef(null);
  React.useLayoutEffect(() => {
    const el = titleRef.current;
    if (!el) return;
    el.style.fontSize = "20px";
    // scrollHeight > clientHeight+3 indica que o texto está sendo cortado
    if (el.scrollHeight <= el.clientHeight + 3) return;
    for (let s = 18; s >= 12; s -= 2) {
      el.style.fontSize = s + "px";
      if (el.scrollHeight <= el.clientHeight + 3) break;
    }
  }, [title]);

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

      {/* ── Chip flutuante de atualização — só aparece quando SW detecta nova versão ── */}
      {updateReady && updateStatus !== "done" && (
        <div style={{
          position: "absolute", top: "max(14px, calc(env(safe-area-inset-top,0px) + 10px))",
          left: "50%", transform: "translateX(-50%)",
          zIndex: 900, display: "flex", alignItems: "center", gap: 8,
          background: "#051E52", borderRadius: 999,
          padding: "8px 14px 8px 10px",
          boxShadow: "0 6px 22px rgba(5,30,82,.45)",
          animation: "slideDown .35s cubic-bezier(.2,.8,.25,1)",
        }}>
          <style>{`@keyframes slideDown{from{opacity:0;transform:translateX(-50%) translateY(-12px)}to{opacity:1;transform:translateX(-50%) translateY(0)}}`}</style>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.3" strokeLinecap="round" strokeLinejoin="round"><path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0115-6.7L21 8"/></svg>
          <span style={{ font: "600 12.5px var(--ui)", color: "rgba(255,255,255,.85)", whiteSpace: "nowrap" }}>Nova versão disponível</span>
          {updateStatus === "checking"
            ? <div style={{ width: 14, height: 14, borderRadius: 999, border: "2px solid rgba(255,255,255,.35)", borderTopColor: "#fff", animation: "spin .7s linear infinite", flexShrink: 0 }} />
            : <button onClick={onUpdate} style={{ height: 26, padding: "0 10px", borderRadius: 999, border: "none", background: "#fff", color: "#051E52", font: "700 11.5px var(--ui)", cursor: "pointer", flexShrink: 0 }}>Atualizar</button>
          }
        </div>
      )}

      <div style={{ flex: 1, overflow: "auto", paddingBottom: MB_TAB_H }}>

        {/* ── Hero ── */}
        <div style={{ position: "relative", overflow: "hidden", borderRadius: "0 0 28px 28px", background: "#051E52", minHeight: 290 }}>
          {slides && slides.map((url, i) => (
            <div key={i} style={{ position: "absolute", inset: 0, opacity: i === slideIdx ? 1 : 0, transition: "opacity 1.4s ease" }}>
              <img src={url} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
            </div>
          ))}
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(105deg, rgba(5,30,82,.68) 0%, rgba(5,30,82,.45) 50%, rgba(5,30,82,.10) 100%)" }} />

          <div style={{ position: "relative", zIndex: 1, padding: "44px 20px 26px", paddingRight: 158 }}>
            {/* Logo + botão de update no topo direito */}
            <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 0 }}>
              <img src="uploads/logomorarbem2.png" alt="Morar Bem" style={{ width: 162, height: "auto", display: "block", filter: "brightness(0) invert(1)" }} />
            </div>

            {firstName && (
              <div style={{ font: "600 12.5px var(--ui)", color: "rgba(255,255,255,.75)", marginTop: 14, letterSpacing: ".01em" }}>
                Olá, {firstName}! 👋
              </div>
            )}

            {/* Título com mais destaque — font auto-shrink via useLayoutEffect */}
            <h1 ref={titleRef} style={{
              margin: firstName ? "4px 0 0" : "14px 0 0",
              fontSize: "20px", fontWeight: 800, fontFamily: "var(--ui)",
              color: "#fff", lineHeight: 1.2, letterSpacing: "-0.025em",
              textShadow: "0 2px 16px rgba(0,0,0,.5)",
              display: "-webkit-box", WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical", overflow: "hidden",
            }}>
              {title}
            </h1>

            {/* Subtítulo */}
            <p style={{
              margin: "7px 0 0",
              font: "500 12.5px var(--ui)", color: "rgba(255,255,255,.78)",
              lineHeight: 1.5, letterSpacing: ".005em",
              textShadow: "0 1px 8px rgba(0,0,0,.35)",
              display: "-webkit-box", WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical", overflow: "hidden",
            }}>
              {subtitle}
            </p>

            {canInstallPwa && (
              <button onClick={onInstallApp} style={{
                marginTop: 14, display: "inline-flex", alignItems: "center", gap: 7,
                border: "none", background: "#fff", borderRadius: 999,
                padding: "7px 14px", cursor: "pointer",
                color: "#051E52", font: "700 12px var(--ui)",
                boxShadow: "0 4px 18px rgba(0,0,0,.32)", letterSpacing: ".01em",
              }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v13M8 11l4 4 4-4"/><path d="M3 17v2a2 2 0 002 2h14a2 2 0 002-2v-2"/></svg>
                Instalar App
              </button>
            )}
          </div>

          <img src="uploads/mao-celular.png" alt="" onError={e => { e.target.style.display = "none"; }} style={{ position: "absolute", right: 0, bottom: -8, height: 280, width: "auto", zIndex: 2, pointerEvents: "none", userSelect: "none" }} />
          {/* Dots removidos — transição das fotos acontece de forma silenciosa */}
        </div>

        {/* ── Atalhos ── */}
        <style>{`
          @keyframes mbhUp { from { opacity:0; transform: translateY(16px); } to { opacity:1; transform: translateY(0); } }
          @keyframes mbhShine { 0% { transform: translateX(-150%) skewX(-18deg);} 55% { transform: translateX(460%) skewX(-18deg);} 100% { transform: translateX(460%) skewX(-18deg);} }
          @keyframes mbhRing { 0% { box-shadow:0 0 0 0 rgba(255,255,255,.4);} 70% { box-shadow:0 0 0 12px rgba(255,255,255,0);} 100% { box-shadow:0 0 0 0 rgba(255,255,255,0);} }
          @keyframes mbhFloat { 0%,100% { transform: rotate(12deg) translateY(0);} 50% { transform: rotate(12deg) translateY(-7px);} }
          .mbh-sc { position:relative; overflow:hidden; display:block; text-align:left; cursor:pointer;
            background:var(--surface); border:1px solid var(--line); border-radius:20px; padding:16px 15px 17px;
            box-shadow:0 4px 16px rgba(16,18,45,.06); opacity:0; animation:mbhUp .5s cubic-bezier(.2,.8,.25,1) both;
            transition:transform .2s cubic-bezier(.2,.8,.25,1), box-shadow .2s ease; -webkit-tap-highlight-color:transparent; }
          .mbh-sc::after { content:""; position:absolute; inset:0; border-radius:20px; pointer-events:none;
            background:radial-gradient(130% 90% at 112% -12%, color-mix(in srgb, var(--c) 16%, transparent), transparent 55%); }
          .mbh-sc:active { transform:scale(.96); }
          @media (hover:hover){ .mbh-sc:hover{ transform:translateY(-4px); box-shadow:0 16px 30px rgba(16,18,45,.14);} .mbh-sc:hover .mbh-arrow{ transform:translateX(4px); opacity:.95;} .mbh-sc:hover .mbh-ico{ transform:scale(1.07) rotate(-3deg);} }
          .mbh-ico { width:46px; height:46px; border-radius:14px; display:flex; align-items:center; justify-content:center; margin-bottom:13px; transition:transform .25s cubic-bezier(.2,.8,.25,1); }
          .mbh-arrow { position:absolute; top:18px; right:15px; opacity:.4; transition:transform .25s ease, opacity .25s ease; }
          .mbh-more { position:relative; overflow:hidden; border-radius:26px; padding:19px;
            background:linear-gradient(135deg, var(--g1), var(--g2)); color:#fff;
            box-shadow:0 14px 36px color-mix(in srgb, var(--g1) 45%, transparent);
            opacity:0; animation:mbhUp .55s .3s cubic-bezier(.2,.8,.25,1) both; }
          .mbh-shine { position:absolute; top:0; bottom:0; left:0; width:42%; pointer-events:none;
            background:linear-gradient(105deg, transparent, rgba(255,255,255,.22), transparent);
            animation:mbhShine 5s ease-in-out infinite; }
          .mbh-bolt { animation:mbhFloat 3.6s ease-in-out infinite; }
          .mbh-ring { animation:mbhRing 2.6s ease-out infinite; }
          @media (prefers-reduced-motion: reduce){ .mbh-sc,.mbh-more{ animation:none; opacity:1;} .mbh-shine,.mbh-bolt,.mbh-ring{ animation:none;} }
        `}</style>
        <div className="mbh-sc-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, padding: "18px 16px 4px" }}>
          {[
            { ic: "home",   t: "Novo Lar",        d: "Sua nova casa",       c: "#0EA371", c2: "#37D39D", fn: onNovoLar  },
            { ic: "bolt",   t: "Serviços",         d: "Tudo para o lar",     c: "#E0852B", c2: "#F4B24C", fn: onServices },
            { ic: "store",  t: "Produtos",         d: "Lojas e delivery",    c: "#8B5CF6", c2: "#A78BFA", fn: onShop     },
            { ic: "map",    t: "Descubra no mapa", d: "Parceiros por perto", c: "#2563EB", c2: "#5B8DEF", fn: onDescobrir },
          ].map((f, i) => (
            <button key={f.t} onClick={f.fn} className="mbh-sc" style={{ "--c": f.c, animationDelay: (i * 75) + "ms" }}>
              <span className="mbh-arrow"><Icon name="chevR" size={15} color="var(--muted)" sw={2.6} /></span>
              <span className="mbh-ico" style={{ background: `linear-gradient(145deg, ${f.c2}, ${f.c})`, boxShadow: `0 7px 16px ${f.c}55` }}>
                <Icon name={f.ic} size={21} color="#fff" />
              </span>
              <span style={{ display: "block", font: "800 13.5px var(--ui)", color: "var(--text)", letterSpacing: "-.01em" }}>{f.t}</span>
              <span style={{ display: "block", font: "500 11px var(--ui)", color: "var(--muted)", marginTop: 2 }}>{f.d}</span>
            </button>
          ))}
        </div>

        {/* ── Blog preview — Inspiração e informação ── */}
        {onOpenBlog && <HomeBlogPreview onOpenBlog={onOpenBlog} />}

        {/* ── Edições do guia impresso — carousel spotlight ── */}
        <div style={{ marginTop: 22 }}>
          <div style={{ padding: "0 16px 12px" }}>
            <h3 style={{ margin: 0, font: "800 18px var(--ui)", color: "var(--text)", letterSpacing: "-0.01em" }}>Edições do guia impresso</h3>
            <div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)", marginTop: 2 }}>Anos levando o melhor da sua cidade até você</div>
          </div>
          <EditionsCarousel editions={editions} />
        </div>

        {/* ── Seja Parceiro ── */}
        <div style={{ margin: "20px 16px 24px", borderRadius: 22, overflow: "hidden", background: "var(--surface)", boxShadow: "0 6px 24px rgba(16,18,45,.08)", border: "1px solid var(--line)" }}>
          {/* Topo colorido */}
          <div style={{ background: "linear-gradient(135deg, #0B3A6E 0%, #1561B3 100%)", padding: "20px 20px 18px" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
              <div style={{ width: 44, height: 44, borderRadius: 13, background: "rgba(255,255,255,.18)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <Icon name="store" size={22} color="#fff" sw={2} />
              </div>
              <div>
                <div style={{ font: "800 15px var(--ui)", color: "#fff" }}>Leve seu negócio ao próximo nível</div>
                <div style={{ font: "500 11.5px var(--ui)", color: "rgba(255,255,255,.78)", marginTop: 2 }}>Seja um parceiro Morar Bem</div>
              </div>
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {["📍 Apareça no mapa", "📲 Mais clientes", "📊 Gestão simples"].map(t => (
                <span key={t} style={{ background: "rgba(255,255,255,.15)", border: "1px solid rgba(255,255,255,.12)", color: "#fff", font: "600 10.5px var(--ui)", padding: "5px 10px", borderRadius: 999 }}>{t}</span>
              ))}
            </div>
          </div>
          {/* Rodapé claro */}
          <div style={{ padding: "16px 20px 18px", display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{ flex: 1 }}>
              <div style={{ font: "700 13px var(--ui)", color: "var(--text)", lineHeight: 1.4 }}>Centenas de negócios já estão no guia. Junte-se a nós.</div>
              <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", marginTop: 3 }}>Cadastro gratuito · Sem mensalidade inicial</div>
            </div>
            <button
              onClick={() => setPartnerFormOpen(true)}
              style={{ flexShrink: 0, height: 42, padding: "0 18px", borderRadius: 12, border: "none", background: "var(--accent)", color: "#fff", font: "700 13px var(--ui)", cursor: "pointer", display: "flex", alignItems: "center", gap: 6, boxShadow: "0 4px 14px var(--accent-shadow)" }}
            >
              Seja Parceiro
              <Icon name="chevR" size={14} color="#fff" sw={2.4} />
            </button>
          </div>
        </div>

        {/* ── Muito mais vem por aí ── */}
        <div className="mbh-more" style={{ margin: "20px 16px 24px", "--g1": cardGrad.c1, "--g2": cardGrad.c2 }}>
          <span className="mbh-shine" />
          <span className="mbh-bolt" style={{ position: "absolute", right: -14, top: -22, pointerEvents: "none" }}>
            <Icon name="bolt" size={118} color="rgba(255,255,255,.12)" fill="rgba(255,255,255,.12)" sw={0} />
          </span>
          <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 12, marginBottom: 15 }}>
            <div className="mbh-ring" style={{ width: 44, height: 44, borderRadius: 14, background: "rgba(255,255,255,.18)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name="bolt" size={22} color="#fff" fill="#fff" sw={1.5} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ font: "800 15.5px var(--ui)", letterSpacing: "-.01em" }}>Muito mais vem por aí</div>
              <div style={{ font: "500 11.5px var(--ui)", opacity: .82, marginTop: 2 }}>Em breve disponível para você</div>
            </div>
            <span style={{ font: "800 9.5px var(--ui)", background: "rgba(255,255,255,.22)", padding: "5px 10px", borderRadius: 999, letterSpacing: ".06em", whiteSpace: "nowrap" }}>EM BREVE</span>
          </div>
          <div style={{ position: "relative", display: "flex", flexWrap: "wrap", gap: 8 }}>
            {["🛍️ Loja & Delivery", "📅 Agendamento", "💰 BemCash & Cashback", "⭐ Clube de Benefícios"].map(t => (
              <span key={t} style={{ font: "600 11.5px var(--ui)", background: "rgba(255,255,255,.15)", border: "1px solid rgba(255,255,255,.16)", padding: "6px 12px", borderRadius: 999 }}>{t}</span>
            ))}
          </div>
        </div>

      </div>

      {/* ── Formulário de Lead (sobrepõe a tela) ── */}
      {partnerFormOpen && (
        <PartnerLeadScreen onBack={() => setPartnerFormOpen(false)} />
      )}
    </div>
  );
}

Object.assign(window, { GUIDE_EDITIONS, GuideCover, HomeIntro, HomeBlogPreview, PartnerLeadScreen });
