/* OpenSyn homepage — animated run trace (a worked example moving L5→L1 and back) */
const { Button: OSBtn3 } = window.OpenSynDesignSystem_a3458e;
const OSGlyph3 = window.OSGlyph;
const { useState: useState3, useEffect: useEffect3, useRef: useRef3 } = React;
const { WRAP, SectionLabel, CrtFrame } = window;

/* --- graph geometry ---------------------------------------------------- */
const WF_NODES = [
  { id: "g",  type: "pentagon", x: 300, y: 46,  col: "#E95C2B", L: "L5", name: "Governance" },
  { id: "i",  type: "square",   x: 300, y: 130, col: "#F0C83D", L: "L4", name: "Intelligence" },
  { id: "o",  type: "triangle", x: 300, y: 214, col: "#4C9B63", L: "L3", name: "Operations" },
  { id: "c",  type: "circle",   x: 300, y: 298, col: "#4f6be0", L: "L2", name: "Coordination" },
  { id: "t1", type: "plus",     x: 168, y: 388, col: "#4f6be0", L: "L1", name: "Retrieve" },
  { id: "t2", type: "plus",     x: 300, y: 388, col: "#4f6be0", L: "L1", name: "Implement" },
  { id: "t3", type: "plus",     x: 432, y: 388, col: "#4f6be0", L: "L1", name: "Verify" },
];
const WF_NODE = Object.fromEntries(WF_NODES.map((n) => [n.id, n]));

const WF_EDGES = {
  "g-i":   ["M300 46 L300 130"],
  "i-o":   ["M300 130 L300 214"],
  "o-c":   ["M300 214 L300 298"],
  "c-fan": ["M300 298 L168 388", "M300 298 L300 388", "M300 298 L432 388"],
  "esc":   ["M432 388 C 508 322 498 252 314 220"],
  "appr":  ["M286 208 C 178 152 178 96 286 52"],
};

const KIND_COL = { info: "#4f6be0", ok: "#4C9B63", intervene: "#E95C2B", attention: "#F0C83D" };

/* --- the worked example: "Add OAuth login to the API" ------------------ */
const WF_STEPS = [
  { nodes: ["g"],            edge: "g-i",   kind: "info",      code: "ACK-OBJ",   head: "Objective accepted",     line: "L5 Governance accepts the objective — add OAuth login to the API — and sets the risk boundary: no auto-merge." },
  { nodes: ["i"],            edge: "i-o",   kind: "attention", code: "W-1102",    head: "Intelligence scan",      line: "L4 scans prior auth work and flags a token-refresh edge case as a likely failure mode." },
  { nodes: ["o"],            edge: "o-c",   kind: "info",      code: "RUN-7F2A",  head: "Run allocated",          line: "L3 Operations opens run RUN-7F2A — budget cap set, retries = 3." },
  { nodes: ["c"],            edge: "c-fan", kind: "info",      code: "A-00001",   head: "Subtasks routed",        line: "L2 Coordination splits the work into three bounded tasks: retrieve · implement · verify." },
  { nodes: ["t1","t2","t3"], edge: null,    kind: "info",      code: "RUN-7F2A",  head: "Tasks executing",        line: "L1 units run in parallel: pull the spec, write the handler, run the test suite." },
  { nodes: ["t3"],           edge: null,    kind: "intervene", code: "E-4471",    head: "Verifier failure ×1",    line: "Test suite fails — token expiry unhandled, exactly as L4 predicted. Local retry attempted first." },
  { nodes: ["t2","t3"],      edge: null,    kind: "ok",        code: "ACK-PASS",  head: "Retry passes",           line: "Handler patched, suite green. Artifact v2 written to the log — autonomy stayed local." },
  { nodes: ["o","t3"],       edge: "esc",   kind: "intervene", code: "E-2210",    head: "Escalate by exception",  line: "Budget hits 92% of cap. The threshold trips: an escalation packet rises to L3 for a call." },
  { nodes: ["g","o"],        edge: "appr",  kind: "ok",        code: "ACK-MERGE", head: "Human policy closure",   line: "L3 clears budget; the irreversible merge routes to L5. A human approves. Run closed nominal." },
];

