/* global React, Icon, Reveal, FEATURED */

const Listings = ({ setPage }) => {
  const [op, setOp] = React.useState("Comprar");
  const [type, setType] = React.useState("Todos");
  const [quartosFilter, setQuartosFilter] = React.useState(0);
  const [priceMax, setPriceMax] = React.useState(null);
  const [areaMin, setAreaMin] = React.useState(0);
  const [sort, setSort] = React.useState("recent");
  const [openFilter, setOpenFilter] = React.useState(null);
  const filterRef = React.useRef(null);

  React.useEffect(() => {
    const onClick = (e) => {
      if (filterRef.current && !filterRef.current.contains(e.target)) setOpenFilter(null);
    };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);

  const go = (id) => () => { setPage(id); window.scrollTo({ top: 0, behavior: "smooth" }); };

  // If Lançamentos selected, redirect to launches page
  React.useEffect(() => {
    if (op === "Lançamentos") {
      setPage("launches");
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  }, [op, setPage]);

  // Apply filters
  const filtered = React.useMemo(() => {
    let items = FEATURED.slice();
    // Operation
    if (op === "Comprar") items = items.filter(x => x.type === "VENDA");
    else if (op === "Alugar") items = items.filter(x => x.type === "ALUGUEL");
    // Type
    if (type !== "Todos") {
      const map = {
        "Casas": "casa",
        "Apartamentos": "apartamento",
        "Coberturas": "cobertura",
        "Comercial": "comercial",
        "Terrenos": "terreno",
        "Rural": "rural",
      };
      const cat = map[type];
      if (cat) items = items.filter(x => x.category === cat);
    }
    // Quartos
    if (quartosFilter > 0) items = items.filter(x => x.quartos >= quartosFilter);
    // Price
    if (priceMax) items = items.filter(x => x.priceNum <= priceMax);
    // Area
    if (areaMin > 0) items = items.filter(x => x.area >= areaMin);
    // Sort
    if (sort === "priceAsc") items.sort((a,b) => a.priceNum - b.priceNum);
    else if (sort === "priceDesc") items.sort((a,b) => b.priceNum - a.priceNum);
    else if (sort === "areaDesc") items.sort((a,b) => b.area - a.area);
    return items;
  }, [op, type, quartosFilter, priceMax, areaMin, sort]);

  const sortLabels = {
    recent: "Mais recentes",
    priceAsc: "Menor preço",
    priceDesc: "Maior preço",
    areaDesc: "Maior área",
  };

  const priceLabel = priceMax === null ? "Preço" : priceMax === 999999 ? "Aluguel" : `Até R$ ${(priceMax / 1000000).toFixed(1).replace(".", ",")}M`;
  const quartosLabel = quartosFilter === 0 ? "Quartos" : `${quartosFilter}+ quartos`;
  const areaLabel = areaMin === 0 ? "Área" : `${areaMin}+ m²`;

  return (
    <div className="bn-page listings-page">
      <div className="listings-hero">
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 48, alignItems: "end" }}>
          <div>
            <span className="eyebrow" style={{ marginBottom: 16, display: "inline-block" }}>Portfólio · {FEATURED.length} imóveis disponíveis</span>
            <h1>Encontre o<br/>seu <em><i style={{ fontStyle: "italic" }}>próximo lugar</i></em></h1>
            <p>Cada imóvel passa por análise técnica e curadoria de fotografia/vídeo antes de chegar aqui. Sem anúncios genéricos.</p>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", opacity: 0.6 }}>Ordenar por</div>
            <select
              value={sort}
              onChange={(e) => setSort(e.target.value)}
              style={{ padding: "12px 16px", border: "1px solid var(--line)", background: "var(--bg)", fontFamily: "var(--f-sans)", fontSize: 13, cursor: "pointer" }}>
              {Object.entries(sortLabels).map(([k, lbl]) => <option key={k} value={k}>{lbl}</option>)}
            </select>
          </div>
        </div>
      </div>

      {/* Filter bar */}
      <div className="filter-bar" ref={filterRef}>
        {["Comprar", "Alugar", "Lançamentos"].map(o => (
          <button key={o} className={`filter-chip ${op === o ? "active" : ""}`} onClick={() => setOp(o)}>{o}</button>
        ))}
        <div className="filter-divider"></div>
        {["Todos", "Casas", "Apartamentos", "Coberturas", "Comercial", "Terrenos", "Rural"].map(t => (
          <button key={t} className={`filter-chip ${type === t ? "active" : ""}`} onClick={() => setType(t)}>{t}</button>
        ))}
        <div className="filter-divider"></div>

        {/* Quartos dropdown */}
        <div style={{ position: "relative" }}>
          <button className={`filter-chip ${quartosFilter > 0 ? "active" : ""}`} onClick={(e) => { e.stopPropagation(); setOpenFilter(openFilter === "q" ? null : "q"); }}>
            {quartosLabel} <Icon name="chev" size={10} />
          </button>
          {openFilter === "q" && (
            <FilterDropdown options={[
              { label: "Qualquer", val: 0 },
              { label: "1+", val: 1 },
              { label: "2+", val: 2 },
              { label: "3+", val: 3 },
              { label: "4+", val: 4 },
              { label: "5+", val: 5 },
            ]} value={quartosFilter} onSelect={(v) => { setQuartosFilter(v); setOpenFilter(null); }} />
          )}
        </div>

        {/* Price dropdown */}
        <div style={{ position: "relative" }}>
          <button className={`filter-chip ${priceMax !== null ? "active" : ""}`} onClick={(e) => { e.stopPropagation(); setOpenFilter(openFilter === "p" ? null : "p"); }}>
            {priceLabel} <Icon name="chev" size={10} />
          </button>
          {openFilter === "p" && (
            <FilterDropdown options={[
              { label: "Qualquer", val: null },
              { label: "Até R$ 500.000", val: 500000 },
              { label: "Até R$ 1.000.000", val: 1000000 },
              { label: "Até R$ 2.000.000", val: 2000000 },
              { label: "Até R$ 3.000.000", val: 3000000 },
              { label: "Até R$ 5.000.000", val: 5000000 },
              { label: "Sem limite", val: 99999999 },
            ]} value={priceMax} onSelect={(v) => { setPriceMax(v); setOpenFilter(null); }} />
          )}
        </div>

        {/* Area dropdown */}
        <div style={{ position: "relative" }}>
          <button className={`filter-chip ${areaMin > 0 ? "active" : ""}`} onClick={(e) => { e.stopPropagation(); setOpenFilter(openFilter === "a" ? null : "a"); }}>
            {areaLabel} <Icon name="chev" size={10} />
          </button>
          {openFilter === "a" && (
            <FilterDropdown options={[
              { label: "Qualquer", val: 0 },
              { label: "60+ m²", val: 60 },
              { label: "100+ m²", val: 100 },
              { label: "150+ m²", val: 150 },
              { label: "250+ m²", val: 250 },
              { label: "400+ m²", val: 400 },
            ]} value={areaMin} onSelect={(v) => { setAreaMin(v); setOpenFilter(null); }} />
          )}
        </div>

        {(type !== "Todos" || quartosFilter > 0 || priceMax !== null || areaMin > 0) && (
          <button className="filter-chip" onClick={() => { setType("Todos"); setQuartosFilter(0); setPriceMax(null); setAreaMin(0); }} style={{ color: "var(--gold-deep)", borderColor: "var(--gold)" }}>
            ✕ Limpar
          </button>
        )}

        <div className="filter-count"><em>{filtered.length}</em> de {FEATURED.length} imóveis</div>
      </div>

      <div className="listings-container full">
        {filtered.length === 0 ? (
          <div style={{ padding: "120px 80px", textAlign: "center" }}>
            <div className="display" style={{ fontSize: 56, marginBottom: 16, color: "var(--gold-deep)" }}>Nenhum imóvel</div>
            <p style={{ fontSize: 16, opacity: 0.65, maxWidth: 480, margin: "0 auto" }}>Não encontramos imóveis com esses filtros. Tente ampliar os critérios ou fale com a Denise pelo WhatsApp para uma busca personalizada.</p>
          </div>
        ) : (
          <div className="listings-grid">
            {filtered.map((p, i) => (
              <Reveal key={p.id} delay={Math.min(i * 0.04, 0.4)} className="list-card" as="article">
                <div onClick={go("detail")}>
                  <div className="img-wrap">
                    <img src={p.img} alt={p.title} />
                    <div className="badge-row">
                      <span>{p.type}</span>
                      {p.badge && <span className={p.badge === "EXCLUSIVO" ? "gold" : p.badge === "LANÇAMENTO" ? "navy" : ""}>{p.badge}</span>}
                    </div>
                    {p.video && (
                      <div className="video-pip"><span className="dot"></span> VÍDEO</div>
                    )}
                    <div className="gallery-count">
                      <Icon name="camera" size={11} /> {p.fotos}
                    </div>
                  </div>
                  <div className="loc">{p.loc}</div>
                  <div className="ttl">{p.title}</div>
                  <div className="meta">
                    {p.quartos > 0 && <span><Icon name="bed" size={12} /> {p.quartos}</span>}
                    {p.suites > 0 && <span><Icon name="bath" size={12} /> {p.suites}</span>}
                    <span><Icon name="area" size={12} /> {p.area > 5000 ? `${(p.area / 10000).toFixed(1)} ha` : `${p.area} m²`}</span>
                    {p.vagas > 0 && <span><Icon name="car" size={12} /> {p.vagas}</span>}
                  </div>
                  <div className="price-row">
                    <span className="price">{p.price}</span>
                    <span className="ref">{p.id}</span>
                  </div>
                </div>
              </Reveal>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// =====================================================
// Filter Dropdown (reusable)
// =====================================================
const FilterDropdown = ({ options, value, onSelect }) => (
  <div style={{
    position: "absolute",
    top: "calc(100% + 6px)",
    left: 0,
    background: "var(--bg)",
    border: "1px solid var(--line)",
    boxShadow: "0 16px 40px -16px rgba(0,0,0,0.2)",
    zIndex: 60,
    minWidth: 180,
    maxHeight: 280,
    overflowY: "auto",
    borderRadius: 4,
  }}>
    {options.map((o, i) => (
      <div key={i}
           onClick={() => onSelect(o.val)}
           style={{
             padding: "12px 16px",
             fontSize: 13,
             cursor: "pointer",
             borderBottom: i < options.length - 1 ? "1px solid var(--line-soft)" : "none",
             background: value === o.val ? "var(--ink)" : "transparent",
             color: value === o.val ? "var(--bg)" : "var(--ink)",
             transition: "background 0.15s, color 0.15s",
           }}
           onMouseEnter={(e) => { if (value !== o.val) e.currentTarget.style.background = "var(--bg-soft)"; }}
           onMouseLeave={(e) => { if (value !== o.val) e.currentTarget.style.background = "transparent"; }}>
        {o.label}
      </div>
    ))}
  </div>
);

window.Listings = Listings;
