// Per-agent showcase — one mini visualization per sub-agent

function AgentsSection() {
  const [active, setActive] = useState('pace');
  const [paused, setPaused] = useState(false);
  const agents = [
    { id: 'pace',  code: '01', name: 'Pace',          color: '#a29bfe', summary: 'XGBoost lap-time + P10/P90 bootstrap CI',             Viz: PaceAgentViz },
    { id: 'tire',  code: '02', name: 'Tire',          color: '#ff2d3a', summary: 'TCN + MC Dropout · laps-to-cliff with P10/P50/P90',   Viz: TireAgentViz },
    { id: 'race',  code: '03', name: 'Race Situation', color: '#ffbd33', summary: 'LightGBM overtake prob. + 3-lap safety-car prior',   Viz: RaceAgentViz },
    { id: 'pit',   code: '04', name: 'Pit Strategy',  color: '#3385ff', summary: 'Pit-duration quantiles + undercut probability',       Viz: PitAgentViz },
    { id: 'radio', code: '05', name: 'Radio',         color: '#43ff64', summary: 'RoBERTa sentiment + SetFit intent + BERT-large NER',  Viz: RadioAgentViz },
    { id: 'rag',   code: '06', name: 'RAG',           color: '#6c5ce7', summary: 'Qdrant + BGE-M3 over FIA Sporting Regs 2023–25',      Viz: RagAgentViz },
  ];
  const a = agents.find(x => x.id === active);

  useEffect(() => {
    if (paused) return;
    const id = setInterval(() => {
      setActive(cur => {
        const i = agents.findIndex(x => x.id === cur);
        return agents[(i + 1) % agents.length].id;
      });
    }, 6000);
    return () => clearInterval(id);
  }, [paused]);

  return (
    <section className="section" id="agents">
      <div className="container-wide">
        <div className="section-head left agents-head" style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'end', marginBottom: 40, maxWidth: '100%', gap: 24 }}>
          <div>
            <span className="eyebrow"><span className="eyebrow-bar"/>Sub-agents</span>
            <h2 style={{ marginTop: 20 }}>Six specialists. One table.</h2>
          </div>
          <p style={{ maxWidth: 420, margin: 0 }}>
            Each sub-agent reasons in its own head, outputs structured Pydantic predictions, and hands them to the orchestrator.
          </p>
        </div>

        <div className="agents-layout"
             onMouseEnter={() => setPaused(true)}
             onMouseLeave={() => setPaused(false)}>
          <div className="agents-tabs">
            {agents.map(ag => (
              <button key={ag.id}
                      onClick={() => setActive(ag.id)}
                      onMouseEnter={() => setActive(ag.id)}
                      className={`agent-tab ${ag.id === active ? 'active' : ''}`}>
                <span className="agent-tab-dot" style={{ background: ag.color }}/>
                <div>
                  <div className="agent-tab-code mono">{ag.code}</div>
                  <div className="agent-tab-name">{ag.name}</div>
                  <div className="agent-tab-sum">{ag.summary}</div>
                </div>
              </button>
            ))}
          </div>

          <div className="agents-stage" key={active}>
            <a.Viz/>
          </div>
        </div>
      </div>
      <style>{`
        #agents .agents-layout {
          display: grid;
          grid-template-columns: 320px 1fr;
          gap: 28px;
          align-items: start;
        }
        #agents .agents-tabs {
          display: flex; flex-direction: column; gap: 6px;
        }
        #agents .agent-tab {
          all: unset;
          cursor: pointer;
          display: grid; grid-template-columns: 10px 1fr; gap: 14px;
          padding: 14px 16px;
          border-radius: 12px;
          border: 1px solid transparent;
          transition: all 0.2s cubic-bezier(0.2,0,0,1);
        }
        #agents .agent-tab:hover { background: var(--bg-2); }
        #agents .agent-tab.active {
          background: var(--bg-2);
          border-color: var(--divider-strong);
          transform: translateX(4px);
        }
        #agents .agent-tab-dot {
          width: 10px; height: 10px; border-radius: 50%;
          margin-top: 7px;
          transition: box-shadow 0.2s;
        }
        #agents .agent-tab.active .agent-tab-dot {
          box-shadow: 0 0 12px currentColor;
        }
        #agents .agent-tab-code { font-size: 10px; color: var(--fg-4); letter-spacing: 0.14em; margin-bottom: 2px; }
        #agents .agent-tab-name { font-family: var(--font-display); font-size: 17px; font-weight: 500; letter-spacing: -0.01em; color: var(--fg-1); margin-bottom: 3px; }
        #agents .agent-tab-sum { font-size: 12px; color: var(--fg-3); line-height: 1.4; }
        #agents .agents-stage {
          background: var(--bg-2);
          border: 1px solid var(--divider);
          border-radius: 18px;
          padding: 28px;
          animation: agentIn 0.45s cubic-bezier(0.2,0,0,1);
          min-height: 460px;
        }
        @keyframes agentIn {
          from { opacity: 0; transform: translateY(10px); }
          to { opacity: 1; transform: none; }
        }
        @media (max-width: 1000px) {
          #agents .agents-layout { grid-template-columns: 1fr; }
        }
        @media (max-width: 780px) {
          #agents .agents-head { grid-template-columns: 1fr !important; gap: 16px !important; }
        }
      `}</style>
    </section>
  );
}

