// Cockpit Dashboard — themed for dark + light
// Theme prop: 'dark' | 'light'

function buildTheme(mode, tokens = {}) {
  const hue = tokens.accentHue ?? 128;
  const ch  = tokens.accentChroma ?? 0.18;
  const lightnessDark  = tokens.accentLight ?? 0.86;
  const lightnessLight = Math.max(0.42, Math.min(0.62, lightnessDark - 0.3));
  const borderBoost = tokens.borderEmphasis === 'strong' ? 0.05 : 0;

  if (mode === 'dark') {
    return {
      bg0: 'oklch(0.16 0.005 250)',
      bg1: 'oklch(0.185 0.006 250)',
      bg2: 'oklch(0.21 0.007 250)',
      bg3: 'oklch(0.245 0.008 250)',
      border:       `oklch(${0.27 + borderBoost} 0.008 250)`,
      borderStrong: `oklch(${0.34 + borderBoost} 0.01 250)`,
      text0: 'oklch(0.97 0.005 250)',
      text1: 'oklch(0.78 0.008 250)',
      text2: 'oklch(0.58 0.008 250)',
      text3: 'oklch(0.44 0.008 250)',
      accent:    `oklch(${lightnessDark} ${ch} ${hue})`,
      accentInk: `oklch(0.2 ${ch * 0.4} ${hue})`,
      accentMuted: `oklch(0.32 ${ch * 0.4} ${hue})`,
      success: 'oklch(0.78 0.16 155)',
      warn: 'oklch(0.82 0.15 75)',
      error: 'oklch(0.7 0.2 22)',
      info: 'oklch(0.78 0.13 235)',
      chart1: `oklch(${lightnessDark} ${ch} ${hue})`,
      chart2: 'oklch(0.78 0.13 235)',
      chart3: 'oklch(0.82 0.15 75)',
      chart4: 'oklch(0.7 0.18 320)',
      gridLine: `oklch(${0.27 + borderBoost} 0.008 250)`,
      selectionBg: `oklch(0.32 ${ch * 0.4} ${hue} / 0.22)`,
    };
  }
  return {
    bg0: 'oklch(0.985 0.003 90)',
    bg1: 'oklch(1 0 0)',
    bg2: 'oklch(0.975 0.004 90)',
    bg3: 'oklch(0.95 0.005 90)',
    border:       `oklch(${0.91 - borderBoost} 0.005 90)`,
    borderStrong: `oklch(${0.83 - borderBoost} 0.006 90)`,
    text0: 'oklch(0.22 0.01 250)',
    text1: 'oklch(0.4 0.01 250)',
    text2: 'oklch(0.55 0.01 250)',
    text3: 'oklch(0.68 0.008 250)',
    accent:    `oklch(${lightnessLight} ${ch * 0.9} ${hue})`,
    accentInk: 'oklch(0.99 0 0)',
    accentMuted: `oklch(0.92 ${ch * 0.4} ${hue})`,
    success: 'oklch(0.58 0.14 155)',
    warn: 'oklch(0.65 0.15 75)',
    error: 'oklch(0.55 0.2 22)',
    info: 'oklch(0.55 0.14 235)',
    chart1: `oklch(${lightnessLight} ${ch * 0.9} ${hue})`,
    chart2: 'oklch(0.55 0.14 235)',
    chart3: 'oklch(0.65 0.15 75)',
    chart4: 'oklch(0.55 0.18 320)',
    gridLine: `oklch(${0.93 - borderBoost} 0.005 90)`,
    selectionBg: `oklch(0.92 ${ch * 0.4} ${hue} / 0.5)`,
  };
}

const densityProfiles = {
  compact:     { padCard: '10px 12px', padRow: '6px 12px', padPanelHd: '8px 12px', gap: 8,  rowMin: 92,  bodyFs: 12,   tableFs: 11.5, statFs: 24 },
  default:     { padCard: '14px 16px', padRow: '9px 14px', padPanelHd: '10px 14px',gap: 12, rowMin: 110, bodyFs: 13,   tableFs: 12,   statFs: 28 },
  comfortable: { padCard: '18px 20px', padRow: '12px 16px',padPanelHd: '12px 16px',gap: 16, rowMin: 128, bodyFs: 13.5, tableFs: 12.5, statFs: 32 },
};