/* --- draw one node glyph as native SVG -------------------------------- */
function WfNode({ n, state }) {
  const r = n.id.startsWith("t") ? 11 : 15;
  const dim = "rgba(255,255,255,0.28)";
  const active = state === "active";
  const done = state === "done";
  const stroke = active ? n.col : done ? n.col : dim;
  const sw = active ? 2.6 : 1.8;
  const fill = (active || done) && n.type !== "plus" ? n.col : "none";
  const fillOp = active ? 0.9 : done ? 0.18 : 0;
  const common = { stroke, strokeWidth: sw, strokeLinejoin: "round", strokeLinecap: "round", fill, fillOpacity: fillOp, filter: active ? "url(#wfGlow)" : "none" };
  let shape;
  if (n.type === "plus") {
    shape = <path d={`M${n.x} ${n.y - r} V${n.y + r} M${n.x - r} ${n.y} H${n.x + r}`} {...common} fill="none" strokeWidth={active ? 3 : 2.2} />;
  } else if (n.type === "circle") {
    shape = <circle cx={n.x} cy={n.y} r={r} {...common} />;
  } else if (n.type === "square") {
    shape = <rect x={n.x - r} y={n.y - r} width={r * 2} height={r * 2} rx="2.5" {...common} />;
  } else if (n.type === "triangle") {
    shape = <path d={`M${n.x - r} ${n.y - r * 0.72} H${n.x + r} L${n.x} ${n.y + r} Z`} {...common} />;
  } else { // pentagon
    const pts = [0, 1, 2, 3, 4].map((k) => {
      const a = (-90 + k * 72) * Math.PI / 180;
      return `${(n.x + r * Math.cos(a)).toFixed(1)},${(n.y + r * Math.sin(a)).toFixed(1)}`;
    }).join(" ");
    shape = <polygon points={pts} {...common} />;
  }
  return shape;
}

function WorkflowGraph({ step }) {
  const cur = WF_STEPS[step];
  const doneNodes = new Set();
  for (let s = 0; s < step; s++) WF_STEPS[s].nodes.forEach((id) => doneNodes.add(id));
  const activeNodes = new Set(cur.nodes);
  const activeEdges = cur.edge ? WF_EDGES[cur.edge] : [];
  const pulseCol = KIND_COL[cur.kind];

  return (
    <svg viewBox="0 0 520 430" style={{ width: "100%", height: "auto", display: "block" }} aria-label="Run trace graph">
      <defs>
        <filter id="wfGlow" x="-60%" y="-60%" width="220%" height="220%">
          <feGaussianBlur stdDeviation="3.4" result="b" />
          <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
      </defs>

      {/* left layer labels */}
      {["g", "i", "o", "c"].map((id) => {
        const n = WF_NODE[id];
        return (
          <g key={"lbl" + id}>
            <text x="20" y={n.y - 3} fontFamily="var(--font-mono)" fontSize="12" fontWeight="700" fill="#fff" letterSpacing="0.06em">{n.L}</text>
            <text x="20" y={n.y + 12} fontFamily="var(--font-mono)" fontSize="9.5" fill="#8b93bd" letterSpacing="0.08em">{n.name.toUpperCase()}</text>
          </g>
        );
      })}
      <text x="20" y={385} fontFamily="var(--font-mono)" fontSize="12" fontWeight="700" fill="#fff" letterSpacing="0.06em">L1</text>
      <text x="20" y={400} fontFamily="var(--font-mono)" fontSize="9.5" fill="#8b93bd" letterSpacing="0.08em">TASK UNITS</text>

      {/* all edges, faint */}
      {Object.values(WF_EDGES).flat().map((d, i) => (
        <path key={"e" + i} d={d} fill="none" stroke="rgba(255,255,255,0.12)" strokeWidth="1.5" />
      ))}
      {/* active edges, lit */}
      {activeEdges.map((d, i) => (
        <path key={"ae" + step + i} d={d} fill="none" stroke={pulseCol} strokeWidth="2.2" strokeDasharray="5 6" opacity="0.85">
          <animate attributeName="stroke-dashoffset" from="22" to="0" dur="0.9s" repeatCount="indefinite" />
        </path>
      ))}
      {/* travelling pulse on each active edge */}
      {activeEdges.map((d, i) => (
        <circle key={"p" + step + i} r="4.2" fill={pulseCol} filter="url(#wfGlow)">
          <animateMotion dur="1.25s" repeatCount="indefinite" path={d} keyPoints="0;1" keyTimes="0;1" calcMode="linear" />
        </circle>
      ))}

      {/* t-node sublabels */}
      {["t1", "t2", "t3"].map((id) => {
        const n = WF_NODE[id];
        const on = activeNodes.has(id) || doneNodes.has(id);
        return <text key={"tl" + id} x={n.x} y={414} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9.5" letterSpacing="0.04em" fill={on ? "rgba(246,244,239,0.82)" : "#6f77a8"}>{n.name}</text>;
      })}

      {/* nodes */}
      {WF_NODES.map((n) => (
        <WfNode key={n.id} n={n} state={activeNodes.has(n.id) ? "active" : doneNodes.has(n.id) ? "done" : "idle"} />
      ))}
    </svg>
  );
}

