// Sections: scroll-driven narrative chapters

const { useState: useState2, useEffect: useEffect2, useRef: useRef2, useMemo: useMemo2 } = React;

// ---------- Scroll reveal hook ----------
function useReveal(threshold = 0.15) {
  const ref = useRef2(null);
  const [visible, setVisible] = useState2(false);
  useEffect2(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setVisible(true);
          io.disconnect();
        }
      },
      { threshold }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, [threshold]);
  return [ref, visible];
}

function Reveal({ children, delay = 0, as = "div", ...rest }) {
  const [ref, visible] = useReveal();
  const Tag = as;
  return (
    <Tag
      ref={ref}
      {...rest}
      style={{
        ...rest.style,
        opacity: visible ? 1 : 0,
        transform: visible ? "translateY(0)" : "translateY(18px)",
        transition: `opacity 800ms cubic-bezier(.2,.7,.2,1) ${delay}ms, transform 900ms cubic-bezier(.2,.7,.2,1) ${delay}ms`,
      }}
    >
      {children}
    </Tag>
  );
}

// ---------- Hero ----------
const PILLARS = [
  {
    id: "adoption",
    section: "adoption",
    label: "Adoption",
    role: "The journey",
    question: "Where is the team?",
    steps: ["Explore", "Experiment", "Embed", "Evolve"],
    color: "var(--saffron)",
  },
  {
    id: "dora",
    section: "dora",
    label: "DORA AI",
    role: "The compass",
    question: "How ready is the team?",
    steps: ["Stance", "Data", "VCS", "Batches", "User", "Platform"],
    color: "var(--t-pos)",
  },
  {
    id: "method",
    section: "method",
    label: "Method",
    role: "The practice",
    question: "How do we adopt AI?",
    steps: ["Map", "Diagnose", "Design", "Guardrail", "Measure"],
    color: "var(--t-neu)",
  },
];

