/*
  inv-grid.jsx — cuadrícula con filtros (segmentado, slider, más filtros) + paginación.
*/

const PAGE_SIZE = 6;

function uniqueSorted(arr) {return Array.from(new Set(arr)).sort((a, b) => a.localeCompare(b));}

function fmtPriceShort(v) {
  if (v >= 1000000) {const m = v / 1000000;return "$" + (m % 1 === 0 ? m : m.toFixed(1)) + "M";}
  if (v >= 1000) return "$" + Math.round(v / 1000) + "k";
  return "$" + v;
}

function PCard({ p }) {
  const price = fmtPrice(p);
  return (
    <a className="pcard" href={`propiedad.php?id=${p.id}`} style={{ borderWidth: "1px", borderRadius: "10px" }}>
      <div className="pcard-media">
        <img src={p.cover} alt={p.title} loading="lazy" />
        <span className="pcard-badge">{OP_LABEL[p.operation]}</span>
        <span className="pcard-type" style={{ borderRadius: "0px 35px 0px 0px", padding: "5px 19px", letterSpacing: "1px", textAlign: "left" }}>{TYPE_LABEL[p.type]}</span>
      </div>
      <div className="pcard-body">
        <div className="pcard-meta"><b>{OP_LABEL[p.operation]}</b> · {TYPE_LABEL[p.type]}</div>
        <div className="pcard-price">{price.value}<span className="per">{price.per}</span></div>
        <div className="pcard-title">{p.title}</div>
        <div className="pcard-zone"><IconPin />{p.zone}</div>
        <div className="pcard-specs"><PropSpecs p={p} /></div>
      </div>
    </a>);

}

function RangeSlider({ min, max, value, step, onChange }) {
  const [lo, hi] = value;
  const pct = (v) => max > min ? (v - min) / (max - min) * 100 : 0;
  return (
    <div className="inv-fgroup inv-range">
      <span className="inv-flabel">Rango de precio</span>
      <div className="inv-range-top"><span>{fmtPriceShort(lo)}</span><span>{fmtPriceShort(hi)}</span></div>
      <div className="inv-range-slider">
        <div className="inv-range-track"></div>
        <div className="inv-range-fill" style={{ left: pct(lo) + "%", width: pct(hi) - pct(lo) + "%" }}></div>
        <input type="range" min={min} max={max} step={step} value={lo}
        onChange={(e) => onChange([Math.min(Number(e.target.value), hi), hi])} />
        <input type="range" min={min} max={max} step={step} value={hi}
        onChange={(e) => onChange([lo, Math.max(Number(e.target.value), lo)])} />
      </div>
    </div>);

}

