/* Hero — three variants: terminal, diagram, editorial */

const TerminalDemo = () => {
  const [step, setStep] = React.useState(0);
  const [restart, setRestart] = React.useState(0);

  // Steps:
  // 0: prompt
  // 1: typing curl
  // 2: 402 response
  // 3: payment
  // 4: 200 response
  // 5: done
  React.useEffect(() => {
    const timers = [];
    timers.push(setTimeout(() => setStep(1), 600));
    timers.push(setTimeout(() => setStep(2), 1900));
    timers.push(setTimeout(() => setStep(3), 3300));
    timers.push(setTimeout(() => setStep(4), 4600));
    timers.push(setTimeout(() => setStep(5), 6200));
    timers.push(setTimeout(() => setRestart((r) => r + 1), 11500));
    return () => timers.forEach(clearTimeout);
  }, [restart]);

  const cmd = "curl -X POST https://api.weather-pro.dev/forecast";
  const typedLen = step >= 2 ? cmd.length : step === 1 ? Math.min(cmd.length, Math.floor((Date.now() % 1300) / 1300 * cmd.length)) : 0;

  // Simpler: animate typing via state
  const [typed, setTyped] = React.useState("");
  React.useEffect(() => {
    if (step !== 1) {
      if (step >= 2) setTyped(cmd);
      else setTyped("");
      return;
    }
    let i = 0;
    const id = setInterval(() => {
      i++;
      setTyped(cmd.slice(0, i));
      if (i >= cmd.length) clearInterval(id);
    }, 28);
    return () => clearInterval(id);
  }, [step, restart]);

  return (
    <div className="term">
      <div className="term-head">
        <span>~/extodan/demo · zsh</span>
        <span style={{ display: "flex", gap: 16 }}>
          <Status tone="ok">live</Status>
        </span>
      </div>
      <div className="term-body">
        <div className="term-line"><span className="term-prompt">$ </span><span className="term-cmd">{typed}</span>{step === 1 && <span className="cursor" />}</div>

        {step >= 2 && (
          <>
            <div className="term-line term-meta" style={{ marginTop: 8 }}>{"< HTTP/1.1 "}<span className="term-status-402">402 Payment Required</span></div>
            <div className="term-line term-meta">{"< X-Payment-Required: "}<span className="term-val">$0.0010 USDC</span></div>
            <div className="term-line term-meta">{"< X-Payment-Network: "}<span className="term-val">base-mainnet</span></div>
            <div className="term-line term-meta">{"< X-Payment-Recipient: "}<span className="term-val">0x7a3e…b21f</span></div>
          </>
        )}

        {step >= 3 && (
          <div style={{ marginTop: 14, paddingLeft: 14, borderLeft: "1px solid var(--rule)" }}>
            <div className="term-line term-comment"># extodan-sdk: signing payment payload…</div>
            <div className="term-line term-comment"># settling on base-mainnet…</div>
            {step >= 4 && <div className="term-line"><span className="term-key">tx </span><span className="term-val">0x9f1c…ae84</span><span className="term-meta">  ·  </span><span className="term-status-200">confirmed</span><span className="term-meta">  ·  </span><span className="term-val">412ms</span></div>}
          </div>
        )}

        {step >= 4 && (
          <>
            <div className="term-line term-meta" style={{ marginTop: 14 }}>{"> X-Payment-Tx: "}<span className="term-val">0x9f1c…ae84</span></div>
            <div className="term-line term-meta">{"< HTTP/1.1 "}<span className="term-status-200">200 OK</span></div>
            <div className="term-line term-meta">{"< Content-Type: application/json"}</div>
            <div className="term-line term-meta">{"<"}</div>
            <div className="term-line"><span className="term-val">{`{ "lat": 37.78, "lon": -122.41, "forecast": [`}</span></div>
            <div className="term-line"><span className="term-val">{`    { "t": "+0h",  "tempC": 14, "cond": "clear" },`}</span></div>
            <div className="term-line"><span className="term-val">{`    { "t": "+24h", "tempC": 16, "cond": "fog"   },`}</span></div>
            <div className="term-line"><span className="term-val">{`    { "t": "+48h", "tempC": 13, "cond": "rain"  } ] }`}</span></div>
          </>
        )}

        {step >= 5 && (
          <div className="term-line term-comment" style={{ marginTop: 14 }}># total cycle: 1 request, 1 payment, 1 response · 612ms</div>
        )}

        {step < 5 && step > 0 && <div style={{ marginTop: 8 }}><span className="cursor" /></div>}
      </div>
    </div>
  );
};

