// Additional web screens — Overview, Map, Logs, Settings
// All 1280×860, sit alongside FleetDashboard

function WebShell({ t, accent, active, children }) {
  return (
    <div style={{
      width: 1280, height: 860, background: t.bg0, color: t.t0,
      fontFamily: OR.font.sans, display: 'grid', gridTemplateColumns: '220px 1fr', overflow: 'hidden',
      ['--accent']: accent,
    }}>
      <ORStyles/>
      <div style={{ borderRight: `1px solid ${t.line}`, background: t.bg1, display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '16px 16px 14px', borderBottom: `1px solid ${t.line}` }}>
          <ORWordmark color={t.t0} accent={accent} size={14}/>
        </div>
        <div style={{ padding: 12, flex: 1 }}>
          {[
            { i: Icons.home, l: 'Overview', k: 'overview' },
            { i: Icons.robot, l: 'Fleet', k: 'fleet', n: '6' },
            { i: Icons.store, l: 'Skills', k: 'skills', n: '142' },
            { i: Icons.map, l: 'Map', k: 'map' },
            { i: Icons.repeat, l: 'Automations', k: 'auto', n: '24' },
            { i: Icons.terminal, l: 'Logs', k: 'logs' },
            { i: Icons.settings, l: 'Settings', k: 'settings' },
          ].map((m, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px',
              borderRadius: 6, fontSize: 13, color: m.k === active ? t.t0 : t.t1,
              background: m.k === active ? t.bg3 : 'transparent', cursor: 'pointer', marginBottom: 2,
            }}>
              <Icon d={m.i} size={15}/>
              <span style={{ flex: 1 }}>{m.l}</span>
              {m.n && <span style={{ fontFamily: OR.font.mono, fontSize: 10, color: t.t2 }}>{m.n}</span>}
            </div>
          ))}
        </div>
        <div style={{ padding: 12, borderTop: `1px solid ${t.line}` }}>
          <div style={{ padding: 10, background: t.bg2, borderRadius: 6, fontSize: 11, color: t.t2, fontFamily: OR.font.mono }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: t.ok, marginBottom: 4 }}>
              <Pip color={t.ok} pulse size={6}/> hub.local
            </div>
            <div>v0.9.4 · 14ms</div>
          </div>
        </div>
      </div>
      <div style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>{children}</div>
    </div>
  );
}

