// ============================================================
// Browse.html — filterable listing grid with sticky QC map.
// Apple-Maps-meets-Airbnb-Explore: chips to filter, list+map split.
// ============================================================

const ALL_TAGS = ["River View", "Patio", "Date Night", "Hidden Gem", "Free", "Live Music", "Family Friendly", "Outdoors"];

function Browse() {
  const initialCat = param("cat") || "all";
  const [cat, setCat] = React.useState(initialCat);
  const [tag, setTag] = React.useState(null);
  const [sort, setSort] = React.useState("featured");
  const [view, setView] = React.useState("grid"); // split | grid
  const [hover, setHover] = React.useState(null);
  const [dataVersion, setDataVersion] = React.useState(0);

  // Re-render when live data loads from fetch
  React.useEffect(() => {
    const handler = () => setDataVersion((v) => v + 1);
    window.addEventListener("qc:data-loaded", handler);
    return () => window.removeEventListener("qc:data-loaded", handler);
  }, []);

  const CATEGORIES = window.QC.CATEGORIES;
  const LISTINGS = window.QC.LISTINGS;

  let results = LISTINGS.filter((l) => (cat === "all" || l.categoryId === cat));
  if (tag) results = results.filter((l) => l.tags.includes(tag));
  if (sort === "az") results = [...results].sort((a, b) => a.name.localeCompare(b.name));
  if (sort === "city") results = [...results].sort((a, b) => a.city.localeCompare(b.city));

  const catName = cat === "all" ? "Everything" : (CATEGORIES.find((c) => c.id === cat)?.name || "Everything");

  return (
    <>
      <SiteNav active="directory" />

      {/* compact header */}
      <section style={{ borderBottom: "1px solid var(--rule)", padding: "40px 0 30px" }}>
        <div className="wrap">
          <div className="dhero-breadcrumb" style={{ color: "var(--ink-3)", marginBottom: 12 }}>
            <a href={href.directory}>Directory</a>
            <span className="sep">/</span>
            <span>Browse</span>
          </div>
          <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 400, fontSize: "clamp(34px,4.4vw,56px)",
                       letterSpacing: "-0.028em", margin: 0, lineHeight: 1.02 }}>
            Browse <em style={{ fontStyle: "italic", color: "var(--brick)" }}>{catName}</em> in the QC
          </h1>
        </div>
      </section>

      {/* sticky filter bar */}
      <div className="browse-bar">
        <div className="wrap browse-bar-inner">
          <div className="chip-row">
            <button className={`chip ${cat === "all" ? "active" : ""}`} onClick={() => setCat("all")}>All</button>
            {CATEGORIES.map((c) => (
              <button key={c.id} className={`chip ${cat === c.id ? "active" : ""}`} onClick={() => setCat(c.id)}>
                {c.name}
              </button>
            ))}
          </div>
          <div className="browse-tools">
            <span className="browse-count">{results.length} places</span>
            <div className="seg">
              <button className={view === "split" ? "active" : ""} onClick={() => setView("split")} aria-label="Map view">
                <DIcon name="map" size={16} />
              </button>
              <button className={view === "grid" ? "active" : ""} onClick={() => setView("grid")} aria-label="Grid view">
                <DIcon name="grid" size={16} />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* secondary tag row */}
      <div className="wrap" style={{ paddingTop: 18 }}>
        <div className="chip-row" style={{ alignItems: "center" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.12em",
                          textTransform: "uppercase", color: "var(--ink-3)", marginRight: 4 }}>Filter:</span>
          {ALL_TAGS.map((t) => (
            <button key={t} className={`chip ${tag === t ? "active" : ""}`}
                    onClick={() => setTag(tag === t ? null : t)}>{t}</button>
          ))}
        </div>
      </div>

      {/* results */}
      {view === "split" ? (
        <div className="wrap">
          <div className="browse-split">
            <div className="browse-list">
              <div className="card-grid">
                {results.map((l) => (
                  <div key={l.id} onMouseEnter={() => setHover(l.id)} onMouseLeave={() => setHover(null)}>
                    <ListingCard l={l} />
                  </div>
                ))}
              </div>
              {results.length === 0 && <Empty />}
            </div>
            <div className="browse-map-col">
              <QCMap pins={results} activeId={hover} onPin={setHover} />
            </div>
          </div>
        </div>
      ) : (
        <section className="d-section" style={{ paddingTop: 36 }}>
          <div className="wrap">
            <div className="card-grid cols-4">
              {results.map((l) => <ListingCard key={l.id} l={l} />)}
            </div>
            {results.length === 0 && <Empty />}
          </div>
        </section>
      )}

      <SiteFooter />
    </>
  );
}

function Empty() {
  return (
    <div style={{ padding: "80px 0", textAlign: "center", color: "var(--ink-3)" }}>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 28, color: "var(--ink-2)", marginBottom: 8 }}>
        Nothing matches that yet.
      </div>
      <p style={{ fontSize: 14 }}>Try clearing a filter — the QC is bigger than this prototype&rsquo;s sample data.</p>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<Browse />);