/* Hero variant 2 — annotated diagram */
const HeroDiagram = () => {
  return (
    <div className="diag scan" style={{ aspectRatio: "1.15 / 1", position: "relative", padding: 32 }}>
      <Crosshairs />
      <div className="coord-label" style={{ top: 12, left: 16 }}>FIG.01</div>
      <div className="coord-label" style={{ top: 12, right: 16 }}>x402 / EXCHANGE</div>
      <div className="coord-label" style={{ bottom: 12, left: 16 }}>t=0ms → t=612ms</div>
      <div className="coord-label" style={{ bottom: 12, right: 16 }}>USDC · BASE</div>

      <svg viewBox="0 0 600 520" style={{ width: "100%", height: "100%" }} fill="none" stroke="currentColor">
        <defs>
          <marker id="ah" 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>

        {/* Client node */}
        <g>
          <rect x="40" y="60" width="140" height="80" stroke="var(--fg-dim)" strokeWidth="1" />
          <text x="50" y="82" fill="var(--fg)" fontFamily="var(--mono)" fontSize="13" stroke="none">CLIENT</text>
          <text x="50" y="102" fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="10" stroke="none">agent · browser · curl</text>
          <text x="50" y="124" fill="var(--fg-dim)" fontFamily="var(--mono)" fontSize="10" stroke="none">wallet · 0x7a3e…</text>
        </g>

        {/* Server node */}
        <g>
          <rect x="420" y="60" width="140" height="80" stroke="var(--fg-dim)" strokeWidth="1" />
          <text x="430" y="82" fill="var(--fg)" fontFamily="var(--mono)" fontSize="13" stroke="none">SERVER</text>
          <text x="430" y="102" fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="10" stroke="none">api endpoint</text>
          <text x="430" y="124" fill="var(--fg-dim)" fontFamily="var(--mono)" fontSize="10" stroke="none">price · $0.0010</text>
        </g>

        {/* Settlement node */}
        <g>
          <rect x="220" y="380" width="160" height="80" stroke="var(--fg-dim)" strokeWidth="1" />
          <text x="230" y="402" fill="var(--fg)" fontFamily="var(--mono)" fontSize="13" stroke="none">SETTLEMENT</text>
          <text x="230" y="422" fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="10" stroke="none">base · usdc</text>
          <text x="230" y="444" fill="var(--fg-dim)" fontFamily="var(--mono)" fontSize="10" stroke="none">~412ms · 0.0001¢ gas</text>
        </g>

        {/* Arrows: req */}
        <path d="M 180 90 L 415 90" stroke="var(--fg-dim)" strokeWidth="1" markerEnd="url(#ah)" />
        <text x="240" y="80" fill="var(--fg)" fontFamily="var(--mono)" fontSize="10" stroke="none">① GET /resource</text>

        {/* Arrows: 402 */}
        <path d="M 415 115 L 185 115" stroke="var(--fg-dim)" strokeWidth="1" markerEnd="url(#ah)" strokeDasharray="3 3" />
        <text x="220" y="135" fill="var(--warn)" fontFamily="var(--mono)" fontSize="10" stroke="none">② 402 Payment Required</text>

        {/* Payment to settlement */}
        <path d="M 110 150 Q 110 280, 240 380" stroke="var(--fg-dim)" strokeWidth="1" markerEnd="url(#ah)" />
        <text x="60" y="270" fill="var(--fg)" fontFamily="var(--mono)" fontSize="10" stroke="none">③ signed payment</text>

        {/* Settlement to server */}
        <path d="M 380 400 Q 500 320, 490 150" stroke="var(--fg-dim)" strokeWidth="1" markerEnd="url(#ah)" />
        <text x="445" y="280" fill="var(--fg)" fontFamily="var(--mono)" fontSize="10" stroke="none">④ confirmed</text>

        {/* 200 response */}
        <path d="M 415 70 L 185 70" stroke="var(--fg)" strokeWidth="1.4" markerEnd="url(#ah)" />
        <text x="225" y="58" fill="var(--ok)" fontFamily="var(--mono)" fontSize="10" stroke="none">⑤ 200 OK + payload</text>

        {/* Tick marks */}
        <g stroke="var(--fg-faint)">
          <line x1="40" y1="500" x2="560" y2="500" />
          {[0, 100, 200, 300, 400, 500, 612].map((t, i) => (
            <g key={t}>
              <line x1={40 + (t / 612) * 520} y1="496" x2={40 + (t / 612) * 520} y2="504" />
              <text x={40 + (t / 612) * 520} y="514" fill="var(--fg-faint)" fontFamily="var(--mono)" fontSize="9" textAnchor="middle" stroke="none">{t}ms</text>
            </g>
          ))}
        </g>

        {/* Signal dot animation */}
        <circle r="4" fill="var(--fg)" stroke="none">
          <animateMotion dur="3.2s" repeatCount="indefinite" path="M 180 90 L 415 90 L 415 115 L 185 115 L 110 150 L 240 380 L 380 400 L 490 150 L 415 70 L 185 70" />
        </circle>
      </svg>
    </div>
  );
};