/* --- the section ------------------------------------------------------- */
const WF_KEY = "opensyn-trace-step";

function WorkflowSection() {
  const reduce = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const [step, setStep] = useState3(() => {
    const s = parseInt(localStorage.getItem(WF_KEY), 10);
    return Number.isInteger(s) && s >= 0 && s < WF_STEPS.length ? s : 0;
  });
  const [playing, setPlaying] = useState3(!reduce);
  const timer = useRef3(null);

  useEffect3(() => { localStorage.setItem(WF_KEY, String(step)); }, [step]);

  useEffect3(() => {
    if (!playing) return;
    const last = step === WF_STEPS.length - 1;
    timer.current = setTimeout(() => {
      setStep((s) => (s + 1) % WF_STEPS.length);
    }, last ? 3200 : 2000);
    return () => clearTimeout(timer.current);
  }, [step, playing]);

  const cur = WF_STEPS[step];

  return (
    <section id="trace" style={{ background: "var(--surface-page)", padding: "clamp(72px, 10vw, 128px) 0", borderBottom: "1px solid var(--border-soft)" }}>
      <div style={WRAP}>
        <div style={{ maxWidth: "680px", marginBottom: "40px" }}>
          <SectionLabel code="RUN-7F2A">Watch a run move through the stack</SectionLabel>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(30px, 4.2vw, 50px)", lineHeight: 1.04, letterSpacing: "-0.02em", color: "var(--text-body)", margin: "0 0 18px", textWrap: "balance" }}>
            One task, traced end to end.
          </h2>
          <p style={{ fontFamily: "var(--font-sans)", fontSize: "var(--fs-body)", lineHeight: 1.6, color: "var(--text-muted)", margin: 0, maxWidth: "60ch" }}>
            A worked example — <strong style={{ color: "var(--text-body)" }}>“add OAuth login to the API.”</strong> Watch
            it delegate down the layers, recover locally, and escalate by exception only when a budget threshold trips.
          </p>
        </div>

        <CrtFrame>
          <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: "var(--scanlines)", pointerEvents: "none", zIndex: 3, opacity: "var(--os-scanline-op, 0.7)" }} />
          <header style={{ display: "flex", alignItems: "baseline", gap: "10px", padding: "12px 18px", borderBottom: "1px solid var(--c-line-dark)", position: "relative", zIndex: 2 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase" }}>Run trace · RUN-7F2A</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: "10.5px", letterSpacing: "0.06em", color: "#8b93bd", marginLeft: "auto" }}>Add OAuth login to the API</span>
          </header>

          <div className="os-trace-body" style={{ position: "relative", zIndex: 2, display: "grid", gridTemplateColumns: "minmax(0, 1.05fr) minmax(0, 0.95fr)", gap: "8px" }}>
            {/* graph */}
            <div style={{ padding: "20px 14px", borderRight: "1px solid rgba(255,255,255,0.08)" }}>
              <WorkflowGraph step={step} />
            </div>

            {/* readout + log */}
            <div style={{ padding: "20px 18px 18px", display: "flex", flexDirection: "column" }}>
              <div style={{ display: "flex", alignItems: "center", gap: "9px", marginBottom: "8px" }}>
                <span style={{ width: "9px", height: "9px", borderRadius: "999px", background: KIND_COL[cur.kind], boxShadow: `0 0 10px ${KIND_COL[cur.kind]}`, flex: "none" }} />
                <span style={{ fontFamily: "var(--font-mono)", fontSize: "10.5px", fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", color: KIND_COL[cur.kind] }}>{cur.code}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: "10.5px", letterSpacing: "0.08em", color: "#8b93bd", marginLeft: "auto" }}>{String(step + 1).padStart(2, "0")} / {String(WF_STEPS.length).padStart(2, "0")}</span>
              </div>
              <h3 style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: "18px", lineHeight: 1.25, color: "#fff", margin: "0 0 6px" }}>{cur.head}</h3>
              <p style={{ fontFamily: "var(--font-sans)", fontSize: "13.5px", lineHeight: 1.55, color: "rgba(246,244,239,0.78)", margin: 0, minHeight: "62px" }}>{cur.line}</p>

              {/* event log */}
              <div style={{ marginTop: "14px", paddingTop: "12px", borderTop: "1px dashed rgba(255,255,255,0.14)", display: "flex", flexDirection: "column", gap: "5px", flex: 1 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: "9.5px", fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "#6f77a8", marginBottom: "3px" }}>Event log</span>
                {WF_STEPS.slice(0, step + 1).map((s, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: "8px", opacity: i === step ? 1 : 0.5, transition: "opacity 200ms var(--ease-crt, ease)" }}>
                    <span style={{ width: "3px", height: "13px", background: KIND_COL[s.kind], flex: "none", borderRadius: "1px" }} />
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: "10px", letterSpacing: "0.04em", color: KIND_COL[s.kind], width: "74px", flex: "none" }}>{s.code}</span>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", letterSpacing: "0.02em", color: "rgba(246,244,239,0.82)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.head}</span>
                  </div>
                ))}
              </div>

              {/* controls */}
              <div style={{ display: "flex", alignItems: "center", gap: "10px", marginTop: "16px" }}>
                <button onClick={() => setPlaying((p) => !p)} style={traceBtn}>{playing ? "❚❚ Pause" : "▶ Play"}</button>
                <button onClick={() => { setStep((s) => (s + 1) % WF_STEPS.length); setPlaying(false); }} style={traceBtn}>Step →</button>
                <button onClick={() => { setStep(0); }} style={traceBtn}>↺ Restart</button>
                <div style={{ display: "flex", gap: "4px", marginLeft: "auto" }}>
                  {WF_STEPS.map((_, i) => (
                    <button key={i} onClick={() => { setStep(i); setPlaying(false); }} aria-label={`Step ${i + 1}`} style={{
                      width: "10px", height: "10px", padding: 0, border: "none", cursor: "pointer",
                      background: i === step ? "var(--c-signal-orange)" : i < step ? "rgba(246,244,239,0.4)" : "rgba(246,244,239,0.16)",
                      borderRadius: "1px",
                    }} />
                  ))}
                </div>
              </div>
            </div>
          </div>
        </CrtFrame>
      </div>
    </section>
  );
}

const traceBtn = {
  fontFamily: "var(--font-mono)", fontSize: "11px", fontWeight: 600, letterSpacing: "0.06em",
  textTransform: "uppercase", color: "rgba(246,244,239,0.9)", background: "rgba(255,255,255,0.06)",
  border: "1px solid rgba(255,255,255,0.2)", borderRadius: "var(--radius-sm)", padding: "7px 11px", cursor: "pointer",
};

Object.assign(window, { WorkflowSection });