function HeroSection() {
  const [hovered, setHovered] = useState2(null);
  const { audience } = useAudience();
  const isClient = audience === "client";

  const eyebrow = isClient
    ? "How Proshore teams deliver with AI"
    : "The Proshore AI Adoption Method";

  return (
    <section className="hero">
      <div className="hero-grid">
        <div className="hero-top">
          <div className="section-label">{eyebrow}</div>
          {isClient ? (
            <>
              <h1 className="hero-title">
                Faster delivery,
                <br />
                <em><span className="t-pos">the same standards.</span></em>
              </h1>
              <p className="hero-sub">
                Your delivery team adopts AI through a small, repeatable cycle: find what
                slows the work down, change it, measure the result. Predictable cycles,
                less repetitive effort, <span className="saffron">a team that keeps getting sharper.</span>
              </p>
            </>
          ) : (
            <>
              <h1 className="hero-title">
                AI as an
                <br />
                <em><span className="t-pos">Amplifier.</span></em>
              </h1>
              <p className="hero-sub">
                A method, <span className="saffron">not a playbook,</span> any Proshore team can apply to itself to adopt AI
                with system-level thinking. Built for teams. Readable by clients.
              </p>
            </>
          )}
        </div>

        <div className="hero-pillars-diagram">
          {/* Entablature: the framework roof */}
          <div className="pillars-entablature">
            <span>Three Pillars of AI Adoption</span>
          </div>

          {/* The three pillars */}
          <div className="pillars-row">
            {PILLARS.map((p) => {
              const isHovered = hovered === p.id;
              return (
                <a
                  key={p.id}
                  href={`#${p.section}`}
                  className={`pillar ${isHovered ? "pillar--active" : ""}`}
                  style={{ "--pillar-color": p.color }}
                  onMouseEnter={() => setHovered(p.id)}
                  onMouseLeave={() => setHovered(null)}
                >
                  {/* Capital: the decorative top */}
                  <div className="pillar-capital" />

                  {/* Shaft: the main body */}
                  <div className="pillar-shaft">
                    <div className="pillar-role">{p.role}</div>
                    <div className="pillar-label">{p.label}</div>
                    <div className="pillar-question">{p.question}</div>
                    <div className="pillar-steps">
                      {p.steps.map((s, i) => (
                        <span key={i} className="pillar-step-tag">{s}</span>
                      ))}
                    </div>
                  </div>

                  {/* Base: the bottom pedestal */}
                  <div className="pillar-base" />
                </a>
              );
            })}
          </div>

          {/* Stylobate: the foundation */}
          <div className="pillars-stylobate">
            <span>Your delivery team</span>
          </div>

          {/* Connection labels between pillars */}
          <div className="pillars-connections">
            <span className="pillars-conn-label">Method feeds capability improvements</span>
            <span className="pillars-conn-label">Capabilities inform adoption readiness</span>
          </div>
        </div>

        <div className="hero-meta">
          <div>
            <div className="hero-meta-label">Owner</div>
            <div>Babish</div>
          </div>
          <div>
            <div className="hero-meta-label">Audience</div>
            <div>{isClient ? "Clients · Delivery teams · Leadership" : "Leadership · Delivery teams · Clients"}</div>
          </div>
          <div>
            <div className="hero-meta-label">Scope</div>
            <div>Design · PM · Dev · QA · DevOps · Ops</div>
          </div>
          <div>
            <div className="hero-meta-label">Status</div>
            <div>{isClient ? "Engagement playbook" : "Draft · v1.8"}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Why-a-method section ----------
function WhyMethodSection() {
  const [mode, setMode] = useState2("without"); // "without" | "with"
  const { audience } = useAudience();
  return (
    <section className="section section-lavender">
      <Reveal>
        <div className="section-label">{audience === "client" ? "Why a method, not a playbook" : "04. Why a method, not a playbook"}</div>
      </Reveal>
      <Reveal delay={80}>
        <h2 className="section-title">
          Treating AI as a <span className="t-neg">tool</span> speeds up one stage. <em>Treating it as a system <span className="t-pos">improvement</span> changes the whole workflow.</em>
        </h2>
      </Reveal>
      <Reveal delay={160}>
        <p className="section-body">
          Tool-first AI rollouts focus on one stage: pick a tool, ask developers to use it, measure velocity.
          Results stay uneven because the tool is being added to one part of the workflow, not improving
          the workflow itself.
        </p>
      </Reveal>

      <Reveal delay={220}>
        <div className="compare">
          <div className="compare-toggle">
            <button
              className={mode === "without" ? "active" : ""}
              onClick={() => setMode("without")}
            >
              Without the method
            </button>
            <button
              className={mode === "with" ? "active" : ""}
              onClick={() => setMode("with")}
            >
              With the method
            </button>
          </div>
          <div className="compare-stage">
            <Pipeline
              bottleneckIdx={mode === "without" ? 3 : null}
              method={mode === "with"}
              draggable={false}
              metaphor="flow"
            />
          </div>
          <div className="compare-caption">
            {mode === "without" ? (
              <>
                <span className="dot" style={{ background: "var(--accent)" }} />
                AI speeds up Develop. Refine stays ambiguous. The bottleneck doesn't disappear. It moves downstream to Test.
              </>
            ) : (
              <>
                <span className="dot" style={{ background: "var(--flow-good)" }} />
                The method finds the real bottleneck first. AI is designed in where it matters, with guardrails. The system, not just a stage, gets better.
              </>
            )}
          </div>
        </div>
      </Reveal>
    </section>
  );
}

// ---------- Convictions ----------
function ConvictionsSection() {
  const { audience } = useAudience();
  const isClient = audience === "client";
  return (
    <section className="section section-dark">
      <Reveal>
        <div className="section-label dim">{isClient ? "Four convictions" : "05. Four convictions"}</div>
      </Reveal>
      <Reveal delay={80}>
        <h2 className="section-title light">
          Before jumping in to the method, the stance.
        </h2>
      </Reveal>
      <Reveal delay={140}>
        <p className="section-body dim">
          Four non-negotiables that keep teams from drifting into common traps.
        </p>
      </Reveal>

      <div className="convictions">
        {CONVICTIONS.map((c, i) => (
          <Reveal key={c.num} delay={i * 120}>
            <article className={`conviction ${c.emphasis ? "emphasis" : ""}`}>
              <div className="conviction-num">{c.num}</div>
              <div className="conviction-short">{c.short}</div>
              <h3 className="conviction-headline"
                dangerouslySetInnerHTML={{ __html: c.emphasis ? `<em>${c.headline}</em>` : c.headline }} />
              <p className="conviction-body" dangerouslySetInnerHTML={{ __html: c.body }} />
            </article>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ---------- Pipeline explorer (click any stage) ----------
function ExploreSection() {
  const [activeId, setActiveId] = useState2("refine");
  const [bottleneck, setBottleneck] = useState2(1); // refine by default
  const [metaphor, setMetaphor] = useState2("flow");
  const { audience } = useAudience();
  const isClient = audience === "client";

  const stage = STAGES.find((s) => s.id === activeId) || STAGES[0];

  // When bottleneck moves, sync active card
  useEffect2(() => {
    if (bottleneck !== null) setActiveId(STAGES[bottleneck].id);
  }, [bottleneck]);

  return (
    <section className="section section-light" id="explore">
      <Reveal>
        <div className="section-label">
          {isClient ? "Where AI lands, by stage" : "08. Design Intervention, example"}
        </div>
      </Reveal>
      <Reveal delay={80}>
        <h2 className="section-title">
          {isClient ? (
            <>AI fits the stage <em>where work actually slows down.</em></>
          ) : (
            <>Idenfity the bottleneck. <em>Possible intervention change.</em></>
          )}
        </h2>
      </Reveal>
      <Reveal delay={140}>
        <p className="section-body">
          {isClient
            ? "You don't pick AI from a menu. You name the stage where work slows down, and the AI improvement is the one that fits that stage. Click any stage to see what that improvement could look like."
            : "AI goes where friction is, not where AI is attractive. The right intervention depends entirely on which stage is holding the system back."}
        </p>
      </Reveal>

      <div className="explorer">
        <div className="explorer-stage">
          <Pipeline
            bottleneckIdx={bottleneck}
            onBottleneckChange={setBottleneck}
            activeStage={activeId}
            onStageClick={(id) => {
              setActiveId(id);
              setBottleneck(STAGES.findIndex((s) => s.id === id));
            }}
            metaphor={metaphor}
          />
          <div className="metaphor-switch">
            <span>{isClient ? "Drag the slowdown to any stage" : "Drag the bottlneck in each stage"}</span>
          </div>
        </div>

        <aside className="intervention-card">
          <div className="intervention-eyebrow">
            <span className="pill">Stage · {stage.label}</span>
            <span className="muted">{stage.produces}</span>
          </div>
          <h3 className="intervention-title">
            <em>{isClient ? "If this stage is the slowdown:" : "If this is your bottleneck:"}</em> {stage.aiIntervention.title}
          </h3>
          <div className="intervention-friction">
            <div className="kv-label">Typical friction</div>
            <div dangerouslySetInnerHTML={{ __html: stage.typicalFriction }} />
          </div>
          <div className="intervention-grid">
            <div>
              <div className="kv-label">What AI does</div>
              <div dangerouslySetInnerHTML={{ __html: stage.aiIntervention.what }} />
            </div>
            <div>
              <div className="kv-label">What the human does</div>
              <div dangerouslySetInnerHTML={{ __html: stage.aiIntervention.human }} />
            </div>
            <div className="full">
              <div className="kv-label">Output</div>
              <div dangerouslySetInnerHTML={{ __html: stage.aiIntervention.output }} />
            </div>
          </div>
        </aside>
      </div>
    </section>
  );
}

// ---------- 5-step method walkthrough ----------
function MethodSection() {
  const [active, setActive] = useState2(0);
  const timerRef = useRef2(null);
  const { audience } = useAudience();

  const go = (n) => {
    setActive(n);
    // pause auto-advance on manual select
    if (timerRef.current) clearInterval(timerRef.current);
  };

  // auto-advance when visible for the first time
  const [ref, visible] = useReveal();
  useEffect2(() => {
    if (!visible) return;
    timerRef.current = setInterval(() => {
      setActive((a) => (a + 1) % METHOD_STEPS.length);
    }, 4200);
    return () => clearInterval(timerRef.current);
  }, [visible]);

  const activeStep = METHOD_STEPS[active];
  const capName = (cap) => pickCopy(cap.name, audience);

  return (
    <section className="section section-lavender method" ref={ref}>
      <Reveal>
        <div className="section-label">{audience === "client" ? "The method, in five steps" : "06. The method, in five steps"}</div>
      </Reveal>
      <Reveal delay={80}>
        <h2 className="section-title">
          Every team runs these <em>in order.</em> The answers differ. The thinking is the same.
        </h2>
      </Reveal>

      <div className="method-layout">
        <nav className="method-nav">
          {METHOD_STEPS.map((s, i) => (
            <button
              key={s.n}
              className={`method-nav-item ${active === i ? "active" : ""}`}
              onClick={() => go(i)}
            >
              <span className="method-num">{String(s.n).padStart(2, "0")}</span>
              <span className="method-name">{s.name}</span>
              <span className="method-sub">{pickCopy(s.sub, audience)}</span>
            </button>
          ))}
        </nav>

        <div className="method-detail" key={active}>
          <div className="method-detail-eyebrow">
            Step {activeStep.n} of 5
          </div>
          <h3 className="method-detail-title">
            <em>{activeStep.name}</em>: {pickCopy(activeStep.sub, audience)}
          </h3>
          <p className="method-detail-body" dangerouslySetInnerHTML={{ __html: pickCopy(activeStep.body, audience) }} />

          {activeStep.dora.length > 0 && (
            <div className="method-dora">
              <div className="kv-label">DORA capabilities at play</div>
              <div className="method-dora-badges">
                {activeStep.dora.map((id) => {
                  const cap = DORA_CAPABILITIES.find((c) => c.id === id);
                  if (!cap) return null;
                  return (
                    <span key={id} className="method-dora-badge">
                      <span className="method-dora-badge-num">{cap.num}</span>
                      {capName(cap)}
                    </span>
                  );
                })}
              </div>
            </div>
          )}

          <div className="method-output">
            <div className="kv-label">Output</div>
            <div dangerouslySetInnerHTML={{ __html: pickCopy(activeStep.output, audience) }} />
          </div>
          <div className="method-progress">
            {METHOD_STEPS.map((_, i) => (
              <span key={i} className={i <= active ? "on" : ""} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Diagnose pipeline ----------
function DiagnosePipeline({ ratings, onCycle }) {
  const [t, setT] = useState2(0);
  useEffect2(() => {
    let raf;
    const start = performance.now();
    const tick = (now) => { setT((now - start) / 1000); raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const W = 1100, H = 320, pad = 60, trackY = 170;
  const stepW = (W - pad * 2) / (STAGES.length - 1);
  const stageX = (i) => pad + i * stepW;
  const trackW = W - pad * 2;
  const sevIdx = (key) => SEVERITY_LEVELS.findIndex((s) => s.key === key);

  // Worst stage drives particle slowdown
  const worstI = STAGES.reduce((wi, s, i) =>
    sevIdx(ratings[s.id]) > sevIdx(ratings[STAGES[wi].id]) ? i : wi, 0);
  const worstSevI = sevIdx(ratings[STAGES[worstI].id]);
  const worstBX = worstSevI > 0 ? (stageX(worstI) - pad) / trackW : null;

  // Flowing particles
  const pts = [];
  for (let i = 0; i < 9; i++) {
    let p = ((i / 9) + t * 0.12) % 1;
    if (worstBX !== null) {
      const dist = p - worstBX;
      if (dist > -0.12 && dist < 0) {
        const slow = 1 - (0.12 + dist) / 0.12;
        p = worstBX + dist * (1 - (worstSevI / 4) * 0.65 * slow);
      }
    }
    pts.push(pad + p * trackW);
  }

  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="pipeline-svg"
      style={{ width: "100%", height: "auto", userSelect: "none" }}>

      {/* Track */}
      <line x1={pad} y1={trackY} x2={W - pad} y2={trackY}
        stroke="var(--ink-dim)" strokeWidth="1.5" />

      {/* Particles */}
      {pts.map((x, i) => (
        <circle key={i} cx={x} cy={trackY} r={3} fill="var(--ink)" opacity={0.72} />
      ))}

      {/* Feedback cycle arcs */}
      <path d={`M ${stageX(4)} ${trackY - 7} Q ${stageX(3.3)} ${trackY - 70} ${stageX(3)} ${trackY - 7}`}
        fill="none" stroke="var(--ink-dim)" strokeWidth="1" strokeDasharray="3 3" />
      <path d={`M ${stageX(6)} ${trackY - 7} Q ${stageX(3.5)} ${trackY - 116} ${stageX(1)} ${trackY - 7}`}
        fill="none" stroke="var(--ink-dim)" strokeWidth="1" strokeDasharray="3 3" />

      {/* Stages */}
      {STAGES.map((s, i) => {
        const x = stageX(i);
        const sev = SEVERITY_LEVELS.find((sv) => sv.key === ratings[s.id]) || SEVERITY_LEVELS[0];
        const isBn = sev.key !== "flowing";
        const si = sevIdx(sev.key);
        const pulseBase = 14 + si * 2;
        const pulsePeak = 22 + si * 3;
        const dur = `${2.2 - si * 0.2}s`;

        return (
          <g key={s.id} transform={`translate(${x}, ${trackY})`}
            style={{ cursor: "pointer" }} onClick={() => onCycle(s.id)}>

            {/* Pulse ring: only for bottleneck stages */}
            {isBn && (
              <circle fill={sev.color} opacity="0.18">
                <animate attributeName="r" values={`${pulseBase};${pulsePeak};${pulseBase}`}
                  dur={dur} repeatCount="indefinite" />
                <animate attributeName="opacity" values="0.22;0.04;0.22"
                  dur={dur} repeatCount="indefinite" />
              </circle>
            )}

            {/* Node: always colored */}
            <circle r={isBn ? 13 : 9}
              fill={sev.color}
              opacity={isBn ? 1 : 0.55}
              style={{ transition: "r 260ms ease, fill 260ms ease, opacity 260ms ease" }}
            />

            {/* Stage name above */}
            <text y={-26} textAnchor="middle" className="stage-label"
              fill={isBn ? "var(--ink)" : "var(--ink-dim)"}
              style={{ fontWeight: isBn ? 700 : 500 }}>
              {s.label}
            </text>

            {/* Severity label below: always shown */}
            <text y={34} textAnchor="middle"
              style={{ fontSize: 10, fontFamily: "var(--sans)", fontWeight: 700,
                fill: sev.color, letterSpacing: "0.07em", opacity: isBn ? 1 : 0.7 }}>
              {sev.label.toUpperCase()}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

// ---------- Diagnostic (severity rating) ----------
function DiagnosticSection() {
  const sevIdx = (key) => SEVERITY_LEVELS.findIndex((s) => s.key === key);

  const [ratings, setRatings] = useState2({
    idea: "flowing", refine: "bottleneck", plan: "friction",
    develop: "slowdown", test: "chaotic", deploy: "friction",
    monitor: "flowing", iterate: "flowing",
  });

  const cycleRating = (stageId) => setRatings((prev) => {
    const idx = sevIdx(prev[stageId]);
    return { ...prev, [stageId]: SEVERITY_LEVELS[(idx + 1) % SEVERITY_LEVELS.length].key };
  });

  const top = [...STAGES].sort((a, b) => sevIdx(ratings[b.id]) - sevIdx(ratings[a.id]))[0];
  const topSev = SEVERITY_LEVELS.find((s) => s.key === ratings[top.id]);

  return (
    <section className="section section-light">
      <Reveal>
        <div className="section-label">07. Diagnose your own bottleneck, Example</div>
      </Reveal>
      <Reveal delay={80}>
        <h2 className="section-title">
          Rate each stage. <em>The highest severity is where to start.</em>
        </h2>
      </Reveal>
      <Reveal delay={140}>
        <p className="section-body">
          Click any stage to cycle its severity. The worst stage is your first intervention target.
          Illustrative: your team rates this for real in Step 2.
        </p>
      </Reveal>

      <DiagnosePipeline ratings={ratings} onCycle={cycleRating} />

      <div className="diagnostic-verdict">
        {topSev && topSev.key !== "flowing" ? (
          <>
            <div className="kv-label">Probable bottleneck</div>
            <div className="verdict-value">
              <em>{top.label}</em>{": "}
              <span style={{ color: topSev.color }}>{topSev.label}</span>
            </div>
          </>
        ) : (
          <div className="muted">Click stages to set severity. All stages clear.</div>
        )}
      </div>

      <div className="sev-legend">
        {SEVERITY_LEVELS.map((s) => (
          <div key={s.key} className="sev-legend-item">
            <span className="sev-legend-dot" style={{ background: s.color }} />
            <span style={{ color: s.color }}>{s.label}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- Worked example ----------
function ExampleSection() {
  const ex = WORKED_EXAMPLE;
  const [openStep, setOpenStep] = useState2(1);

  const steps = [
    { n: 1, name: "Map", html: ex.map },
    {
      n: 2,
      name: "Diagnose",
      html: `<div><strong>Bottleneck:</strong> ${ex.diagnosis.bottleneck}</div>
        <div class="mt-8"><strong>Evidence:</strong> ${ex.diagnosis.evidence}</div>
        <div class="mt-8"><strong>Hypothesis:</strong> ${ex.diagnosis.hypothesis}</div>`,
    },
    {
      n: 3,
      name: "Design",
      html: `<div class="example-headline">${ex.design.headline}</div>
        <div class="mt-8"><strong>What AI does:</strong> ${ex.design.what}</div>
        <div class="mt-8"><strong>Context it needs:</strong> ${ex.design.context}</div>
        <div class="mt-8"><strong>What the human does:</strong> ${ex.design.human}</div>
        <div class="mt-8"><strong>Output:</strong> ${ex.design.output}</div>`,
    },
    {
      n: 4,
      name: "Guardrail",
      html: `<div><strong>Review point:</strong> ${ex.guardrails.review}</div>
        <div class="mt-8"><strong>Decision boundary:</strong> ${ex.guardrails.boundary}</div>
        <div class="mt-8"><strong>Escape hatch:</strong> ${ex.guardrails.escape}</div>`,
    },
    {
      n: 5,
      name: "Measure",
      html: `<div><strong>Bottleneck signal:</strong> ${ex.measure.bottleneckSignal}</div>
        <div class="mt-8"><strong>System signal:</strong> ${ex.measure.systemSignal}</div>
        <div class="mt-8"><strong>Decision:</strong> ${ex.measure.decision}</div>`,
    },
  ];

  return (
    <section className="section section-lavender">
      <Reveal>
        <div className="section-label">08. The method in action</div>
      </Reveal>
      <Reveal delay={80}>
        <h2 className="section-title">
          One team's journey. <em>Your output will differ. That's the point.</em>
        </h2>
      </Reveal>
      <Reveal delay={140}>
        <div className="example-placeholder-note">
          Illustrative placeholder. Replace with a real Proshore team's first cycle.
        </div>
      </Reveal>
      <Reveal delay={180}>
        <div className="example-context">
          <div className="kv-label">Context · {ex.teamName}</div>
          <p dangerouslySetInnerHTML={{ __html: ex.context }} />
        </div>
      </Reveal>

      <div className="example-steps">
        {steps.map((s) => (
          <Reveal key={s.n} delay={s.n * 80}>
            <button
              className={`example-step ${openStep === s.n ? "open" : ""}`}
              onClick={() => setOpenStep(openStep === s.n ? 0 : s.n)}
            >
              <div className="example-step-head">
                <span className="example-step-num">{String(s.n).padStart(2, "0")}</span>
                <span className="example-step-name">{s.name}</span>
                <span className="example-step-toggle">{openStep === s.n ? "−" : "+"}</span>
              </div>
              <div
                className="example-step-body"
                style={{
                  maxHeight: openStep === s.n ? 600 : 0,
                }}
              >
                <div className="example-step-inner" dangerouslySetInnerHTML={{ __html: s.html }} />
              </div>
            </button>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ---------- Ops / Collapsible ----------
function Collapsible({ title, children, initialOpen = false }) {
  const [open, setOpen] = useState2(initialOpen);
  return (
    <div className={`collapsible ${open ? "open" : ""}`}>
      <button className="collapsible-head" onClick={() => setOpen(!open)}>
        <span>{title}</span>
        <span className="collapsible-toggle">{open ? "−" : "+"}</span>
      </button>
      <div className="collapsible-body" style={{ maxHeight: open ? 1200 : 0 }}>
        <div className="collapsible-inner">{children}</div>
      </div>
    </div>
  );
}

function OpsSection() {
  return (
    <section className="section section-light ops">
      <Reveal>
        <div className="section-label">09. Operational detail</div>
      </Reveal>
      <Reveal delay={80}>
        <h2 className="section-title">
          How this runs. <em>Collapsed by default. Expand what you need.</em>
        </h2>
      </Reveal>

      <div className="collapsibles">
        <Collapsible title="Who facilitates · who participates · cadence">
          <p><strong>Facilitator:</strong> a team lead, engineering manager, or scrum master. Not an AI expert. A good facilitator who keeps the team honest about the real workflow.</p>
          <p><strong>Participants:</strong> the whole delivery team (devs, PM, QA, designer, DevOps). Client stakeholders if they're embedded. No subsets.</p>
          <p><strong>Cadence:</strong> first pass in 1–2 weeks of part-time effort, then a 2–4 sprint measurement window. Quarterly after that. A 15-minute check per retro between cycles.</p>
        </Collapsible>

        <Collapsible title="Risks leadership should know about">
          <p><strong>Over-reliance.</strong> Engineers must be able to read, debug, and explain any output shipped under their name. Guardrails make review non-negotiable.</p>
          <p><strong>Inconsistent quality across teams.</strong> The method is the consistency. Leadership reviews the quality of thinking, not the specific tool choices.</p>
          <p><strong>Hallucinations reaching production.</strong> Step 4 defines a human review point for every intervention that touches clients, users, or production.</p>
          <p><strong>Shadow-AI usage.</strong> Almost always a signal that formal governance is too narrow. Guardrails are few and clearly explained: the sanctioned path is the convenient path.</p>
        </Collapsible>

        <Collapsible title="How leadership knows the framework is working">
          <p><strong>Method adoption:</strong> % of teams who've run at least one full cycle · quality of thinking in team outputs · % running on a quarterly rhythm.</p>
          <p><strong>System-level outcomes (watched, not chased):</strong> cycle time · escaped defect rate · change failure rate · rework rate · client satisfaction.</p>
          <p><strong>Capability growth:</strong> team leads' facilitation fluency · cross-team learnings captured · teams' confidence to design their own interventions.</p>
        </Collapsible>

        <Collapsible title="Appendix · recommended tooling categories">
          <ul className="tool-list">
            <li><span className="mono">chat w/ project context</span><span>Ideation, refinement, research</span></li>
            <li><span className="mono">rapid prototyping tool</span><span>Visual mocks during refinement</span></li>
            <li><span className="mono">IDE-integrated agent</span><span>In-editor coding assistance</span></li>
            <li><span className="mono">coding CLI agent</span><span>Multi-file development tasks</span></li>
            <li><span className="mono">MCP / integration layer</span><span>Connect AI to real project data</span></li>
            <li><span className="mono">observability + AI</span><span>Monitoring and anomaly detection</span></li>
          </ul>
          <p className="muted">Specific tool picks are published separately and updated as the landscape evolves.</p>
        </Collapsible>

        <Collapsible title="Appendix · role shifts to expect">
          <ul className="roles-list">
            <li><strong>Developer</strong> → from writing features line-by-line to orchestrating systems with AI.</li>
            <li><strong>PM</strong> → from writing requirements from scratch to curating context and pressure-testing ideas.</li>
            <li><strong>QA</strong> → from executing tests to designing strategy and directing AI execution.</li>
            <li><strong>Designer</strong> → from mockups as deliverables to interactive prototypes that translate intent early.</li>
            <li><strong>DevOps</strong> → from manual runbooks to AI-augmented release and observability.</li>
            <li><strong>Team lead / EM</strong> → from coordinating humans to orchestrating humans and AI together.</li>
          </ul>
          <p className="muted">None of these shifts make the role smaller. Every one makes the role more leveraged.</p>
        </Collapsible>
      </div>
    </section>
  );
}

// ---------- Closer ----------
function CloserSection() {
  const { audience } = useAudience();
  const isClient = audience === "client";

  return (
    <section className="section section-dark closer">
      <Reveal>
        <h2 className="closer-title">
          {isClient ? (
            <>Faster cycles, less repetition, <em>a team that keeps getting sharper.</em></>
          ) : (
            <>We don't hand teams an answer. <em>We hand them a method.</em></>
          )}
        </h2>
      </Reveal>
      <Reveal delay={120}>
        <p className="closer-sub">
          {isClient ? (
            <>That's what AI adoption looks like when it's done as a workflow improvement,
            not a tool rollout. We'd like to walk you through how it would run on a project
            we'd deliver together.</>
          ) : (
            <>Any Proshore team, regardless of where they are today, can apply this method to their
            own delivery system and arrive at their own answer. The answers will differ; the
            thinking will be the same.</>
          )}
        </p>
      </Reveal>
      <Reveal delay={220}>
        <div className="closer-meta">
          {isClient ? (
            <>
              <span>Owned by the delivery team</span>
              <span className="dot-sep">·</span>
              <span>Visible to your stakeholders</span>
              <span className="dot-sep">·</span>
              <span>Reviewed quarterly</span>
            </>
          ) : (
            <>
              <span>End of framework</span>
              <span className="dot-sep">·</span>
              <span>Owned by the team. Visible to leadership. Re-run quarterly.</span>
            </>
          )}
        </div>
      </Reveal>
    </section>
  );
}

Object.assign(window, {
  HeroSection,
  WhyMethodSection,
  ConvictionsSection,
  ExploreSection,
  MethodSection,
  DiagnosticSection,
  ExampleSection,
  OpsSection,
  CloserSection,
  Reveal,
});
