// pages-projects.jsx — Projects index + case study + sectors hub
const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP } = React;

function ProjectsIndex({ navigate, initialFilter }) {
  const [filter, setFilter] = useStateP(initialFilter || "all");
  const [view, setView] = useStateP("grid");

  const filtered = useMemoP(() => {
    if (filter === "all") return PROJECTS;
    return PROJECTS.filter(p => p.sector === filter);
  }, [filter]);

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

  return (
    <main data-screen-label="02 Projects">
      <section className="section tight" style={{ paddingBottom: 16 }}>
        <div className="wrap">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", gap: 24, flexWrap: "wrap", marginBottom: 28 }}>
            <div>
              <div className="eyebrow">— Index of work · {PROJECTS.length} entries</div>
              <h1 className="display" style={{ fontSize: "clamp(48px, 7vw, 120px)", margin: "20px 0 0", fontWeight: 300 }}>
                Projects
              </h1>
            </div>
            <div className="body" style={{ maxWidth: "44ch" }}>
              Filter by sector. Cards marked <span className="note-bar" style={{ display: "inline-flex" }}>Study</span> are concepts or 3D-visualisation work; the rest are delivered turnkey or design-only engagements.
            </div>
          </div>

          {/* toolbar */}
          <div className="proj-toolbar" data-comment-anchor="proj-toolbar">
            <div className="filter-chips">
              {SECTORS.map(s => (
                <button
                  key={s.id}
                  className={`chip ${filter === s.id ? "on" : ""}`}
                  onClick={() => setFilter(s.id)}
                >
                  {s.label}
                  <span style={{ marginLeft: 8, opacity: 0.55 }}>
                    {s.id === "all" ? PROJECTS.length : PROJECTS.filter(p => p.sector === s.id).length}
                  </span>
                </button>
              ))}
            </div>
            <div className="view-toggle">
              <span>View</span>
              <button className={view === "grid" ? "on" : ""} onClick={() => setView("grid")}>Grid</button>
              <span style={{ opacity: 0.4 }}>/</span>
              <button className={view === "list" ? "on" : ""} onClick={() => setView("list")}>List</button>
            </div>
          </div>

          {/* grid */}
          {view === "grid" && (
            <div className="proj-grid">
              {filtered.map((p, i) => (
                <div
                  key={p.id}
                  className={`proj-cell ${p.span || "s4"}`}
                >
                  <div className={`proj-card ${p.aspect || ""}`} onClick={() => navigate({ name: "case", id: p.id })}>
                    <div className="frame">
                      <div className="img" style={{ backgroundImage: `url(${p.cover})` }} />
                      {p.studyOnly && (
                        <div style={{ position: "absolute", top: 14, left: 14, background: "rgba(14,12,10,0.78)", color: "var(--paper)", padding: "6px 10px", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase" }}>
                          Study · 3D
                        </div>
                      )}
                    </div>
                    <div className="meta">
                      <div className="idx">{String(i + 1).padStart(2, "0")} —</div>
                      <div className="title">{p.title}</div>
                      <div className="submeta">{p.sector} · {p.year}</div>
                    </div>
                    <div style={{ paddingTop: 6, fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.18em", color: "var(--muted)", textTransform: "uppercase", paddingLeft: 36 }}>
                      {p.location} · {p.area}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* list */}
          {view === "list" && (
            <div className="proj-list">
              {filtered.map((p, i) => (
                <div className="proj-row" key={p.id} onClick={() => navigate({ name: "case", id: p.id })}>
                  <div className="idx">{String(i + 1).padStart(2, "0")} —</div>
                  <div className="title">{p.title}</div>
                  <div className="cell">{p.location}</div>
                  <div className="cell year">{p.scope}</div>
                  <div className="cell area">{p.area}</div>
                  <div className="thumb" style={{ backgroundImage: `url(${p.cover})` }} />
                </div>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* note bar */}
      <section style={{ background: "var(--sand)", padding: "20px 0", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
        <div className="wrap" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <div className="label">Editorial note — photographer credit & client release confirmed before each name is published.</div>
          <button className="btn btn-sm btn-arrow" onClick={() => navigate({ name: "contact" })}>Start a similar project</button>
        </div>
      </section>
    </main>
  );
}

// ---------- Case study ----------
function CaseStudy({ project, navigate, openLightbox }) {
  if (!project) return null;
  const gallery = (CASE_GALLERIES[project.id] || [
    project.cover,
    "media/project-villa-7.webp",
    "media/project-villa-15.webp",
    "media/project-dsc-0281-hdr.webp",
  ]);
  const nextProject = PROJECTS[(PROJECTS.findIndex(p => p.id === project.id) + 1) % PROJECTS.length];

  return (
    <main data-screen-label={`03 Case Study — ${project.title}`}>
      {/* Case hero */}
      <section className="case-hero" data-comment-anchor="case-hero">
        <div className="img" style={{ backgroundImage: `url(${project.cover})` }} />
        <div className="scrim" />
        <div className="label-grid">
          <div>
            <div className="crumbs">
              <a onClick={() => navigate({ name: "projects" })} style={{ cursor: "pointer" }}>Projects</a>
              <span>›</span>
              <span>{project.sector}</span>
              <span>›</span>
              <span>{project.id}</span>
            </div>
            <h1>
              {project.title.split(" — ").map((part, i) => (
                <React.Fragment key={i}>
                  {i > 0 && <em>&nbsp;— </em>}
                  {part}
                </React.Fragment>
              ))}
            </h1>
          </div>
          <div className="right-meta">
            {project.location}<br/>
            {project.year}<br/>
            {project.area}<br/>
            {project.studyOnly ? "Study · Visualisation" : "Delivered"}
          </div>
        </div>
      </section>

      {/* Meta row */}
      <div className="wrap">
        <div className="case-meta-row">
          <div className="item"><span className="label">Sector</span><div className="val">{project.sector}</div></div>
          <div className="item"><span className="label">Location</span><div className="val">{project.location}</div></div>
          <div className="item"><span className="label">Scope</span><div className="val">{project.scope}</div></div>
          <div className="item"><span className="label">Year</span><div className="val">{project.year}</div></div>
          <div className="item"><span className="label">Area</span><div className="val">{project.area}</div></div>
        </div>
      </div>

      {/* Concept */}
      <section className="case-section">
        <div className="wrap">
          <div className="case-2col">
            <div>
              <div className="eyebrow">◇ — Concept</div>
              <p className="lede" style={{ marginTop: 24 }}>
                {project.concept}
              </p>
            </div>
            <div className="body">
              <p style={{ marginTop: 0 }}>
                Brief: a residence that "felt at rest". The owners — based in
                London and Dubai — wanted to drop into the apartment after a flight
                and not feel marketed at. The starting condition was a developer shell
                with marble that, frankly, fought us. We softened the floor with rugs,
                quieted the joinery, and let the sky carry the room.
              </p>
              <p>
                The plan was redrawn lightly — two walls relocated, a fireplace removed —
                with the architect-of-record. Approvals were processed in parallel so the
                build sequence held. Renders below were issued before any joinery was cut.
              </p>
              <a
                className="link-arrow"
                onClick={() => openLightbox(gallery, 0)}
                style={{ cursor: "pointer", display: "inline-flex", marginTop: 24 }}
              >
                Open gallery — {gallery.length} frames
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* Gallery */}
      <section style={{ paddingBottom: 80 }}>
        <div className="wrap">
          <div className="gallery">
            <div className="g full" style={{ backgroundImage: `url(${gallery[0]})` }} onClick={() => openLightbox(gallery, 0)} />
            <div className="g half"  style={{ backgroundImage: `url(${gallery[1]})` }} onClick={() => openLightbox(gallery, 1)} />
            <div className="g half"  style={{ backgroundImage: `url(${gallery[2] || gallery[1]})` }} onClick={() => openLightbox(gallery, 2)} />
            <div className="g third" style={{ backgroundImage: `url(${gallery[3] || gallery[0]})` }} onClick={() => openLightbox(gallery, 3)} />
            <div className="g third" style={{ backgroundImage: `url(${gallery[4] || gallery[1]})` }} onClick={() => openLightbox(gallery, 4)} />
            <div className="g third" style={{ backgroundImage: `url(${gallery[0]})` }} onClick={() => openLightbox(gallery, 0)} />
          </div>
        </div>
      </section>

      {/* Materials */}
      <section className="case-section sand" style={{ background: "var(--sand)" }}>
        <div className="wrap">
          <SectionHead
            roman="II."
            title="Materials & finishes."
            aside="A short specification — the load-bearing material choices that set the room's temperature."
          />
          <div className="materials">
            {MATERIALS.map((m, i) => (
              <div className="material" key={i}>
                <div className="swatch" style={{ background: m.swatch }} />
                <h4>{m.title}</h4>
                <p>{m.note}</p>
              </div>
            ))}
          </div>
          <div className="label" style={{ marginTop: 24 }}>Full BOQ and supplier list issued to client at handover.</div>
        </div>
      </section>

      {/* Process for this project */}
      <section className="case-section dark" style={{ background: "var(--noir)", color: "var(--paper)" }}>
        <div className="wrap">
          <SectionHead
            roman="III."
            title={<>Process — from <em>brief</em> to handover.</>}
            aside="How this particular project ran. One project manager, photoreal renders pre-commitment, in-house approvals."
          />
          <ProcessStrip />
        </div>
      </section>

      {/* Outcome + next */}
      <section className="case-section">
        <div className="wrap">
          <div className="case-2col">
            <div>
              <div className="eyebrow">◇ — Outcome</div>
              <p className="lede" style={{ marginTop: 24 }}>
                Built and handed over in 22 weeks from contract sign-off,
                including DDA approvals and snagging. Photographer credit on file with the studio.
              </p>
            </div>
            <div className="body">
              <p style={{ marginTop: 0 }}>
                The owners moved in the following month. A small punch list closed within
                14 days. The apartment was used for a private editorial shoot in May 2024,
                with client and photographer release available on request.
              </p>
              <div style={{ marginTop: 24, display: "flex", gap: 12, flexWrap: "wrap" }}>
                <button className="btn btn-arrow" onClick={() => navigate({ name: "contact", subject: project.title })}>
                  Start a similar project
                </button>
                <button className="btn btn-ghost btn-arrow" onClick={() => navigate({ name: "case", id: nextProject.id })}>
                  Next — {nextProject.title}
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

// ---------- Sectors hub page ----------
function Sectors({ navigate }) {
  return (
    <main data-screen-label="04 Sectors">
      <section className="section tight" style={{ paddingBottom: 24 }}>
        <div className="wrap">
          <div className="eyebrow">— Sectors served · 6 hubs</div>
          <h1 className="display" style={{ fontSize: "clamp(48px, 7vw, 120px)", margin: "20px 0 24px", fontWeight: 300 }}>
            <em style={{ color: "var(--brass)", fontStyle: "italic" }}>Sectors.</em>
          </h1>
          <p className="lede" style={{ maxWidth: "44ch" }}>
            The work is filed by sector — residential and commercial — and by where the studio's
            craft is most visible. Each hub leads to a filtered project index.
          </p>
        </div>
      </section>
      <section className="section">
        <div className="wrap">
          <div className="sector-grid" style={{ gridAutoRows: "minmax(280px, auto)" }}>
            {SECTOR_CARDS.map((s, i) => (
              <div
                key={s.id}
                className={`sector ${s.size}`}
                onClick={() => navigate({ name: "projects", filter: s.id })}
              >
                <div className="img" style={{ backgroundImage: `url(${s.cover})` }} />
                <div className="scrim" />
                <div className="corner-idx">— {String(i + 1).padStart(2, "0")}</div>
                <div className="label-block">
                  <h3>{s.label}</h3>
                  <div className="count">{s.count} →</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

window.ProjectsIndex = ProjectsIndex;
window.CaseStudy = CaseStudy;
window.Sectors = Sectors;
