// Phase 0 Labs, interactive widgets shared across pages
// SystemDiagram: the brand mark expanded into a live architecture visualization
// CodeBlock, EvalDashboard, Pillar cards, terminal panels.

const { useState, useEffect, useRef } = React;

// Code block with syntax-coloring (very simple, keyword/string/comment).
function CodeBlock({ title = '', lines = [], live = false, height }) {
  return (
    <div style={{
      background: T.panel, border: `1px solid ${T.border}`,
      fontFamily: FONT.mono, fontSize: 12.5, lineHeight: 1.7,
      height,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '10px 14px', borderBottom: `1px solid ${T.border}`,
        color: T.dim, fontSize: 10.5, letterSpacing: 1.2,
      }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#3D3D3A' }} />
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#3D3D3A' }} />
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#3D3D3A' }} />
        </div>
        <span style={{ textTransform: 'uppercase' }}>{title}</span>
        {live && <span style={{ color: T.teal, display: 'flex', gap: 6, alignItems: 'center' }}>
          <Dot color={T.teal} size={6} /> LIVE
        </span>}
      </div>
      <div style={{ padding: '16px 18px', overflow: 'auto' }}>
        {lines.map((line, i) => (
          <div key={i} style={{
            display: 'flex', gap: 14,
            color: line.kind === 'comment' ? T.dimmer : T.text,
          }}>
            <span style={{ color: T.dimmer, userSelect: 'none', minWidth: 24, textAlign: 'right' }}>
              {String(i + 1).padStart(2, '0')}
            </span>
            <span style={{ flex: 1, whiteSpace: 'pre' }}>{renderTokens(line)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function renderTokens(line) {
  if (line.kind === 'comment') {
    return <span style={{ color: T.dimmer, fontStyle: 'italic' }}>{line.text}</span>;
  }
  if (line.tokens) {
    return line.tokens.map((tk, i) => (
      <span key={i} style={{ color: tokenColor(tk.kind) }}>{tk.text}</span>
    ));
  }
  return line.text;
}

function tokenColor(kind) {
  switch (kind) {
    case 'keyword': return T.purple;
    case 'string': return T.teal;
    case 'number': return T.amber;
    case 'fn': return T.blue;
    case 'key': return T.purple;
    case 'punct': return T.dim;
    case 'type': return T.amber;
    default: return T.text;
  }
}

// SystemDiagram, interactive architecture visualization built on the brand mark.
// Hover/click a node to highlight its role; renders flowing data along edges.
function SystemDiagram({ size = 480, interactive = true }) {
  const [hovered, setHovered] = useState(null);
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick(t => (t + 1) % 6), 1100);
    return () => clearInterval(id);
  }, []);

  const nodes = [
    { id: 'teams', label: 'TEAMS', sub: 'embedded experts', x: 0, y: -120, color: T.purple },
    { id: 'planning', label: 'PLANNING', sub: 'blueprint + roadmap', x: 105, y: -60, color: T.purple },
    { id: 'scale', label: 'SCALE', sub: 'infra + performance', x: 105, y: 60, color: T.purple },
    { id: 'agentic', label: 'AGENTIC', sub: 'agents + orchestration', x: 0, y: 120, color: T.purple },
    { id: 'observe', label: 'OBSERVE', sub: 'tracing + cost', x: -105, y: 60, color: T.purple },
    { id: 'governance', label: 'GOVERNANCE', sub: 'policy + compliance', x: -105, y: -60, color: T.purple },
    { id: 'core', label: 'PHASE 0', sub: 'control plane', x: 0, y: 0, color: T.blue, isCore: true },
  ];

  const radius = 220;
  const center = radius;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: 24, alignItems: 'stretch' }}>
      <div style={{
        background: T.panel, border: `1px solid ${T.border}`,
        position: 'relative', overflow: 'hidden', minHeight: 460,
      }}>
        <div style={{
          position: 'absolute', top: 12, left: 16, right: 16,
          display: 'flex', justifyContent: 'space-between',
          fontFamily: FONT.mono, fontSize: 10.5, letterSpacing: 1.2,
          color: T.dim, textTransform: 'uppercase',
        }}>
          <span>FIG. 01, control plane</span>
          <span style={{ color: T.teal, display: 'flex', gap: 6, alignItems: 'center' }}>
            <Dot color={T.teal} size={6} /> 06 nodes · live
          </span>
        </div>
        <svg viewBox={`0 0 ${radius * 2} ${radius * 2}`} width="100%" height="100%" style={{ display: 'block' }}>
          {/* Hex frame */}
          <polygon
            points={`${center},${center - 150} ${center + 130},${center - 75} ${center + 130},${center + 75} ${center},${center + 150} ${center - 130},${center + 75} ${center - 130},${center - 75}`}
            fill="none" stroke={T.blue} strokeWidth="1.5" opacity="0.35"
          />
          {/* Governance ring */}
          <ellipse cx={center} cy={center} rx="78" ry="98" fill="none"
            stroke={T.teal} strokeWidth="1.2" strokeDasharray="5 1.4" opacity="0.6">
            <animateTransform attributeName="transform" type="rotate"
              from={`0 ${center} ${center}`} to={`360 ${center} ${center}`}
              dur="80s" repeatCount="indefinite" />
          </ellipse>
          {/* Spokes from core to outer */}
          {nodes.filter(n => !n.isCore).map((n, i) => {
            const isActive = tick === i;
            return (
              <g key={`spoke-${n.id}`}>
                <line x1={center} y1={center} x2={center + n.x} y2={center + n.y}
                  stroke={T.borderStrong} strokeWidth="1" opacity="0.5" />
                {isActive && (
                  <circle r="3" fill={T.teal}>
                    <animateMotion dur="1.1s" path={`M ${center} ${center} L ${center + n.x} ${center + n.y}`} />
                  </circle>
                )}
              </g>
            );
          })}
          {/* Outer-ring connections */}
          {nodes.filter(n => !n.isCore).map((n, i, arr) => {
            const next = arr[(i + 1) % arr.length];
            return (
              <line key={`edge-${n.id}`}
                x1={center + n.x} y1={center + n.y}
                x2={center + next.x} y2={center + next.y}
                stroke={T.borderStrong} strokeWidth="0.8" opacity="0.3" />
            );
          })}
          {/* Nodes */}
          {nodes.map(n => {
            const isHover = hovered === n.id;
            const cx = center + n.x;
            const cy = center + n.y;
            return (
              <g key={n.id}
                onMouseEnter={() => interactive && setHovered(n.id)}
                onMouseLeave={() => interactive && setHovered(null)}
                style={{ cursor: interactive ? 'pointer' : 'default' }}>
                {n.isCore ? (
                  <>
                    <circle cx={cx} cy={cy} r="22" fill={T.ink} stroke={T.blue} strokeWidth="1.5" />
                    <circle cx={cx} cy={cy} r="6" fill={T.blue} opacity="0.3" />
                    <circle cx={cx} cy={cy} r="3" fill={T.blue} />
                  </>
                ) : (
                  <>
                    <circle cx={cx} cy={cy} r={isHover ? 18 : 14}
                      fill={T.ink} stroke={n.color} strokeWidth={isHover ? 2 : 1.4}
                      style={{ transition: 'r 160ms' }} />
                    <circle cx={cx} cy={cy} r="3" fill={n.color} />
                  </>
                )}
                <text x={cx} y={cy + (n.y < 0 ? -28 : n.isCore ? 40 : 32)}
                  textAnchor="middle"
                  fontFamily={FONT.mono} fontSize="10" letterSpacing="1.2"
                  fill={isHover || n.isCore ? T.text : T.dim}
                  style={{ textTransform: 'uppercase' }}>
                  {n.label}
                </text>
                {(isHover || n.isCore) && (
                  <text x={cx} y={cy + (n.y < 0 ? -16 : n.isCore ? 54 : 44)}
                    textAnchor="middle"
                    fontFamily={FONT.mono} fontSize="9" letterSpacing="0.8"
                    fill={T.dim}>
                    {n.sub}
                  </text>
                )}
              </g>
            );
          })}
        </svg>
      </div>
      <div style={{
        background: T.panel, border: `1px solid ${T.border}`, borderRadius: 10,
        padding: 22, fontFamily: FONT.sans, fontSize: 14,
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        <div style={{
          fontSize: 13, fontWeight: 500, color: T.dim,
          paddingBottom: 12, borderBottom: `1px solid ${T.border}`,
        }}>Node registry</div>
        {nodes.map(n => {
          const active = hovered === n.id || (hovered === null && n.isCore);
          const display = n.label.charAt(0) + n.label.slice(1).toLowerCase();
          return (
            <div key={n.id}
              onMouseEnter={() => setHovered(n.id)}
              onMouseLeave={() => setHovered(null)}
              style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                padding: '8px 10px', cursor: 'pointer', borderRadius: 6,
                background: active ? `${n.color}10` : 'transparent',
                borderLeft: `2px solid ${active ? n.color : 'transparent'}`,
                transition: 'all 120ms',
              }}>
              <span style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                <Dot color={n.color} size={6} glow={active} />
                <span style={{ color: active ? T.text : T.dim, fontWeight: 500 }}>{display}</span>
              </span>
              <span style={{ color: T.dimmer, fontSize: 13 }}>{n.sub}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Eval / observability dashboard mock
function EvalDashboard() {
  const metrics = [
    { label: 'EVAL PASS', value: '94.2%', delta: '+1.8', color: T.teal },
    { label: 'p50 LATENCY', value: '142ms', delta: '−12', color: T.blue },
    { label: 'TOKEN COST', value: '$0.0023', delta: '−6.4%', color: T.teal },
    { label: 'POLICY VIOLATIONS', value: '0', delta: '24h', color: T.dim },
  ];
  // Faux sparkline data
  const spark = (seed) => Array.from({ length: 24 }, (_, i) => {
    const x = Math.sin((i + seed) * 0.7) * 0.4 + Math.cos((i + seed) * 0.3) * 0.3;
    return 0.5 + x * 0.4;
  });
  return (
    <div style={{
      background: T.panel, border: `1px solid ${T.border}`,
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '12px 18px', borderBottom: `1px solid ${T.border}`,
        fontFamily: FONT.mono, fontSize: 11, letterSpacing: 1.2,
        color: T.dim, textTransform: 'uppercase',
      }}>
        <span>FIG. 02, eval + observability · last 24h</span>
        <span style={{ color: T.teal, display: 'flex', gap: 6, alignItems: 'center' }}>
          <Dot color={T.teal} size={6} /> streaming
        </span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)' }}>
        {metrics.map((m, i) => (
          <div key={m.label} style={{
            padding: 20, borderRight: i < 3 ? `1px solid ${T.border}` : 'none',
            display: 'flex', flexDirection: 'column', gap: 8,
          }}>
            <div style={{
              fontFamily: FONT.mono, fontSize: 10.5, letterSpacing: 1.2,
              color: T.dim, textTransform: 'uppercase',
            }}>{m.label}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
              <span style={{
                fontFamily: FONT.sans, fontSize: 28, fontWeight: 500,
                color: T.text, letterSpacing: -0.5,
              }}>{m.value}</span>
              <span style={{
                fontFamily: FONT.mono, fontSize: 11, color: m.color,
              }}>{m.delta}</span>
            </div>
            <Sparkline values={spark(i * 3)} color={m.color} />
          </div>
        ))}
      </div>
      <div style={{
        padding: 18, borderTop: `1px solid ${T.border}`,
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24,
      }}>
        <div>
          <div style={{
            fontFamily: FONT.mono, fontSize: 10.5, letterSpacing: 1.2,
            color: T.dim, textTransform: 'uppercase', marginBottom: 12,
          }}>RECENT RUNS</div>
          <div style={{ fontFamily: FONT.mono, fontSize: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {[
              ['orc-00142', 'pass', '1.4s', T.teal],
              ['orc-00141', 'pass', '0.9s', T.teal],
              ['orc-00140', 'flag', '2.1s', T.amber],
              ['orc-00139', 'pass', '1.2s', T.teal],
              ['orc-00138', 'pass', '0.8s', T.teal],
            ].map(([id, status, dur, c]) => (
              <div key={id} style={{ display: 'flex', justifyContent: 'space-between', color: T.dim }}>
                <span style={{ color: T.text }}>{id}</span>
                <span style={{ color: c }}>● {status}</span>
                <span>{dur}</span>
              </div>
            ))}
          </div>
        </div>
        <div>
          <div style={{
            fontFamily: FONT.mono, fontSize: 10.5, letterSpacing: 1.2,
            color: T.dim, textTransform: 'uppercase', marginBottom: 12,
          }}>POLICY BOUNDARY</div>
          <div style={{ fontFamily: FONT.mono, fontSize: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {[
              ['pii.redaction', 'enforced', T.teal],
              ['model.allowlist', 'enforced', T.teal],
              ['region.eu-only', 'enforced', T.teal],
              ['tool.exec_sandbox', 'enforced', T.teal],
              ['rate.per_tenant', 'enforced', T.teal],
            ].map(([k, v, c]) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: T.text }}>{k}</span>
                <span style={{ color: c }}>● {v}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function Sparkline({ values, color, w = 200, h = 28 }) {
  const max = Math.max(...values, 0.01);
  const points = values.map((v, i) => `${(i / (values.length - 1)) * w},${h - (v / max) * h}`).join(' ');
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ display: 'block' }}>
      <polyline points={points} fill="none" stroke={color} strokeWidth="1.4" opacity="0.85" />
    </svg>
  );
}

// Pillar card used in services / platform pages
function PillarCard({ num, color, title, sub, items }) {
  return (
    <div style={{
      background: T.panel, border: `1px solid ${T.border}`,
      padding: 28, position: 'relative',
      display: 'flex', flexDirection: 'column', gap: 16,
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 2, background: color,
      }} />
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontFamily: FONT.mono, fontSize: 11, letterSpacing: 1.5, textTransform: 'uppercase',
      }}>
        <span style={{ color, display: 'flex', alignItems: 'center', gap: 8 }}>
          <Dot color={color} size={8} /> {num} / {sub}
        </span>
      </div>
      <h3 style={{
        fontFamily: FONT.sans, fontSize: 28, fontWeight: 400,
        color: T.text, margin: 0, letterSpacing: -0.4, lineHeight: 1.15,
      }}>{title}</h3>
      <div style={{ height: 1, background: T.border, margin: '4px 0' }} />
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map(b => (
          <li key={b} style={{
            fontFamily: FONT.sans, fontSize: 14, color: T.text,
            paddingLeft: 18, position: 'relative', lineHeight: 1.5,
          }}>
            <span style={{
              position: 'absolute', left: 0, top: 7, width: 6, height: 6,
              border: `1px solid ${color}`,
            }} />
            {b}
          </li>
        ))}
      </ul>
    </div>
  );
}

window.CodeBlock = CodeBlock;
window.SystemDiagram = SystemDiagram;
window.EvalDashboard = EvalDashboard;
window.PillarCard = PillarCard;