// ── tiny svg icons (no library) ──
const Icon = ({ d, size = 14, stroke = 1.5, style }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={style}>
    {d}
  </svg>
);
const I = {
  search: <Icon d={<><circle cx="11" cy="11" r="7"/><path d="m20 20-3-3"/></>} />,
  bell: <Icon d={<><path d="M6 8a6 6 0 0 1 12 0c0 7 3 8 3 8H3s3-1 3-8"/><path d="M10 20a2 2 0 0 0 4 0"/></>} />,
  plus: <Icon d={<><path d="M12 5v14M5 12h14"/></>} />,
  cmd: <Icon d={<><path d="M9 6V4a2 2 0 1 0-2 2h2zm0 0v6m0-6h6m-6 6H7a2 2 0 1 0 2 2v-2zm6-6V4a2 2 0 1 1 2 2h-2zm0 0v6m0 0h2a2 2 0 1 1-2 2v-2z"/></>} />,
  arrowUp: <Icon d={<><path d="m6 14 6-6 6 6"/></>} />,
  arrowDown: <Icon d={<><path d="m6 10 6 6 6-6"/></>} />,
  arrowRight: <Icon d={<><path d="M5 12h14m-6-6 6 6-6 6"/></>} />,
  more: <Icon d={<><circle cx="5" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/></>} />,
  filter: <Icon d={<><path d="M3 5h18l-7 9v6l-4-2v-4z"/></>} />,
  download: <Icon d={<><path d="M12 3v12m-5-5 5 5 5-5M5 21h14"/></>} />,
  check: <Icon d={<><path d="m5 12 5 5L20 7"/></>} />,
  dot: <Icon d={<><circle cx="12" cy="12" r="3" fill="currentColor"/></>} />,
  // sidebar
  home: <Icon d={<><path d="M3 12 12 4l9 8M5 10v10h14V10"/></>} />,
  layers: <Icon d={<><path d="m3 7 9-4 9 4-9 4-9-4zM3 12l9 4 9-4M3 17l9 4 9-4"/></>} />,
  pulse: <Icon d={<><path d="M3 12h4l3-8 4 16 3-8h4"/></>} />,
  inbox: <Icon d={<><path d="M3 13h4l2 3h6l2-3h4M3 13l3-9h12l3 9v6H3z"/></>} />,
  users: <Icon d={<><circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.5"/><path d="M3 20c0-3 3-5 6-5s6 2 6 5M15 20c0-2 2-4 5-4"/></>} />,
  gear: <Icon d={<><circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.1-1.2l2-1.5-2-3.4-2.3.9a7 7 0 0 0-2.1-1.2L14 3h-4l-.5 2.6a7 7 0 0 0-2.1 1.2l-2.3-.9-2 3.4 2 1.5A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.5 2 3.4 2.3-.9c.6.5 1.3.9 2.1 1.2L10 21h4l.5-2.6c.8-.3 1.5-.7 2.1-1.2l2.3.9 2-3.4-2-1.5c.1-.4.1-.8.1-1.2z"/></>} />,
  database: <Icon d={<><ellipse cx="12" cy="5" rx="8" ry="3"/><path d="M4 5v6c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 11v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6"/></>} />,
  zap: <Icon d={<><path d="M13 2 4 14h7l-1 8 9-12h-7z"/></>} />,
  branch: <Icon d={<><circle cx="6" cy="5" r="2"/><circle cx="6" cy="19" r="2"/><circle cx="18" cy="7" r="2"/><path d="M6 7v10M6 14a8 8 0 0 0 8-8v-1"/></>} />,
};

const fontStack = `'Geist', 'Inter', -apple-system, BlinkMacSystemFont, system-ui, sans-serif`;
const monoStack = `'Geist Mono', 'JetBrains Mono', ui-monospace, SFMono-Regular, monospace`;

// ── seeded data ──
const services = [
  { id: 'svc_a91f', name: 'api-gateway', region: 'us-east-1', p99: 142, rps: '12.4k', errors: 0.03, status: 'healthy', deploys: 8, owner: 'platform' },
  { id: 'svc_22b3', name: 'auth-service', region: 'us-east-1', p99: 89, rps: '8.7k', errors: 0.01, status: 'healthy', deploys: 4, owner: 'identity' },
  { id: 'svc_7c4d', name: 'billing-worker', region: 'eu-west-1', p99: 318, rps: '2.1k', errors: 0.42, status: 'degraded', deploys: 12, owner: 'payments' },
  { id: 'svc_e801', name: 'search-index', region: 'us-west-2', p99: 204, rps: '4.9k', errors: 0.08, status: 'healthy', deploys: 3, owner: 'discovery' },
  { id: 'svc_f330', name: 'ingest-pipeline', region: 'us-east-1', p99: 76, rps: '21.8k', errors: 0.00, status: 'healthy', deploys: 19, owner: 'data' },
  { id: 'svc_9a12', name: 'notification-svc', region: 'eu-west-1', p99: 612, rps: '1.4k', errors: 1.20, status: 'incident', deploys: 6, owner: 'growth' },
  { id: 'svc_4d77', name: 'media-encoder', region: 'us-west-2', p99: 1240, rps: '0.8k', errors: 0.18, status: 'healthy', deploys: 2, owner: 'media' },
  { id: 'svc_b602', name: 'webhooks', region: 'us-east-1', p99: 96, rps: '3.3k', errors: 0.04, status: 'healthy', deploys: 7, owner: 'platform' },
];

const events = [
  { t: '14:02:11', kind: 'deploy', tag: 'success', svc: 'api-gateway', msg: 'v2.41.0 rolled out · 6 regions · 0 errors', actor: 'aria.k' },
  { t: '14:01:47', kind: 'alert',  tag: 'error',   svc: 'notification-svc', msg: 'p99 latency 612ms breached SLO (500ms)', actor: 'pagerduty' },
  { t: '13:59:02', kind: 'deploy', tag: 'success', svc: 'ingest-pipeline', msg: 'v1.18.3 — schema migration complete', actor: 'jonas.r' },
  { t: '13:54:31', kind: 'commit', tag: 'info',    svc: 'billing-worker', msg: 'fix(retry): exponential backoff cap', actor: 'mei.l' },
  { t: '13:51:08', kind: 'alert',  tag: 'warn',    svc: 'billing-worker', msg: 'error rate climbing — 0.42% over 5m', actor: 'monitor' },
  { t: '13:47:55', kind: 'deploy', tag: 'success', svc: 'auth-service', msg: 'v3.02.1 — passkey rollout 25%→50%', actor: 'aria.k' },
  { t: '13:42:19', kind: 'commit', tag: 'info',    svc: 'search-index', msg: 'feat(query): boost recency for trending', actor: 'sam.p' },
  { t: '13:38:00', kind: 'access', tag: 'info',    svc: '—',          msg: 'API key rotated · ci-bot · expires 2026-07-30', actor: 'system' },
];

// build a smooth-ish line series
const buildSeries = (n, base, amp, seed = 1) => {
  const out = [];
  let v = base;
  for (let i = 0; i < n; i++) {
    v += (Math.sin(i * 0.6 + seed) + Math.cos(i * 0.31 + seed * 1.7)) * amp * 0.4;
    out.push(Math.max(0, v));
  }
  return out;
};

// ── chart pieces ──
function Sparkline({ data, color, w = 88, h = 26, fill }) {
  const max = Math.max(...data), min = Math.min(...data);
  const dx = w / (data.length - 1);
  const norm = v => h - ((v - min) / (max - min || 1)) * (h - 4) - 2;
  const path = data.map((v, i) => `${i ? 'L' : 'M'}${(i * dx).toFixed(2)} ${norm(v).toFixed(2)}`).join(' ');
  const area = `${path} L${w} ${h} L0 ${h} Z`;
  return (
    <svg width={w} height={h} style={{ display: 'block' }}>
      {fill && <path d={area} fill={fill} opacity="0.35" />}
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function AreaChart({ t, height = 220 }) {
  const W = 720, H = height, padL = 36, padR = 12, padT = 12, padB = 26;
  const N = 48;
  const s1 = buildSeries(N, 60, 12, 0.7);
  const s2 = buildSeries(N, 38, 9, 2.3);
  const s3 = buildSeries(N, 22, 7, 4.1);
  const all = [...s1, ...s2, ...s3];
  const max = Math.max(...all) * 1.1, min = 0;
  const x = i => padL + (i / (N - 1)) * (W - padL - padR);
  const y = v => H - padB - ((v - min) / (max - min)) * (H - padT - padB);
  const toPath = arr => arr.map((v, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)} ${y(v).toFixed(1)}`).join(' ');
  const toArea = arr => `${toPath(arr)} L${x(N - 1)} ${H - padB} L${padL} ${H - padB} Z`;
  const yTicks = [0, 25, 50, 75, 100];
  const xTicks = ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00'];
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height, display: 'block' }}>
      <defs>
        <linearGradient id={`g1-${t.bg0}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={t.chart1} stopOpacity="0.35"/>
          <stop offset="100%" stopColor={t.chart1} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {/* grid */}
      {yTicks.map((v, i) => (
        <g key={i}>
          <line x1={padL} y1={y(v)} x2={W - padR} y2={y(v)} stroke={t.gridLine} strokeWidth="1" strokeDasharray={i ? '2 4' : ''}/>
          <text x={padL - 8} y={y(v) + 3} textAnchor="end" fontSize="10" fill={t.text2} fontFamily={monoStack}>{v}</text>
        </g>
      ))}
      {xTicks.map((tx, i) => (
        <text key={i} x={padL + (i / (xTicks.length - 1)) * (W - padL - padR)} y={H - 8} textAnchor="middle" fontSize="10" fill={t.text2} fontFamily={monoStack}>{tx}</text>
      ))}
      <path d={toArea(s1)} fill={`url(#g1-${t.bg0})`} />
      <path d={toPath(s1)} fill="none" stroke={t.chart1} strokeWidth="1.75"/>
      <path d={toPath(s2)} fill="none" stroke={t.chart2} strokeWidth="1.5" strokeDasharray="0"/>
      <path d={toPath(s3)} fill="none" stroke={t.chart3} strokeWidth="1.5" opacity="0.85"/>
      {/* current value marker */}
      <circle cx={x(N - 1)} cy={y(s1[N - 1])} r="3" fill={t.chart1}/>
      <circle cx={x(N - 1)} cy={y(s1[N - 1])} r="6" fill={t.chart1} opacity="0.2"/>
    </svg>
  );
}

function Bars({ t, height = 88 }) {
  const W = 280, H = height, n = 24;
  const data = buildSeries(n, 14, 6, 3).map(v => Math.max(2, v));
  const max = Math.max(...data);
  const bw = (W - 4) / n - 2;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height, display: 'block' }}>
      {data.map((v, i) => {
        const h = (v / max) * (H - 8);
        const isLast = i === n - 1;
        return <rect key={i} x={2 + i * (bw + 2)} y={H - h - 2} width={bw} height={h} rx="1.5" fill={isLast ? t.accent : t.chart2} opacity={isLast ? 1 : 0.55}/>;
      })}
    </svg>
  );
}

