/* ============================================================
   pipeline.jsx, Part 1 (what happened + architecture) and the
   interactive pipeline runner (the centerpiece).
   ============================================================ */
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

/* ---- Interactive pipeline runner ---- */
function PipelineRunner() {
  const N = STAGES.length;
  const STAGE_DUR = 2000;          // ms of real time per stage
  const TOTAL = N * STAGE_DUR;

  const [run, setRun] = useStateP(false);
  const [idx, setIdx] = useStateP(-1);          // active stage index while running
  const [doneIds, setDoneIds] = useStateP([]);  // completed stage ids
  const [gates, setGates] = useStateP([]);       // passed gate indices
  const [secs, setSecs] = useStateP(0);          // simulated clock (0..480 => 0:00..8:00)
  const [finished, setFinished] = useStateP(false);
  const [selected, setSelected] = useStateP(0);  // stage shown in the detail panel
  const [status, setStatus] = useStateP("Idle, press Run to watch the pipeline turn one topic into a publish-ready article.");

  const startRef = useRefP(0);
  const rafRef = useRefP(null);

  const stop = () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); rafRef.current = null; };

  const reset = () => {
    stop(); setRun(false); setIdx(-1); setDoneIds([]); setGates([]); setSecs(0);
    setFinished(false); setSelected(0);
    setStatus("Idle, press Run to watch the pipeline turn one topic into a publish-ready article.");
  };

  const start = () => {
    stop();
    setRun(true); setFinished(false); setDoneIds([]); setGates([]); setIdx(0); setSecs(0);
    startRef.current = performance.now();
    const loop = (now) => {
      const el = now - startRef.current;
      const p = Math.min(el / TOTAL, 1);
      const s = Math.floor(el / STAGE_DUR);
      setSecs(Math.round(p * 480));
      if (s >= N) {
        setIdx(-1);
        setDoneIds(STAGES.map(x => x.id));
        setGates([0, 1, 2, 3, 4, 5]);
        setSelected(N - 1);
        setSecs(480);
        setStatus("Published ✓, the page is live. Every stage saved its own inspectable artifact.");
        setRun(false); setFinished(true); stop();
        return;
      }
      const cur = Math.min(s, N - 1);
      setIdx(cur);
      setDoneIds(STAGES.slice(0, s).map(x => x.id));
      const gp = []; for (let g = 0; g < s && g < N - 1; g++) gp.push(g);
      setGates(gp);
      const tin = el - cur * STAGE_DUR;
      const li = Math.min(Math.floor(tin / (STAGE_DUR / 3)), 2);
      setStatus(STAGES[cur].status[li]);
      setSelected(cur);
      rafRef.current = requestAnimationFrame(loop);
    };
    rafRef.current = requestAnimationFrame(loop);
  };

  useEffectP(() => () => stop(), []);

  const mmss = (t) => `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`;
  const pct = finished ? 100 : (secs / 480) * 100;
  const sel = STAGES[selected];

  const dots = ["#22d3ee", "var(--accent-1)", "var(--accent-2)"];

  return (
    <div className="runner reveal">
      <div className="runner-glow" />
      <div className="runner-top">
        <div className="title">
          <span className="dot3">{dots.map((c, i) => <i key={i} style={{ background: c }} />)}</span>
          <span className="lbl">Pipeline run</span>
          <span className="sub">topic → publish-ready · 7 stages · 6 gates</span>
        </div>
        <div className="runner-controls">
          <span className="runner-clock">
            <Icon name="clock" style={{ width: 14, height: 14, opacity: .6 }} />
            <b>{mmss(secs)}</b> / 8:00
          </span>
          {!run && !finished && (
            <button className="run-btn" onClick={start}><Icon name="play" /> Run pipeline</button>
          )}
          {run && (
            <button className="run-btn running" onClick={reset}><Icon name="pause" /> Stop</button>
          )}
          {finished && (
            <button className="run-btn running" onClick={start}><Icon name="rotate" /> Run again</button>
          )}
        </div>
      </div>

      <div className="runner-progress"><i style={{ width: pct + "%" }} /></div>

      <div className="flow">
        <div className="flow-track">
          {STAGES.map((st, i) => {
            const isActive = run && idx === i;
            const isDone = doneIds.includes(st.id);
            const isSel = selected === i;
            const cls = ["stage", isActive ? "active" : "", isDone ? "done" : "", isSel ? "selected" : ""].join(" ");
            return (
              <React.Fragment key={st.id}>
                <button className={cls} onClick={() => setSelected(i)}>
                  <span className="s-check"><Icon name="check" /></span>
                  <div className="s-top">
                    <span className="s-num">{String(st.id).padStart(2, "0")}</span>
                    <span className="s-ico"><Icon name={st.icon} /></span>
                  </div>
                  <h4>{st.name}</h4>
                  <span className="s-art"><Icon name={isDone ? "fileCheck" : "fileText"} /> {st.artifact}</span>
                </button>
                {i < N - 1 && (
                  <div className={"gate" + (gates.includes(i) ? " passed" : "")}>
                    <span className="line"><i style={{ width: gates.includes(i) ? "100%" : "0" }} /></span>
                    <span className="diamond"><Icon name="shieldCheck" /></span>
                    <span className="g-lbl">gate</span>
                  </div>
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      <div className="runner-status">
        <span className="tag">{run ? "▸ running" : finished ? "✓ done" : "○ idle"}</span>
        <span>{status}</span>
        {run && <span className="cursor" />}
      </div>

      <div className="stage-detail">
        <div className="col ahrefs">
          <div className="dh"><Icon name="terminal" style={{ width: 15, height: 15 }} /> Ryan's pipeline · {sel.name}</div>
          <p>{sel.principle}</p>
          <span className="artifact"><Icon name="save" /> saves → {sel.artifact}</span>
        </div>
        <div className="col builder">
          <div className="dh"><Icon name="sparkles" style={{ width: 15, height: 15 }} /> How PSEO Builder does it</div>
          <p>{sel.builder}</p>
        </div>
      </div>

      <div className="runner-foot">
        <Icon name="info" /> Reconstructed from the public Ahrefs Podcast episode &amp; Tim Soulo's LinkedIn post. Click any stage to inspect it.
      </div>
    </div>
  );
}

/* ---- Part 1 section ---- */
function PipelineSection() {
  return (
    <section className="section" id="pipeline">
      <div className="wrap">
        <div className="two-col reveal" style={{ marginBottom: "var(--space-16)" }}>
          <div>
            <SectionHead part="Part 01" label="What just happened"
              title='The AI content debate is over. <span class="gr">Execution</span> is the new fight.' />
          </div>
          <div className="prose stack-lg">
            <p>In May 2026, Ahrefs' CMO Tim Soulo admitted in public that his Director of Content had stopped hand-writing the company's blog.</p>
            <p>Ahrefs is a bootstrapped, <b>$100M+ ARR</b> software company whose growth engine for a decade has been an authoritative, hand-written blog, the case study every SaaS company has tried to copy since 2017. And they are now publishing AI-generated articles. <b>Fifteen live, about thirty more updated the same way,</b> eight minutes from topic to publish-ready draft.</p>
            <div className="tldr">
              <div className="t">TL;DR</div>
              <p>"AI content is slop" just lost its biggest holdout. The remaining debate isn't <i>whether</i> AI content can rank, Ahrefs proved it does. It's <b>who has the pipeline to execute it without producing slop.</b></p>
            </div>
          </div>
        </div>

        <div className="reveal" style={{ marginBottom: "var(--space-12)" }}>
          <div className="part-label" style={{ marginBottom: 18 }}><span>What Ryan Law actually built</span></div>
          <div className="arch-grid">
            {ARCHITECTURE.map((a) => (
              <div className="arch-card" key={a.k}>
                <div className="ico"><Icon name={a.icon} /></div>
                <div className="k">{a.k}</div>
                <h3>{a.title}</h3>
                <p>{a.desc}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="reveal" style={{ marginTop: "var(--space-16)" }}>
          <div className="part-label" style={{ marginBottom: 8 }}><span>See it run</span></div>
          <p className="sec-intro" style={{ marginTop: 8, marginBottom: 28, maxWidth: "64ch" }}>
            The architecture above produces real articles instead of slop because of <b style={{ color: "var(--ink-900)" }}>how</b> it runs, research first, an inspectable artifact saved at every step, and a quality gate between each stage. Press Run.
          </p>
          <PipelineRunner />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { PipelineRunner, PipelineSection });
