/* Portfolio view: filter chips + result grid. */
function Portfolio({ items, onOpen, onBack }) {
  const filters = ["Todos", "Casa", "Apartamento", "Terreno"];
  const [active, setActive] = React.useState("Todos");
  const shown = active === "Todos" ? items : items.filter(i => i.type === active);

  return (
    <div style={{ background: "var(--bg)", minHeight: "100vh" }}>
      <div style={{ borderBottom: "1px solid var(--surface-line)", paddingTop: "var(--header-h)" }}>
        <div style={{ maxWidth: 1280, margin: "0 auto", padding: "44px 40px 0" }}>
          <button onClick={onBack} style={backBtn}><Icon name="arrow-left" size={16} color="var(--accent)" /> Voltar ao início</button>
          <div className="cn-eyebrow" style={{ marginTop: 26 }}>Portfólio · {items.length} imóveis em Gurupi</div>
          <h1 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: "clamp(36px, 5vw, 50px)", color: "var(--fg)", margin: "14px 0 0", lineHeight: 1.05 }}>
            Imóveis disponíveis
          </h1>
          <p style={{ fontFamily: "var(--font-sans)", fontWeight: 300, fontSize: 16, color: "var(--fg-muted)", maxWidth: 560, margin: "16px 0 0", lineHeight: 1.7 }}>
            Casas, apartamentos e terrenos avaliados e documentados. Não achou o ideal? Me chama no WhatsApp que eu busco para você.
          </p>

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 18, marginTop: 38, paddingBottom: 22 }}>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {filters.map(f => (
                <button key={f} onClick={() => setActive(f)} style={{
                  fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 500, letterSpacing: "0.11em", textTransform: "uppercase",
                  padding: "9px 18px", borderRadius: "var(--r-pill)", cursor: "pointer", transition: "border-color var(--dur) var(--ease), background-color var(--dur) var(--ease), color var(--dur) var(--ease)",
                  border: "1px solid " + (active === f ? "var(--accent)" : "var(--surface-line)"),
                  background: active === f ? "var(--accent)" : "transparent",
                  color: active === f ? "var(--accent-ink)" : "var(--fg-muted)"
                }}>{f}</button>
              ))}
            </div>
            <a href={window.CARINA_WHATS_SITE} target="_blank" rel="noopener" style={{ display: "flex", alignItems: "center", gap: 9, fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--accent)", letterSpacing: "0.06em", textDecoration: "none" }}>
              <Icon name="whatsapp" size={15} color="var(--accent)" /> Falar com a Carina
            </a>
          </div>
        </div>
      </div>

      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "44px 40px 120px" }}>
        <div className="cn-3col" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 26 }}>
          {shown.map(it => <ListingCard key={it.id} item={it} onOpen={onOpen} />)}
        </div>
        {shown.length === 0 && (
          <div style={{ textAlign: "center", padding: "80px 0", color: "var(--fg-muted)", fontFamily: "var(--font-sans)" }}>
            Nenhum imóvel nesta categoria no momento.
          </div>
        )}
      </div>
    </div>
  );
}

