/* Case study template — hero, overview, problem, process, outcome, next/prev */

function CaseStudy({ projectId, navigate }) {
  const projects = window.PROJECTS;
  const idx = Math.max(0, projects.findIndex(p => p.id === projectId));
  const project = projects[idx];
  const cs = window.CASE_STUDY_DEFAULTS;

  const prev = projects[(idx - 1 + projects.length) % projects.length];
  const next = projects[(idx + 1) % projects.length];

  // Each editorial case page has its own URL:
  //   #/case/stablex — Stablex block's "View case study" (replaces the old bespoke page)
  //   #/case/morpara — Morpara block's "View case study" (independent copy)
  //   #/case/algora — Algora block's "View case study" (independent copy of Morpara's)
  if ((projectId === "morpara" && window.MorparaCase) || (projectId === "stablex" && window.StablexCaseV2) || (projectId === "algora" && window.AlgoraCase)) {
    const Page = projectId === "morpara" ? window.MorparaCase : projectId === "algora" ? window.AlgoraCase : window.StablexCaseV2;
    return (
      <main className="pb-0" style={{ background: "#FCFCFC" }}>
        <Page navigate={navigate} />
      </main>
    );
  }

  // The hero project (Algora/Stablex/Morpara) routes to the bespoke Stablex story.
  if (project.id === "lumen-billing" && window.StablexCase) {
    return (
      <main className="pb-0 bg-ink">
        <window.StablexCase navigate={navigate} />
        <section className="px-6 py-20 border-t border-line">
          <div className="max-w-[1240px] mx-auto grid grid-cols-1 md:grid-cols-2 gap-6">
            <NavCard direction="prev" project={prev} navigate={navigate} />
            <NavCard direction="next" project={next} navigate={navigate} />
          </div>
        </section>
      </main>
    );
  }

  return (
    <main className="pt-28 pb-0">
      {/* HERO */}
      <section className="px-6">
        <div className="max-w-[1240px] mx-auto">
          <Reveal>
            <button
              onClick={() => { navigate("home"); setTimeout(()=>document.querySelector('#work')?.scrollIntoView({behavior:'smooth'}), 80); }}
              className="text-xs uppercase tracking-[0.18em] text-muted hover:text-white transition inline-flex items-center gap-2"
            >
              <span aria-hidden="true">←</span> All work
            </button>
          </Reveal>

          <Reveal delay={80}>
            <div className="mt-8 flex items-center gap-3">
              <span className="font-display text-muted text-xl tabular-nums">{project.n}</span>
              <span className="h-px w-10 bg-line" />
              <Tag>{project.tag}</Tag>
            </div>
          </Reveal>

          <Reveal delay={120}>
            <h1 className="mt-6 font-display text-[44px] md:text-[80px] leading-[0.98] tracking-[-0.025em] max-w-[22ch]">
              {project.title}<span className="text-muted">.</span>
            </h1>
          </Reveal>

          <Reveal delay={180}>
            <div className="mt-8 grid grid-cols-2 md:grid-cols-4 gap-px bg-line rounded-card overflow-hidden border border-line">
              {[
                ["Role", "Lead Product Designer"],
                ["Team", "1 PM · 2 Eng · 1 Researcher"],
                ["Duration", "6 months"],
                ["Year", "2024 — 2025"],
              ].map(([k,v]) => (
                <div key={k} className="bg-surface p-5">
                  <div className="text-[10px] uppercase tracking-[0.18em] text-muted">{k}</div>
                  <div className="mt-2 text-sm">{v}</div>
                </div>
              ))}
            </div>
          </Reveal>

          <Reveal delay={260}>
            <div className="mt-14 stripe-placeholder rounded-card border border-line aspect-[16/8] relative overflow-hidden">
              <div className="absolute inset-0 flex items-end p-8">
                <div className="font-mono text-[12px] uppercase tracking-[0.2em] text-muted">
                  [ hero image · 16:8 · full-bleed product shot or process photo ]
                </div>
              </div>
              <div className="absolute right-8 top-8 size-32 rounded-full"
                   style={{ background: "radial-gradient(closest-side, rgba(21,217,151,.4), transparent 75%)", filter:"blur(20px)" }} />
            </div>
          </Reveal>
        </div>
      </section>

      {/* OVERVIEW */}
      <CSSection title="Overview" eyebrow="01">
        {cs.overview.map((p,i)=>(
          <p key={i}>{p}</p>
        ))}
      </CSSection>

      {/* PROBLEM */}
      <CSSection title="The problem" eyebrow="02" accentLeft>
        {cs.problem.map((p,i)=>(<p key={i}>{p}</p>))}
        <div className="mt-10 grid grid-cols-1 md:grid-cols-3 gap-4 not-prose">
          {[
            ["Two thirds", "of new admins gave up before reaching their first invoice"],
            ["87 flows", "lived behind a single sidebar nobody dared touch"],
            ["12 teams", "had each shipped their own pattern over five years"],
          ].map(([v, l]) => (
            <div key={v} className="rounded-card border border-line bg-surface p-6">
              <div className="font-display text-3xl text-white">{v}</div>
              <div className="text-sm text-muted mt-2">{l}</div>
            </div>
          ))}
        </div>
      </CSSection>

      {/* PROCESS */}
      <CSSection title="Process" eyebrow="03">
        {cs.process.map((p, i) => (
          <React.Fragment key={i}>
            <p>{p}</p>
            {i < cs.process.length && (
              <div className="not-prose my-10 stripe-placeholder rounded-card border border-line aspect-[16/9] relative overflow-hidden">
                <div className="absolute inset-0 flex items-end p-6">
                  <div className="font-mono text-[10px] uppercase tracking-[0.2em] text-muted">
                    [ process image {i + 1} · {["wall of flows", "diary study artifact", "incremental migration shipping log"][i] || "process artifact"} ]
                  </div>
                </div>
              </div>
            )}
          </React.Fragment>
        ))}
      </CSSection>

      {/* OUTCOME */}
      <section className="px-6 py-24 border-y border-line bg-[#0c0c0e]">
        <div className="max-w-[1240px] mx-auto">
          <Reveal>
            <SectionEyebrow>04 · Outcome</SectionEyebrow>
          </Reveal>
          <Reveal delay={80}>
            <h2 className="mt-5 font-display text-[36px] md:text-[56px] leading-[1.02] max-w-[24ch]">
              Six months later, the console got out of the way.
            </h2>
          </Reveal>

          <div className="mt-14 grid grid-cols-1 md:grid-cols-2 gap-px bg-line rounded-card overflow-hidden border border-line">
            {cs.outcome.map((m) => (
              <div key={m.label} className="bg-surface p-8 md:p-10">
                <div className="font-display text-[44px] md:text-[64px] leading-none text-white">
                  {m.value}
                </div>
                <div className="mt-4 text-muted max-w-[42ch]">{m.label}</div>
              </div>
            ))}
          </div>

          <Reveal delay={200}>
            <blockquote className="mt-16 max-w-[60ch]">
              <div className="font-display text-2xl md:text-3xl leading-snug text-white/90">
                “The team stopped being afraid of the console. That's the part the metrics don't show.”
              </div>
              <div className="mt-4 text-sm text-muted">— Engineering lead, post-launch retro</div>
            </blockquote>
          </Reveal>
        </div>
      </section>

      {/* PREV / NEXT NAV */}
      <section className="px-6 py-20">
        <div className="max-w-[1240px] mx-auto grid grid-cols-1 md:grid-cols-2 gap-6">
          <NavCard direction="prev" project={prev} navigate={navigate} />
          <NavCard direction="next" project={next} navigate={navigate} />
        </div>
      </section>
    </main>
  );
}