function Heatmap({ t }) {
  // 7 rows × 24 cols
  const cells = [];
  for (let r = 0; r < 7; r++) for (let c = 0; c < 24; c++) {
    const v = Math.max(0, Math.sin(c * 0.4 + r) + Math.cos(r * 0.7 + c * 0.2) + 1.2) / 3.2;
    cells.push({ r, c, v });
  }
  return (
    <svg viewBox="0 0 288 84" style={{ width: '100%', height: 84, display: 'block' }}>
      {cells.map((cell, i) => (
        <rect key={i} x={cell.c * 12} y={cell.r * 12} width={10} height={10} rx="1.5"
          fill={t.accent} opacity={0.08 + cell.v * 0.85} />
      ))}
    </svg>
  );
}

// ── shell pieces ──
const Pill = ({ children, tone, t }) => {
  const map = {
    healthy: { bg: t.bg2, fg: t.success, dot: t.success, label: 'Healthy' },
    degraded:{ bg: t.bg2, fg: t.warn,    dot: t.warn,    label: 'Degraded' },
    incident:{ bg: t.bg2, fg: t.error,   dot: t.error,   label: 'Incident' },
    success: { bg: t.bg2, fg: t.success, dot: t.success, label: 'deploy' },
    error:   { bg: t.bg2, fg: t.error,   dot: t.error,   label: 'alert' },
    warn:    { bg: t.bg2, fg: t.warn,    dot: t.warn,    label: 'alert' },
    info:    { bg: t.bg2, fg: t.info,    dot: t.info,    label: 'info' },
  };
  const s = map[tone] || map.info;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '2px 8px 2px 6px', borderRadius: 'var(--cp-radius-xs)',
      background: s.bg, color: s.fg,
      fontSize: 11, fontFamily: 'var(--cp-mono)', lineHeight: 1.4,
      border: `1px solid ${t.border}`,
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: s.dot, boxShadow: tone === 'incident' ? `0 0 0 2px ${t.bg2}, 0 0 8px ${s.dot}` : 'none' }}/>
      {children || s.label}
    </span>
  );
};