function InvGrid() {
  const all = (window.PROPERTIES || []).filter((p) => p.status === "disponible");
  const [op, setOp] = React.useState("");
  const [type, setType] = React.useState("");
  const [beds, setBeds] = React.useState(0);
  const [baths, setBaths] = React.useState(0);
  const [minM2, setMinM2] = React.useState(0);
  const [sort, setSort] = React.useState("recent");
  const [showMore, setShowMore] = React.useState(false);
  const [page, setPage] = React.useState(1);

  const zones = uniqueSorted(all.map((p) => p.zone));
  const types = uniqueSorted(all.map((p) => p.type));
  const [zone, setZone] = React.useState("");

  // Límites de precio según operación + tipo seleccionados
  const priceBase = all.filter((p) => (!op || p.operation === op) && (!type || p.type === type));
  const prices = priceBase.length ? priceBase.map((p) => p.price) : all.map((p) => p.price);
  const pMin = Math.min(...prices),pMax = Math.max(...prices);
  const step = Math.max(1, Math.round((pMax - pMin) / 100));

  const [price, setPrice] = React.useState([pMin, pMax]);
  // Reinicia rango y página cuando cambian operación/tipo
  React.useEffect(() => {setPrice([pMin, pMax]);}, [op, type]);
  React.useEffect(() => {setPage(1);}, [op, type, zone, beds, baths, minM2, sort, price[0], price[1]]);

  let list = all.filter((p) => {
    if (op && p.operation !== op) return false;
    if (type && p.type !== type) return false;
    if (zone && p.zone !== zone) return false;
    if (beds && (p.bedrooms || 0) < beds) return false;
    if (baths && (p.bathrooms || 0) < baths) return false;
    if (p.price < price[0] || p.price > price[1]) return false;
    const m2 = (p.type === "terreno" ? p.landM2 : p.constructionM2) || 0;
    if (minM2 && m2 < minM2) return false;
    return true;
  });
  list = list.slice().sort((a, b) => {
    if (sort === "price-asc") return a.price - b.price;
    if (sort === "price-desc") return b.price - a.price;
    return (b.updatedAt || "").localeCompare(a.updatedAt || "");
  });

  const totalPages = Math.max(1, Math.ceil(list.length / PAGE_SIZE));
  const curPage = Math.min(page, totalPages);
  const pageList = list.slice((curPage - 1) * PAGE_SIZE, curPage * PAGE_SIZE);

  const clear = () => {setOp("");setType("");setZone("");setBeds(0);setBaths(0);setMinM2(0);setSort("recent");setPrice([pMin, pMax]);};
  const hasFilters = op || type || zone || beds || baths || minM2 || price[0] > pMin || price[1] < pMax;

  const Sel = ({ value, onChange, label, children }) =>
  <label className="inv-fgroup">
      <span className="inv-flabel">{label}</span>
      <span className="inv-sel"><select value={value} onChange={(e) => onChange(e.target.value)}>{children}</select></span>
    </label>;


  const ops = [["", "Todas"], ["venta", "Venta"], ["renta", "Renta"], ["preventa", "Preventa"]];

  return (
    <>
      <div className="inv-filters">
        <div className="inv-filters-inner">
          <div className="inv-filters-title">Busca la tuya</div>
          <div className="inv-fgroup inv-fgroup-op">
            <span className="inv-flabel">Operación</span>
            <div className="seg">
              {ops.map(([v, l]) =>
              <button key={v} className={op === v ? "active" : ""} onClick={() => setOp(v)}>{l}</button>
              )}
            </div>
          </div>

          <Sel value={type} onChange={setType} label="Tipo de propiedad">
            <option value="">Tipo de propiedad</option>
            {types.map((t) => <option key={t} value={t}>{TYPE_LABEL[t]}</option>)}
          </Sel>

          <button className={showMore ? "inv-more-btn active" : "inv-more-btn"} onClick={() => setShowMore((s) => !s)}>
            <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M2 4h12M4 8h8M6 12h4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /></svg>
            Más filtros
          </button>

          {hasFilters && <button className="inv-clear" onClick={clear}>Limpiar</button>}
          <span className="inv-filters-spacer"></span>
          <span className="inv-count">{list.length} {list.length === 1 ? "propiedad" : "propiedades"}</span>
        </div>

        {showMore &&
        <div className="inv-more-panel">
            <div className="inv-more-inner">
              <RangeSlider min={pMin} max={pMax} step={step} value={[Math.max(price[0], pMin), Math.min(price[1], pMax)]} onChange={setPrice} />
              <Sel value={zone} onChange={setZone} label="Zona">
                <option value="">Todas</option>
                {zones.map((z) => <option key={z} value={z}>{z}</option>)}
              </Sel>
              <Sel value={beds} onChange={(v) => setBeds(Number(v))} label="Recámaras">
                <option value="0">Cualquiera</option>
                <option value="1">1+</option><option value="2">2+</option>
                <option value="3">3+</option><option value="4">4+</option>
              </Sel>
              <Sel value={baths} onChange={(v) => setBaths(Number(v))} label="Baños">
                <option value="0">Cualquiera</option>
                <option value="1">1+</option><option value="2">2+</option><option value="3">3+</option>
              </Sel>
              <Sel value={minM2} onChange={(v) => setMinM2(Number(v))} label="Superficie mín.">
                <option value="0">Cualquiera</option>
                <option value="80">80 m²+</option><option value="120">120 m²+</option>
                <option value="200">200 m²+</option><option value="400">400 m²+</option>
              </Sel>
              <Sel value={sort} onChange={setSort} label="Ordenar">
                <option value="recent">Recientes</option>
                <option value="price-asc">Precio: menor</option>
                <option value="price-desc">Precio: mayor</option>
              </Sel>
            </div>
          </div>
        }
      </div>

      <div className="inv-grid-wrap">
        <div className="inv-grid">
          {pageList.length === 0 ?
          <div className="inv-empty">
              <b>Sin resultados</b>
              No hay propiedades con esos filtros. Prueba con otros criterios.
            </div> :
          pageList.map((p) => <PCard key={p.id} p={p} />)}
        </div>

        {totalPages > 1 &&
        <div className="inv-pagination">
            <button className="inv-page-btn inv-page-arrow" disabled={curPage === 1}
          onClick={() => setPage(curPage - 1)} aria-label="Anterior">‹</button>
            {Array.from({ length: totalPages }, (_, i) => i + 1).map((n) =>
          <button key={n} className={n === curPage ? "inv-page-btn active" : "inv-page-btn"}
          onClick={() => setPage(n)}>{n}</button>
          )}
            <button className="inv-page-btn inv-page-arrow" disabled={curPage === totalPages}
          onClick={() => setPage(curPage + 1)} aria-label="Siguiente">›</button>
          </div>
        }
      </div>
    </>);

}

function InvApp() {
  return (
    <div className="inv-page">
      <InvNav active="propiedades.html" />
      <header className="inv-head" style={{ opacity: "1" }}>
        <div className="inv-head-inner">
          <h1 className="inv-title">Inventario de Propiedades</h1>
        </div>
      </header>
      <InvGrid />
      <InvFooter />
      <WaFloat />
    </div>);

}

function InvLoading() {
  return (
    <div className="inv-page">
      <InvNav active="propiedades.html" />
      <header className="inv-head" style={{ opacity: 1 }}>
        <div className="inv-head-inner"><h1 className="inv-title">Inventario de Propiedades</h1></div>
      </header>
      <div style={{ textAlign: "center", padding: "5rem 1rem", color: "var(--ink-3)" }}>Cargando inventario…</div>
    </div>);
}

// Carga el inventario desde la base de datos en vivo (Supabase). Si aún no está
// configurada o falla, usa el inventario incluido (properties.js) como respaldo.
function loadInventory() {
  if (window.ECDB && ECDB.isConfigured()) {
    return ECDB.loadPublic().catch((e) => {
      console.warn("Inventario: respaldo local —", e.message);
      return (window.PROPERTIES || []).filter((p) => p.status === "disponible");
    });
  }
  return Promise.resolve(window.PROPERTIES || []);
}

const invRoot = ReactDOM.createRoot(document.getElementById("root"));
invRoot.render(<InvLoading />);
loadInventory().then((list) => {
  window.PROPERTIES = list;
  invRoot.render(<InvApp />);
});