// sections.jsx — Loop diagram, Pillars, Steps detail, Embodiments, Comparison
// Exports to window for app.jsx to consume.

const { useState, useEffect, useRef, useMemo } = React;

// ─── shared loop data ────────────────────────────────────────────────
const LOOP_STAGES = [
{ key: 'collect', num: '01', label: 'Collect', short: 'Push robot logs from MCAP, ROS, frames.', shipping: true,
  body: 'Push robot logs to vfrog from your existing hardware — MCAP, ROS / ROS 2 bags, raw frames, or via our SDK. Ingest, index, and search across runs, embodiments, and sessions.',
  side: [['Format', 'MCAP, rosbag, raw'], ['SDK', 'Python, C++, JS'], ['Search', 'Cross-run, cross-embodiment']] },
{ key: 'telemetry', num: '02', label: 'Telemetry', short: 'Live signals from every deployed robot.', shipping: false,
  body: 'Stream telemetry from every deployed robot — state, sensors, policy confidence, intervention events — straight back into the loop. Real-world ground truth for Evaluate, drift signals for retraining.',
  side: [['Streams', 'State · sensors · confidence · interventions'], ['Ingest', 'Live to loop'], ['Status', 'Shipping H2 2026']] },
{ key: 'train', num: '03', label: 'Train', short: 'Fine-tune any model, with synthetic data.', shipping: true,
  body: 'Fine-tune the model you brought (or one we provide). Auto-labeling on the data you uploaded. Synthetic data generated to fill the gaps. One-click training, multi-architecture, GPU-elastic.',
  side: [['Models', 'Pi, OpenVLA, Diffusion Policy, custom'], ['Compute', 'GPU-elastic'], ['Synthetic', 'In-loop generation']] },
{ key: 'evaluate', num: '04', label: 'Evaluate', short: 'Benchmark, replay, cross-embodiment.', shipping: false,
  body: 'Benchmark your skill against your own test suite, replay failures, qualify it for production. Cross-embodiment evaluation so a skill trained on one rig holds up on another.',
  side: [['Bench', 'Custom test suites'], ['Replay', 'Failure-mode debugging'], ['Status', 'Shipping H2 2026']] },
{ key: 'deploy', num: '05', label: 'Deploy', short: 'Sub-50ms on Jetson, Orin, Coral, x86.', shipping: true,
  body: 'One command to ship to the robot. Sub-50ms inference on Jetson, Orin, Coral, and x86 industrial PCs. Telemetry feeds back into the loop; the model retrains when its hit rate slips.',
  side: [['Targets', 'Jetson, Orin, Coral, x86'], ['Latency', '< 50 ms'], ['Format', 'ONNX, TorchScript']] }];