const Kbd = ({ children, t }) => (
  <span style={{
    fontFamily: 'var(--cp-mono)', fontSize: 10.5, padding: '1px 5px',
    border: `1px solid ${t.border}`, borderBottomWidth: 2,
    borderRadius: 'var(--cp-radius-xs)', background: t.bg2, color: t.text1,
    minWidth: 16, textAlign: 'center', display: 'inline-block',
  }}>{children}</span>
);

const NavItem = ({ icon, label, count, active, t, sub }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 9,
    padding: sub ? '5px 8px 5px 28px' : '6px 8px',
    borderRadius: 'var(--cp-radius-sm)', cursor: 'pointer',
    background: active ? t.bg3 : 'transparent',
    color: active ? t.text0 : t.text1,
    fontSize: 12.5, fontWeight: active ? 500 : 400,
    border: active ? `1px solid ${t.border}` : '1px solid transparent',
    position: 'relative',
  }}>
    {active && <span style={{ position: 'absolute', left: -1, top: 6, bottom: 6, width: 2, background: t.accent, borderRadius: 2 }}/>}
    {icon && <span style={{ color: active ? t.accent : t.text2, display: 'inline-flex' }}>{icon}</span>}
    <span style={{ flex: 1 }}>{label}</span>
    {count != null && (
      <span style={{ fontFamily: 'var(--cp-mono)', fontSize: 10.5, color: t.text2, padding: '1px 6px', background: t.bg2, borderRadius: 999, border: `1px solid ${t.border}` }}>{count}</span>
    )}
  </div>
);

const Stat = ({ label, value, unit, delta, deltaDir, series, t, accent }) => (
  <div style={{
    background: t.bg1, border: `1px solid ${t.border}`, borderRadius: 'var(--cp-radius)',
    padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 8,
    minHeight: 110,
  }}>
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <span style={{ fontSize: 11.5, color: t.text2, letterSpacing: 0.2, textTransform: 'uppercase', fontWeight: 500 }}>{label}</span>
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 2,
        fontSize: 11, fontFamily: 'var(--cp-mono)',
        color: deltaDir === 'up' ? t.success : deltaDir === 'down' ? t.error : t.text2,
      }}>
        <span style={{ display: 'inline-flex', transform: deltaDir === 'down' ? 'rotate(180deg)' : 'none' }}>{I.arrowUp}</span>
        {delta}
      </span>
    </div>
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
      <span style={{ fontFamily: 'var(--cp-mono)', fontSize: 28, fontWeight: 500, color: t.text0, letterSpacing: -0.5 }}>{value}</span>
      <span style={{ fontFamily: 'var(--cp-mono)', fontSize: 12, color: t.text2 }}>{unit}</span>
    </div>
    <div style={{ marginTop: 'auto' }}>
      <Sparkline data={series} color={accent || t.accent} fill={accent || t.accent} w={240} h={28}/>
    </div>
  </div>
);

