/* =====================================================================
   PUBLIC — Listings (split list left, sticky map right, live filters)
   ===================================================================== */
function ListingsScreen() {
  const s = useStore();
  const G = window.GLR;
  const [type, setType] = useState("All");
  const [deal, setDeal] = useState("All");
  const [cls, setCls] = useState("All");
  const [status, setStatus] = useState("Available");
  const [sub, setSub] = useState("");
  const [sort, setSort] = useState("Newest");
  const [hovered, setHovered] = useState(null);
  const mobile = useIsMobile();
  const [mView, setMView] = useState("list");

  const TYPES = ["All", ...s.categories.types];
  const subsOpts = useMemo(() => Array.from(new Set(s.listings.map((l) => l.submarket))), [s.listings]);

  const results = useMemo(() => {
    let r = s.listings.filter((l) => {
      if (type !== "All" && l.type !== type) return false;
      if (deal !== "All" && l.deal !== deal) return false;
      if (cls !== "All" && l.cls !== cls) return false;
      if (status === "Available" && l.status === "closed") return false;
      if (status === "Under LOI" && l.status !== "loi") return false;
      if (sub && l.submarket !== sub) return false;
      return true;
    });
    if (sort === "Size ↓") r = [...r].sort((a, b) => b.sf - a.sf);
    if (sort === "Size ↑") r = [...r].sort((a, b) => a.sf - b.sf);
    return r;
  }, [s.listings, type, deal, cls, status, sub, sort]);

  const activeChips = [];
  if (type !== "All") activeChips.push(["Type: " + type, () => setType("All")]);
  if (deal !== "All") activeChips.push([deal, () => setDeal("All")]);
  if (cls !== "All") activeChips.push(["Class " + cls, () => setCls("All")]);
  if (sub) activeChips.push([sub, () => setSub("")]);

  return (
    <div className="fade-in" style={{ minHeight: "100vh", display: "flex", flexDirection: "column" }}>
      <Nav cur="Properties" />

      {/* filter bar */}
      <div style={{ borderBottom: "1px solid var(--line)", background: "var(--paper)", position: "sticky", top: mobile ? 62 : 72, zIndex: 30 }}>
        <div className="wrap-wide" style={{ padding: mobile ? "12px 18px" : "16px 32px" }}>
          <div className="row gap12 ac wrapf">
            <div className="input-ic ls-search" style={{ width: 230 }}>
              <Icon name="search" size={16} className="ic" />
              <input className="input" placeholder="Address or keyword" />
            </div>
            <Dropdown label="Type" value={type} setValue={setType} opts={TYPES} />
            <Dropdown label="Deal" value={deal} setValue={setDeal} opts={["All", "Lease", "Sale"]} />
            <Dropdown label="Submarket" value={sub || "All"} setValue={(v) => setSub(v === "All" ? "" : v)} opts={["All", ...subsOpts]} />
            <Dropdown label="Class" value={cls} setValue={setCls} opts={["All", "A", "B", "C"]} />
            <Dropdown label="Status" value={status} setValue={setStatus} opts={["Available", "Under LOI", "All"]} />
            <div className="grow m-hide" />
            <div className="row gap8 ac">
              <span className="label" style={{ color: "var(--slate)" }}>Sort</span>
              <select className="select" style={{ width: 130, height: 36 }} value={sort} onChange={(e) => setSort(e.target.value)}>
                {["Newest", "Size ↓", "Size ↑"].map((o) => <option key={o}>{o}</option>)}
              </select>
            </div>
          </div>
          {activeChips.length > 0 && (
            <div className="row gap8 ac wrapf" style={{ marginTop: 14 }}>
              <span className="small muted">{results.length} results</span>
              <div className="vrule" style={{ height: 18 }} />
              {activeChips.map(([t, clear], i) => (
                <button key={i} className="chip on" onClick={clear}>{t} <span className="x">×</span></button>
              ))}
              <button className="linklike small" onClick={() => { setType("All"); setDeal("All"); setCls("All"); setSub(""); setStatus("Available"); }}>Clear all</button>
            </div>
          )}
        </div>
      </div>

      {/* split body */}
      {mobile ? (
        <div style={{ flex: 1, position: "relative" }}>
          {mView === "list" ? (
            <div style={{ padding: "16px 18px 90px" }}>
              <div className="row jb ac" style={{ marginBottom: 14 }}>
                <h2 className="h3">{results.length} availabilities</h2>
                <span className="small muted">Indianapolis metro</span>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 14 }}>
                {results.map((l, i) => <ListRow key={l.id} l={l} i={i} active={false} onHover={() => {}} G={G} />)}
              </div>
              {results.length === 0 && (
                <div className="card pad32" style={{ textAlign: "center", marginTop: 12 }}>
                  <Icon name="search" size={28} style={{ color: "var(--slate-2)" }} />
                  <h3 className="h3" style={{ marginTop: 12 }}>No matching properties</h3>
                  <p className="muted" style={{ marginTop: 6 }}>Try widening your filters.</p>
                </div>
              )}
            </div>
          ) : (
            <div style={{ height: "calc(100vh - 130px)" }}>
              <LeafletMap listings={results} activeId={hovered} onPick={(id) => { const l = results.find((x) => x.id === id); if (l) navigate("/properties/" + l.slug); }} height="100%" />
            </div>
          )}
          <div className="ls-toggle">
            <button className={mView === "list" ? "on" : ""} onClick={() => setMView("list")}><Icon name="list" size={16} /> List</button>
            <button className={mView === "map" ? "on" : ""} onClick={() => setMView("map")}><Icon name="pin" size={16} /> Map</button>
          </div>
        </div>
      ) : (
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.15fr) minmax(0,1fr)", flex: 1, minHeight: 0 }}>
        {/* list */}
        <div className="scroll-y" style={{ borderRight: "1px solid var(--line)", maxHeight: "calc(100vh - 73px)", overflowX: "hidden" }}>
          <div style={{ padding: "20px 28px" }}>
            <div className="row jb ac" style={{ marginBottom: 16 }}>
              <h2 className="h3">{results.length} availabilities</h2>
              <span className="small muted">Indianapolis metro</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1fr)", gap: 18 }}>
              {results.map((l, i) => (
                <ListRow key={l.id} l={l} i={i} active={hovered === l.id} onHover={setHovered} G={G} />
              ))}
            </div>
            {results.length === 0 && (
              <div className="card pad32" style={{ textAlign: "center", marginTop: 12 }}>
                <Icon name="search" size={28} style={{ color: "var(--slate-2)" }} />
                <h3 className="h3" style={{ marginTop: 12 }}>No matching properties</h3>
                <p className="muted" style={{ marginTop: 6 }}>Try widening your filters.</p>
              </div>
            )}
          </div>
        </div>

        {/* sticky map */}
        <div style={{ position: "sticky", top: 73, height: "calc(100vh - 73px)" }}>
          <LeafletMap listings={results} activeId={hovered} onPick={(id) => { const l = results.find((x) => x.id === id); if (l) navigate("/properties/" + l.slug); }} height="100%" />
          <div style={{ position: "absolute", bottom: 16, left: 14, zIndex: 500 }} className="card pad16">
            <div className="small b6">{results.length} properties in view</div>
            <div className="xsmall muted" style={{ marginTop: 2 }}>Click a pin to open the listing</div>
          </div>
        </div>
      </div>
      )}
    </div>
  );
}