/* Hero variant 3 — editorial */
const HeroEditorial = () => (
  <div style={{ position: "relative", padding: "60px 40px", borderLeft: "1px solid var(--rule)", height: "100%", display: "flex", flexDirection: "column", justifyContent: "space-between", minHeight: 480 }}>
    <div>
      <div className="eyebrow" style={{ marginBottom: 28 }}>Specification 0402</div>
      <div style={{ fontFamily: "var(--sans)", fontSize: 24, lineHeight: 1.4, letterSpacing: "-0.012em", color: "var(--fg-dim)", maxWidth: 480 }}>
        <span style={{ color: "var(--fg)" }}>HTTP 402 Payment Required.</span>{" "}
        Reserved in 1996. Implemented in 2025. The web's missing payment primitive, finally available to anyone with a server and anyone with a wallet.
      </div>
    </div>
    <div style={{ display: "flex", gap: 60, marginTop: 60, flexWrap: "wrap" }}>
      <div>
        <div className="stat-num">$0.001</div>
        <div className="stat-label">Min. settled payment</div>
      </div>
      <div>
        <div className="stat-num">412<span style={{ color: "var(--fg-faint)", fontSize: "0.5em" }}>ms</span></div>
        <div className="stat-label">P50 settlement</div>
      </div>
      <div>
        <div className="stat-num">0%</div>
        <div className="stat-label">Account setup required</div>
      </div>
    </div>
  </div>
);

const Hero = ({ variant = "terminal" }) => {
  return (
    <section style={{ position: "relative", paddingTop: 80, paddingBottom: 100 }}>
      <div className="shell">
        <div style={{ display: "grid", gridTemplateColumns: "1.05fr 1fr", gap: 80, alignItems: "start" }}>
          <div>
            <Marker section="00" label="OVERVIEW" />
            <h1 className="h-display" style={{ marginTop: 36, marginBottom: 28 }}>
              The x402<br />infrastructure<br />layer.
            </h1>
            <p className="lede" style={{ marginBottom: 36 }}>
              x402 turns any HTTP endpoint into a paid endpoint. No accounts. No credit cards. Payment happens inside the request, in milliseconds. Extodan is the marketplace, wallet, publishing, and protection infrastructure that makes it usable at scale.
            </p>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
              <a href="#waitlist" className="btn btn--primary">Join the waitlist <span className="arrow">→</span></a>
              <a href="#protocol" className="btn">Read the spec</a>
            </div>
            <div style={{ marginTop: 48, display: "flex", gap: 24, alignItems: "center", color: "var(--fg-faint)", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", flexWrap: "wrap" }}>
              <Status tone="ok">Base mainnet · live</Status>
              <span>USDC settlement</span>
              <span>HTTP-native</span>
              <span>SDK · TS / Py / Go</span>
            </div>
          </div>

          <div style={{ position: "relative" }}>
            <div className="coord-label" style={{ position: "absolute", top: -22, left: 0 }}>FIG.01 · {variant === "terminal" ? "EXCHANGE" : variant === "diagram" ? "PROTOCOL" : "SPEC.0402"}</div>
            <div className="coord-label" style={{ position: "absolute", top: -22, right: 0 }}>{variant.toUpperCase()}</div>
            {variant === "terminal" && <TerminalDemo />}
            {variant === "diagram" && <HeroDiagram />}
            {variant === "editorial" && <HeroEditorial />}
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Hero, TerminalDemo, HeroDiagram, HeroEditorial });