// ── main dashboard ──
function CockpitDashboard({ theme = 'dark', tokens = {} }) {
  const baseTheme = buildTheme(theme, tokens);
  const density = densityProfiles[tokens.density] || densityProfiles.default;
  const radius = tokens.radius ?? 8;
  const fontUI = tokens.fonts?.ui || fontStack;
  const fontMono = tokens.fonts?.mono || monoStack;
  const t = { ...baseTheme, density, radius, fontUI, fontMono };

  const [selected, setSelected] = React.useState(['svc_22b3', 'svc_7c4d']);
  const [activeTab, setActiveTab] = React.useState('Overview');
  const [range, setRange] = React.useState('24h');

  const toggleRow = (id) => setSelected(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);

  return (
    <div style={{
      width: 1440, height: 920,
      background: t.bg0, color: t.text0,
      fontFamily: fontUI, fontSize: density.bodyFs, lineHeight: 1.5,
      display: 'grid',
      gridTemplateColumns: '232px 1fr',
      letterSpacing: 0,
      WebkitFontSmoothing: 'antialiased',
      borderRadius: radius, overflow: 'hidden',
      border: `1px solid ${t.border}`,
      ['--cp-radius']: `${radius}px`,
      ['--cp-radius-sm']: `${Math.max(2, radius - 2)}px`,
      ['--cp-radius-xs']: `${Math.max(2, radius - 4)}px`,
      ['--cp-mono']: fontMono,
    }} className="cp-root">
      <style>{`
        .cp-root button, .cp-root input { font-family: inherit; }
      `}</style>
      {/* ── SIDEBAR ── */}
      <aside style={{
        background: t.bg1, borderRight: `1px solid ${t.border}`,
        display: 'flex', flexDirection: 'column', minHeight: 0,
      }}>
        {/* workspace switcher */}
        <div style={{ padding: '12px 12px 10px', borderBottom: `1px solid ${t.border}` }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 9,
            padding: '6px 8px', borderRadius: 'var(--cp-radius-sm)', cursor: 'pointer',
            border: `1px solid ${t.border}`, background: t.bg2,
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: 'var(--cp-radius-sm)',
              background: t.accent, color: t.accentInk,
              display: 'grid', placeItems: 'center',
              fontFamily: 'var(--cp-mono)', fontWeight: 600, fontSize: 11,
            }}>NX</div>
            <div style={{ flex: 1, lineHeight: 1.2, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 500, color: t.text0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Nexus Labs</div>
              <div style={{ fontSize: 10.5, color: t.text2, fontFamily: 'var(--cp-mono)' }}>production</div>
            </div>
            <span style={{ color: t.text2, display: 'inline-flex' }}>{I.arrowDown}</span>
          </div>
        </div>

        {/* nav */}
        <div style={{ flex: 1, overflow: 'auto', padding: '10px 8px' }}>
          <div style={{ fontSize: 10.5, color: t.text3, padding: '6px 10px 4px', textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 500 }}>Workspace</div>
          <NavItem icon={I.home} label="Overview" active t={t}/>
          <NavItem icon={I.layers} label="Services" count="24" t={t}/>
          <NavItem icon={I.pulse} label="Metrics" t={t}/>
          <NavItem icon={I.database} label="Logs" t={t}/>
          <NavItem icon={I.branch} label="Deploys" count="3" t={t}/>
          <NavItem icon={I.inbox} label="Inbox" count="12" t={t}/>

          <div style={{ fontSize: 10.5, color: t.text3, padding: '14px 10px 4px', textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 500 }}>Pinned</div>
          <NavItem label="api-gateway" t={t} sub icon={<span style={{width:6, height:6, borderRadius:99, background:t.success, display:'inline-block'}}/>}/>
          <NavItem label="auth-service" t={t} sub icon={<span style={{width:6, height:6, borderRadius:99, background:t.success, display:'inline-block'}}/>}/>
          <NavItem label="billing-worker" t={t} sub icon={<span style={{width:6, height:6, borderRadius:99, background:t.warn, display:'inline-block'}}/>}/>
          <NavItem label="ingest-pipeline" t={t} sub icon={<span style={{width:6, height:6, borderRadius:99, background:t.success, display:'inline-block'}}/>}/>

          <div style={{ fontSize: 10.5, color: t.text3, padding: '14px 10px 4px', textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 500 }}>Account</div>
          <NavItem icon={I.users} label="Team" t={t}/>
          <NavItem icon={I.gear} label="Settings" t={t}/>
        </div>

        {/* user card */}
        <div style={{
          padding: '10px 12px', borderTop: `1px solid ${t.border}`,
          display: 'flex', alignItems: 'center', gap: 9,
        }}>
          <div style={{
            width: 26, height: 26, borderRadius: 999,
            background: `linear-gradient(135deg, ${t.chart2}, ${t.chart4})`,
            color: '#fff', display: 'grid', placeItems: 'center',
            fontSize: 11, fontWeight: 600, fontFamily: 'var(--cp-mono)',
          }}>AK</div>
          <div style={{ flex: 1, lineHeight: 1.2, minWidth: 0 }}>
            <div style={{ fontSize: 12, color: t.text0, fontWeight: 500 }}>Aria Kessler</div>
            <div style={{ fontSize: 10.5, color: t.text2, fontFamily: 'var(--cp-mono)' }}>aria@nexus.dev</div>
          </div>
          <span style={{ color: t.text2 }}>{I.more}</span>
        </div>
      </aside>

      {/* ── MAIN ── */}
      <main style={{ display: 'flex', flexDirection: 'column', minWidth: 0, minHeight: 0 }}>
        {/* topbar */}
        <header style={{
          height: 48, padding: '0 16px', borderBottom: `1px solid ${t.border}`,
          display: 'flex', alignItems: 'center', gap: 12, background: t.bg0,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: t.text2 }}>
            <span>Nexus Labs</span>
            <span style={{ color: t.text3 }}>/</span>
            <span style={{ color: t.text1 }}>production</span>
            <span style={{ color: t.text3 }}>/</span>
            <span style={{ color: t.text0, fontWeight: 500 }}>Overview</span>
          </div>
          <div style={{ flex: 1 }}/>
          {/* search */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '4px 8px 4px 10px', minWidth: 320,
            border: `1px solid ${t.border}`, borderRadius: 'var(--cp-radius-sm)',
            background: t.bg1, color: t.text2, fontSize: 12.5,
          }}>
            <span style={{ display: 'inline-flex' }}>{I.search}</span>
            <span style={{ flex: 1 }}>Search services, deploys, logs…</span>
            <Kbd t={t}>⌘</Kbd><Kbd t={t}>K</Kbd>
          </div>
          <button style={iconBtn(t)} aria-label="Notifications">{I.bell}<span style={{
            position:'absolute', top: 6, right: 6, width: 6, height: 6, borderRadius: 99, background: t.error,
          }}/></button>
          <button style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            background: t.accent, color: t.accentInk,
            border: 'none', borderRadius: 'var(--cp-radius-sm)', padding: '6px 12px',
            fontSize: 12.5, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
          }}>{I.plus} New deploy</button>
        </header>

        {/* page */}
        <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
          {/* page header */}
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18 }}>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: -0.4, color: t.text0 }}>Overview</h1>
                <Pill tone="healthy" t={t}>All systems operational</Pill>
              </div>
              <div style={{ fontSize: 12.5, color: t.text2, fontFamily: 'var(--cp-mono)' }}>
                Last sync <span style={{ color: t.text1 }}>14:02:11 UTC</span> · 24 services · 6 regions
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <SegGroup t={t} value={range} onChange={setRange} options={['1h','6h','24h','7d','30d']}/>
              <button style={ghostBtn(t)}>{I.filter} Filter</button>
              <button style={ghostBtn(t)}>{I.download} Export</button>
            </div>
          </div>

          {/* stat row */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16 }}>
            <Stat t={t} label="Requests / sec" value="54.7" unit="k" delta="+12.4%" deltaDir="up"
              series={buildSeries(40, 50, 7, 1)} accent={t.accent}/>
            <Stat t={t} label="p99 latency" value="218" unit="ms" delta="−8.1%" deltaDir="up"
              series={buildSeries(40, 220, 30, 2.2)} accent={t.chart2}/>
            <Stat t={t} label="Error rate" value="0.07" unit="%" delta="+0.02%" deltaDir="down"
              series={buildSeries(40, 0.05, 0.04, 3.4)} accent={t.warn}/>
            <Stat t={t} label="Active sessions" value="48.2" unit="k" delta="+3.7%" deltaDir="up"
              series={buildSeries(40, 45, 6, 4.7)} accent={t.chart4}/>
          </div>

          {/* main grid */}
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12, marginBottom: 16 }}>
            {/* big chart */}
            <Panel t={t}>
              <PanelHead t={t}
                title="Traffic & latency"
                meta={<div style={{ display: 'flex', gap: 14, fontFamily: 'var(--cp-mono)', fontSize: 11.5 }}>
                  <Legend color={t.chart1} label="rps"/>
                  <Legend color={t.chart2} label="p95"/>
                  <Legend color={t.chart3} label="p99"/>
                </div>}
                tabs={['Overview','Latency','Errors','Saturation']}
                active={activeTab} setActive={setActiveTab}
              />
              <div style={{ padding: '8px 16px 14px' }}>
                <AreaChart t={t}/>
              </div>
            </Panel>

            {/* deploy frequency */}
            <Panel t={t}>
              <PanelHead t={t} title="Deploys" meta={<span style={{ fontFamily: 'var(--cp-mono)', fontSize: 11.5, color: t.text2 }}>last 24h</span>}/>
              <div style={{ padding: '6px 16px 4px' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
                  <span style={{ fontFamily: 'var(--cp-mono)', fontSize: 26, fontWeight: 500, color: t.text0, letterSpacing: -0.5 }}>61</span>
                  <span style={{ fontFamily: 'var(--cp-mono)', fontSize: 12, color: t.success }}>+18</span>
                </div>
                <Bars t={t}/>
              </div>
              <div style={{ borderTop: `1px solid ${t.border}`, padding: '10px 16px' }}>
                <div style={{ fontSize: 11, color: t.text2, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 8 }}>Request heatmap · 7d × 24h</div>
                <Heatmap t={t}/>
              </div>
            </Panel>
          </div>

          {/* services table + activity */}
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
            <Panel t={t}>
              <PanelHead t={t} title="Services"
                meta={<>
                  <span style={{ fontFamily: 'var(--cp-mono)', fontSize: 11.5, color: t.text2 }}>{services.length} total · {selected.length} selected</span>
                </>}
                actions={<>
                  <button style={ghostBtn(t, 'sm')}>{I.filter} Region: us-east-1</button>
                  <button style={ghostBtn(t, 'sm')}>Sort: p99 desc</button>
                  <button style={iconBtn(t, 'sm')} aria-label="more">{I.more}</button>
                </>}
              />
              <ServicesTable t={t} selected={selected} toggle={toggleRow}/>
            </Panel>

            <Panel t={t}>
              <PanelHead t={t} title="Activity"
                meta={<span style={{ fontFamily: 'var(--cp-mono)', fontSize: 11.5, color: t.text2 }}>live</span>}
              />
              <ActivityFeed t={t}/>
            </Panel>
          </div>

          {/* footer hints */}
          <div style={{
            marginTop: 18, padding: '10px 14px',
            border: `1px solid ${t.border}`, borderRadius: 'var(--cp-radius)', background: t.bg1,
            display: 'flex', alignItems: 'center', gap: 18,
            fontSize: 12, color: t.text2,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Kbd t={t}>⌘</Kbd><Kbd t={t}>K</Kbd> <span>Command</span></div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Kbd t={t}>g</Kbd><Kbd t={t}>d</Kbd> <span>Dashboard</span></div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Kbd t={t}>g</Kbd><Kbd t={t}>i</Kbd> <span>Inbox</span></div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Kbd t={t}>c</Kbd> <span>Create</span></div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Kbd t={t}>?</Kbd> <span>Shortcuts</span></div>
            <div style={{ flex: 1 }}/>
            <span style={{ fontFamily: 'var(--cp-mono)', fontSize: 11.5 }}>build 2.41.0 · region us-east-1</span>
          </div>
        </div>
      </main>
    </div>
  );
}

// ── helpers ──
function iconBtn(t, size) {
  return {
    width: size === 'sm' ? 26 : 30, height: size === 'sm' ? 26 : 30,
    display: 'inline-grid', placeItems: 'center',
    border: `1px solid ${t.border}`, borderRadius: 'var(--cp-radius-sm)',
    background: t.bg1, color: t.text1, cursor: 'pointer', position: 'relative',
  };
}
function ghostBtn(t, size) {
  return {
    display: 'inline-flex', alignItems: 'center', gap: 6,
    border: `1px solid ${t.border}`, borderRadius: 'var(--cp-radius-sm)',
    padding: size === 'sm' ? '4px 8px' : '6px 10px',
    fontSize: 12, color: t.text1, background: t.bg1, cursor: 'pointer',
    fontFamily: 'inherit',
  };
}

function SegGroup({ t, value, onChange, options }) {
  return (
    <div style={{ display: 'inline-flex', border: `1px solid ${t.border}`, borderRadius: 'var(--cp-radius-sm)', background: t.bg1, padding: 2 }}>
      {options.map(o => (
        <button key={o} onClick={() => onChange(o)} style={{
          padding: '3px 9px', fontSize: 11.5, fontFamily: 'var(--cp-mono)',
          border: 'none', borderRadius: 'var(--cp-radius-xs)', cursor: 'pointer',
          background: value === o ? t.bg3 : 'transparent',
          color: value === o ? t.text0 : t.text2,
          fontWeight: value === o ? 500 : 400,
        }}>{o}</button>
      ))}
    </div>
  );
}

function Panel({ children, t }) {
  return (
    <section style={{
      background: t.bg1, border: `1px solid ${t.border}`, borderRadius: 'var(--cp-radius)',
      display: 'flex', flexDirection: 'column', minWidth: 0,
    }}>{children}</section>
  );
}

function PanelHead({ t, title, meta, actions, tabs, active, setActive }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 14px',
      borderBottom: `1px solid ${t.border}`,
      minHeight: 42,
    }}>
      <h3 style={{ margin: 0, fontSize: 13, fontWeight: 600, color: t.text0 }}>{title}</h3>
      {tabs && (
        <div style={{ display: 'flex', gap: 4, marginLeft: 8 }}>
          {tabs.map(tab => (
            <button key={tab} onClick={() => setActive(tab)} style={{
              padding: '4px 8px', fontSize: 12,
              border: 'none', background: 'transparent', cursor: 'pointer',
              color: active === tab ? t.text0 : t.text2,
              fontWeight: active === tab ? 500 : 400,
              borderBottom: active === tab ? `1.5px solid ${t.accent}` : '1.5px solid transparent',
              borderRadius: 0, marginBottom: -10, paddingBottom: 11,
              fontFamily: 'inherit',
            }}>{tab}</button>
          ))}
        </div>
      )}
      <div style={{ flex: 1 }}/>
      {meta}
      {actions}
    </div>
  );
}

