/* Hero variations — 3 takes on agentic + mobile */

const { useState: useS_H, useEffect: useE_H, useRef: useR_H } = React;

// ─────────────────────────────────────────────────────────────────────
// Shared bits
function HeroFrame({ children, label, accent = "blue" }) {
  return (
    <div className={"hero-frame hero-accent-" + accent}>
      <div className="hero-frame-label">{label}</div>
      {children}
    </div>
  );
}

function useTyped(strings, opts = {}) {
  const { speed = 28, hold = 1400, deleteSpeed = 14 } = opts;
  const [text, setText] = useS_H("");
  const [i, setI] = useS_H(0);
  const [del, setDel] = useS_H(false);
  useE_H(() => {
    const target = strings[i % strings.length];
    let t;
    if (!del && text.length < target.length) {
      t = setTimeout(() => setText(target.slice(0, text.length + 1)), speed);
    } else if (!del && text.length === target.length) {
      t = setTimeout(() => setDel(true), hold);
    } else if (del && text.length > 0) {
      t = setTimeout(() => setText(target.slice(0, text.length - 1)), deleteSpeed);
    } else if (del && text.length === 0) {
      setDel(false); setI(i + 1);
    }
    return () => clearTimeout(t);
  }, [text, i, del]);
  return text;
}

