/* Animated agent network — autonomous agents paying APIs */
const AgentNetwork = () => {
  const ref = React.useRef(null);
  const [active, setActive] = React.useState(false);
  const [pulse, setPulse] = React.useState(0);

  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => setActive(e.isIntersecting));
    }, { threshold: 0.2 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);

  React.useEffect(() => {
    if (!active) return;
    const id = setInterval(() => setPulse((p) => (p + 1) % 100), 1100);
    return () => clearInterval(id);
  }, [active]);

  // Agents on the left, APIs on the right
  const agents = [
    { id: "a1", y: 90, name: "researcher-01", balance: "8.42" },
    { id: "a2", y: 180, name: "scraper-04", balance: "12.10" },
    { id: "a3", y: 270, name: "trader-12", balance: "1.20" },
    { id: "a4", y: 360, name: "summarizer-08", balance: "0.84" },
    { id: "a5", y: 450, name: "planner-22", balance: "5.61" },
  ];
  const apis = [
    { id: "p1", y: 80, name: "llm-router/chat", price: "$0.0040" },
    { id: "p2", y: 175, name: "satellite/imagery", price: "$0.012" },
    { id: "p3", y: 270, name: "geocode/reverse", price: "$0.0002" },
    { id: "p4", y: 365, name: "news-firehose", price: "$0.0009" },
    { id: "p5", y: 460, name: "whois/realtime", price: "$0.0015" },
  ];

  // Random connections; pulse a few each tick
  const conns = [
    [0, 0], [0, 2], [1, 1], [1, 3], [2, 0], [2, 4],
    [3, 0], [3, 2], [4, 1], [4, 3], [4, 4],
  ];

  return (
    <section ref={ref} style={{ borderTop: "1px solid var(--rule)", padding: "120px 0" }}>
      <div className="shell">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 80, alignItems: "start" }}>
          <div>
            <Marker section="03" label="WHY NOW" />
            <h2 className="h-section reveal" style={{ marginTop: 28, marginBottom: 24 }}>
              Agents need to pay.<br />Cards weren't built for them.
            </h2>
            <p className="lede reveal" style={{ marginBottom: 32 }}>
              Autonomous agents are being deployed by the millions. They browse, call APIs, and hire other agents as subcontractors. Every existing payment system requires a human to set up an account. x402 is the first that doesn't.
            </p>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, borderTop: "1px solid var(--rule)" }}>
              {[
                ["Authentication", "The payment is the auth. No keys to leak."],
                ["Granularity", "Per-request, not per-month. Pay only for what's used."],
                ["Latency", "Settled inline. No webhook waits, no retry loops."],
                ["Reach", "Any wallet can pay any endpoint. No relationships required."],
              ].map(([k, v]) => (
                <li key={k} style={{ borderBottom: "1px solid var(--rule)", display: "grid", gridTemplateColumns: "180px 1fr", gap: 24, padding: "14px 0" }}>
                  <span className="mono" style={{ color: "var(--fg-faint)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase" }}>{k}</span>
                  <span style={{ fontSize: 14.5, color: "var(--fg-dim)", lineHeight: 1.55 }}>{v}</span>
                </li>
              ))}
            </ul>
          </div>

          <div className="diag scan" style={{ position: "relative", padding: 32, aspectRatio: "1.1 / 1" }}>
            <Crosshairs />
            <div className="coord-label" style={{ top: 12, left: 16 }}>FIG.03 · AGENT NETWORK</div>
            <div className="coord-label" style={{ top: 12, right: 16 }}>{active ? "LIVE" : "IDLE"}</div>
            <div className="coord-label" style={{ bottom: 12, left: 16 }}>tick={pulse}</div>
            <div className="coord-label" style={{ bottom: 12, right: 16 }}>$0.0148/s aggregate</div>

            <svg viewBox="0 0 700 540" style={{ width: "100%", height: "100%" }} fill="none">
              <defs>
                <marker id="ah3" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="5" markerHeight="5" orient="auto">
                  <path d="M0,0 L10,5 L0,10 z" fill="var(--fg-dim)" stroke="none" />
                </marker>
              </defs>

              <text x="40" y="38" fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="10" letterSpacing="2">AGENTS</text>
              <text x="660" y="38" fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="10" textAnchor="end" letterSpacing="2">x402 ENDPOINTS</text>

              {/* connection lines */}
              {conns.map(([ai, pi], i) => {
                const a = agents[ai];
                const p = apis[pi];
                const isPulsing = active && (pulse + i) % 3 === 0;
                return (
                  <g key={i}>
                    <line x1="170" y1={a.y} x2="510" y2={p.y} stroke={isPulsing ? "var(--fg)" : "var(--rule-strong)"} strokeWidth={isPulsing ? 1.2 : 0.7} markerEnd={isPulsing ? "url(#ah3)" : undefined} />
                    {isPulsing && (
                      <circle r="3" fill="var(--fg)">
                        <animateMotion dur="1.05s" repeatCount="1" path={`M 170 ${a.y} L 510 ${p.y}`} />
                      </circle>
                    )}
                  </g>
                );
              })}

              {/* Agents */}
              {agents.map((a, i) => (
                <g key={a.id}>
                  <rect x="20" y={a.y - 22} width="150" height="44" stroke="var(--fg-dim)" />
                  <text x="30" y={a.y - 4} fill="var(--fg)" fontFamily="var(--mono)" fontSize="11">{a.name}</text>
                  <text x="30" y={a.y + 12} fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="9">${a.balance} USDC</text>
                </g>
              ))}

              {/* APIs */}
              {apis.map((p, i) => (
                <g key={p.id}>
                  <rect x="510" y={p.y - 22} width="170" height="44" stroke="var(--fg-dim)" />
                  <text x="520" y={p.y - 4} fill="var(--fg)" fontFamily="var(--mono)" fontSize="11">{p.name}</text>
                  <text x="520" y={p.y + 12} fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="9">{p.price} / call</text>
                </g>
              ))}
            </svg>
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { AgentNetwork });