// ─── LoopSection ─────────────────────────────────────────────────────
function LoopSection({ showRoadmap, treatment }) {
  const [active, setActive] = useState(0);
  const containerRef = useRef(null);
  const [nodePositions, setNodePositions] = useState([]);

  // measure node positions for the connector overlay
  useEffect(() => {
    if (treatment !== 'flow') return;
    const measure = () => {
      const container = containerRef.current;
      if (!container) return;
      const cRect = container.getBoundingClientRect();
      const nodes = container.querySelectorAll('.loop-node .disk');
      const positions = Array.from(nodes).map((n) => {
        const r = n.getBoundingClientRect();
        return {
          x: r.left + r.width / 2 - cRect.left,
          y: r.top + r.height / 2 - cRect.top,
          r: r.width / 2
        };
      });
      setNodePositions(positions);
    };
    measure();
    const ro = new ResizeObserver(measure);
    if (containerRef.current) ro.observe(containerRef.current);
    window.addEventListener('resize', measure);
    return () => {ro.disconnect();window.removeEventListener('resize', measure);};
  }, [treatment]);

  // auto-advance active stage
  useEffect(() => {
    const id = setInterval(() => setActive((a) => (a + 1) % LOOP_STAGES.length), 3200);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="sec" id="loop">
      <div className="wrap">
        <div className="sec-header">
          <div className="index">§ 01 / LOOP</div>
          <div className="head-body">
            <div className="eyebrow accent"><span className="dot"></span>THE FIVE-STAGE LOOP</div>
            <h2 className="section-h">Most platforms own one stage of the loop. <em>vfrog is building all five.</em></h2>
            <p className="lead">The robotics AI loop has five stages: Collect, Telemetry, Train, Evaluate, Deploy. Most physical AI infrastructure companies cover one or two — a training harness here, a teleop kit there, an evaluation tool somewhere else. vfrog runs the whole loop in one platform, talks to whatever hardware and model you've already chosen, and generates synthetic data to cover the gaps your real data never will.</p>
          </div>
        </div>

        <div className="loop-diagram" ref={containerRef}>
          {treatment === 'flow' &&
          <LoopFlow stages={LOOP_STAGES} active={active} setActive={setActive} showRoadmap={showRoadmap} positions={nodePositions} />
          }
          {treatment === 'circle' &&
          <LoopCircle stages={LOOP_STAGES} active={active} setActive={setActive} showRoadmap={showRoadmap} />
          }
          {treatment === 'schematic' &&
          <LoopSchematic stages={LOOP_STAGES} showRoadmap={showRoadmap} />
          }

          <div className="loop-caption">
            Model-agnostic <span className="pipe">│</span> Multi-embodiment <span className="pipe">│</span> Bring your own collection hardware, model, cloud
          </div>
        </div>

        <LoopDetailPanel stage={LOOP_STAGES[active]} />
      </div>
    </section>);

}

// ─── LoopFlow — horizontal pipeline with animated particles ─────────
function LoopFlow({ stages, active, setActive, showRoadmap, positions }) {
  // animated particles travel between nodes
  return (
    <div style={{ position: 'relative' }}>
      <div className="loop-flow">
        {stages.map((s, i) =>
        <div
          key={s.key}
          className={`loop-node ${s.shipping ? 'shipping' : 'roadmap'} ${active === i ? 'active' : ''}`}
          onClick={() => setActive(i)}
          onMouseEnter={() => setActive(i)}>
          
            <div className="num">{s.num}</div>
            <div className="disk"></div>
            <div className="label">{s.label}</div>
            <div className="desc-1l">{s.short}</div>
            {showRoadmap && !s.shipping && <div className="badge">Shipping H2 2026</div>}
          </div>
        )}
      </div>

      {/* connector + particle overlay */}
      {positions.length === stages.length &&
      <svg
        className="loop-connectors"
        width="100%"
        height="100%"
        viewBox={`0 0 ${positions[positions.length - 1].x + 100} 400`}
        preserveAspectRatio="none"
        style={{ position: 'absolute', top: 0, left: 0, pointerEvents: 'none' }}>
        
          <defs>
            <linearGradient id="connGrad" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0%" stopColor="#f5b733" stopOpacity="0.8" />
              <stop offset="100%" stopColor="#f5b733" stopOpacity="0.3" />
            </linearGradient>
            <filter id="glow">
              <feGaussianBlur stdDeviation="2" result="blur" />
              <feMerge>
                <feMergeNode in="blur" /><feMergeNode in="SourceGraphic" />
              </feMerge>
            </filter>
          </defs>

          {/* straight connectors between adjacent disks */}
          {positions.slice(0, -1).map((p, i) => {
          const next = positions[i + 1];
          const x1 = p.x + p.r;
          const x2 = next.x - next.r;
          const y = p.y;
          return (
            <g key={i}>
                <line x1={x1} y1={y} x2={x2} y2={y}
              stroke="rgba(245,183,51,0.2)" strokeWidth="1" strokeDasharray="3 4" />
                {/* arrowhead */}
                <path d={`M ${x2 - 6} ${y - 4} L ${x2} ${y} L ${x2 - 6} ${y + 4}`}
              stroke="rgba(245,183,51,0.5)" strokeWidth="1" fill="none" />
                {/* moving particle */}
                <circle r="3" fill="#f5b733" filter="url(#glow)">
                  <animateMotion
                  dur={`${2.2 + i * 0.15}s`}
                  repeatCount="indefinite"
                  begin={`${i * 0.4}s`}
                  path={`M ${x1} ${y} L ${x2} ${y}`} />
                
                </circle>
              </g>);

        })}

          {/* return arrow from last to first (loop back) */}
          {positions.length >= 2 && (() => {
          const first = positions[0];
          const last = positions[positions.length - 1];
          const y = first.y + first.r + 50;
          const yPeak = first.y + first.r + 90;
          const x1 = last.x;
          const x2 = first.x;
          const d = `M ${x1} ${last.y + last.r} C ${x1} ${yPeak}, ${x2} ${yPeak}, ${x2} ${first.y + first.r}`;
          return (
            <g>
                <path d={d} stroke="rgba(245,183,51,0.25)" strokeWidth="1" strokeDasharray="3 4" fill="none" />
                <path d={`M ${x2 - 5} ${first.y + first.r + 8} L ${x2} ${first.y + first.r + 2} L ${x2 + 5} ${first.y + first.r + 8}`}
              stroke="rgba(245,183,51,0.6)" strokeWidth="1" fill="none" />
                <circle r="3" fill="#f5b733" filter="url(#glow)">
                  <animateMotion dur="3.4s" repeatCount="indefinite" path={d} />
                </circle>
              </g>);

        })()}
        </svg>
      }
    </div>);

}

// ─── LoopCircle — circular layout ───────────────────────────────────
function LoopCircle({ stages, active, setActive, showRoadmap }) {
  const cx = 280,cy = 280,r = 200;
  const n = stages.length;
  // start at top, go clockwise
  const positions = stages.map((_, i) => {
    const angle = -Math.PI / 2 + i * 2 * Math.PI / n;
    return { x: cx + r * Math.cos(angle), y: cy + r * Math.sin(angle), angle };
  });

  return (
    <div className="loop-circle">
      <svg width="560" height="560" style={{ position: 'absolute', inset: 0 }}>
        <defs>
          <filter id="circGlow">
            <feGaussianBlur stdDeviation="2" result="blur" />
            <feMerge><feMergeNode in="blur" /><feMergeNode in="SourceGraphic" /></feMerge>
          </filter>
        </defs>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="rgba(245,183,51,0.18)" strokeWidth="1" strokeDasharray="3 5" />
        {/* particle traveling around the circle */}
        <circle r="4" fill="#f5b733" filter="url(#circGlow)">
          <animateMotion
            dur="14s"
            repeatCount="indefinite"
            path={`M ${cx} ${cy - r} A ${r} ${r} 0 1 1 ${cx - 0.01} ${cy - r}`} />
          
        </circle>
      </svg>
      {positions.map((p, i) => {
        const s = stages[i];
        return (
          <div
            key={s.key}
            className="node"
            style={{ left: p.x, top: p.y }}
            onMouseEnter={() => setActive(i)}
            onClick={() => setActive(i)}>
            
            <div className={`loop-node ${s.shipping ? 'shipping' : 'roadmap'} ${active === i ? 'active' : ''}`} style={{ padding: 0 }}>
              <div className="num">{s.num}</div>
              <div className="disk"></div>
              <div className="label">{s.label}</div>
              {showRoadmap && !s.shipping && <div className="badge">H2 2026</div>}
            </div>
          </div>);

      })}
      <div className="center-label">
        <div className="big">
          The loop runs<br />
          <span className="accent">around your model.</span>
        </div>
      </div>
    </div>);

}

// ─── LoopSchematic — pure ASCII-style table ─────────────────────────
function LoopSchematic({ stages, showRoadmap }) {
  return (
    <pre className="loop-schematic">
      <span>{`  ┌───────────┐    ┌───────────┐    ┌───────────┐    ┌───────────┐    ┌───────────┐\n`}</span>
      <span>{`  │  COLLECT  │ ─→ │ TELEMETRY │ ─→ │   TRAIN   │ ─→ │ EVALUATE  │ ─→ │  DEPLOY   │ ─┐\n`}</span>
      <span>{`  └───────────┘    └───────────┘    └───────────┘    └───────────┘    └───────────┘  │\n`}</span>
      <span>{`        `}</span><span className="check">✓</span><span>{`                `}</span><span className="road">○</span><span>{`                `}</span><span className="check">✓</span><span>{`                `}</span><span className="road">○</span><span>{`                `}</span><span className="check">✓</span><span>{`        │\n`}</span>
      <span>{`        │                                                                            │\n`}</span>
      <span>{`        └────────────────────────────────────────────────────────────────────────────┘\n`}</span>
      <span>{`                        `}</span><span className="acc">↩ RETRAIN ON DRIFT — SYNTHETIC DATA WOVEN THROUGH</span><span>{`\n\n`}</span>
      <span>{`        `}</span><span className="check">✓</span><span>{` = `}</span><span className="mut">shipping today</span><span>{`     `}</span><span className="road">○</span><span>{` = `}</span><span className="mut">{showRoadmap ? 'shipping H2 2026' : 'roadmap'}</span><span>{`\n`}</span>
    </pre>);

}

// ─── LoopDetailPanel ────────────────────────────────────────────────
function LoopDetailPanel({ stage }) {
  return (
    <div className="loop-detail-panel">
      <div>
        <div className="stage-num">STAGE {stage.num}</div>
        <h3 className="stage-name">{stage.label}</h3>
        <div className={`stage-status ${stage.shipping ? '' : 'road'}`}>
          <span className="dot"></span>{stage.shipping ? 'SHIPPING TODAY' : 'SHIPPING H2 2026'}
        </div>
      </div>
      <p className="stage-body">{stage.body}</p>
      <div className="stage-side">
        {stage.side.map(([k, v]) =>
        <div className="kv" key={k}><span>{k}</span><b>{v}</b></div>
        )}
      </div>
    </div>);

}

// ─── Pillars (Section 4) ────────────────────────────────────────────
function Pillars() {
  const data = [
  { eyebrow: 'Model-agnostic', headline: "Train the model you've already picked.",
    body: "Pi, OpenVLA, Diffusion Policy, your own internal architecture — vfrog trains and deploys whatever you bring. Open weights or in-house, no mandated model, no lock-in. Your data is your moat; we're the loop around it." },
  { eyebrow: 'Synthetic data, built in', headline: 'Cover the edge cases your real data never will.',
    body: "Teleop data is expensive and slow. Failure data is rare on purpose. vfrog generates synthetic frames from your scenes so you can train through the long tail — without sending an operator back into the field. Same loop. More data." },
  { eyebrow: 'The full loop', headline: 'From a robot run to a redeployed skill, in one workflow.',
    body: "Collect from your fleet. Stream telemetry from deployed runs. Train on your data. Evaluate against your benchmarks. Deploy to your hardware. Retrain when it drifts. One platform, five stages." }];

  return (
    <section className="sec" id="pillars">
      <div className="wrap">
        <div className="sec-header">
          <div className="index">§ 02 / PILLARS</div>
          <div className="head-body">
            <div className="eyebrow">THREE THINGS, NO MORE</div>
            <h2 className="section-h">The wedge, in three claims you can verify.</h2>
          </div>
        </div>
        <div className="pillars">
          {data.map((p, i) =>
          <div className="pillar" key={i}>
              <div className="num">P/{String(i + 1).padStart(2, '0')}</div>
              <div className="eyebrow accent">{p.eyebrow}</div>
              <h3>{p.headline}</h3>
              <p>{p.body}</p>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ─── Steps detail (Section 5) ───────────────────────────────────────
function StepsDetail({ showRoadmap }) {
  const steps = [
  { num: '01', name: 'Collect', shipping: true,
    body: "Push robot logs to vfrog from your existing hardware — MCAP, ROS / ROS 2 bags, raw frames, or via our SDK. Ingest, index, and search across runs, embodiments, and sessions.",
    meta: [['INPUT', 'MCAP · rosbag · frames'], ['SDK', 'Python · C++ · JS']] },
  { num: '02', name: 'Telemetry', shipping: false,
    body: "Stream telemetry from every deployed robot — state, sensors, policy confidence, intervention events — straight back into the loop. Real-world ground truth for Evaluate, drift signals for retraining.",
    meta: [['STREAMS', 'State · sensors · confidence · interventions'], ['STATUS', 'H2 2026']] },
  { num: '03', name: 'Train', shipping: true,
    body: "Fine-tune the model you brought (or one we provide). Auto-labeling on the data you uploaded. Synthetic data generated to fill the gaps. One-click training, multi-architecture, GPU-elastic.",
    meta: [['MODELS', 'Pi · OpenVLA · DP · custom'], ['COMPUTE', 'GPU-elastic']] },
  { num: '04', name: 'Evaluate', shipping: false,
    body: "Benchmark your skill against your own test suite, replay failures, qualify it for production. Cross-embodiment evaluation so a skill trained on one rig holds up on another.",
    meta: [['BENCH', 'Custom test suites'], ['STATUS', 'H2 2026']] },
  { num: '05', name: 'Deploy', shipping: true,
    body: "One command to ship to the robot. Sub-50ms inference on Jetson, Orin, Coral, and x86 industrial PCs. Telemetry feeds back into the loop; the model retrains when its hit rate slips.",
    meta: [['TARGETS', 'Jetson · Orin · Coral · x86'], ['LATENCY', '< 50 ms']] }];

  return (
    <section className="sec" id="how">
      <div className="wrap">
        <div className="sec-header">
          <div className="index">§ 05 / HOW</div>
          <div className="head-body">
            <div className="eyebrow">THE LOOP, IN DETAIL</div>
            <h2 className="section-h">Five stages your team is already doing — <em>without building the platform.</em></h2>
          </div>
        </div>
        <div className="steps">
          {steps.map((s) =>
          <div className="step" key={s.num}>
              <div className="num">STEP / {s.num}</div>
              <h3 className="stage-name">
                {s.name}
                {showRoadmap && !s.shipping && <span className="badge">Shipping H2 2026</span>}
              </h3>
              <p className="body">{s.body}</p>
              <div className="meta">
                {s.meta.map(([k, v]) => <div key={k}><b>{k}</b>{v}</div>)}
              </div>
            </div>
          )}
          <div className="steps-closing">
            <span className="accent">→</span> That's the loop. That's the whole product.
          </div>
        </div>
      </div>
    </section>);

}

// ─── Embodiments (Section 6) ────────────────────────────────────────
function Embodiments() {
  const items = [
  { name: 'Manipulation', body: "Single-arm, bimanual, dexterous. Fine-tune the gripper-camera skill that the VLA can't quite nail." },
  { name: 'Mobile robotics / AMRs', body: "Lane keeping, obstacle classification, dock detection. Specialized heads for the long tail of warehouse and factory floor." },
  { name: 'Humanoids', body: "Object affordance, scene parsing, third-person view perception. The thin, fast models that ride alongside the policy." },
  { name: 'Industrial automation', body: "Defect detection, kitting QA, visual safety interlocks. Models that ship to the cell, not the cloud." },
  { name: 'Drones and aerial', body: "Landing zone classification, asset inspection, thermal anomaly. Small enough to live on the airframe." },
  { name: 'Autonomous vehicles', body: "Edge-case perception (construction zones, weather, animals). Targeted skills you'd never retrain a foundation model for." }];

  return (
    <section className="sec" id="embodiments">
      <div className="wrap">
        <div className="sec-header">
          <div className="index">§ 06 / EMBODIMENTS</div>
          <div className="head-body">
            <div className="eyebrow">BUILT FOR THE WAY ROBOTICS LABS WORK</div>
            <h2 className="section-h">One platform. <em>Every embodiment.</em></h2>
          </div>
        </div>
        <div className="embodiments">
          {items.map((e, i) =>
          <div className="embodiment" key={e.name}>
              <div className="e-name"><span className="marker">E/{String(i + 1).padStart(2, '0')}</span>{e.name}</div>
              <p className="e-body">{e.body}</p>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ─── Comparison (Section 7) ─────────────────────────────────────────
function Comparison() {
  const items = [
  { archetype: 'vs. closed foundation-model platforms',
    answer: <>They sell you their model. <span className="accent">We let you bring yours.</span> Your model choice is supposed to be your moat — own it.</> },
  { archetype: 'vs. single-stage tools',
    answer: <>Training-only. Eval-only. Hardware-only. Every gap in the loop is a script your team has to write. <span className="accent">We run the whole loop in one platform.</span></> },
  { archetype: 'vs. other full-loop platforms',
    answer: <>Same five stages. <span className="accent">We add synthetic data</span> — the one capability that breaks the teleop-data ceiling — and we work across embodiments out of the box.</> },
  { archetype: 'vs. building it yourself',
    answer: <>A robot-learning platform is six to twelve engineering-months for v1, plus an ongoing platform engineer. <span className="accent">Spend them shipping robot skills instead.</span></> }];

  return (
    <section className="sec" id="compare">
      <div className="wrap">
        <div className="sec-header">
          <div className="index">§ 07 / COMPARE</div>
          <div className="head-body">
            <div className="eyebrow">HOW VFROG IS DIFFERENT</div>
            <h2 className="section-h">Pick the loop. Pick the model. Pick the robot. <em>Don't pick two of them.</em></h2>
          </div>
        </div>
        <div className="compare">
          {items.map((c, i) =>
          <div className="compare-card" key={i}>
              <div className="vs">C/{String(i + 1).padStart(2, '0')}</div>
              <div className="archetype">{c.archetype}</div>
              <p className="answer">{c.answer}</p>
            </div>
          )}
        </div>
      </div>
    </section>);

}

Object.assign(window, {
  LoopSection, Pillars, StepsDetail, Embodiments, Comparison
});