/* Landmark Studio — Projects page.
   Filter UI inspired by reference: three axis-tabs on the left (Typology / Country / Status),
   options for the active axis laid out in a multi-column grid on the right.
   Selecting an option becomes the section title for the project grid below. */

const { useState: useStateP, useMemo: useMemoP, useEffect: useEffectP } = React;

function ProjectFilters({ axes, activeAxis, setActiveAxis, active, setActive }) {
  const current = axes.find(a => a.key === activeAxis);
  // Split options into 4 balanced columns to mirror the reference layout
  const cols = 4;
  const columns = Array.from({ length: cols }, () => []);
  const opts = ['all', ...current.options];
  opts.forEach((o, i) => columns[i % cols].push(o));

  return (
    <div className="pjx-filters">
      <div className="pjx-filters-grid">
        <div className="pjx-axes-tabs">
          {axes.map(ax => (
            <button
              key={ax.key}
              className={`pjx-axis-tab ${activeAxis === ax.key ? 'on' : ''}`}
              onClick={() => setActiveAxis(ax.key)}>
              {ax.label}
            </button>
          ))}
        </div>
        <div className="pjx-options-grid">
          {columns.map((col, ci) => (
            <ul key={ci}>
              {col.map(opt => {
                const isAll = opt === 'all';
                const label = isAll ? `All ${current.label}` : opt;
                const isOn  = isAll ? active[activeAxis] === 'all' : active[activeAxis] === opt;
                return (
                  <li key={opt}>
                    <button
                      className={`pjx-opt ${isOn ? 'on' : ''}`}
                      onClick={() => setActive(s => ({ ...s, [activeAxis]: isAll ? 'all' : opt }))}>
                      {label}
                    </button>
                  </li>
                );
              })}
            </ul>
          ))}
        </div>
      </div>
      <div className="pjx-filters-divider" aria-hidden="true">
        <svg width="22" height="14" viewBox="0 0 22 14" fill="none">
          <path d="M1 1 L11 12 L21 1" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square"/>
        </svg>
      </div>
    </div>
  );
}

function ProjectCard({ p, onPick }) {
  return (
    <button className="pjx-card" onClick={() => onPick(p)}>
      <div className="pjx-card-frame">
        <img src={p.image} alt={p.title} loading="lazy"/>
      </div>
      <div className="pjx-card-meta">
        <div className="pjx-card-title">{p.title}</div>
        <div className="pjx-card-sub">{p.location}</div>
      </div>
    </button>
  );
}

const ProjectsPage = () => {
  const [activeAxis, setActiveAxis] = useStateP('typology');
  const [active, setActive] = useStateP({ typology: 'all', country: 'all', status: 'all' });
  const [picked, setPicked] = useStateP(null);

  const axes = [
    { key: 'typology', label: 'Typology', options: LANDMARK_TYPOLOGIES },
    { key: 'country',  label: 'Country',  options: LANDMARK_COUNTRIES },
    { key: 'status',   label: 'Status',   options: LANDMARK_STATUSES },
  ];

  const filtered = useMemoP(() => {
    return MOMO_PROJECTS.filter(p =>
      p.status !== 'Feasibility' &&
      (active.typology === 'all' || p.typology === active.typology) &&
      (active.country  === 'all' || p.country  === active.country) &&
      (active.status   === 'all' || p.status   === active.status)
    );
  }, [active]);

  // Title that sits above the grid — follows the reference ("ALL PROJECTS", or the picked option)
  const gridTitle = useMemoP(() => {
    const picks = [active.typology, active.country, active.status].filter(v => v !== 'all');
    if (picks.length === 0) return 'All Projects';
    return picks.join(' · ');
  }, [active]);

  useEffectP(() => {
    document.body.style.overflow = picked ? 'hidden' : '';
  }, [picked]);

  useEffectP(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(en => {
        if (en.isIntersecting) {
          en.target.classList.add('in');
          io.unobserve(en.target);
        }
      });
    }, { threshold: 0.08, rootMargin: '0px 0px -8% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [active, activeAxis]);

  return (
    <>
      <Nav active="projects"/>

      <header className="pjx-hero">
        <div className="container">
          <div className="eyebrow reveal">Index · Selected works · 2014–2026</div>
          <h1 className="pjx-h1 reveal">
            Projects, <span className="italic accent">by typology.</span>
          </h1>
          <p className="pjx-lead reveal">
            {MOMO_PROJECTS.filter(p => p.status !== 'Feasibility').length} projects across protected areas, public space, urban landscapes,
            resorts, residential and academic ground. Filter by typology, country or current status —
            select any project to read its case study.
          </p>
        </div>
      </header>

      <section className="pjx-section">
        <div className="container">
          <ProjectFilters
            axes={axes}
            activeAxis={activeAxis}
            setActiveAxis={setActiveAxis}
            active={active}
            setActive={setActive}
          />

          <div className="pjx-grid-title">
            <span className="pjx-grid-title-text">{gridTitle.toUpperCase()}</span>
            <span className="pjx-grid-count">{filtered.length} project{filtered.length === 1 ? '' : 's'}</span>
          </div>

          <div className={`pjx-grid axis-${active.typology}-${active.country}-${active.status}`}>
            {filtered.map((p, i) => (
              <ProjectCard key={p.id} p={p} onPick={setPicked}/>
            ))}
            {filtered.length === 0 && (
              <div className="pjx-empty">
                <div className="pjx-empty-mark">[ &nbsp; ]</div>
                <div>Nothing matches this filter combination.</div>
                <button onClick={() => setActive({ typology:'all', country:'all', status:'all' })}>
                  Reset filters →
                </button>
              </div>
            )}
          </div>
        </div>
      </section>

      <Footer/>
      <CaseStudy item={picked} onClose={() => setPicked(null)}/>
    </>
  );
};

ReactDOM.createRoot(document.getElementById('app')).render(<ProjectsPage/>);