function Legend({ color, label }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
      <span style={{ width: 8, height: 8, borderRadius: 2, background: color }}/>
      {label}
    </span>
  );
}

function ServicesTable({ t, selected, toggle }) {
  const cols = [
    { k: 'name', label: 'Service', w: '1.6fr' },
    { k: 'id', label: 'ID', w: '1fr' },
    { k: 'region', label: 'Region', w: '1fr' },
    { k: 'rps', label: 'rps', w: '0.7fr', align: 'right' },
    { k: 'p99', label: 'p99', w: '0.8fr', align: 'right' },
    { k: 'errors', label: 'errors %', w: '0.8fr', align: 'right' },
    { k: 'trend', label: '24h', w: '1fr' },
    { k: 'status', label: 'Status', w: '1fr' },
  ];
  const grid = `28px ${cols.map(c => c.w).join(' ')} 32px`;

  return (
    <div style={{ overflow: 'auto' }}>
      {/* header */}
      <div style={{
        display: 'grid', gridTemplateColumns: grid,
        padding: '8px 14px', gap: 10,
        borderBottom: `1px solid ${t.border}`,
        fontSize: 11, color: t.text2, textTransform: 'uppercase', letterSpacing: 0.4, fontWeight: 500,
        background: t.bg0,
      }}>
        <div style={{ display: 'grid', placeItems: 'center' }}>
          <Checkbox t={t} checked={selected.length > 0 && selected.length < services.length ? 'indet' : selected.length === services.length}/>
        </div>
        {cols.map(c => <div key={c.k} style={{ textAlign: c.align || 'left' }}>{c.label}</div>)}
        <div></div>
      </div>
      {services.map((s, i) => {
        const isSel = selected.includes(s.id);
        const trend = buildSeries(20, 30, 8, i + 1);
        return (
          <div key={s.id} onClick={() => toggle(s.id)} style={{
            display: 'grid', gridTemplateColumns: grid, gap: 10,
            padding: '9px 14px', alignItems: 'center',
            borderBottom: i === services.length - 1 ? 'none' : `1px solid ${t.border}`,
            background: isSel ? t.selectionBg : 'transparent',
            cursor: 'pointer',
            position: 'relative',
          }}>
            {isSel && <span style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 2, background: t.accent }}/>}
            <div style={{ display: 'grid', placeItems: 'center' }}>
              <Checkbox t={t} checked={isSel}/>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
              <span style={{
                width: 6, height: 6, borderRadius: 99,
                background: s.status === 'healthy' ? t.success : s.status === 'degraded' ? t.warn : t.error,
              }}/>
              <span style={{ color: t.text0, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.name}</span>
              <span style={{ fontSize: 10.5, color: t.text3, fontFamily: 'var(--cp-mono)', padding: '0 5px', border: `1px solid ${t.border}`, borderRadius: 3 }}>{s.owner}</span>
            </div>
            <div style={{ fontFamily: 'var(--cp-mono)', fontSize: 11.5, color: t.text2 }}>{s.id}</div>
            <div style={{ fontFamily: 'var(--cp-mono)', fontSize: 12, color: t.text1 }}>{s.region}</div>
            <div style={{ fontFamily: 'var(--cp-mono)', fontSize: 12, color: t.text0, textAlign: 'right' }}>{s.rps}</div>
            <div style={{ fontFamily: 'var(--cp-mono)', fontSize: 12, color: s.p99 > 500 ? t.error : s.p99 > 250 ? t.warn : t.text0, textAlign: 'right' }}>{s.p99}<span style={{ color: t.text3 }}>ms</span></div>
            <div style={{ fontFamily: 'var(--cp-mono)', fontSize: 12, color: s.errors > 0.5 ? t.error : s.errors > 0.1 ? t.warn : t.text1, textAlign: 'right' }}>{s.errors.toFixed(2)}</div>
            <div><Sparkline data={trend} color={s.status === 'incident' ? t.error : s.status === 'degraded' ? t.warn : t.accent} w={88} h={20}/></div>
            <div><Pill tone={s.status} t={t}/></div>
            <div style={{ color: t.text3, display: 'grid', placeItems: 'center' }}>{I.more}</div>
          </div>
        );
      })}
    </div>
  );
}

