// Projects index — filterable grid with animated re-layout

function ProjectsIndex({ initialSector }) {
  const all = window.HORTON.projects;
  const sectors = window.HORTON.sectors;

  // read sector from hash query if provided
  const getSectorFromHash = () => {
    const m = window.location.hash.match(/sector=([\w-]+)/);
    return m ? m[1] : "all";
  };

  const [active, setActive] = useState(initialSector || getSectorFromHash());
  const [hovered, setHovered] = useState(null);

  useEffect(() => {
    const onHash = () => setActive(getSectorFromHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const filtered = useMemo(() =>
    active === "all" ? all : all.filter(p => p.sector === active),
    [active, all]
  );

  // assign visual spans deterministically so layout is rich but stable
  const layoutFor = (idx) => {
    const cycle = idx % 6;
    if (cycle === 0) return "span-8";
    if (cycle === 1) return "span-4";
    if (cycle === 2) return "span-4";
    if (cycle === 3) return "span-4";
    if (cycle === 4) return "span-4";
    return "span-8";
  };

  const onChip = (id) => {
    setActive(id);
    if (id === "all") {
      window.history.replaceState(null, "", "#/projects");
    } else {
      window.history.replaceState(null, "", `#/projects?sector=${id}`);
    }
  };

  return (
    <main className="page-fade">
      <EditorialTopBar />
      {/* Header */}
      <section className="wrap projects-header">
        <div>
          <div className="eyebrow" style={{ marginBottom: "1.5rem" }}>
            <span className="sector-dot" style={{ marginRight: "0.6rem" }}></span>
            Projects index · 40+ named projects
          </div>
          <h1 className="h-display" style={{ fontSize: "clamp(2.6rem, 5.6vw, 5rem)" }}>
            Twelve years of <em style={{ fontStyle: "italic" }}>commercial fit-out.</em>
          </h1>
          <p className="body-lg" style={{ marginTop: "1.5rem", maxWidth: "56ch", color: "var(--graphite)" }}>
            Workplace HQs, restaurants, retail, healthcare campuses and university interiors — designed,
            built and handed over by one team. Filter by sector below.
          </p>
        </div>
        <div className="count">
          <div style={{ marginBottom: "0.5rem" }}>Showing</div>
          <div style={{ fontFamily: "var(--serif)", fontSize: "3rem", letterSpacing: "-0.02em", lineHeight: 1, color: "var(--ink)" }}>
            {filtered.length.toString().padStart(2, "0")}
          </div>
          <div style={{ marginTop: "0.5rem" }}>of {all.length}</div>
        </div>
      </section>

      <div className="big-marquee">
        <div className="big-marquee-track">
          {[...all, ...all].map((p, i) => (
            <span key={i}>
              {p.name}<em>·</em>
            </span>
          ))}
        </div>
      </div>

      {/* Chips */}
      <section className="wrap">
        <div className="chips">
          <button
            className={`chip ${active === "all" ? "active" : ""}`}
            onClick={() => onChip("all")}
          >
            All sectors <span className="c-num">{all.length}</span>
          </button>
          {sectors.map(s => {
            const c = all.filter(p => p.sector === s.id).length;
            return (
              <button
                key={s.id}
                className={`chip ${active === s.id ? "active" : ""}`}
                onClick={() => onChip(s.id)}
                disabled={c === 0}
                style={c === 0 ? { opacity: 0.4, cursor: "not-allowed" } : {}}
              >
                {s.name}
                <span className="c-num">{c}</span>
              </button>
            );
          })}
        </div>
      </section>

      {/* Grid */}
      <section className="wrap" style={{ paddingBottom: "5rem" }}>
        <div className="proj-grid">
          {filtered.map((p, i) => (
            <a
              key={p.slug}
              className={`proj-card ${layoutFor(i)}`}
              href={`#/projects/${p.slug}`}
              style={{ animation: `pageFade 500ms cubic-bezier(.2,.7,.2,1) ${i * 40}ms backwards` }}
              onMouseEnter={() => setHovered(p.slug)}
              onMouseLeave={() => setHovered(null)}
            >
              <div className="img-wrap">
                <img src={p.thumb} alt={p.name} loading="lazy" />
              </div>
              <div className="proj-card-meta">
                <div className="name">{p.name}</div>
                <div className="info">{p.year}</div>
              </div>
              <div className="proj-card-meta-row">
                <span>{p.sectorName}</span>
                <span style={{ opacity: 0.55 }}>·</span>
                <span>{p.location}</span>
                <span style={{ opacity: 0.55 }}>·</span>
                <span>{p.scope}</span>
              </div>
            </a>
          ))}
        </div>

        {filtered.length === 0 && (
          <div style={{ padding: "6rem 0", textAlign: "center" }}>
            <div className="eyebrow" style={{ marginBottom: "1rem" }}>Nothing to show yet</div>
            <p className="body" style={{ maxWidth: "44ch", margin: "0 auto" }}>
              This sector is named on our roster but not yet showcased here.
              <br />Get in touch and we'll send the full project list.
            </p>
          </div>
        )}
      </section>

      <CTABand />
    </main>
  );
}

window.ProjectsIndex = ProjectsIndex;
