/* Protocol explainer — animated as scrolled */
const Protocol = () => {
  const ref = React.useRef(null);
  const p = useScrollProgress(ref);

  // 4 stages: 0=request, 1=402, 2=payment, 3=200
  const stage = p < 0.18 ? 0 : p < 0.42 ? 1 : p < 0.68 ? 2 : 3;

  const steps = [
    {
      n: "01",
      label: "Request",
      title: "An HTTP request hits a paid endpoint.",
      body: "The server doesn't care who you are. No API key. No login. Just a request for the resource.",
      code: "GET /forecast HTTP/1.1\nHost: api.weather-pro.dev",
    },
    {
      n: "02",
      label: "402 Payment Required",
      title: "The server replies with the price.",
      body: "Instead of 200 OK, it returns 402 with payment terms — recipient address, amount, network, and a one-time challenge.",
      code: "HTTP/1.1 402 Payment Required\nX-Payment-Required: 0.0010 USDC\nX-Payment-Network: base-mainnet\nX-Payment-Recipient: 0x7a3e…b21f",
    },
    {
      n: "03",
      label: "Settlement",
      title: "The client signs and pays inline.",
      body: "An SDK or wallet signs a payment payload and submits it. USDC moves on Base. There's no checkout page, no redirect, no human.",
      code: "POST /forecast HTTP/1.1\nX-Payment-Tx: 0x9f1c…ae84\nX-Payment-Network: base-mainnet",
    },
    {
      n: "04",
      label: "200 OK",
      title: "The response returns. Cycle complete.",
      body: "Total elapsed: ~600ms. The request, the payment, the response — all on the same connection. No accounts were created. No invoices were generated.",
      code: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{ \"forecast\": [ … ] }",
    },
  ];

  return (
    <section ref={ref} id="protocol" style={{ position: "relative", paddingTop: 120, paddingBottom: 120, borderTop: "1px solid var(--rule)" }}>
      <div className="shell">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.1fr", gap: 80, alignItems: "start" }}>
          {/* LEFT: sticky header + stage list */}
          <div style={{ position: "sticky", top: 100 }}>
            <Marker section="01" label="PROTOCOL" />
            <h2 className="h-section reveal" style={{ marginTop: 28, marginBottom: 32 }}>
              How the<br />request gets paid.
            </h2>
            <p className="lede reveal" style={{ marginBottom: 48 }}>
              The whole exchange happens at the protocol level. No checkout flow. No redirect. The payment is a header.
            </p>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, borderTop: "1px solid var(--rule)" }}>
              {steps.map((s, i) => (
                <li key={s.n} style={{ borderBottom: "1px solid var(--rule)", padding: "18px 0", display: "grid", gridTemplateColumns: "60px 1fr auto", gap: 20, alignItems: "center", opacity: stage >= i ? 1 : 0.32, transition: "opacity 0.4s" }}>
                  <span className="mono" style={{ color: stage === i ? "var(--fg)" : "var(--fg-faint)", fontSize: 13 }}>{s.n}</span>
                  <span style={{ fontFamily: "var(--sans)", fontSize: 17, color: stage >= i ? "var(--fg)" : "var(--fg-dim)", letterSpacing: "-0.012em" }}>{s.label}</span>
                  <span className="mono" style={{ color: "var(--fg-faint)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase" }}>
                    {stage === i ? <Status tone={i === 1 ? "warn" : i === 3 ? "ok" : "ok"}>active</Status> : stage > i ? "✓ done" : "—"}
                  </span>
                </li>
              ))}
            </ul>
          </div>

          {/* RIGHT: animated diagram */}
          <div>
            <div className="diag scan" style={{ aspectRatio: "1 / 1", padding: 32, position: "relative" }}>
              <Crosshairs />
              <div className="coord-label" style={{ top: 12, left: 16 }}>FIG.02</div>
              <div className="coord-label" style={{ top: 12, right: 16 }}>STAGE {String(stage + 1).padStart(2, "0")}/04</div>
              <div className="coord-label" style={{ bottom: 12, left: 16 }}>{steps[stage].label.toUpperCase()}</div>
              <div className="coord-label" style={{ bottom: 12, right: 16 }}>p={p.toFixed(2)}</div>

              <svg viewBox="0 0 600 540" style={{ width: "100%", height: "100%" }} fill="none">
                <defs>
                  <marker id="ah2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto">
                    <path d="M0,0 L10,5 L0,10 z" fill="currentColor" stroke="none" />
                  </marker>
                </defs>

                {/* Boxes */}
                <g>
                  <rect x="40" y="80" width="160" height="100" stroke="var(--fg-dim)" />
                  <text x="50" y="104" fill="var(--fg)" fontFamily="var(--mono)" fontSize="13">CLIENT</text>
                  <text x="50" y="124" fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="10">ai agent · curl · browser</text>
                  <text x="50" y="158" fill="var(--fg-dim)" fontFamily="var(--mono)" fontSize="10">balance: 12.4 USDC</text>
                </g>
                <g>
                  <rect x="400" y="80" width="160" height="100" stroke="var(--fg-dim)" />
                  <text x="410" y="104" fill="var(--fg)" fontFamily="var(--mono)" fontSize="13">SERVER</text>
                  <text x="410" y="124" fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="10">api.weather-pro.dev</text>
                  <text x="410" y="158" fill="var(--fg-dim)" fontFamily="var(--mono)" fontSize="10">price: $0.0010 / call</text>
                </g>
                <g opacity={stage >= 2 ? 1 : 0.3}>
                  <rect x="220" y="380" width="160" height="100" stroke="var(--fg-dim)" />
                  <text x="230" y="404" fill="var(--fg)" fontFamily="var(--mono)" fontSize="13">SETTLEMENT</text>
                  <text x="230" y="424" fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="10">base · usdc</text>
                  <text x="230" y="458" fill="var(--fg-dim)" fontFamily="var(--mono)" fontSize="10">finality ~412ms</text>
                </g>

                {/* Arrow stage 0: GET */}
                <g opacity={stage === 0 ? 1 : 0.25}>
                  <path d="M 200 110 L 395 110" stroke={stage === 0 ? "var(--fg)" : "var(--fg-dim)"} strokeWidth={stage === 0 ? 1.6 : 1} markerEnd="url(#ah2)" />
                  <text x="240" y="100" fill={stage === 0 ? "var(--fg)" : "var(--fg-faint)"} fontFamily="var(--mono)" fontSize="11">GET /forecast</text>
                </g>
                {/* Stage 1: 402 */}
                <g opacity={stage === 1 ? 1 : stage > 1 ? 0.4 : 0.18}>
                  <path d="M 395 145 L 205 145" stroke={stage === 1 ? "var(--warn)" : "var(--fg-dim)"} strokeWidth={stage === 1 ? 1.6 : 1} strokeDasharray="4 3" markerEnd="url(#ah2)" />
                  <text x="220" y="170" fill={stage === 1 ? "var(--warn)" : "var(--fg-faint)"} fontFamily="var(--mono)" fontSize="11">402 PAYMENT REQUIRED</text>
                </g>
                {/* Stage 2: payment leg */}
                <g opacity={stage === 2 ? 1 : stage > 2 ? 0.4 : 0.18}>
                  <path d="M 120 180 Q 100 280, 240 380" stroke={stage === 2 ? "var(--fg)" : "var(--fg-dim)"} strokeWidth={stage === 2 ? 1.6 : 1} markerEnd="url(#ah2)" />
                  <text x="50" y="280" fill={stage === 2 ? "var(--fg)" : "var(--fg-faint)"} fontFamily="var(--mono)" fontSize="11">SIGN + PAY</text>
                  <path d="M 380 410 Q 520 320, 480 180" stroke={stage === 2 ? "var(--fg)" : "var(--fg-dim)"} strokeWidth={stage === 2 ? 1.6 : 1} markerEnd="url(#ah2)" />
                  <text x="450" y="290" fill={stage === 2 ? "var(--fg)" : "var(--fg-faint)"} fontFamily="var(--mono)" fontSize="11">CONFIRM</text>
                </g>
                {/* Stage 3: 200 */}
                <g opacity={stage === 3 ? 1 : 0.18}>
                  <path d="M 395 80 L 205 80" stroke={stage === 3 ? "var(--ok)" : "var(--fg-dim)"} strokeWidth={stage === 3 ? 1.8 : 1} markerEnd="url(#ah2)" />
                  <text x="230" y="68" fill={stage === 3 ? "var(--ok)" : "var(--fg-faint)"} fontFamily="var(--mono)" fontSize="11">200 OK + JSON</text>
                </g>

                {/* Signal dot for current stage */}
                {stage === 0 && <circle r="4" fill="var(--fg)"><animateMotion dur="1.4s" repeatCount="indefinite" path="M 200 110 L 395 110" /></circle>}
                {stage === 1 && <circle r="4" fill="var(--warn)"><animateMotion dur="1.4s" repeatCount="indefinite" path="M 395 145 L 205 145" /></circle>}
                {stage === 2 && <circle r="4" fill="var(--fg)"><animateMotion dur="2.4s" repeatCount="indefinite" path="M 120 180 Q 100 280, 240 380 M 380 410 Q 520 320, 480 180" /></circle>}
                {stage === 3 && <circle r="4" fill="var(--ok)"><animateMotion dur="1.4s" repeatCount="indefinite" path="M 395 80 L 205 80" /></circle>}
              </svg>
            </div>

            {/* Code excerpt panel */}
            <div style={{ marginTop: 18, border: "1px solid var(--rule)", padding: "16px 20px", background: "#060607" }}>
              <div className="mono" style={{ fontSize: 10.5, letterSpacing: "0.08em", color: "var(--fg-faint)", textTransform: "uppercase", marginBottom: 10 }}>
                wire format · {steps[stage].label}
              </div>
              <pre className="mono" style={{ margin: 0, fontSize: 12, lineHeight: 1.65, color: "var(--fg)", whiteSpace: "pre-wrap" }}>{steps[stage].code}</pre>
            </div>
          </div>
        </div>

        {/* Vertical scroll indicator */}
        <div style={{ marginTop: 80, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.08em", color: "var(--fg-faint)", textTransform: "uppercase", textAlign: "center" }}>
          ↓ scroll to advance
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Protocol });
