// Projects index page — filterable grid.

function Projects({ navigate, initialFilter = "all" }) {
  const data = window.DS_DATA;
  const [filter, setFilter] = useState(initialFilter);
  const [sort, setSort] = useState("year-desc");
  const [view, setView] = useState("grid");

  useEffect(() => { setFilter(initialFilter); }, [initialFilter]);

  const filtered = useMemo(() => {
    let list = data.projects;
    if (filter !== "all") list = list.filter((p) => p.sector === filter);
    if (sort === "year-desc") list = [...list].sort((a, b) => b.year - a.year);
    if (sort === "year-asc") list = [...list].sort((a, b) => a.year - b.year);
    if (sort === "az") list = [...list].sort((a, b) => a.name.localeCompare(b.name));
    return list;
  }, [filter, sort, data.projects]);

  const chips = [
    { id: "all", label: "All", count: data.projects.length },
    ...data.sectors.map((s) => ({ id: s.id, label: s.label, count: data.projects.filter((p) => p.sector === s.id).length })),
  ];

  return (
    <div className="page-enter" data-screen-label="02 Projects">
      <section style={{ background: "var(--bg)" }}>
        <div className="container" style={{ paddingTop: "clamp(56px, 6vw, 96px)", paddingBottom: "clamp(28px, 3vw, 48px)" }}>
          <Eyebrow>Portfolio</Eyebrow>
          <h1 className="h-1" style={{ maxWidth: "16ch", marginTop: 12 }}>
            {filter === "all" ? "Selected work — every sector, attributed." : (data.sectors.find((s) => s.id === filter)?.label || "All") + " portfolio."}
          </h1>
          <p className="lede muted" style={{ maxWidth: "52ch", marginTop: 18 }}>
            {filter === "all"
              ? "A working portfolio of recent named builds across hospitality, commercial, residential, healthcare, wellness and tower construction. Each card opens a structured case study."
              : data.sectors.find((s) => s.id === filter)?.blurb}
          </p>
        </div>

        <div className="container">
          <hr className="hairline" />
          {/* Filter + sort bar */}
          <div className="filter-bar" style={{ justifyContent: "space-between" }}>
            <div className="filter-bar" style={{ padding: 0 }}>
              {chips.map((c) => (
                <button
                  key={c.id}
                  className={"chip" + (filter === c.id ? " is-active" : "")}
                  onClick={() => setFilter(c.id)}
                >
                  {c.label} <span className="chip-count">{String(c.count).padStart(2, "0")}</span>
                </button>
              ))}
            </div>
            <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
              <span className="label">View</span>
              <div className="locale-switch">
                <button className={view === "grid" ? "is-active" : ""} onClick={() => setView("grid")}>GRID</button>
                <button className={view === "index" ? "is-active" : ""} onClick={() => setView("index")}>INDEX</button>
              </div>
              <span className="label" style={{ marginLeft: 16 }}>Sort</span>
              <select
                value={sort}
                onChange={(e) => setSort(e.target.value)}
                style={{ border: "1px solid var(--border)", background: "transparent", padding: "8px 12px", fontFamily: "inherit", fontSize: 13, color: "var(--text)" }}
              >
                <option value="year-desc">Newest first</option>
                <option value="year-asc">Oldest first</option>
                <option value="az">A–Z</option>
              </select>
            </div>
          </div>
          <hr className="hairline" />
        </div>

        <div className="container" style={{ paddingTop: "clamp(36px, 4vw, 56px)", paddingBottom: "clamp(72px, 8vw, 120px)" }}>
          {view === "grid" ? (
            <div className="project-grid">
              {filtered.map((p) => (
                <ProjectCard key={p.id} project={p} onClick={() => navigate({ name: "project", id: p.id })} />
              ))}
            </div>
          ) : (
            <ProjectIndexTable projects={filtered} navigate={navigate} />
          )}
          {filtered.length === 0 ? (
            <div style={{ padding: "80px 0", textAlign: "center", color: "var(--muted)" }}>No projects under this filter.</div>
          ) : null}
        </div>
      </section>
    </div>
  );
}

function ProjectIndexTable({ projects, navigate }) {
  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: "60px 1.5fr 1.4fr 1.2fr 1.4fr 80px", gap: 16, padding: "14px 0", borderBottom: "1px solid var(--border)", borderTop: "1px solid var(--border)" }} className="label">
        <span>No.</span>
        <span>Project</span>
        <span>Sector</span>
        <span>Location</span>
        <span>Scope</span>
        <span style={{ textAlign: "right" }}>Year</span>
      </div>
      {projects.map((p, i) => (
        <button
          key={p.id}
          onClick={() => navigate({ name: "project", id: p.id })}
          style={{
            display: "grid", gridTemplateColumns: "60px 1.5fr 1.4fr 1.2fr 1.4fr 80px", gap: 16,
            padding: "20px 0", borderBottom: "1px solid var(--border)", alignItems: "center",
            cursor: "pointer", textAlign: "left", width: "100%",
            transition: "background 0.16s ease"
          }}
          className="project-index-row"
          onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface)"}
          onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
        >
          <span className="label numerals" style={{ color: "var(--muted)" }}>{String(i + 1).padStart(2, "0")}</span>
          <span style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <span style={{ width: 56, height: 56, overflow: "hidden", flexShrink: 0, background: "var(--surface)" }}>
              <img src={p.heroImage} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            </span>
            <span>
              <span className="h-4" style={{ display: "block" }}>{p.name}</span>
              <span className="small muted">{p.subtitle}</span>
            </span>
          </span>
          <span className="small">{p.sectorLabel}</span>
          <span className="small">{p.location}</span>
          <span className="small">{p.scope}</span>
          <span className="small numerals" style={{ textAlign: "right" }}>{p.year}</span>
        </button>
      ))}
    </div>
  );
}

Object.assign(window, { Projects });