// ---------- Pace agent — sparkline with confidence ----------
function PaceAgentViz() {
  const data = Array.from({ length: 20 }, (_, i) => ({
    x: i, actual: 87.4 + Math.sin(i * 0.7) * 0.3 + i * 0.03,
    pred: 87.6 + Math.sin((i + 2) * 0.6) * 0.25 + i * 0.035
  }));
  return (
    <AgentStage agentName="Pace Agent" color="#a29bfe" reasoning={[
      'Stint start · lap 38',
      'Compound age 10 laps · deg 0.08 s/lap',
      'Clean air since lap 44',
      '→ predicted pace 87.48s ± 0.04'
    ]} prediction={{ label: 'Next lap', value: '1:27.482', conf: 0.87 }}>
      <div className="pace-agent-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div style={{ background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10, padding: 16 }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 10 }}>Lap time — last 20</div>
          <svg viewBox="0 0 360 140" style={{ width: '100%' }}>
            <defs>
              <linearGradient id="paceFill" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#a29bfe" stopOpacity="0.28"/>
                <stop offset="100%" stopColor="#a29bfe" stopOpacity="0"/>
              </linearGradient>
            </defs>
            {(() => {
              const W = 360, H = 140, pad = 16;
              const min = 86.8, max = 89;
              const xs = x => pad + (x / 19) * (W - pad * 2);
              const ys = y => pad + (1 - (y - min) / (max - min)) * (H - pad * 2 - 12);
              const actualP = data.map((p, i) => `${i === 0 ? 'M' : 'L'}${xs(p.x)},${ys(p.actual)}`).join(' ');
              const predP   = data.map((p, i) => `${i === 0 ? 'M' : 'L'}${xs(p.x)},${ys(p.pred)}`).join(' ');
              const area = actualP + ` L${xs(19)},${H - pad} L${xs(0)},${H - pad} Z`;
              return (
                <>
                  <path d={area} fill="url(#paceFill)"/>
                  <path d={predP} fill="none" stroke="#a29bfe" strokeWidth="1.5" strokeDasharray="4 3" opacity="0.7"/>
                  <path d={actualP} fill="none" stroke="#a29bfe" strokeWidth="2" style={{ filter: 'drop-shadow(0 0 6px rgba(162,155,254,0.6))' }}/>
                  {data.map((p, i) => i === data.length - 1 && (
                    <circle key={i} cx={xs(p.x)} cy={ys(p.actual)} r="4" fill="#fff" stroke="#a29bfe" strokeWidth="2"/>
                  ))}
                </>
              );
            })()}
          </svg>
        </div>
        <div style={{ background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10, padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>Feature importance</div>
          {[
            ['Tire age',      0.28],
            ['Fuel load',     0.22],
            ['Track evo',     0.18],
            ['Compound',      0.15],
            ['Traffic',       0.10],
            ['Weather',       0.07],
          ].map(([k, v]) => (
            <div key={k} style={{ display: 'grid', gridTemplateColumns: '80px 1fr 40px', alignItems: 'center', gap: 8, fontSize: 11 }}>
              <span style={{ color: 'var(--fg-2)' }}>{k}</span>
              <span style={{ height: 6, background: 'var(--hairline)', borderRadius: 3, overflow: 'hidden' }}>
                <span style={{ display: 'block', width: `${v * 100}%`, height: '100%', background: '#a29bfe', animation: 'barGrow 0.8s cubic-bezier(0.2,0,0,1)' }}/>
              </span>
              <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', textAlign: 'right' }}>{v.toFixed(2)}</span>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @keyframes barGrow { from { width: 0; } }
        @media (max-width: 640px) {
          .pace-agent-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </AgentStage>
  );
}

// ---------- Tire agent — compound degradation curves ----------
function TireAgentViz() {
  return (
    <AgentStage agentName="Tire Agent" color="#ff2d3a" reasoning={[
      'Current compound: Medium · age 14 laps',
      'Actual deg rate 0.08s/lap · within P50',
      'Cliff detected at ~22 laps (P90)',
      '→ recommend pit window lap 34–37'
    ]} prediction={{ label: 'Cliff at', value: '22 laps', conf: 0.79 }}>
      <div style={{ background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10, padding: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14 }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>Degradation curve · per compound</div>
          <div style={{ display: 'flex', gap: 14, fontSize: 10, fontFamily: 'var(--font-mono)' }}>
            <span className="tire soft"><span className="tire-swatch"/>SOFT</span>
            <span className="tire medium"><span className="tire-swatch"/>MED</span>
            <span className="tire hard"><span className="tire-swatch"/>HARD</span>
          </div>
        </div>
        <svg viewBox="0 0 560 260" style={{ width: '100%' }}>
          {(() => {
            const W = 560, H = 260, pad = { l: 36, r: 20, t: 10, b: 28 };
            const xs = x => pad.l + (x / 30) * (W - pad.l - pad.r);
            const ys = y => pad.t + (1 - y / 2.5) * (H - pad.t - pad.b);
            const compounds = [
              { c: '#ff2d3a', rate: 0.12, peakAt: 14 },
              { c: '#ffcf2d', rate: 0.065, peakAt: 22 },
              { c: '#e6e6e6', rate: 0.038, peakAt: 30 },
            ];
            return (
              <>
                {/* grid */}
                {[0, 0.25, 0.5, 0.75, 1].map((p, i) => (
                  <line key={i} x1={pad.l} x2={W - pad.r}
                        y1={pad.t + p * (H - pad.t - pad.b)} y2={pad.t + p * (H - pad.t - pad.b)}
                        stroke="rgba(255,255,255,0.05)"/>
                ))}
                {/* y labels */}
                {[0, 0.5, 1, 1.5, 2].map(v => (
                  <text key={v} x={pad.l - 8} y={ys(v) + 3} textAnchor="end"
                        fontFamily="var(--font-mono)" fontSize="9" fill="rgba(255,255,255,0.4)">+{v.toFixed(1)}s</text>
                ))}
                {/* x labels */}
                {[0, 10, 20, 30].map(v => (
                  <text key={v} x={xs(v)} y={H - 10} textAnchor="middle"
                        fontFamily="var(--font-mono)" fontSize="9" fill="rgba(255,255,255,0.4)">{v}</text>
                ))}
                {/* compound curves with uncertainty bands */}
                {compounds.map((comp, idx) => {
                  const pts = Array.from({ length: 30 }, (_, i) => {
                    const accel = i > comp.peakAt ? (i - comp.peakAt) * 0.1 : 0;
                    return { x: i, y: comp.rate * i + accel * accel * 0.04 };
                  });
                  const band = pts.map(p => ({ x: p.x, lo: Math.max(0, p.y - 0.15 - p.y * 0.1), hi: p.y + 0.15 + p.y * 0.12 }));
                  const up = band.map(p => `${xs(p.x)},${ys(p.hi)}`);
                  const dn = band.slice().reverse().map(p => `${xs(p.x)},${ys(p.lo)}`);
                  const pathD = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${xs(p.x)},${ys(p.y)}`).join(' ');
                  return (
                    <g key={idx}>
                      <path d={`M${up.join('L')}L${dn.join('L')}Z`} fill={comp.c} opacity="0.15"/>
                      <path d={pathD} fill="none" stroke={comp.c} strokeWidth="2"
                            style={{ filter: `drop-shadow(0 0 6px ${comp.c}60)` }}/>
                    </g>
                  );
                })}
                {/* "now" vertical */}
                <line x1={xs(14)} x2={xs(14)} y1={pad.t} y2={H - pad.b}
                      stroke="rgba(255,255,255,0.4)" strokeDasharray="2 3"/>
                <text x={xs(14) + 5} y={pad.t + 10} fontFamily="var(--font-mono)" fontSize="9"
                      fill="rgba(255,255,255,0.6)">NOW L14</text>
              </>
            );
          })()}
        </svg>
      </div>
    </AgentStage>
  );
}

// ---------- Race situation — radial gauges ----------
function RaceAgentViz() {
  return (
    <AgentStage agentName="Race Situation Agent" color="#ffbd33" reasoning={[
      'No yellow flags in last 5 laps',
      'Overtake window opening T10–T11',
      'SAI gap 1.8s · within DRS threshold',
      '→ low SC risk, overtake favorable'
    ]} prediction={{ label: 'Overtake SAI', value: '64%', conf: 0.82 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Gauge label="P(Safety Car)" value={0.18} color="#ffbd33" sub="next 3 laps"/>
        <Gauge label="P(Overtake SAI)" value={0.64} color="#43ff64" sub="DRS zone T1"/>
      </div>
      <div style={{ marginTop: 16, padding: 14, background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 10 }}>Race control feed</div>
        {[
          ['L46', 'Yellow flag cleared', '#43ff64'],
          ['L47', 'DRS enabled',         '#a29bfe'],
          ['L48', 'Track limits · T9 warning #2', '#ffbd33'],
        ].map(([lap, msg, c]) => (
          <div key={lap} style={{ display: 'grid', gridTemplateColumns: '36px 1fr 10px', gap: 12, padding: '6px 0', fontSize: 12, borderBottom: '1px solid var(--hairline)' }}>
            <span className="mono" style={{ color: 'var(--fg-4)' }}>{lap}</span>
            <span style={{ color: 'var(--fg-1)' }}>{msg}</span>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: c, marginTop: 6 }}/>
          </div>
        ))}
      </div>
    </AgentStage>
  );
}

function Gauge({ label, value, color, sub }) {
  const R = 60, C = 2 * Math.PI * R;
  const dash = C * 0.75; // only 270 deg used
  const filled = dash * value;
  return (
    <div style={{ background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10, padding: 16, textAlign: 'center', position: 'relative' }}>
      <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8 }}>{label}</div>
      <svg viewBox="0 0 160 140" style={{ width: 160, height: 140 }}>
        <g transform="translate(80, 80)" style={{ transform: 'translate(80px, 80px) rotate(135deg)', transformOrigin: '80px 80px' }}>
          <circle r={R} fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="10" strokeDasharray={`${dash} ${C}`}/>
          <circle r={R} fill="none" stroke={color} strokeWidth="10" strokeLinecap="round"
                  strokeDasharray={`${filled} ${C}`}
                  style={{ filter: `drop-shadow(0 0 8px ${color}80)`, transition: 'stroke-dasharray 1s cubic-bezier(0.2,0,0,1)' }}/>
        </g>
        <text x="80" y="80" textAnchor="middle" fontFamily="var(--font-display)" fontSize="28" fontWeight="600" fill="#fff" letterSpacing="-0.02em">
          {Math.round(value * 100)}%
        </text>
        <text x="80" y="100" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="rgba(255,255,255,0.5)" letterSpacing="0.1em">
          {sub.toUpperCase()}
        </text>
      </svg>
    </div>
  );
}

// ---------- Pit strategy — scenario tree ----------
function PitAgentViz() {
  return (
    <AgentStage agentName="Pit Strategy Agent" color="#3385ff" reasoning={[
      '500 Monte Carlo scenarios · 5-lap horizon',
      'Undercut lap 35: gain +1.2s vs extend',
      'Risk: SC on lap 40 costs 8s if pitted',
      '→ optimal: pit lap 35, medium'
    ]} prediction={{ label: 'Optimal action', value: 'Pit L35 · MED', conf: 0.87 }}>
      <div style={{ background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10, padding: 20, position: 'relative' }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 16 }}>Scenario tree · P(win position)</div>
        <svg viewBox="0 0 560 260" style={{ width: '100%' }}>
          {(() => {
            const nodes = [
              { id: 'root', x: 40,  y: 130, label: 'Now · L34', sub: 'P3' },
              { id: 'A',    x: 200, y: 60,  label: 'Pit L35 · MED', p: 0.72, sub: '+1 pos · 72%' },
              { id: 'B',    x: 200, y: 130, label: 'Pit L35 · HARD', p: 0.58, sub: 'even · 58%' },
              { id: 'C',    x: 200, y: 200, label: 'Extend to L40',  p: 0.42, sub: '−1 pos · 42%' },
              { id: 'A1',   x: 380, y: 40,  label: 'No SC',   p: 0.71, sub: '+1 pos' },
              { id: 'A2',   x: 380, y: 90,  label: 'SC L38',  p: 0.48, sub: 'even' },
              { id: 'B1',   x: 380, y: 140, label: 'No SC',   p: 0.60, sub: 'even' },
              { id: 'C1',   x: 380, y: 200, label: 'SC L40+', p: 0.78, sub: 'saved' },
            ];
            const edges = [
              ['root','A',0.4],['root','B',0.3],['root','C',0.3],
              ['A','A1',0.82],['A','A2',0.18],['B','B1',0.6],['C','C1',0.25]
            ];
            const find = id => nodes.find(n => n.id === id);
            const colorFor = p => p >= 0.65 ? '#43ff64' : p >= 0.5 ? '#3385ff' : '#ff5733';
            return (
              <>
                {edges.map(([a, b, w], i) => {
                  const from = find(a), to = find(b);
                  return (
                    <path key={i} d={`M${from.x + 60},${from.y} C${(from.x + to.x)/2},${from.y} ${(from.x + to.x)/2},${to.y} ${to.x - 60},${to.y}`}
                          fill="none" stroke="rgba(255,255,255,0.2)" strokeWidth={1 + w * 3}/>
                  );
                })}
                {nodes.map((n, i) => {
                  const isRoot = n.id === 'root';
                  const c = isRoot ? '#3385ff' : colorFor(n.p);
                  return (
                    <g key={n.id}>
                      <rect x={n.x - 60} y={n.y - 18} width="120" height="36" rx="6"
                            fill="var(--bg-2)" stroke={c} strokeWidth={isRoot ? 1.5 : 1}
                            style={{ filter: isRoot ? `drop-shadow(0 0 10px ${c}80)` : '' }}/>
                      <text x={n.x} y={n.y - 2} textAnchor="middle"
                            fontFamily="var(--font-display)" fontSize="10" fill="#fff" fontWeight="500">{n.label}</text>
                      <text x={n.x} y={n.y + 11} textAnchor="middle"
                            fontFamily="var(--font-mono)" fontSize="8" fill={c}>{n.sub}</text>
                    </g>
                  );
                })}
              </>
            );
          })()}
        </svg>
      </div>
    </AgentStage>
  );
}

// ---------- Radio agent — waveform + classification ----------
function RadioAgentViz() {
  const bars = Array.from({ length: 80 }, (_, i) => {
    return 0.2 + Math.abs(Math.sin(i * 0.5)) * 0.6 + Math.random() * 0.15;
  });
  return (
    <AgentStage agentName="Radio Agent" color="#43ff64" reasoning={[
      'Whisper transcription · 0.8s audio',
      'SetFit intent → PROBLEM',
      'BERT sentiment → negative (0.91)',
      '→ emit tire_stress signal to orchestrator'
    ]} prediction={{ label: 'Intent', value: 'PROBLEM', conf: 0.91 }}>
      <div style={{ background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10, padding: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12, flexWrap: 'wrap', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'rgba(67,255,100,0.15)', border: '1px solid #43ff64', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#43ff64" strokeWidth="2">
                <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>
                <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>
                <line x1="12" y1="19" x2="12" y2="23"/>
              </svg>
            </div>
            <div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>L33 · LEC → BOX</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 500, fontStyle: 'italic', marginTop: 2 }}>"Tyres are gone, mate."</div>
            </div>
          </div>
          <span className="pill" style={{ background: 'rgba(67,255,100,0.1)', color: '#43ff64', borderColor: 'rgba(67,255,100,0.3)' }}>negative</span>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 2, height: 60, margin: '14px 0' }}>
          {bars.map((b, i) => (
            <div key={i} style={{
              flex: 1,
              height: `${b * 100}%`,
              background: 'linear-gradient(180deg, #43ff64 0%, rgba(67,255,100,0.3) 100%)',
              borderRadius: 1,
              opacity: i < 64 ? 1 : 0.3,
              animation: `wave ${1 + (i % 5) * 0.1}s ease-in-out infinite alternate`
            }}/>
          ))}
        </div>

        <div className="radio-agent-metrics" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginTop: 12 }}>
          {[
            ['Intent',    'PROBLEM',         0.91],
            ['Sentiment', 'negative',        0.87],
            ['Entity',    'tyres',           0.95],
            ['RCM',       'tire_stress',     0.88],
          ].map(([k, v, c]) => (
            <div key={k} style={{ padding: 10, background: 'var(--bg-2)', border: '1px solid var(--divider)', borderRadius: 6 }}>
              <div className="mono" style={{ fontSize: 9, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 3 }}>{k}</div>
              <div style={{ fontSize: 12, color: '#fff', fontWeight: 500, marginBottom: 4 }}>{v}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: '#43ff64' }}>{c.toFixed(2)}</div>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @keyframes wave { to { transform: scaleY(0.5); } }
        @media (max-width: 640px) {
          .radio-agent-metrics { grid-template-columns: repeat(2, 1fr) !important; }
        }
      `}</style>
    </AgentStage>
  );
}

// ---------- RAG agent — retrieval trail ----------
function RagAgentViz() {
  return (
    <AgentStage agentName="RAG Agent" color="#6c5ce7" reasoning={[
      'Query embedded with BGE-M3',
      'Qdrant cosine top-5, best 0.82',
      'Reranked → SR 55.2 + SR 55.3',
      '→ cited answer synthesized'
    ]} prediction={{ label: 'Top source', value: 'FIA SR 55.2', conf: 0.82 }}>
      <div style={{ background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10, padding: 20 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>Retrieval trail</div>
        <div style={{ fontSize: 14, color: 'var(--fg-1)', fontFamily: 'var(--font-display)', marginBottom: 14, padding: '10px 14px', background: 'var(--bg-2)', borderRadius: 6, border: '1px solid var(--divider)' }}>
          "Can a driver overtake under VSC?"
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {[
            { src: 'FIA SR 55.2',  score: 0.82, snippet: 'Under VSC, overtaking is prohibited except...' },
            { src: 'FIA SR 55.3',  score: 0.79, snippet: 'Drivers must respect a delta time proportional...' },
            { src: 'FIA SR 55.5',  score: 0.64, snippet: 'Lap times set during the VSC period may be...' },
            { src: 'FIA SR 41.6',  score: 0.41, snippet: 'A Safety Car is used when competitors cannot safely...' },
            { src: 'FIA SR 55.1',  score: 0.33, snippet: 'The Virtual Safety Car may be deployed by the FIA...' },
          ].map((r, i) => (
            <div key={i} style={{
              display: 'grid',
              gridTemplateColumns: '110px 1fr 80px',
              gap: 12, alignItems: 'center',
              padding: '10px 12px',
              background: i < 2 ? 'rgba(108,92,231,0.08)' : 'transparent',
              border: `1px solid ${i < 2 ? 'rgba(108,92,231,0.3)' : 'var(--divider)'}`,
              borderRadius: 6
            }}>
              <span className="mono" style={{ fontSize: 11, color: i < 2 ? '#a29bfe' : 'var(--fg-3)' }}>{r.src}</span>
              <span style={{ fontSize: 12, color: 'var(--fg-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.snippet}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ flex: 1, height: 4, background: 'var(--hairline)', borderRadius: 2, overflow: 'hidden' }}>
                  <span style={{ display: 'block', width: `${r.score * 100}%`, height: '100%', background: i < 2 ? '#a29bfe' : 'var(--fg-4)' }}/>
                </span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{r.score.toFixed(2)}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </AgentStage>
  );
}

// ---------- Shared frame used by each agent viz ----------
function AgentStage({ agentName, color, reasoning, prediction, children }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div className="mono" style={{ fontSize: 10, color, letterSpacing: '0.14em', textTransform: 'uppercase' }}>Sub-agent · live</div>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600, letterSpacing: '-0.025em', margin: '6px 0 0' }}>{agentName}</h3>
        </div>
        <div style={{ textAlign: 'right', padding: '10px 16px', background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10 }}>
          <div className="mono" style={{ fontSize: 9, color: 'var(--fg-4)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>{prediction.label}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, color: '#fff', marginTop: 2 }}>{prediction.value}</div>
          <div className="mono" style={{ fontSize: 10, color, marginTop: 2 }}>conf {prediction.conf.toFixed(2)}</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 240px', gap: 20 }} className="agent-stage-layout">
        <div>{children}</div>
        <div style={{ padding: 16, background: 'var(--bg-3)', border: '1px solid var(--divider)', borderRadius: 10 }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>Reasoning trace</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {reasoning.map((r, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '14px 1fr', gap: 10, alignItems: 'flex-start' }}>
                <span style={{
                  width: 14, height: 14, marginTop: 3,
                  borderRadius: '50%',
                  border: `1px solid ${i === 3 ? color : 'var(--divider-strong)'}`,
                  background: i === 3 ? color : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'var(--font-mono)', fontSize: 8, color: i === 3 ? '#0c0d14' : 'var(--fg-3)'
                }}>{i + 1}</span>
                <span style={{ fontSize: 12, color: i === 3 ? '#fff' : 'var(--fg-2)', lineHeight: 1.5 }}>{r}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 800px) { .agent-stage-layout { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

Object.assign(window, { AgentsSection });