function TopBar({ t, accent, breadcrumb, right }) {
  return (
    <div style={{ height: 52, borderBottom: `1px solid ${t.line}`, padding: '0 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: t.t1 }}>
        {breadcrumb.map((b, i) => (
          <React.Fragment key={i}>
            {i > 0 && <Icon d={Icons.chev} size={12} stroke={t.t3}/>}
            <span style={{ color: i === breadcrumb.length - 1 ? t.t0 : t.t2, fontWeight: i === breadcrumb.length - 1 ? 500 : 400, fontFamily: i < breadcrumb.length - 1 ? OR.font.mono : OR.font.sans }}>{b}</span>
          </React.Fragment>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        {right}
        <div style={{ width: 30, height: 30, borderRadius: '50%', background: accent, color: t.bg0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 600 }}>K</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// OVERVIEW — fleet-wide dashboard
// ─────────────────────────────────────────────────────────────
function FleetOverview({ accent = '#FF8A2B', dark = true }) {
  const t = useTheme(dark, accent);
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => { const id = setInterval(() => setTick(x => x + 1), 1500); return () => clearInterval(id); }, []);

  const taskData = React.useMemo(() => Array.from({ length: 60 }, (_, i) => 20 + Math.sin(i / 4) * 8 + Math.cos(i / 7) * 6 + Math.random() * 4), [tick]);
  const upData = React.useMemo(() => Array.from({ length: 60 }, (_, i) => 95 + Math.sin(i / 5) * 4), []);

  return (
    <WebShell t={t} accent={accent} active="overview">
      <TopBar t={t} accent={accent} breadcrumb={['Home', 'Overview']} right={<>
        <span style={{ fontSize: 11, fontFamily: OR.font.mono, color: t.t2, padding: '5px 10px', border: `1px solid ${t.line}`, borderRadius: 4 }}>
          last 24h ▾
        </span>
      </>}/>
      <div style={{ padding: 24, overflow: 'auto', flex: 1 }}>
        <div style={{ marginBottom: 4, fontSize: 12, color: t.t2, fontFamily: OR.font.mono }}>Saturday · 14:22 · all systems nominal</div>
        <h1 style={{ fontFamily: OR.font.display, fontSize: 36, fontWeight: 500, letterSpacing: '-0.025em', margin: '0 0 24px' }}>
          Hello, Kai. <span style={{ color: t.t2 }}>4 robots online,</span> 2 working.
        </h1>

        {/* Headline metrics */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 20 }}>
          {[
            { k: 'tasks completed', v: '127', sub: '+18 vs yesterday', spark: taskData, color: accent },
            { k: 'uptime', v: '99.97%', sub: '4h 12m maintenance', spark: upData, color: t.ok },
            { k: 'energy used', v: '4.2 kWh', sub: '$0.62 estimate', spark: taskData.map(x => x * 0.7), color: t.info },
            { k: 'incidents', v: '1', sub: 'ada-02 · low signal', spark: [0,0,0,0,0,0,0,0,1,0,0,0], color: t.warn },
          ].map((m, i) => (
            <div key={i} style={{ padding: 16, background: t.bg1, border: `1px solid ${t.line}`, borderRadius: 10 }}>
              <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, textTransform: 'uppercase', letterSpacing: '0.1em' }}>{m.k}</div>
              <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 8 }}>
                <div style={{ fontSize: 32, fontWeight: 500, fontFamily: OR.font.display, letterSpacing: '-0.02em' }}>{m.v}</div>
                <Sparkline values={m.spark} color={m.color} width={80} height={28}/>
              </div>
              <div style={{ fontSize: 11, color: t.t2, fontFamily: OR.font.mono, marginTop: 6 }}>{m.sub}</div>
            </div>
          ))}
        </div>

        {/* Two col body */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16 }}>
          {/* Activity timeline */}
          <div style={{ background: t.bg1, border: `1px solid ${t.line}`, borderRadius: 10, padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
              <span style={{ fontSize: 12, fontWeight: 500 }}>Activity · last 24h</span>
              <span style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2 }}>per-robot · stacked</span>
            </div>

            {/* Stacked timeline */}
            <div>
              {[
                { name: 'Ada-01', kind: 'humanoid', segs: [['active', 0, 30], ['idle', 30, 38], ['active', 38, 78], ['error', 78, 80], ['active', 80, 100]] },
                { name: 'Rex-04', kind: 'quadruped', segs: [['idle', 0, 20], ['active', 20, 60], ['charging', 60, 70], ['active', 70, 100]] },
                { name: 'Arm-12', kind: 'arm', segs: [['active', 0, 15], ['idle', 15, 80], ['active', 80, 100]] },
                { name: 'Sky-02', kind: 'drone', segs: [['active', 0, 10], ['idle', 10, 50], ['charging', 50, 100]] },
                { name: 'Roam-7', kind: 'rover', segs: [['active', 0, 25], ['charging', 25, 35], ['active', 35, 90], ['idle', 90, 100]] },
                { name: 'Ada-02', kind: 'humanoid', segs: [['active', 0, 60], ['error', 60, 75], ['idle', 75, 100]] },
              ].map((r, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '110px 1fr', gap: 12, alignItems: 'center', marginBottom: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: t.t1 }}>
                    <RobotGlyph kind={r.kind} size={20} color={t.t1} accent={accent}/>
                    {r.name}
                  </div>
                  <div style={{ display: 'flex', height: 22, borderRadius: 4, overflow: 'hidden', background: t.bg2 }}>
                    {r.segs.map((s, si) => {
                      const c = s[0] === 'active' ? accent : s[0] === 'idle' ? t.bg3 : s[0] === 'charging' ? t.info : t.danger;
                      return <div key={si} style={{ width: `${s[2] - s[1]}%`, background: c, opacity: s[0] === 'active' ? 1 : 0.7 }}/>;
                    })}
                  </div>
                </div>
              ))}
            </div>

            {/* Legend + axis */}
            <div style={{ marginTop: 12, paddingTop: 12, borderTop: `1px solid ${t.line}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', gap: 14, fontSize: 10, fontFamily: OR.font.mono, color: t.t2 }}>
                {[['active', accent], ['idle', t.bg3], ['charging', t.info], ['error', t.danger]].map(([l, c]) => (
                  <span key={l} style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                    <span style={{ width: 8, height: 8, background: c, borderRadius: 2 }}/> {l}
                  </span>
                ))}
              </div>
              <div style={{ display: 'flex', gap: 32, fontSize: 10, fontFamily: OR.font.mono, color: t.t3 }}>
                {['00:00', '06:00', '12:00', '18:00', 'now'].map(x => <span key={x}>{x}</span>)}
              </div>
            </div>
          </div>

          {/* Right rail: feed + alerts */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {/* Alerts */}
            <div style={{ background: t.bg1, border: `1px solid ${t.line}`, borderRadius: 10, padding: 16 }}>
              <div style={{ fontSize: 12, fontWeight: 500, marginBottom: 12 }}>Alerts · 3</div>
              {[
                { sev: 'warn', t: 'Ada-02 lost network', sub: '2 min ago · zone 1', c: t.warn },
                { sev: 'info', t: 'OTA update 2.4.2 available', sub: '14 min ago · 4 robots', c: t.info },
                { sev: 'ok', t: 'Sky-02 finished charging', sub: '32 min ago · dock 3', c: t.ok },
              ].map((a, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '8px 1fr', gap: 10, padding: '10px 0', borderTop: i ? `1px solid ${t.line}` : 'none' }}>
                  <Pip color={a.c} size={6}/>
                  <div>
                    <div style={{ fontSize: 12, color: t.t0 }}>{a.t}</div>
                    <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, marginTop: 2 }}>{a.sub}</div>
                  </div>
                </div>
              ))}
            </div>

            {/* Recent skills */}
            <div style={{ background: t.bg1, border: `1px solid ${t.line}`, borderRadius: 10, padding: 16, flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 500, marginBottom: 12 }}>Top skills today</div>
              {[
                { i: '🧹', n: 'tidy-room', count: 14, time: '2.1h' },
                { i: '🍳', n: 'cook-breakfast', count: 3, time: '0.6h' },
                { i: '📦', n: 'patrol-perimeter', count: 47, time: '5.2h' },
                { i: '🌱', n: 'water-plants', count: 8, time: '0.4h' },
              ].map((s, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '24px 1fr auto', gap: 10, padding: '8px 0', alignItems: 'center', borderTop: i ? `1px solid ${t.line}` : 'none' }}>
                  <span style={{ fontSize: 16 }}>{s.i}</span>
                  <span style={{ fontSize: 12, fontFamily: OR.font.mono, color: t.t1 }}>{s.n}</span>
                  <span style={{ fontSize: 11, fontFamily: OR.font.mono, color: t.t2 }}>{s.count}× · {s.time}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </WebShell>
  );
}

// ─────────────────────────────────────────────────────────────
// MAP — spatial view of robots
// ─────────────────────────────────────────────────────────────
function FleetMap({ accent = '#FF8A2B', dark = true }) {
  const t = useTheme(dark, accent);
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => { const id = setInterval(() => setTick(x => x + 1), 1500); return () => clearInterval(id); }, []);

  // Floor plan rooms
  const rooms = [
    { id: 'kitchen', x: 60, y: 80, w: 280, h: 180, label: 'Kitchen' },
    { id: 'living', x: 340, y: 80, w: 320, h: 240, label: 'Living room' },
    { id: 'lab', x: 60, y: 260, w: 280, h: 200, label: 'Lab · zone 2' },
    { id: 'workbench', x: 660, y: 80, w: 200, h: 160, label: 'Workbench' },
    { id: 'hall', x: 340, y: 320, w: 320, h: 140, label: 'Hallway' },
    { id: 'dock', x: 660, y: 240, w: 200, h: 220, label: 'Dock · charging' },
  ];

  const robots = [
    { id: 'ada', name: 'Ada-01', kind: 'humanoid', x: 200, y: 170, status: 'active', task: 'cleanup-kitchen', selected: true },
    { id: 'rex', name: 'Rex-04', kind: 'quadruped', x: 480, y: 380, status: 'active', task: 'patrol' },
    { id: 'arm', name: 'Arm-12', kind: 'arm', x: 760, y: 160, status: 'idle' },
    { id: 'sky', name: 'Sky-02', kind: 'drone', x: 760, y: 350, status: 'charging' },
    { id: 'roam', name: 'Roam-7', kind: 'rover', x: 500, y: 200, status: 'active', task: 'tidy' },
    { id: 'ada2', name: 'Ada-02', kind: 'humanoid', x: 140, y: 360, status: 'error' },
  ];

  return (
    <WebShell t={t} accent={accent} active="map">
      <TopBar t={t} accent={accent} breadcrumb={['Map', 'Lab · floor 1']} right={<>
        <button style={btnGhost3(t)}>2D</button>
        <button style={{ ...btnGhost3(t), background: t.bg3 }}>Plan</button>
        <button style={btnGhost3(t)}>3D</button>
      </>}/>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', flex: 1, overflow: 'hidden' }}>
        {/* Map */}
        <div style={{ position: 'relative', overflow: 'hidden', background: t.bg0 }}>
          <div className="or-grid" style={{ position: 'absolute', inset: 0, opacity: 0.5 }}/>
          <svg viewBox="0 0 920 540" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
            {/* rooms */}
            {rooms.map(r => (
              <g key={r.id}>
                <rect x={r.x} y={r.y} width={r.w} height={r.h} fill={t.bg1} stroke={t.line} strokeWidth="1.5"/>
                <text x={r.x + 10} y={r.y + 18} fontFamily="JetBrains Mono" fontSize="10" fill={t.t2} letterSpacing="1">{r.label.toUpperCase()}</text>
              </g>
            ))}

            {/* Heatmap of activity */}
            <g opacity="0.3">
              <circle cx="200" cy="170" r="60" fill={accent}/>
              <circle cx="500" cy="380" r="50" fill={accent}/>
              <circle cx="500" cy="200" r="35" fill={accent}/>
            </g>

            {/* Path of selected robot */}
            <path d="M 140 160 Q 180 140 220 170 T 280 200" fill="none" stroke={accent} strokeWidth="2" strokeDasharray="4 4" opacity="0.7"/>

            {/* Robots */}
            {robots.map(r => {
              const c = r.status === 'active' ? t.ok : r.status === 'idle' ? t.t2 : r.status === 'charging' ? t.info : t.danger;
              return (
                <g key={r.id} transform={`translate(${r.x}, ${r.y})`}>
                  {r.selected && (
                    <>
                      <circle r="22" fill="none" stroke={accent} strokeWidth="2"/>
                      <circle r="32" fill="none" stroke={accent} strokeWidth="1" opacity="0.4"/>
                    </>
                  )}
                  {r.status === 'active' && (
                    <circle r={14 + (tick % 2) * 4} fill="none" stroke={c} strokeWidth="1" opacity="0.4"/>
                  )}
                  <circle r="14" fill={t.bg2} stroke={c} strokeWidth="2"/>
                  <foreignObject x="-10" y="-10" width="20" height="20">
                    <div style={{ width: 20, height: 20, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <RobotGlyph kind={r.kind} size={16} color={c} accent={accent}/>
                    </div>
                  </foreignObject>
                  <text y="32" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="10" fill={t.t1}>{r.name}</text>
                </g>
              );
            })}
          </svg>

          {/* Map controls */}
          <div style={{ position: 'absolute', top: 16, left: 16, display: 'flex', flexDirection: 'column', gap: 4, background: t.bg1, border: `1px solid ${t.line}`, borderRadius: 6, padding: 4 }}>
            <button style={mapBtn(t)}>+</button>
            <button style={mapBtn(t)}>−</button>
            <div style={{ height: 1, background: t.line, margin: '2px 6px' }}/>
            <button style={mapBtn(t)}><Icon d={Icons.layers} size={14}/></button>
          </div>

          {/* Map legend */}
          <div style={{ position: 'absolute', bottom: 16, left: 16, background: t.bg1, border: `1px solid ${t.line}`, borderRadius: 6, padding: 10, fontFamily: OR.font.mono, fontSize: 10, color: t.t2 }}>
            <div style={{ marginBottom: 4 }}>Lab · 920 m² · scan 2 min ago</div>
            <div style={{ display: 'flex', gap: 10 }}>
              {[['active', t.ok], ['idle', t.t2], ['charging', t.info], ['error', t.danger]].map(([l, c]) => (
                <span key={l} style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  <Pip color={c} size={5}/> {l}
                </span>
              ))}
            </div>
          </div>
        </div>

        {/* Right rail — selected robot */}
        <div style={{ borderLeft: `1px solid ${t.line}`, background: t.bg1, padding: 18, overflow: 'auto' }}>
          <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, letterSpacing: '0.1em', marginBottom: 6 }}>SELECTED</div>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 14 }}>
            <div style={{ width: 44, height: 44, background: t.bg2, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <RobotGlyph kind="humanoid" size={32} color={t.t0} accent={accent}/>
            </div>
            <div>
              <div style={{ fontSize: 16, fontWeight: 500, fontFamily: OR.font.display, letterSpacing: '-0.01em' }}>Ada-01</div>
              <div style={{ fontSize: 11, fontFamily: OR.font.mono, color: t.t2 }}>Kitchen · zone 2</div>
            </div>
          </div>

          <div style={{ padding: 10, background: t.bg2, borderRadius: 8, marginBottom: 14 }}>
            <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, marginBottom: 4 }}>NOW</div>
            <div style={{ fontSize: 12, fontFamily: OR.font.mono, color: accent }}>cleanup-kitchen</div>
            <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, marginTop: 2 }}>step 3 / 7 · ~4 min remaining</div>
          </div>

          <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, letterSpacing: '0.1em', marginBottom: 8 }}>WAYPOINTS · 4</div>
          {[
            { n: 'kitchen-counter', d: 'visited 14:21', done: true },
            { n: 'sink', d: 'visited 14:22', done: true },
            { n: 'dishwasher', d: 'next', active: true },
            { n: 'pantry', d: 'queued', done: false },
          ].map((w, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 0', borderTop: i ? `1px solid ${t.line}` : 'none', fontSize: 11, color: w.active ? t.t0 : w.done ? t.t2 : t.t3, fontFamily: OR.font.mono }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: w.active ? accent : w.done ? t.ok : 'transparent', border: `1px solid ${w.active ? accent : w.done ? t.ok : t.bg4}` }}/>
              <span style={{ flex: 1 }}>{w.n}</span>
              <span style={{ color: t.t3 }}>{w.d}</span>
            </div>
          ))}

          <div style={{ marginTop: 18, display: 'flex', gap: 8 }}>
            <button style={{ ...btnGhost3(t), flex: 1 }}>Recall</button>
            <button style={{ ...btnPrim3(t, accent), flex: 1 }}>Set goal</button>
          </div>
        </div>
      </div>
    </WebShell>
  );
}

// ─────────────────────────────────────────────────────────────
// LOGS — system-wide observability
// ─────────────────────────────────────────────────────────────
function FleetLogs({ accent = '#FF8A2B', dark = true }) {
  const t = useTheme(dark, accent);

  const logs = [
    ['14:22:13.482', 'INFO',  'ada-01',   'planner',  'lifting → transport phase',                                  'INFO'],
    ['14:22:13.221', 'DEBUG', 'ada-01',   'motion',   'joint[7].target = 1.482 rad · current 1.471',                 'DEBUG'],
    ['14:22:12.998', 'INFO',  'ada-01',   'motion',   'grasp confirmed · 12N · slip 0.02',                            'INFO'],
    ['14:22:12.541', 'WARN',  'ada-01',   'grasp',    'low friction detected · re-grasp scheduled (attempt 2/3)',     'WARN'],
    ['14:22:11.832', 'INFO',  'ada-01',   'motion',   'arm trajectory accepted · ETA 1.4s · 24 waypoints',            'INFO'],
    ['14:22:11.044', 'DEBUG', 'rex-04',   'nav',      'localized at (12.4, -3.2) · cov 0.04',                         'DEBUG'],
    ['14:22:10.218', 'INFO',  'ada-01',   'planner',  'goal received: place mug in dishwasher',                       'INFO'],
    ['14:22:09.755', 'DEBUG', 'ada-01',   'vision',   '14 objects detected · max conf 0.94 (mug)',                    'DEBUG'],
    ['14:22:08.611', 'ERROR', 'ada-02',   'network',  'WebSocket connection lost · retry 1/5 in 4s',                  'ERROR'],
    ['14:22:08.412', 'INFO',  'roam-7',   'planner',  'docking sequence requested',                                   'INFO'],
    ['14:22:07.998', 'INFO',  'sky-02',   'power',    'charging started · 23% → target 80% in ~38min',                'INFO'],
    ['14:22:06.443', 'DEBUG', 'rex-04',   'sensors',  'lidar: 14400 points · 21fps',                                  'DEBUG'],
    ['14:22:05.221', 'INFO',  'arm-12',   'lifecycle','idle → entered standby (saved 14W)',                           'INFO'],
    ['14:22:04.118', 'WARN',  'ada-02',   'imu',      'temperature 78°C · throttling joint controller',               'WARN'],
    ['14:22:03.882', 'DEBUG', 'ada-01',   'sched',    'slot freed: cpu[3] · arm-trajectory',                          'DEBUG'],
    ['14:22:03.001', 'INFO',  'ada-01',   'skill',    'cleanup-kitchen v2.1.0 · step 3/7 began',                      'INFO'],
  ];

  const sevColor = (s) => ({ INFO: t.t1, DEBUG: t.t2, WARN: t.warn, ERROR: t.danger }[s] || t.t1);

  return (
    <WebShell t={t} accent={accent} active="logs">
      <TopBar t={t} accent={accent} breadcrumb={['Logs', 'all robots · live']} right={<>
        <span style={{ fontSize: 11, fontFamily: OR.font.mono, color: t.ok, padding: '5px 10px', display: 'flex', alignItems: 'center', gap: 6, border: `1px solid ${t.line}`, borderRadius: 4 }}>
          <Pip color={t.ok} pulse size={6}/> tailing
        </span>
      </>}/>
      <div style={{ display: 'grid', gridTemplateColumns: '200px 1fr 280px', flex: 1, overflow: 'hidden' }}>
        {/* Filter rail */}
        <div style={{ borderRight: `1px solid ${t.line}`, padding: 16, overflow: 'auto', background: t.bg1 }}>
          <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, letterSpacing: '0.1em', marginBottom: 8 }}>SEVERITY</div>
          {[
            ['ERROR', t.danger, 4],
            ['WARN', t.warn, 12],
            ['INFO', t.t1, 482],
            ['DEBUG', t.t2, 14820],
          ].map(([n, c, count], i) => (
            <label key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0', fontSize: 12, fontFamily: OR.font.mono, color: t.t1, cursor: 'pointer' }}>
              <span style={{ width: 12, height: 12, borderRadius: 3, background: n === 'DEBUG' ? 'transparent' : c, border: `1px solid ${c}` }}>
                {n !== 'DEBUG' && <Icon d={Icons.check} size={10} stroke="#0a0b0d" sw={3}/>}
              </span>
              <span style={{ flex: 1, color: c }}>{n}</span>
              <span style={{ fontSize: 10, color: t.t3 }}>{count}</span>
            </label>
          ))}

          <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, letterSpacing: '0.1em', marginTop: 18, marginBottom: 8 }}>ROBOT</div>
          {['ada-01', 'ada-02', 'rex-04', 'arm-12', 'sky-02', 'roam-7'].map((r, i) => (
            <label key={r} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 0', fontSize: 12, fontFamily: OR.font.mono, color: t.t1, cursor: 'pointer' }}>
              <span style={{ width: 12, height: 12, borderRadius: 3, border: `1px solid ${t.bg4}`, background: i < 3 ? accent : 'transparent' }}/>
              {r}
            </label>
          ))}

          <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, letterSpacing: '0.1em', marginTop: 18, marginBottom: 8 }}>SOURCE</div>
          {['planner', 'motion', 'vision', 'grasp', 'nav', 'network', 'sched'].map((s, i) => (
            <label key={s} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 0', fontSize: 12, fontFamily: OR.font.mono, color: t.t1, cursor: 'pointer' }}>
              <span style={{ width: 12, height: 12, borderRadius: 3, border: `1px solid ${t.bg4}` }}/>
              {s}
            </label>
          ))}
        </div>

        {/* Log table */}
        <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          {/* Search */}
          <div style={{ padding: 12, borderBottom: `1px solid ${t.line}` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', background: t.bg2, border: `1px solid ${t.line}`, borderRadius: 6, fontFamily: OR.font.mono, fontSize: 12, color: t.t1 }}>
              <Icon d={Icons.search} size={13} stroke={t.t2}/>
              <span style={{ color: t.t2 }}>severity:warn OR </span>
              <span style={{ color: accent }}>robot:ada-01</span>
              <span style={{ color: t.t2 }}> AND source:grasp</span>
              <span style={{ marginLeft: 'auto', fontSize: 10, color: t.t3 }}>504 results · live</span>
            </div>
          </div>

          {/* Histogram */}
          <div style={{ padding: '10px 16px', borderBottom: `1px solid ${t.line}`, display: 'flex', alignItems: 'flex-end', gap: 2, height: 60 }}>
            {Array.from({ length: 48 }, (_, i) => {
              const h = 10 + Math.abs(Math.sin(i / 3.2)) * 35 + Math.random() * 8;
              const isErr = i === 28;
              const isWarn = [12, 36, 41].includes(i);
              return (
                <div key={i} style={{
                  flex: 1, height: h,
                  background: isErr ? t.danger : isWarn ? t.warn : accent,
                  opacity: i > 40 ? 0.95 : 0.6,
                  borderRadius: '2px 2px 0 0',
                }}/>
              );
            })}
          </div>

          {/* Log lines */}
          <div style={{ flex: 1, overflow: 'auto', padding: '4px 12px', fontFamily: OR.font.mono, fontSize: 11, lineHeight: 1.7 }}>
            {logs.map((l, i) => (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '110px 50px 80px 80px 1fr', gap: 10,
                padding: '3px 8px', borderRadius: 3,
                background: i === 8 ? hexA(t.danger, 0.08) : i === 3 || i === 13 ? hexA(t.warn, 0.06) : 'transparent',
                color: t.t1,
              }}>
                <span style={{ color: t.t3 }}>{l[0]}</span>
                <span style={{ color: sevColor(l[1]), fontWeight: 600 }}>{l[1]}</span>
                <span style={{ color: t.t1 }}>{l[2]}</span>
                <span style={{ color: t.t2 }}>{l[3]}</span>
                <span style={{ color: sevColor(l[5]), whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{l[4]}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Detail panel */}
        <div style={{ borderLeft: `1px solid ${t.line}`, background: t.bg1, padding: 16, overflow: 'auto' }}>
          <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, letterSpacing: '0.1em', marginBottom: 10 }}>SELECTED EVENT</div>
          <div style={{ padding: 10, background: hexA(t.warn, 0.08), border: `1px solid ${hexA(t.warn, 0.3)}`, borderRadius: 6, marginBottom: 14 }}>
            <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.warn, fontWeight: 600, letterSpacing: '0.1em' }}>WARN · grasp</div>
            <div style={{ fontSize: 12, color: t.t0, fontFamily: OR.font.mono, marginTop: 4 }}>low friction detected · re-grasp scheduled</div>
            <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, marginTop: 6 }}>14:22:12.541 · ada-01</div>
          </div>

          <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, letterSpacing: '0.1em', marginBottom: 6 }}>CONTEXT</div>
          <div style={{ background: t.bg2, borderRadius: 6, padding: 10, fontFamily: OR.font.mono, fontSize: 11, color: t.t1, lineHeight: 1.7, marginBottom: 14 }}>
            <div><span style={{ color: t.t3 }}>object:</span> coffee_mug</div>
            <div><span style={{ color: t.t3 }}>conf:</span> 0.94</div>
            <div><span style={{ color: t.t3 }}>force:</span> 8.2N (target 12N)</div>
            <div><span style={{ color: t.t3 }}>slip:</span> 0.18 (max 0.05)</div>
            <div><span style={{ color: t.t3 }}>attempt:</span> 1/3</div>
            <div><span style={{ color: t.t3 }}>span_id:</span> 4af1c</div>
          </div>

          <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, letterSpacing: '0.1em', marginBottom: 6 }}>TRACE · 7 spans</div>
          <div style={{ fontFamily: OR.font.mono, fontSize: 10, color: t.t2 }}>
            {[
              ['planner.execute', 240],
              ['vision.detect', 80],
              ['grasp.plan', 60],
              ['motion.move_to', 320],
              ['grasp.attempt', 180],
              ['grasp.regrasp', 120],
              ['motion.transport', 0],
            ].map(([n, w], i) => (
              <div key={i} style={{ marginBottom: 4 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 2 }}>
                  <span>{n}</span><span>{w}ms</span>
                </div>
                <div style={{ height: 4, background: t.bg2, borderRadius: 99 }}>
                  <div style={{ width: `${(w / 320) * 100}%`, height: '100%', background: i === 5 ? t.warn : accent, borderRadius: 99 }}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </WebShell>
  );
}

// ─────────────────────────────────────────────────────────────
// SETTINGS
// ─────────────────────────────────────────────────────────────
function FleetSettings({ accent = '#FF8A2B', dark = true }) {
  const t = useTheme(dark, accent);

  return (
    <WebShell t={t} accent={accent} active="settings">
      <TopBar t={t} accent={accent} breadcrumb={['Settings', 'Hub & runtime']}/>
      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', flex: 1, overflow: 'hidden' }}>
        {/* Sub nav */}
        <div style={{ borderRight: `1px solid ${t.line}`, padding: 16, background: t.bg1 }}>
          {[
            { l: 'Hub & runtime', active: true, sub: 'Local-first config' },
            { l: 'Account', sub: 'kai@openrobot.app' },
            { l: 'Network', sub: '6 robots paired' },
            { l: 'Data & privacy', sub: 'On-device only' },
            { l: 'Notifications' },
            { l: 'Developer', sub: 'API · webhooks' },
            { l: 'Updates', sub: 'v0.9.4 · check 2h ago' },
            { l: 'About' },
          ].map((s, i) => (
            <div key={i} style={{
              padding: '10px 12px', borderRadius: 6, marginBottom: 2,
              background: s.active ? t.bg3 : 'transparent', cursor: 'pointer',
            }}>
              <div style={{ fontSize: 13, color: s.active ? t.t0 : t.t1, fontWeight: s.active ? 500 : 400 }}>{s.l}</div>
              {s.sub && <div style={{ fontSize: 10, fontFamily: OR.font.mono, color: t.t2, marginTop: 2 }}>{s.sub}</div>}
            </div>
          ))}
        </div>

        {/* Settings body */}
        <div style={{ overflow: 'auto', padding: 32 }}>
          <h1 style={{ fontFamily: OR.font.display, fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em', margin: '0 0 6px' }}>Hub & runtime</h1>
          <p style={{ color: t.t2, fontSize: 13, margin: 0, maxWidth: 540 }}>
            The openrobot hub runs on your network and orchestrates every robot. All data stays
            local unless you opt-in to cloud sync.
          </p>

          {/* Hub status card */}
          <div style={{ marginTop: 24, padding: 18, background: t.bg1, border: `1px solid ${t.line}`, borderRadius: 10, display: 'grid', gridTemplateColumns: '1fr auto', gap: 18, alignItems: 'center' }}>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <div style={{ width: 48, height: 48, borderRadius: 10, background: t.bg2, border: `1px solid ${t.line}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon d={Icons.cpu} size={24} stroke={accent}/>
              </div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 500 }}>hub.local · openrobot v0.9.4</div>
                <div style={{ fontSize: 12, fontFamily: OR.font.mono, color: t.t2, marginTop: 4, display: 'flex', gap: 12 }}>
                  <span style={{ color: t.ok, display: 'flex', alignItems: 'center', gap: 5 }}><Pip color={t.ok} pulse size={5}/> online</span>
                  <span>192.168.1.42</span>
                  <span>uptime 18d</span>
                  <span>load 0.42</span>
                </div>
              </div>
            </div>
            <button style={btnGhost3(t)}>Restart runtime</button>
          </div>

          {/* Toggle settings */}
          <SettingGroup t={t} title="Runtime">
            <SettingRow t={t} accent={accent} title="Auto-start on boot" desc="Launch the openrobot hub when this machine starts." on/>
            <SettingRow t={t} accent={accent} title="Allow remote access" desc="Connect from outside your network via secure relay." on/>
            <SettingRow t={t} accent={accent} title="Background recording" desc="Record telemetry continuously for time-travel debugging. Uses ~2GB/day." />
            <SettingRow t={t} accent={accent} title="Beta features" desc="Enable experimental skills and runtime features."/>
          </SettingGroup>

          <SettingGroup t={t} title="Cloud sync · optional">
            <SettingRow t={t} accent={accent} title="Sync skills" desc="Mirror installed skills across paired hubs." on/>
            <SettingRow t={t} accent={accent} title="Sync routines" desc="Mirror automation routines and triggers."/>
            <SettingRow t={t} accent={accent} title="Anonymous telemetry" desc="Help us improve the platform. No video, audio, or PII ever." on/>
          </SettingGroup>

          <SettingGroup t={t} title="Safety">
            <SettingRow t={t} accent={accent} title="Geofence enforcement" desc="Halt any robot that leaves a defined zone." on lock/>
            <SettingRow t={t} accent={accent} title="Force limits" desc="Cap actuator force per joint. Defaults are conservative." on lock/>
            <div style={{ padding: '14px 16px', borderTop: `1px solid ${t.line}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>Master E-stop button</div>
                <div style={{ fontSize: 11, fontFamily: OR.font.mono, color: t.t2, marginTop: 3 }}>paired · battery 92% · last test 4d ago</div>
              </div>
              <button style={{ ...btnGhost3(t), color: t.danger, borderColor: hexA(t.danger, 0.4) }}>Test e-stop</button>
            </div>
          </SettingGroup>

          <div style={{ marginTop: 32, paddingTop: 16, borderTop: `1px solid ${t.line}`, fontSize: 11, fontFamily: OR.font.mono, color: t.t3, display: 'flex', justifyContent: 'space-between' }}>
            <span>v0.9.4-rc1 · build 3a8f2e1 · MIT</span>
            <span>made by humans + their robots</span>
          </div>
        </div>
      </div>
    </WebShell>
  );
}

function SettingGroup({ t, title, children }) {
  return (
    <div style={{ marginTop: 24 }}>
      <div style={{ fontSize: 11, fontFamily: OR.font.mono, color: t.t2, letterSpacing: '0.12em', marginBottom: 8, textTransform: 'uppercase' }}>{title}</div>
      <div style={{ background: t.bg1, border: `1px solid ${t.line}`, borderRadius: 10, overflow: 'hidden' }}>
        {children}
      </div>
    </div>
  );
}
function SettingRow({ t, accent, title, desc, on, lock }) {
  const [v, setV] = React.useState(!!on);
  return (
    <div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: '1fr auto', gap: 18, alignItems: 'center', borderTop: `1px solid ${t.line}` }}>
      <div>
        <div style={{ fontSize: 13, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8 }}>
          {title}
          {lock && <Icon d={Icons.shield} size={11} stroke={t.t3}/>}
        </div>
        <div style={{ fontSize: 12, color: t.t2, marginTop: 3, lineHeight: 1.45 }}>{desc}</div>
      </div>
      <span onClick={() => !lock && setV(!v)} style={{
        width: 36, height: 20, borderRadius: 99, position: 'relative', cursor: lock ? 'default' : 'pointer',
        background: v ? accent : t.bg3, transition: 'background 0.2s', opacity: lock ? 0.7 : 1,
      }}>
        <span style={{
          position: 'absolute', top: 2, left: v ? 18 : 2,
          width: 16, height: 16, borderRadius: '50%', background: '#fff', transition: 'left 0.2s',
        }}/>
      </span>
    </div>
  );
}

const btnGhost3 = (t) => ({
  display: 'inline-flex', alignItems: 'center', gap: 6,
  padding: '6px 12px', fontSize: 12, fontWeight: 500, fontFamily: OR.font.sans,
  background: 'transparent', color: t.t0,
  border: `1px solid ${t.line}`, borderRadius: 6, cursor: 'pointer',
});
const btnPrim3 = (t, a) => ({
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
  padding: '6px 12px', fontSize: 12, fontWeight: 500, fontFamily: OR.font.sans,
  background: a, color: '#0A0B0D', border: 'none', borderRadius: 6, cursor: 'pointer',
});
const mapBtn = (t) => ({
  width: 28, height: 28, border: 'none', background: 'transparent', color: t.t1,
  borderRadius: 4, fontSize: 14, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
});

Object.assign(window, { FleetOverview, FleetMap, FleetLogs, FleetSettings });