function Checkbox({ t, checked }) {
  const filled = checked === true || checked === 'indet';
  return (
    <span style={{
      width: 14, height: 14, borderRadius: 3,
      border: `1px solid ${filled ? t.accent : t.borderStrong}`,
      background: filled ? t.accent : 'transparent',
      display: 'grid', placeItems: 'center',
      color: t.accentInk,
    }}>
      {checked === true && <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>}
      {checked === 'indet' && <span style={{ width: 7, height: 1.5, background: t.accentInk }}/>}
    </span>
  );
}

function ActivityFeed({ t }) {
  return (
    <div style={{ padding: '4px 0' }}>
      {events.map((e, i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '52px 1fr',
          padding: '10px 14px',
          borderBottom: i === events.length - 1 ? 'none' : `1px dashed ${t.border}`,
          gap: 10,
          position: 'relative',
        }}>
          <div style={{ fontFamily: 'var(--cp-mono)', fontSize: 11, color: t.text3, paddingTop: 1 }}>{e.t}</div>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 2 }}>
              <Pill tone={e.tag} t={t}>{e.kind}</Pill>
              {e.svc !== '—' && <span style={{ fontFamily: 'var(--cp-mono)', fontSize: 11.5, color: t.text1 }}>{e.svc}</span>}
            </div>
            <div style={{ fontSize: 12.5, color: t.text0, lineHeight: 1.45 }}>{e.msg}</div>
            <div style={{ fontSize: 11, color: t.text3, marginTop: 3, fontFamily: 'var(--cp-mono)' }}>by {e.actor}</div>
          </div>
        </div>
      ))}
      <div style={{ padding: '12px 14px' }}>
        <button style={{
          width: '100%', padding: '6px 10px',
          background: 'transparent', color: t.text1,
          border: `1px solid ${t.border}`, borderRadius: 'var(--cp-radius-sm)',
          fontSize: 12, fontFamily: 'inherit', cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>View all activity {I.arrowRight}</button>
      </div>
    </div>
  );
}

window.CockpitDashboard = CockpitDashboard;
Object.assign(window, { buildTheme, densityProfiles, I, Icon, Sparkline, Pill, Kbd, Panel, PanelHead, NavItem, Stat, Checkbox, iconBtn, ghostBtn, SegGroup, Legend, buildSeries, services, events });
