// Architecture — 4-step flow with per-step animated mini-visualizations
const ARCH_STEPS = [
  {
    num: "01",
    title: "Causal Signal Sourcing",
    body: "We start at the oracle — the exact data source that resolves each market — and work backwards to the causal inputs. Raw station data over summaries. Physics over forecasts.",
    visual: "oracle",
  },
  {
    num: "02",
    title: "Autonomous Execution",
    body: "Strategies run continuously. Agents enter positions when thresholds are crossed, manage risk, and redeploy capital without human intervention.",
    visual: "agents",
  },
  {
    num: "03",
    title: "Self-Improving Loop",
    body: "Every resolved market feeds back into the system. Parameters update, edge is re-measured, and underperforming strategies are flagged for replacement.",
    visual: "loop",
  },
  {
    num: "04",
    title: "Multi-Market Coverage",
    body: "Regulated exchanges, decentralised order books, and institutional venues. Multiple asset classes including structured derivatives, event contracts, and commodities — wherever informational asymmetries create systematic mispricings.",
    visual: "venues",
  },
];

function OracleVisual() {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    let raf; const start = performance.now();
    const loop = now => { setT((now - start) / 1000); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);
  const nodes = 7;
  return (
    <svg viewBox="0 0 300 120" width="100%" height="100%">
      {Array.from({ length: nodes }).map((_, i) => {
        const x = 20 + i * 40;
        const y = 60 + Math.sin(t * 1.2 + i * 0.7) * 12;
        const isLast = i === nodes - 1;
        return (
          <g key={i}>
            {i < nodes - 1 && (
              <line x1={x} y1={y} x2={20 + (i+1) * 40} y2={60 + Math.sin(t * 1.2 + (i+1) * 0.7) * 12}
                stroke="var(--accent)" strokeWidth="0.5" opacity={0.3 + (i/nodes) * 0.5} />
            )}
            <circle cx={x} cy={y} r={isLast ? 5 : 2 + (i / nodes) * 2}
              fill={isLast ? "var(--accent)" : "rgba(237,237,239,0.4)"} />
            {isLast && (
              <circle cx={x} cy={y} r="10" fill="none" stroke="var(--accent)" strokeWidth="0.5">
                <animate attributeName="r" values="5;18;5" dur="2s" repeatCount="indefinite" />
                <animate attributeName="opacity" values="1;0;1" dur="2s" repeatCount="indefinite" />
              </circle>
            )}
          </g>
        );
      })}
      <text x="20" y="105" fill="var(--ink-faint)" fontFamily="var(--mono)" fontSize="7" letterSpacing="1.5">RAW · STATION · CAUSAL · ORACLE</text>
    </svg>
  );
}

function AgentsVisual() {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    let raf; const start = performance.now();
    const loop = now => { setT((now - start) / 1000); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);
  const agents = 15;
  return (
    <svg viewBox="0 0 300 120" width="100%" height="100%">
      {Array.from({ length: agents }).map((_, i) => {
        const row = Math.floor(i / 5);
        const col = i % 5;
        const x = 30 + col * 50;
        const y = 25 + row * 35;
        const active = Math.sin(t * 2 + i * 1.3) > 0.5;
        return (
          <g key={i}>
            <rect x={x - 8} y={y - 8} width="16" height="16" fill="none"
              stroke={active ? "var(--accent)" : "rgba(237,237,239,0.15)"} strokeWidth="0.5" />
            {active && <rect x={x - 4} y={y - 4} width="8" height="8" fill="var(--accent)" opacity="0.7" />}
          </g>
        );
      })}
    </svg>
  );
}

function LoopVisual() {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    let raf; const start = performance.now();
    const loop = now => { setT((now - start) / 1000); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);
  const cx = 150, cy = 60, r = 35;
  const angle = t * 0.8;
  return (
    <svg viewBox="0 0 300 120" width="100%" height="100%">
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="rgba(237,237,239,0.15)" strokeWidth="0.5" />
      <circle cx={cx} cy={cy} r={r}
        fill="none" stroke="var(--accent)" strokeWidth="0.8"
        strokeDasharray={`${r * 2 * Math.PI * 0.3} ${r * 2 * Math.PI}`}
        transform={`rotate(${angle * 180 / Math.PI} ${cx} ${cy})`} />
      {[0, 1, 2, 3].map(i => {
        const a = angle + (i * Math.PI / 2);
        const x = cx + Math.cos(a) * r;
        const y = cy + Math.sin(a) * r;
        return <circle key={i} cx={x} cy={y} r="2" fill="var(--accent)" />;
      })}
      <text x={cx} y={cy + 2} textAnchor="middle" fill="var(--ink-dim)" fontFamily="var(--mono)" fontSize="7" letterSpacing="1">RESOLVE</text>
      <text x={cx} y={cy + 12} textAnchor="middle" fill="var(--ink-faint)" fontFamily="var(--mono)" fontSize="6" letterSpacing="1">↻ UPDATE</text>
    </svg>
  );
}

function VenuesVisual() {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    let raf; const start = performance.now();
    const loop = now => { setT((now - start) / 1000); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);
  const venues = ["CEX", "DEX", "CLOB", "RFQ", "OTC"];
  return (
    <svg viewBox="0 0 300 120" width="100%" height="100%">
      {venues.map((v, i) => {
        const x = 25 + i * 55;
        const pulseAmt = 0.5 + Math.sin(t * 1.5 + i * 0.8) * 0.5;
        return (
          <g key={i}>
            <rect x={x - 20} y={30} width="40" height="40" fill="none"
              stroke="rgba(237,237,239,0.2)" strokeWidth="0.5" />
            <rect x={x - 20} y={70 - pulseAmt * 40} width="40" height={pulseAmt * 40}
              fill="var(--accent)" opacity="0.6" />
            <text x={x} y={90} textAnchor="middle" fill="var(--ink-dim)" fontFamily="var(--mono)" fontSize="7" letterSpacing="1.5">{v}</text>
          </g>
        );
      })}
    </svg>
  );
}

function ArchVisual({ kind }) {
  if (kind === "oracle") return <OracleVisual />;
  if (kind === "agents") return <AgentsVisual />;
  if (kind === "loop") return <LoopVisual />;
  if (kind === "venues") return <VenuesVisual />;
  return null;
}

function Architecture() {
  return (
    <section id="architecture" className="arch">
      <div className="section-head">
        <div>
          <div className="label" style={{ marginBottom: 24 }}>Architecture</div>
          <h2>A system that <span className="italic">improves</span> with every resolved market.</h2>
        </div>
        <div className="section-head-meta">
          FOUR STAGES · ONE FEEDBACK LOOP<br/>
          DESIGNED FOR CONTINUOUS OPERATION<br/>
          NO HUMAN IN THE EXECUTION PATH
        </div>
      </div>
      <div className="arch-track">
        {ARCH_STEPS.map((s, i) => (
          <div key={i} className="arch-step">
            <div className="arch-num">{s.num}</div>
            <div className="arch-body">
              <h3>{s.title}</h3>
              <p>{s.body}</p>
            </div>
            <div className="arch-visual"><ArchVisual kind={s.visual} /></div>
          </div>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { Architecture });