function CSSection({ title, eyebrow, children, accentLeft }) {
  return (
    <section className="px-6 py-20">
      <div className="max-w-[1240px] mx-auto grid grid-cols-1 md:grid-cols-[200px_1fr] gap-10">
        <div className="md:sticky md:top-28 self-start">
          <SectionEyebrow>{eyebrow}</SectionEyebrow>
          <h2 className="mt-4 font-display text-3xl md:text-4xl tracking-tight">{title}</h2>
        </div>
        <div className={`max-w-[64ch] space-y-6 text-lg leading-[1.6] text-white/85 ${accentLeft ? "md:border-l md:border-accent md:pl-10" : ""}`}>
          {children}
        </div>
      </div>
    </section>
  );
}

function NavCard({ direction, project, navigate }) {
  const isNext = direction === "next";
  return (
    <button
      onClick={() => { navigate(`case/${project.id}`); window.scrollTo({ top: 0 }); }}
      className={`group text-left rounded-card border border-line bg-surface p-8 hover:border-accent transition glow-border ${isNext ? "md:text-right" : ""}`}
    >
      <div className={`text-xs uppercase tracking-[0.18em] text-muted ${isNext ? "md:justify-end" : ""} flex items-center gap-2`}>
        {!isNext && <span>←</span>}
        <span>{isNext ? "Next project" : "Previous project"}</span>
        {isNext && <span>→</span>}
      </div>
      <div className="mt-5 flex items-baseline gap-3">
        <span className="font-display text-muted text-2xl tabular-nums">{project.n}</span>
        <span className="font-display text-2xl md:text-3xl group-hover:text-accent transition">{project.title}</span>
      </div>
      <div className="mt-3 text-sm text-muted">{project.tag}</div>
    </button>
  );
}

window.CaseStudy = CaseStudy;