/* Property detail: gallery + spec grid + sticky consultant card. */
function PropertyDetail({ item, onBack, onAll }) {
  const media = CARINA_LISTING_MEDIA(item);
  const images = media.filter(entry => entry.type === "image" && entry.url);
  const videos = media.filter(entry => entry.type === "video" && entry.url);
  const listingPhoto = CARINA_LISTING_IMAGE(item);
  const [activeImage, setActiveImage] = React.useState(listingPhoto);
  const pricePerM2 = item.type === "Terreno"
    ? null
    : CARINA_FMT(Math.round(item.price / parseInt(item.specs.find(s => /Área/.test(s[0]))?.[1] || 100)));
  const highlights = item.highlights?.length ? item.highlights : [
    "Documentação 100% regularizada",
    "Avaliação justa de mercado",
    "Localização verificada na prática",
    "Acompanhamento até a assinatura",
    "Aceita financiamento bancário",
    "Visita agendada pelo WhatsApp"
  ];
  const whatsMessage = window.CARINA_PROPERTY_WHATS_MESSAGE(item);

  return (
    <div style={{ background: "var(--bg)", paddingTop: "var(--header-h)" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "28px 40px 0" }}>
        <button onClick={onBack} style={backBtn}><Icon name="arrow-left" size={16} color="var(--accent)" /> Voltar ao portfólio</button>
      </div>

      <div className="cn-gallery" style={{ maxWidth: 1280, margin: "0 auto", padding: "22px 40px 0" }}>
        <div style={{ height: "clamp(320px, 46vw, 484px)", borderRadius: "var(--r-md)", overflow: "hidden", border: "1px solid var(--border-gold)", position: "relative" }}>
          <Photo src={CARINA_NORMALIZE_MEDIA_URL(activeImage || listingPhoto)} alt={item.name} tone={item.tone} watermark={false} corner={false} />
          <span style={{ position: "absolute", left: 20, top: 20, zIndex: 3, fontFamily: "var(--font-sans)", fontSize: 10, fontWeight: 500, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--accent-ink)", background: "var(--accent)", padding: "7px 14px", borderRadius: "var(--r-pill)" }}>{item.tag}</span>
        </div>
        {images.length > 1 && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, minmax(0, 1fr))", gap: 12, marginTop: 14 }}>
            {images.slice(0, 10).map((image, index) => (
              <button key={image.url + index} type="button" onClick={() => setActiveImage(image.url)} aria-label={`Ver imagem ${index + 1} de ${item.name}`} style={{
                height: 92, border: "1px solid " + (activeImage === image.url ? "var(--accent)" : "var(--border-gold)"),
                borderRadius: "var(--r-sm)", overflow: "hidden", padding: 0, background: "var(--bg-card)", cursor: "pointer"
              }}>
                <Photo src={CARINA_NORMALIZE_MEDIA_URL(image.url)} alt="" tone={item.tone} watermark={false} corner={false} />
              </button>
            ))}
          </div>
        )}
      </div>

      <div className="cn-detail-body" style={{ maxWidth: 1280, margin: "0 auto", padding: "44px 40px 120px", display: "grid", gridTemplateColumns: "1fr 360px", gap: 56, alignItems: "start" }}>
        <div>
          <div className="cn-eyebrow" style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Icon name="marker" size={14} color="var(--accent)" /> {item.bairro} · {item.cidade} · {item.type}
          </div>
          <h1 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: "clamp(32px, 4.4vw, 48px)", color: "var(--fg)", margin: "14px 0 0", lineHeight: 1.05 }}>{item.name}</h1>
          <p style={{ fontFamily: "var(--font-sans)", fontWeight: 300, fontSize: 18, color: "var(--ink-300)", lineHeight: 1.82, margin: "20px 0 0", maxWidth: 660 }}>{item.blurb}</p>

          <div style={{ marginTop: 36, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 1, background: "var(--surface-line)", border: "1px solid var(--surface-line)", borderRadius: "var(--r-md)", overflow: "hidden" }}>
            {item.specs.map(([k, v]) => (
              <div key={k} style={{ background: "var(--bg-card)", padding: "20px 22px" }}>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--fg-muted)" }}>{k}</div>
                <div style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 22, color: "var(--fg)", marginTop: 6, lineHeight: 1.15 }}>{v}</div>
              </div>
            ))}
          </div>

          {videos.length > 0 && (
            <div style={{ marginTop: 44 }}>
              <h3 style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 24, color: "var(--fg)", margin: 0 }}>Vídeos do imóvel</h3>
              <div className="cn-2col" style={{ marginTop: 18, display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", gap: 18 }}>
                {videos.map((video, index) => (
                  <div key={video.url + index} style={{ position: "relative", aspectRatio: "16 / 9", border: "1px solid var(--border-gold)", borderRadius: "var(--r-md)", overflow: "hidden", background: "var(--black)" }}>
                    <iframe
                      src={CARINA_VIDEO_EMBED(video.url)}
                      title={`Vídeo ${index + 1} de ${item.name}`}
                      loading="lazy"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                      allowFullScreen
                      style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0 }}
                    ></iframe>
                  </div>
                ))}
              </div>
            </div>
          )}

          <h3 style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 24, color: "var(--fg)", margin: "44px 0 0" }}>O que faz desse imóvel uma boa escolha</h3>
          <div className="cn-2col" style={{ marginTop: 20, display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 40px", maxWidth: 620 }}>
            {highlights.map(a => (
              <div key={a} style={{ display: "flex", alignItems: "center", gap: 12, fontFamily: "var(--font-sans)", fontWeight: 300, fontSize: 16.5, lineHeight: 1.5, color: "var(--ink-300)" }}>
                <Icon name="check" size={16} color="var(--accent)" /> {a}
              </div>
            ))}
          </div>
        </div>

        <aside className="cn-sticky-card" style={{ position: "sticky", top: 100, background: "var(--bg-card)", border: "1px solid var(--border-gold)", borderRadius: "var(--r-md)", padding: 28, boxShadow: "var(--shadow-md)" }}>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--fg-muted)" }}>Valor</div>
          <div style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 38, color: "var(--accent)", margin: "8px 0 0", lineHeight: 1 }}>{CARINA_FMT(item.price)}</div>
          {pricePerM2 && <div style={{ fontFamily: "var(--font-sans)", fontSize: 14, lineHeight: 1.5, color: "var(--fg-muted)", marginTop: 8 }}>{pricePerM2} / m² · aceita financiamento</div>}
          {(item.condominium > 0 || item.iptu > 0) && (
            <div style={{ marginTop: 12, display: "grid", gap: 6, fontFamily: "var(--font-sans)", fontSize: 14, lineHeight: 1.5, color: "var(--fg-muted)" }}>
              {item.condominium > 0 && <span>Condomínio: {CARINA_FMT(item.condominium)}</span>}
              {item.iptu > 0 && <span>IPTU: {CARINA_FMT(item.iptu)}</span>}
            </div>
          )}

          <div style={{ height: 1, background: "var(--surface-line)", margin: "24px 0" }} />

          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{ width: 52, height: 52, borderRadius: "50%", flex: "none", border: "1px solid var(--border-gold-strong)", background: "linear-gradient(150deg,#2a2418,#16110a)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <span style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 19, color: "var(--accent)" }}>C</span>
            </div>
            <div>
              <div style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 15.5, color: "var(--fg)" }}>Carina</div>
              <div style={{ fontFamily: "var(--font-sans)", fontWeight: 300, fontSize: 13.5, color: "var(--fg-muted)", marginTop: 2 }}>Corretora · Creci 39.689 GO</div>
            </div>
          </div>

          <a href={window.CARINA_WHATS_LINK(whatsMessage)} target="_blank" rel="noopener" className="cn-primary-cta cn-primary-cta--block" style={{ marginTop: 22 }}><span className="cn-primary-cta__label">Agendar visita</span></a>
          <button onClick={onAll} style={{
            width: "100%", marginTop: 10, fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 500, letterSpacing: "0.13em",
            textTransform: "uppercase", color: "var(--accent)", background: "transparent", border: "1px solid var(--border-gold-strong)",
            borderRadius: "var(--r-sm)", padding: "14px", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 9
          }}><Icon name="building-2" size={15} color="var(--accent)" /> Ver outros imóveis</button>
        </aside>
      </div>
    </div>
  );
}

