// Project case study template — the hero deliverable.
// Metadata bar (sector · location · scope · area · year · services), build narrative
// (brief → construction approach → joinery → approvals → outcome), gallery w/ lightbox,
// related work, and a "start a similar project" CTA.

function CaseStudy({ id, navigate }) {
  const data = window.DS_DATA;
  const project = data.projects.find((p) => p.id === id);
  const [lightbox, setLightbox] = useState(null); // index or null

  useEffect(() => { window.scrollTo({ top: 0, behavior: "instant" }); }, [id]);

  if (!project) {
    return (
      <div className="container section">
        <h1 className="h-2">Project not found.</h1>
        <p className="muted" style={{ marginTop: 12 }}>The case study you were looking for has been moved or unpublished.</p>
        <div style={{ marginTop: 20 }}>
          <Button onClick={() => navigate({ name: "projects" })}>Back to projects</Button>
        </div>
      </div>
    );
  }

  const related = data.projects.filter((p) => p.id !== project.id && p.sector === project.sector).slice(0, 3);
  const fallbackRelated = data.projects.filter((p) => p.id !== project.id).slice(0, 3);
  const relatedList = related.length >= 2 ? related : fallbackRelated;

  // Build the build-narrative as an ordered list.
  const stages = [
    { code: "01", label: "Brief", body: project.brief },
    { code: "02", label: "Construction approach", body: project.build },
    { code: "03", label: "Joinery & finishes", body: project.joinery },
    { code: "04", label: "Approvals", body: project.approvals },
    { code: "05", label: "Outcome", body: project.outcome },
  ];

  // Gallery layout — alternates between split (7/5) and full (12) rows.
  const gallerySpans = ["span-7", "span-5", "span-12", "span-6", "span-6"];

  return (
    <div className="page-enter" data-screen-label={"03 Case study — " + project.name}>
      {/* Breadcrumb */}
      <div className="container" style={{ paddingTop: 20 }}>
        <div className="label" style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <button onClick={() => navigate({ name: "projects" })} style={{ color: "var(--muted)" }}>Projects</button>
          <span style={{ color: "var(--muted)" }}>/</span>
          <button onClick={() => navigate({ name: "projects", filter: project.sector })} style={{ color: "var(--muted)" }}>{project.sectorLabel}</button>
          <span style={{ color: "var(--muted)" }}>/</span>
          <span className="label-ink">{project.name}</span>
        </div>
      </div>

      {/* Header */}
      <section className="container" style={{ paddingTop: "clamp(28px, 4vw, 56px)", paddingBottom: "clamp(28px, 3vw, 48px)" }}>
        <Eyebrow>Case study — {String(data.projects.indexOf(project) + 1).padStart(2, "0")}</Eyebrow>
        <h1 className="h-1" style={{ marginTop: 14, maxWidth: "14ch" }}>{project.name}</h1>
        <p className="lede" style={{ marginTop: 18, maxWidth: "44ch" }}>{project.summary}</p>
      </section>

      {/* Hero image */}
      <section className="project-hero">
        <img src={project.heroImage} alt={project.name} />
      </section>

      {/* Metadata bar */}
      <section className="container" style={{ paddingTop: "clamp(28px, 3vw, 48px)" }}>
        <MetaBar project={project} />
      </section>

      {/* Narrative */}
      <section className="container" style={{ paddingTop: "clamp(64px, 7vw, 112px)", paddingBottom: "clamp(40px, 5vw, 80px)" }}>
        <div className="two-col">
          <div>
            <Eyebrow>The build</Eyebrow>
            <h2 className="h-2" style={{ marginTop: 12 }}>How we delivered this one.</h2>
          </div>
          <div>
            <ol style={{ margin: 0, padding: 0, listStyle: "none" }}>
              {stages.map((s, i) => (
                <li key={s.code} style={{ display: "grid", gridTemplateColumns: "80px 1fr", gap: 16, padding: "28px 0", borderBottom: i < stages.length - 1 ? "1px solid var(--border)" : "none", alignItems: "start" }}>
                  <span className="step-num" style={{ paddingTop: 8 }}>{s.code} ·</span>
                  <div>
                    <h3 className="h-4" style={{ marginBottom: 8 }}>{s.label}</h3>
                    <p className="paragraph" style={{ color: "var(--text)" }}>{s.body}</p>
                  </div>
                </li>
              ))}
            </ol>
          </div>
        </div>
      </section>

      {/* Gallery */}
      <section className="container" style={{ paddingTop: "clamp(40px, 5vw, 80px)", paddingBottom: "clamp(40px, 5vw, 80px)" }} data-screen-label={"03 Case study / " + project.name + " / Gallery"}>
        <div className="row-between" style={{ marginBottom: 28 }}>
          <Eyebrow>Gallery</Eyebrow>
          <span className="label">Photography credit: in confirmation</span>
        </div>
        <div className="gallery-grid">
          {project.gallery.map((src, i) => (
            <div key={i} className={"gallery-cell " + (gallerySpans[i % gallerySpans.length])} onClick={() => setLightbox(i)}>
              <img src={src} alt="" loading="lazy" />
            </div>
          ))}
          {/* If gallery is short, pad with relevant process imagery so the layout never feels empty */}
          {project.gallery.length < 3 ? (
            <>
              <div className="gallery-cell span-7" onClick={() => setLightbox(project.gallery.length)}>
                <img src="media/process-joinery.webp" alt="In-house joinery" />
              </div>
              <div className="gallery-cell span-5" onClick={() => setLightbox(project.gallery.length + 1)}>
                <img src="media/process-earthwork.webp" alt="Construction stage" />
              </div>
            </>
          ) : null}
        </div>
      </section>

      {/* Stage progress strip — before / during / after placeholder */}
      <section style={{ background: "var(--surface)" }}>
        <div className="container section">
          <SectionHeader eyebrow="Progress" title="Before · during · after." />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }} className="progress-grid">
            {["Before", "During build", "Handover"].map((label, i) => {
              const imgs = [
                ["media/process-earthwork.webp", "media/capability-building.webp", project.heroImage],
                [project.heroImage, "media/process-joinery.webp", "media/capability-building.webp"],
              ][i % 2];
              return (
                <div key={i}>
                  <div style={{ aspectRatio: "4/3", overflow: "hidden", background: "var(--paper)" }}>
                    <img src={imgs[i]} alt={label} className="img-fill" />
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12 }}>
                    <span className="label">{label}</span>
                    <span className="label">{i === 0 ? "Pre-mob" : i === 1 ? "Mid programme" : "On handover"}</span>
                  </div>
                </div>
              );
            })}
          </div>
          <style>{`@media (max-width: 880px) { .progress-grid { grid-template-columns: 1fr !important; } }`}</style>
        </div>
      </section>

      {/* CTA */}
      <section style={{ background: "var(--noir)", color: "#F4F1EA" }}>
        <div className="container section">
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: "clamp(28px, 4vw, 64px)", alignItems: "end" }} className="cta-band">
            <h2 className="h-1" style={{ color: "#F4F1EA", maxWidth: "16ch" }}>
              Building <span style={{ color: "var(--bronze)" }}>something like this?</span>
            </h2>
            <div>
              <p className="lede" style={{ color: "rgba(244,241,234,0.8)", marginBottom: 22, maxWidth: "40ch" }}>
                Tell us the scope and programme — we'll come back within two working days with a sector lead and a build approach.
              </p>
              <Button onClick={() => navigate({ name: "contact", project: project.id })}>Start a similar project</Button>
            </div>
          </div>
          <style>{`@media (max-width: 880px) { .cta-band { grid-template-columns: 1fr !important; } }`}</style>
        </div>
      </section>

      {/* Related */}
      <section className="container section">
        <SectionHeader
          eyebrow="More like this"
          title="Other work in the same sector."
          action={<BtnLink onClick={() => navigate({ name: "projects", filter: project.sector })}>All {project.sectorLabel}</BtnLink>}
        />
        <div className="project-grid">
          {relatedList.map((p) => (
            <ProjectCard key={p.id} project={p} onClick={() => navigate({ name: "project", id: p.id })} />
          ))}
        </div>
      </section>

      {lightbox !== null ? (
        <Lightbox
          images={[...project.gallery, "media/process-joinery.webp", "media/process-earthwork.webp"]}
          startIndex={lightbox}
          onClose={() => setLightbox(null)}
        />
      ) : null}
    </div>
  );
}

function MetaBar({ project }) {
  const cells = [
    { label: "Sector", value: project.sectorLabel },
    { label: "Location", value: project.location },
    { label: "Scope", value: project.scope },
    { label: "Area", value: project.area },
    { label: "Year", value: project.year },
    { label: "Services", value: project.services.join(" · ") },
  ];
  return (
    <div className="case-meta-bar">
      {cells.map((c, i) => (
        <div className="case-meta" key={i}>
          <span className="label">{c.label}</span>
          <span className="case-meta-value">{c.value}</span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { CaseStudy });