function Dropdown({ label, value, setValue, opts }) {
  return (
    <div className="row gap6 ac">
      <span className="label" style={{ whiteSpace: "nowrap" }}>{label}</span>
      <select className="select" style={{ width: "auto", minWidth: 96, height: 36 }} value={value} onChange={(e) => setValue(e.target.value)}>
        {opts.map((o) => <option key={o}>{o}</option>)}
      </select>
    </div>
  );
}

/* compact list row card */
function ListRow({ l, i, active, onHover, G }) {
  return (
    <div className={"card hover"} onClick={() => navigate("/properties/" + l.slug)}
      onMouseEnter={() => onHover(l.id)} onMouseLeave={() => onHover(null)}
      style={{ overflow: "hidden", borderColor: active ? "var(--navy)" : undefined, boxShadow: active ? "var(--shadow)" : undefined }}>
      <div style={{ position: "relative" }}>
        <PhotoBox dataUrl={l.photo} type={l.type} h={130} />
        <div style={{ position: "absolute", top: 10, left: 10 }}><span className="tag" style={{ background: "rgba(255,255,255,0.92)", color: "var(--navy)", fontWeight: 700 }}>{i + 1}</span></div>
        <div style={{ position: "absolute", top: 10, right: 10 }}><StatusTag status={l.status} /></div>
      </div>
      <div className="pad16">
        <div className="row jb ac">
          <span className="tag outline">{l.type}</span>
          {l.gated && <span className="tag gate"><Icon name="lock" size={10} /> NDA</span>}
        </div>
        <h3 className="h3" style={{ marginTop: 10, fontSize: 16.5 }}>{l.address}</h3>
        <p className="xsmall muted" style={{ marginTop: 3 }}>{l.submarket} · Class {l.cls}</p>
        <div className="row jb ac" style={{ marginTop: 12 }}>
          <span className="small tnum b6">{G.fmtSF(l.sf)}</span>
          <span className="small b7" style={{ color: "var(--navy)" }}>{l.price || l.rate}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ListingsScreen });