function CatalogPage({ items, onOpen, onGo, onAll }) {
  const filters = ["Todos", ...Array.from(new Set(items.map(item => item.type).filter(Boolean)))];
  const selected = new URLSearchParams(window.location.search);
  const [query, setQuery] = React.useState({
    busca: selected.get("busca") || "",
    tipo: selected.get("tipo") || "",
    bairro: selected.get("bairro") || "",
    quartos: selected.get("quartos") || "",
    preco: selected.get("preco") || ""
  });
  const active = query.tipo || "Todos";
  React.useEffect(() => {
    const onFilters = (event) => setQuery({
      busca: event.detail.busca || "",
      tipo: event.detail.tipo || "",
      bairro: event.detail.bairro || "",
      quartos: event.detail.quartos || "",
      preco: event.detail.preco || ""
    });
    window.addEventListener("carina:filters", onFilters);
    return () => window.removeEventListener("carina:filters", onFilters);
  }, []);
  const shown = items.filter(item => {
    const search = query.busca.trim().toLowerCase();
    const text = [item.name, item.type, item.bairro, item.cidade, item.description, item.blurb].join(" ").toLowerCase();
    if (search && !text.includes(search)) return false;
    if (query.tipo && item.type !== query.tipo) return false;
    if (query.bairro && item.bairro !== query.bairro) return false;
    if (query.quartos && Number(item.bedrooms || 0) < Number(query.quartos)) return false;
    if (query.preco && Number(item.price || 0) > Number(query.preco)) return false;
    return true;
  });

  return (
    <React.Fragment>
      <CatalogHero onGo={onGo} />
      <section id="imoveis" className="cn-light-section" style={{ background: "var(--ivory-50)", padding: "clamp(72px, 8vw, 104px) 0", scrollMarginTop: "var(--header-h)" }}>
        <div style={{ maxWidth: 1280, margin: "0 auto", padding: "0 40px" }}>
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 24, flexWrap: "wrap" }}>
            <SectionHead
              eyebrow="Catálogo"
              title="Imóveis cadastrados pela Carina"
              sub="As oportunidades abaixo são atualizadas pelo painel de cadastro e ficam disponíveis automaticamente nesta página."
            />
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {filters.map(filter => (
                <button key={filter} type="button" onClick={() => setQuery(current => ({ ...current, tipo: filter === "Todos" ? "" : filter }))} style={{
                  minHeight: 44, fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, letterSpacing: "0.11em",
                  textTransform: "uppercase", padding: "0 16px", borderRadius: "var(--r-pill)", cursor: "pointer",
                  border: "1px solid " + (active === filter ? "var(--accent)" : "var(--border-gold)"),
                  background: active === filter ? "var(--accent)" : "transparent",
                  color: active === filter ? "var(--accent-ink)" : "var(--fg-muted)"
                }}>{filter}</button>
              ))}
            </div>
          </div>

          <div className="cn-3col" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 26, marginTop: 50 }}>
            {shown.map((it, index) => (
              <Reveal key={it.id} delay={index * 60}>
                <ListingCard
                  item={it}
                  onOpen={onOpen}
                  href={window.CARINA_IS_LOCAL_PREVIEW ? undefined : window.CARINA_PROPERTY_URL(it)}
                />
              </Reveal>
            ))}
          </div>

          {shown.length === 0 && (
            <div style={{ textAlign: "center", padding: "80px 0", color: "var(--fg-muted)", fontFamily: "var(--font-sans)" }}>
              Nenhum imóvel encontrado nesta categoria.
            </div>
          )}
        </div>
      </section>
      <FaqSection />
      <Footer onGo={onGo} onAll={onAll} />
    </React.Fragment>
  );
}

const backBtn = { background: "none", border: "none", cursor: "pointer", color: "var(--fg-muted)", fontFamily: "var(--font-sans)", fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", display: "flex", alignItems: "center", gap: 9, padding: 0 };

Object.assign(window, { Portfolio, PropertyDetail, CatalogPage });