// ─────────────────────────────────────────────────────────────────────
// VARIATION 1 — Terminal / agent trace
// Hero with a live agent terminal scrolling through a real task
function HeroV1_AgentTrace({ headline = "YOUR FRIENDLY\nNEIGHBORHOOD\nAGENTIC\nENGINEER" }) {
  const lines = useAgentTrace();
  const lineRef = useR_H(null);
  useE_H(() => {
    if (lineRef.current) lineRef.current.scrollTop = lineRef.current.scrollHeight;
  }, [lines.length]);

  return (
    <section className="hero hero-v1">
      <div className="rr-grid-bg hero-bg" />
      <div className="hero-vignette" />
      <div className="hero-v1-grid">
        <div className="hero-v1-copy">
          <h1 className="hero-h1">
            {headline.split("\n").map((line, i) => (
              <span key={i} className="hero-h1-line">
                {line}
              </span>
            ))}
          </h1>
          <p className="hero-sub">
            <span className="rr-grad-text">10+ years</span> shipping iOS, web,
            and now multi-agent systems for startups, enterprise, and the App Store.
          </p>
          <div className="hero-cta-row">
            <a href="connect.html" className="rr-btn rr-btn-primary">
              ./hire-me <span style={{opacity: 0.6}}>—</span>
            </a>
            <a href="portfolio.html" className="rr-btn rr-btn-ghost">
              cat portfolio.md
            </a>
          </div>
          <div className="hero-meta">
            <div><span className="rr-text-dim">specializing in</span> <span className="rr-grad-text">orchestrated AI</span> · <span className="rr-grad-text">iOS</span> · <span className="rr-grad-text">edge infra</span></div>
          </div>
        </div>

        <div className="hero-v1-terminal">
          <div className="term-chrome">
            <span className="term-dot" style={{ background: "#FF5F57" }} />
            <span className="term-dot" style={{ background: "#FEBC2E" }} />
            <span className="term-dot" style={{ background: "#28C840" }} />
            <span className="term-title">~/atom — claude code</span>
          </div>
          <div className="term-body" ref={lineRef}>
            {lines.map((l, i) => <TermLine key={i} {...l} />)}
            <div className="term-prompt">
              <span style={{ color: "var(--rr-cyan)" }}>ricardo@io</span>
              <span style={{ color: "var(--rr-text-dim)" }}>:</span>
              <span style={{ color: "var(--rr-blue-soft)" }}>~</span>
              <span style={{ color: "var(--rr-text-dim)" }}>$ </span>
              <span className="rr-caret" />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function TermLine({ kind, text, tag, indent = 0 }) {
  const pad = "  ".repeat(indent);
  if (kind === "prompt") {
    return (
      <div className="term-line">
        <span style={{ color: "var(--rr-cyan)" }}>ricardo@io</span>
        <span style={{ color: "var(--rr-text-dim)" }}>:</span>
        <span style={{ color: "var(--rr-blue-soft)" }}>~</span>
        <span style={{ color: "var(--rr-text-dim)" }}>$ </span>
        <span style={{ color: "var(--rr-text)" }}>{text}</span>
      </div>
    );
  }
  if (kind === "agent") {
    return (
      <div className="term-line">
        <span style={{ color: "var(--rr-cyan-bright)" }}>{pad}● </span>
        <span style={{ color: "var(--rr-text-2)" }}>{text}</span>
        {tag && <span className="term-tag">{tag}</span>}
      </div>
    );
  }
  if (kind === "tool") {
    return (
      <div className="term-line">
        <span style={{ color: "var(--rr-text-dim)" }}>{pad}└─ </span>
        <span style={{ color: "var(--rr-amber)" }}>{text}</span>
      </div>
    );
  }
  if (kind === "ok") {
    return (
      <div className="term-line">
        <span style={{ color: "var(--rr-ok)" }}>{pad}✓ </span>
        <span style={{ color: "var(--rr-text-2)" }}>{text}</span>
      </div>
    );
  }
  if (kind === "comment") {
    return (
      <div className="term-line" style={{ color: "var(--rr-code-comment)" }}>{pad}# {text}</div>
    );
  }
  if (kind === "blank") return <div className="term-line">&nbsp;</div>;
  return <div className="term-line" style={{ color: "var(--rr-text-2)" }}>{pad}{text}</div>;
}

function useAgentTrace() {
  const [lines, setLines] = useS_H([]);
  useE_H(() => {
    const script = [
      { kind: "prompt", text: "claude" },
      { kind: "comment", text: "claude code v1.0 · sonnet 4.5 · ~/atom" },
      { kind: "blank" },
      { kind: "agent", text: "port Atom from Objective-C to SwiftUI", tag: "you" },
      { kind: "agent", text: "I'll plan this out, then ship it in steps.", tag: "claude" },
      { kind: "tool", text: "Read(./Atom/)" },
      { kind: "ok", text: "Indexed 84 files · 12,402 LOC Objective-C" },
      { kind: "agent", text: "Drafting migration plan — 6 phases", tag: "claude" },
      { kind: "tool", text: "Edit(AppDelegate.m → AtomApp.swift)" },
      { kind: "tool", text: "Bash(swift build)" },
      { kind: "ok", text: "Build succeeded · 0 warnings" },
      { kind: "tool", text: "Bash(swift test)" },
      { kind: "ok", text: "144 tests passed (94.2% coverage)" },
      { kind: "agent", text: "Spotted 2 retain cycles — patching deinit", tag: "claude", indent: 1 },
      { kind: "tool", text: "Edit(LegacyVC.swift)" },
      { kind: "ok", text: "All checks green · ready for TestFlight" },
      { kind: "blank" },
      { kind: "prompt", text: "fastlane beta" },
      { kind: "tool", text: "Uploading to App Store Connect..." },
      { kind: "ok", text: "Build 1.4.2 (84) shipped in 6m 12s" },
    ];
    let i = 0;
    const tick = () => {
      if (i >= script.length) {
        setTimeout(() => { i = 0; setLines([]); tick(); }, 4000);
        return;
      }
      setLines((prev) => [...prev, script[i]]);
      i++;
      const nextDelay = script[i - 1]?.kind === "ok" ? 600 : 380;
      setTimeout(tick, nextDelay);
    };
    const start = setTimeout(tick, 600);
    return () => clearTimeout(start);
  }, []);
  return lines;
}

// ─────────────────────────────────────────────────────────────────────
// VARIATION 2 — Code editor / iOS native
// Hero with a Xcode-like editor showing real Swift code
function HeroV2_XcodeNative({ headline = "I SHIP CODE\nTHAT SHIPS\nTO THE\nAPP STORE." }) {
  const [activeFile, setActiveFile] = useS_H(0);
  const files = [
    { name: "AgentRunner.swift", icon: "🦅" },
    { name: "ToolKit.swift", icon: "🔧" },
    { name: "Inference.swift", icon: "✨" },
  ];

  return (
    <section className="hero hero-v2">
      <div className="rr-grid-bg hero-bg" />
      <div className="hero-vignette" />
      <div className="hero-v2-grid">
        <div className="hero-v2-copy">
          <div className="hero-kicker">
            <span className="hero-kicker-bracket">[</span>
            iOS · iPadOS · watchOS · tvOS
            <span className="hero-kicker-bracket">]</span>
          </div>
          <h1 className="hero-h1">
            {headline.split("\n").map((line, i) => (
              <span key={i} className="hero-h1-line">
                {line}
              </span>
            ))}
          </h1>
          <p className="hero-sub">
            10+ years. 20+ production apps. Native Swift, SwiftUI, and a
            shop-floor ERP that runs a $45M produce business on iPad.
          </p>
          <div className="hero-cta-row">
            <a href="connect.html" className="rr-btn rr-btn-primary">build with me →</a>
            <a href="portfolio.html" className="rr-btn rr-btn-ghost">see the apps</a>
          </div>
          <div className="hero-stats">
            <Stat n="10+" l="years shipping" />
            <Stat n="20+" l="production apps" />
            <Stat n="84M+" l="users reached" />
          </div>
        </div>

        <div className="hero-v2-editor">
          <div className="ed-tabs">
            {files.map((f, i) => (
              <button key={i} onClick={() => setActiveFile(i)}
                className={"ed-tab" + (i === activeFile ? " is-active" : "")}>
                <span className="ed-tab-icon">{f.icon}</span>
                {f.name}
              </button>
            ))}
            <div className="ed-spacer" />
            <div className="ed-build">
              <span className="rr-dot" style={{ background: "var(--rr-ok)" }} />
              Build Succeeded
            </div>
          </div>
          <div className="ed-body">
            {activeFile === 0 && <CodeAgentRunner />}
            {activeFile === 1 && <CodeToolKit />}
            {activeFile === 2 && <CodeInference />}
          </div>
          <div className="ed-status">
            <span>swift 6.0</span><span>·</span>
            <span>iOS 18.4</span><span>·</span>
            <span>main</span><span>·</span>
            <span style={{ color: "var(--rr-ok)" }}>● 0 errors, 0 warnings</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function Stat({ n, l }) {
  return (
    <div className="hero-stat">
      <div className="hero-stat-n">{n}</div>
      <div className="hero-stat-l">{l}</div>
    </div>
  );
}

function CodeLine({ n, children }) {
  return (
    <div className="ed-line">
      <span className="ed-lineno">{n}</span>
      <span className="ed-code">{children}</span>
    </div>
  );
}
const K = ({ children }) => <span style={{ color: "var(--rr-code-pink)" }}>{children}</span>;
const S = ({ children }) => <span style={{ color: "var(--rr-code-orange)" }}>{children}</span>;
const T = ({ children }) => <span style={{ color: "var(--rr-code-purple)" }}>{children}</span>;
const F = ({ children }) => <span style={{ color: "var(--rr-code-blue)" }}>{children}</span>;
const C = ({ children }) => <span style={{ color: "var(--rr-code-comment)", fontStyle: "italic" }}>{children}</span>;
const N = ({ children }) => <span style={{ color: "var(--rr-code-yellow)" }}>{children}</span>;
const G = ({ children }) => <span style={{ color: "var(--rr-code-green)" }}>{children}</span>;

function CodeAgentRunner() {
  return (
    <div className="ed-pane">
      <CodeLine n={1}><C>// AgentRunner.swift — orchestrates a tool-using agent</C></CodeLine>
      <CodeLine n={2}><K>import</K> <T>Foundation</T></CodeLine>
      <CodeLine n={3}><K>import</K> <T>Combine</T></CodeLine>
      <CodeLine n={4}>&nbsp;</CodeLine>
      <CodeLine n={5}><K>actor</K> <T>AgentRunner</T> {"{"}</CodeLine>
      <CodeLine n={6}>{"  "}<K>private let</K> tools: [<T>Tool</T>]</CodeLine>
      <CodeLine n={7}>{"  "}<K>private let</K> llm: <T>InferenceClient</T></CodeLine>
      <CodeLine n={8}>&nbsp;</CodeLine>
      <CodeLine n={9}>{"  "}<K>func</K> <F>run</F>(task: <T>String</T>) <K>async throws</K> -&gt; <T>Trace</T> {"{"}</CodeLine>
      <CodeLine n={10}>{"    "}<K>var</K> trace = <T>Trace</T>(task: task)</CodeLine>
      <CodeLine n={11}>{"    "}<K>while</K> !trace.isComplete {"{"}</CodeLine>
      <CodeLine n={12}>{"      "}<K>let</K> step = <K>try await</K> llm.<F>plan</F>(trace)</CodeLine>
      <CodeLine n={13}>{"      "}<K>let</K> result = <K>try await</K> <F>execute</F>(step)</CodeLine>
      <CodeLine n={14}>{"      "}trace.<F>append</F>(step, result)</CodeLine>
      <CodeLine n={15}>{"    "}{"}"}</CodeLine>
      <CodeLine n={16}>{"    "}<K>return</K> trace</CodeLine>
      <CodeLine n={17}>{"  "}{"}"}</CodeLine>
      <CodeLine n={18}>{"}"}</CodeLine>
    </div>
  );
}

function CodeToolKit() {
  return (
    <div className="ed-pane">
      <CodeLine n={1}><C>// ToolKit.swift — tool calling for the agent</C></CodeLine>
      <CodeLine n={2}><K>protocol</K> <T>Tool</T>: <T>Sendable</T> {"{"}</CodeLine>
      <CodeLine n={3}>{"  "}<K>var</K> name: <T>String</T> {"{"} <K>get</K> {"}"}</CodeLine>
      <CodeLine n={4}>{"  "}<K>func</K> <F>call</F>(_ args: <T>JSON</T>) <K>async throws</K> -&gt; <T>JSON</T></CodeLine>
      <CodeLine n={5}>{"}"}</CodeLine>
      <CodeLine n={6}>&nbsp;</CodeLine>
      <CodeLine n={7}><K>struct</K> <T>BluetoothScanner</T>: <T>Tool</T> {"{"}</CodeLine>
      <CodeLine n={8}>{"  "}<K>let</K> name = <S>"ble.scan"</S></CodeLine>
      <CodeLine n={9}>{"  "}<K>func</K> <F>call</F>(_ args: <T>JSON</T>) <K>async throws</K> -&gt; <T>JSON</T> {"{"}</CodeLine>
      <CodeLine n={10}>{"    "}<K>let</K> peers = <K>try await</K> <T>CBCentral</T>.<F>scan</F>(<F>UUID</F>: args[<S>"uuid"</S>])</CodeLine>
      <CodeLine n={11}>{"    "}<K>return</K> .<F>array</F>(peers.<F>map</F> {"{"} <S>$0.id</S> {"}"})</CodeLine>
      <CodeLine n={12}>{"  "}{"}"}</CodeLine>
      <CodeLine n={13}>{"}"}</CodeLine>
      <CodeLine n={14}>&nbsp;</CodeLine>
      <CodeLine n={15}><K>struct</K> <T>BeaconRegistrar</T>: <T>Tool</T> {"{"} <C>/* iBeacon · NFC */</C> {"}"}</CodeLine>
    </div>
  );
}

function CodeInference() {
  return (
    <div className="ed-pane">
      <CodeLine n={1}><C>// Inference.swift — Cloudflare Workers AI gateway</C></CodeLine>
      <CodeLine n={2}><K>final class</K> <T>InferenceClient</T> {"{"}</CodeLine>
      <CodeLine n={3}>{"  "}<K>let</K> endpoint = <T>URL</T>(string: <S>"https://gw.ruizrica.io/infer"</S>)!</CodeLine>
      <CodeLine n={4}>&nbsp;</CodeLine>
      <CodeLine n={5}>{"  "}<K>func</K> <F>plan</F>(_ trace: <T>Trace</T>) <K>async throws</K> -&gt; <T>Step</T> {"{"}</CodeLine>
      <CodeLine n={6}>{"    "}<K>var</K> req = <T>URLRequest</T>(url: endpoint)</CodeLine>
      <CodeLine n={7}>{"    "}req.httpMethod = <S>"POST"</S></CodeLine>
      <CodeLine n={8}>{"    "}req.<F>setValue</F>(<S>"application/json"</S>, forHTTPHeaderField: <S>"Content-Type"</S>)</CodeLine>
      <CodeLine n={9}>{"    "}req.httpBody = <K>try</K> <T>JSONEncoder</T>().<F>encode</F>(trace)</CodeLine>
      <CodeLine n={10}>&nbsp;</CodeLine>
      <CodeLine n={11}>{"    "}<K>let</K> (data, _) = <K>try await</K> <T>URLSession</T>.shared.<F>data</F>(<K>for</K>: req)</CodeLine>
      <CodeLine n={12}>{"    "}<K>return</K> <K>try</K> <T>JSONDecoder</T>().<F>decode</F>(<T>Step</T>.<K>self</K>, from: data)</CodeLine>
      <CodeLine n={13}>{"  "}{"}"}</CodeLine>
      <CodeLine n={14}>{"}"}</CodeLine>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// VARIATION 3 — Agent diagram / system map
// Hero with an animated multi-agent topology
function HeroV3_OrchestrationDiagram({ headline = "ORCHESTRATED\nSYSTEMS THAT\nACTUALLY\nSHIP." }) {
  return (
    <section className="hero hero-v3">
      <div className="rr-grid-bg hero-bg" />
      <div className="hero-vignette" />
      <div className="hero-v3-grid">
        <div className="hero-v3-copy">
          <div className="hero-kicker">
            <span style={{ color: "var(--rr-cyan)" }}>◆</span> agentic engineer · est. 2014
          </div>
          <h1 className="hero-h1">
            {headline.split("\n").map((line, i) => (
              <span key={i} className="hero-h1-line">
                {line}
              </span>
            ))}
          </h1>
          <p className="hero-sub">
            I design and ship <span className="rr-grad-text">orchestrated AI systems</span> end-to-end —
            planner / coder / tester topologies, hardened inference, and the
            mobile front-ends that put them in your pocket.
          </p>
          <div className="hero-cta-row">
            <a href="connect.html" className="rr-btn rr-btn-primary">start a project →</a>
            <a href="services.html" className="rr-btn rr-btn-ghost">view services</a>
          </div>
          <AvailabilityTicker />
        </div>

        <div className="hero-v3-diagram">
          <AgentTopology />
        </div>
      </div>
    </section>
  );
}

function AvailabilityTicker() {
  return (
    <div className="hero-ticker">
      <div className="hero-ticker-row">
        <span className="rr-dot rr-dot-amber" />
        <span className="rr-mono">not accepting side work currently</span>
      </div>
      <div className="hero-ticker-row">
        <span style={{ color: "var(--rr-cyan)" }}>$</span>
        <span className="rr-mono rr-text-dim">building Atom · open to advisory chats</span>
      </div>
    </div>
  );
}

function AgentTopology() {
  const [pulse, setPulse] = useS_H(0);
  useE_H(() => {
    const t = setInterval(() => setPulse((p) => (p + 1) % 4), 1200);
    return () => clearInterval(t);
  }, []);

  // Node positions
  const N = {
    user: { x: 50, y: 30, label: "user", kind: "io" },
    planner: { x: 50, y: 130, label: "planner", kind: "core" },
    coder: { x: 170, y: 220, label: "coder", kind: "agent" },
    tester: { x: 50, y: 220, label: "tester", kind: "agent" },
    reviewer: { x: -70, y: 220, label: "reviewer", kind: "agent" },
    tools: { x: 170, y: 320, label: "tools", kind: "io" },
    fs: { x: 50, y: 320, label: "filesystem", kind: "io" },
    git: { x: -70, y: 320, label: "git", kind: "io" },
    output: { x: 50, y: 410, label: "ship → app store", kind: "out" },
  };

  const edges = [
    ["user", "planner"],
    ["planner", "coder"],
    ["planner", "tester"],
    ["planner", "reviewer"],
    ["coder", "tools"],
    ["tester", "fs"],
    ["reviewer", "git"],
    ["tools", "output"],
    ["fs", "output"],
    ["git", "output"],
  ];

  return (
    <svg viewBox="-150 0 400 460" className="agent-topo">
      <defs>
        <linearGradient id="edgeGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#1E7FE0" stopOpacity="0.3"/>
          <stop offset="1" stopColor="#29C5E8" stopOpacity="0.7"/>
        </linearGradient>
        <radialGradient id="coreGlow">
          <stop offset="0" stopColor="#29C5E8" stopOpacity="0.5"/>
          <stop offset="1" stopColor="#29C5E8" stopOpacity="0"/>
        </radialGradient>
      </defs>

      {/* Edges */}
      {edges.map(([from, to], i) => {
        const A = N[from], B = N[to];
        return (
          <g key={i}>
            <line x1={A.x} y1={A.y} x2={B.x} y2={B.y}
              stroke="url(#edgeGrad)" strokeWidth="1.2" />
            <circle r="2.5" fill="#5DDDF7">
              <animateMotion dur={`${2 + (i % 3) * 0.7}s`} repeatCount="indefinite"
                path={`M${A.x} ${A.y} L${B.x} ${B.y}`} />
            </circle>
          </g>
        );
      })}

      {/* Nodes */}
      {Object.entries(N).map(([key, n]) => (
        <Node key={key} {...n} pulse={pulse} />
      ))}
    </svg>
  );
}

function Node({ x, y, label, kind, pulse }) {
  const colors = {
    io: { bg: "#181925", stroke: "#2A2B3A", text: "#B6B7C3" },
    core: { bg: "#1E7FE0", stroke: "#5DDDF7", text: "white" },
    agent: { bg: "#11121A", stroke: "#29C5E8", text: "#29C5E8" },
    out: { bg: "#29C5E8", stroke: "#5DDDF7", text: "#0B0B10" },
  };
  const c = colors[kind] || colors.io;
  const w = 84, h = 28;
  return (
    <g transform={`translate(${x - w / 2} ${y - h / 2})`}>
      {kind === "core" && (
        <circle cx={w/2} cy={h/2} r="50" fill="url(#coreGlow)" />
      )}
      <rect width={w} height={h} rx="4" fill={c.bg} stroke={c.stroke} strokeWidth="1.2" />
      <text x={w/2} y={h/2 + 4} textAnchor="middle" fontFamily="JetBrains Mono, monospace"
        fontSize="11" fill={c.text} fontWeight="600">{label}</text>
    </g>
  );
}

Object.assign(window, {
  HeroV1_AgentTrace, HeroV2_XcodeNative, HeroV3_OrchestrationDiagram
});
