/* Desktop dashboard views — client-facing dummy data (Nova Systems demo) */

/* ===== Overview view — what a client's admin panel could look like ===== */
const ViewOverview = () => {
  const app = useApp();
  // KPIs per spec
  const users   = useLiveNumber(24860, { delta: 18, min: 24700, max: 25100 });
  const systems = useLiveNumber(128,   { delta: 1,  min: 122,   max: 134 });
  const revenue = useLiveNumber(89420, { delta: 120, min: 88500, max: 90600 });
  const health  = useLiveNumber(99.97, { delta: 0.02, min: 99.85, max: 100, decimals: 2 });
  const ops     = useLiveNumber(7890,  { delta: 90,  min: 7600,  max: 8200, interval: 900 });
  const aiSys   = useLiveNumber(24,    { delta: 1,   min: 20,    max: 28 });
  const clients = useLiveNumber(312,   { delta: 2,   min: 304,   max: 322 });
  const infra   = useLiveNumber(42,    { delta: 1,   min: 38,    max: 46 });
  const autos   = useLiveNumber(318,   { delta: 3,   min: 305,   max: 332 });
  const activeMod = useLiveNumber(42,  { delta: 1,   min: 38,    max: 46 });

  const [bars, setBars] = React.useState([38, 56, 44, 72, 60, 82, 68, 90, 78, 96, 84, 100]);
  const [range, setRange] = React.useState('30d');
  React.useEffect(() => {
    const id = setInterval(() => {
      setBars(prev => {
        const next = [...prev.slice(1), Math.max(20, Math.min(100, prev[prev.length-1] + (Math.random()*30-15)))];
        return next.map(v => Math.round(v));
      });
    }, 1500);
    return () => clearInterval(id);
  }, []);

  const openKpi = (k) => app.openModal({ kind: 'detail', item: k });

  return (
    <React.Fragment>
      <div className="dash-kpis">
        <Kpi label="Total Users"   value={fmt(users)} delta="+184 today" trend="up"
          onClick={() => openKpi({ eyebrow: 'USERS', title: 'Total Users', value: users, delta: '+184 today', rows: [
            { label: 'Active 24h', value: '8,420' }, { label: 'New this week', value: '+1,204' }, { label: 'Churn 30d', value: '0.8%' },
          ]})}/>
        <Kpi label="Active Systems" value={fmt(systems)} delta="+4 today" trend="up"
          onClick={() => openKpi({ eyebrow: 'SYSTEMS', title: 'Active Systems', value: systems, delta: '+4 last 24h', rows: [
            { label: 'AI', value: '24' }, { label: 'Web4', value: '18' }, { label: 'Infra', value: '42' },
          ]})}/>
        <Kpi label="Revenue · MTD"  value={'$' + fmt(revenue)} delta="+12.4%" trend="up"
          onClick={() => openKpi({ eyebrow: 'REVENUE', title: 'Revenue · MTD', value: revenue, delta: '+12.4% vs last month', rows: [
            { label: 'Subscriptions', value: '$62,108' }, { label: 'One-time', value: '$27,312' }, { label: 'Refunds', value: '−$840' },
          ]})}/>
        <Kpi label="System Health"  value={fmt(health,2)+'%'} delta="stable" trend="stable"
          onClick={() => openKpi({ eyebrow: 'HEALTH', title: 'System Health', value: Math.round(health*100)/100, delta: 'stable · 3 regions', rows: [
            { label: 'Regions', value: '3' }, { label: 'Uptime 30d', value: '99.98%' }, { label: 'Incidents', value: '0' },
          ]})}/>
      </div>

      <div className="dash-content">
        <section className="dash-chart-card">
          <div className="dash-card-head">
            <div>
              <div className="dash-card-eyebrow">Business Throughput</div>
              <div className="dash-card-title">Transactions / module · {range}</div>
            </div>
            <div className="dash-legend">
              <span><i style={{background:'#22d3ee'}}/> Live</span>
              <span><i style={{background:'#5eead4'}}/> Baseline</span>
              <button className="dash-pill-btn" onClick={() => {
                const next = range === '30d' ? '7d' : range === '7d' ? '24h' : '30d';
                setRange(next);
              }}>{range} <IconChevronDown size={11}/></button>
            </div>
          </div>
          <div className="dash-chart">
            <svg viewBox="0 0 720 200" preserveAspectRatio="none" width="100%" height="200">
              <defs>
                <linearGradient id="dch-fill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0" stopColor="#22d3ee" stopOpacity="0.45"/>
                  <stop offset="1" stopColor="#22d3ee" stopOpacity="0"/>
                </linearGradient>
                <linearGradient id="dch-line" x1="0" y1="0" x2="1" y2="0">
                  <stop offset="0" stopColor="#5eead4"/>
                  <stop offset="1" stopColor="#22d3ee"/>
                </linearGradient>
              </defs>
              {[40, 80, 120, 160].map(y => (
                <line key={y} x1="0" y1={y} x2="720" y2={y} stroke="rgba(255,255,255,0.04)" strokeDasharray="2 4"/>
              ))}
              <LiveChart bars={bars}/>
              <path d="M0,170 C50,168 100,160 150,162 C200,164 250,150 300,148 C350,146 400,138 450,140 C500,142 550,134 600,132 C650,130 700,128 720,128"
                stroke="rgba(255,255,255,0.18)" strokeWidth="1" strokeDasharray="3 3" fill="none"/>
            </svg>
            <div className="dash-chart-tip" style={{left:'70.8%'}}>
              <div className="dash-chart-tip-label">Live · {range}</div>
              <div className="dash-chart-tip-val"><strong className="live">{fmt(ops)}</strong> tx/min</div>
            </div>
            <div className="dash-chart-axis">
              <span>Apr 21</span><span>Apr 28</span><span>May 05</span><span>May 12</span><span>May 19</span>
            </div>
          </div>
        </section>

        <aside className="dash-action">
          <div className="dash-action-head">
            <div className="dash-action-title">Execution Console</div>
            <button className="dash-icon-btn small" onClick={() => app.toast('Console settings (demo)')}><IconMore size={12}/></button>
          </div>
          <div className="dash-action-metric">
            <ActionRow icon={<IconBrain size={13}/>}   label="AI Agents"     val={aiSys}    onClick={() => app.toast('Filter · AI agents')}/>
            <ActionRow icon={<IconUsers size={13}/>}   label="Clients"        val={clients}  onClick={() => app.toast('Filter · Clients')}/>
            <ActionRow icon={<IconCloud size={13}/>}   label="Infrastructure" val={infra}    onClick={() => app.toast('Filter · Infrastructure')}/>
            <ActionRow icon={<IconBolt size={13}/>}    label="Automations"    val={autos}    onClick={() => app.toast('Filter · Automations')}/>
          </div>
          <div className="dash-action-deploy">
            <div className="dash-deploy-bars">
              {bars.map((h, i) => <i key={i} style={{ height: h + '%', opacity: 0.35 + (i/bars.length)*0.65 }}/>)}
            </div>
            <div className="dash-deploy-meta">
              <span>Modules Active</span>
              <strong className="live">{activeMod} / 50</strong>
            </div>
          </div>
          <button className="dash-deploy-btn" onClick={() => app.openModal({ kind: 'deploy', target: 'nova-systems' })}>
            <IconRocket size={14}/> Deploy / Scale
            <IconArrowRight size={13}/>
          </button>
          <div className="dash-mini-list">
            <button className="dash-mini-row" onClick={() => app.toast('Nova Systems · sync')}><span className="dot ok"/>Nova Systems · sync<span className="t">2m</span></button>
            <button className="dash-mini-row" onClick={() => app.toast('Atlas Workspace · build')}><span className="dot ok"/>Atlas Workspace · build<span className="t">7m</span></button>
            <button className="dash-mini-row" onClick={() => app.toast({ msg: 'Orion Control · review', tone: 'warn' })}><span className="dot warn"/>Orion Control · review<span className="t">14m</span></button>
          </div>
        </aside>
      </div>

      <section className="dash-card">
        <div className="dash-card-head">
          <div>
            <div className="dash-card-eyebrow">Recent Activity</div>
            <div className="dash-card-title">Live Deployments</div>
          </div>
          <button className="dash-pill-btn" onClick={() => app.toast('Filter · All regions')}>All regions <IconChevronDown size={11}/></button>
        </div>
        <DeploymentsTable/>
      </section>

      <section className="dash-modules">
        <ModuleCard name="Nova Systems"    tag="SaaS · CORE"  status="healthy" metric="2,481 req/s"  accent="#22d3ee" progress={94}/>
        <ModuleCard name="Atlas Workspace" tag="WEB4"          status="healthy" metric="1,204 nodes" accent="#5eead4" progress={88}/>
        <ModuleCard name="Orion Control"   tag="LAYER-1"       status="syncing" metric="block 482,113" accent="#7c5cff" progress={72}/>
        <ModuleCard name="Web4 Commerce"   tag="MARKETPLACE"   status="healthy" metric="$48.2K NAV"  accent="#fbbf24" progress={91}/>
      </section>

      <section className="dash-card">
        <div className="dash-card-head">
          <div>
            <div className="dash-card-eyebrow">System Events</div>
            <div className="dash-card-title">Ledger · Last 24h</div>
          </div>
          <span className="dash-mini-pill"><span className="dot"/>Streaming</span>
        </div>
        <EventsList/>
      </section>
    </React.Fragment>
  );
};

/* ===== Reusable atoms ===== */
const Kpi = ({ label, value, delta, trend, onClick }) => (
  <button className="dash-kpi clickable" onClick={onClick}>
    <div className="dash-kpi-label">{label}</div>
    <div className="dash-kpi-row">
      <div className="dash-kpi-value live">{value}</div>
      <div className={"dash-kpi-delta " + trend}>
        {trend === 'up' ? '▲' : trend === 'down' ? '▼' : '◆'} {delta}
      </div>
    </div>
    <div className="dash-kpi-spark">
      <svg viewBox="0 0 80 24" preserveAspectRatio="none" width="100%" height="24">
        <path d="M0,18 L10,14 L20,16 L30,10 L40,12 L50,6 L60,8 L70,4 L80,2"
          fill="none" stroke="#22d3ee" strokeWidth="1.4" opacity="0.85"/>
        <path d="M0,18 L10,14 L20,16 L30,10 L40,12 L50,6 L60,8 L70,4 L80,2 L80,24 L0,24 Z"
          fill="#22d3ee" opacity="0.1"/>
      </svg>
    </div>
  </button>
);

const ActionRow = ({ icon, label, val, onClick }) => (
  <button className="dash-action-row" onClick={onClick}>
    <span className="dash-action-icon">{icon}</span>
    <span>{label}</span>
    <span className="dash-action-val live">{fmt(val)}</span>
  </button>
);

const LiveChart = ({ bars }) => {
  const W = 720;
  const N = bars.length;
  const step = W / (N - 1);
  const pts = bars.map((v, i) => [i * step, 180 - (v / 100) * 160]);
  const path = pts.reduce((acc, [x, y], i, a) => {
    if (i === 0) return `M${x},${y}`;
    const [px, py] = a[i - 1];
    const cx = (px + x) / 2;
    return `${acc} C${cx},${py} ${cx},${y} ${x},${y}`;
  }, '');
  const area = path + ` L${W},200 L0,200 Z`;
  const last = pts[pts.length - 1];
  return (
    <React.Fragment>
      <path d={area} fill="url(#dch-fill)"/>
      <path d={path} stroke="url(#dch-line)" strokeWidth="1.8" fill="none"/>
      <circle cx={last[0]} cy={last[1]} r="3.5" fill="#5eead4"/>
      <circle cx={last[0]} cy={last[1]} r="8" fill="#5eead4" opacity="0.2">
        <animate attributeName="r" values="6;12;6" dur="1.8s" repeatCount="indefinite"/>
        <animate attributeName="opacity" values="0.3;0;0.3" dur="1.8s" repeatCount="indefinite"/>
      </circle>
    </React.Fragment>
  );
};

const DEPLOYMENT_ROWS = [
  { name: 'nova-core',      region: 'us-east-1',  status: 'live',     ts: '03:42:18', ops: 4812 },
  { name: 'atlas-edge',     region: 'eu-west-2',  status: 'live',     ts: '03:39:54', ops: 3204 },
  { name: 'orion-rpc-3',    region: 'ap-south-1', status: 'syncing',  ts: '03:36:11', ops: 1820 },
  { name: 'support-pilot',  region: 'us-west-2',  status: 'live',     ts: '03:32:02', ops: 2417 },
  { name: 'web4-commerce',  region: 'eu-central', status: 'live',     ts: '03:28:47', ops: 1582 },
];
const DeploymentsTable = () => (
  <table className="dash-table">
    <thead>
      <tr><th>Service</th><th>Region</th><th>Status</th><th>Time</th><th>Tx/min</th></tr>
    </thead>
    <tbody>
      {DEPLOYMENT_ROWS.map((r, i) => <DeploymentRow key={i} {...r}/>)}
    </tbody>
  </table>
);
const DeploymentRow = ({ name, region, status, ts, ops }) => {
  const app = useApp();
  const live = useLiveNumber(ops, { delta: 40, min: ops - 200, max: ops + 200, interval: 1200 });
  return (
    <tr className="dash-table-row" onClick={() => app.openModal({
      kind: 'detail',
      item: {
        eyebrow: 'DEPLOYMENT',
        title: name,
        value: live,
        delta: `${region} · ${status}`,
        rows: [
          { label: 'Region', value: region },
          { label: 'Status', value: status },
          { label: 'Last update', value: ts },
        ]
      }
    })}>
      <td><span className="dash-table-name">{name}</span></td>
      <td><span className="dash-mono">{region}</span></td>
      <td><span className={"dash-pill-status " + status}><span className="dot"/>{status}</span></td>
      <td className="dash-mono">{ts}</td>
      <td className="dash-mono live">{fmt(live)}</td>
    </tr>
  );
};

const ModuleCard = ({ name, tag, status, metric, accent, progress }) => {
  const app = useApp();
  const live = useLiveNumber(progress, { delta: 0.6, min: progress - 6, max: progress + 4, decimals: 1, interval: 1100 });
  return (
    <button className="dash-module" style={{ '--c': accent }} onClick={() => app.openModal({
      kind: 'detail',
      item: {
        eyebrow: tag,
        title: name,
        value: live,
        delta: status,
        rows: [
          { label: 'Status', value: status },
          { label: 'Metric', value: metric },
          { label: 'Health', value: `${fmt(live,1)}%` },
        ]
      }
    })}>
      <div className="dash-module-head">
        <span className="dash-module-mark">{name[0]}</span>
        <div className="dash-module-id">
          <div className="dash-module-name">{name}</div>
          <div className="dash-module-tag">{tag}</div>
        </div>
        <span className={"dash-pill-status " + (status === 'syncing' ? 'syncing' : 'live')}>
          <span className="dot"/>{status}
        </span>
      </div>
      <div className="dash-module-bar"><i style={{ width: live + '%' }}/></div>
      <div className="dash-module-foot">
        <span className="dash-mono">{metric}</span>
        <span className="dash-mono live">{fmt(live,1)}%</span>
      </div>
    </button>
  );
};

const EVENTS = [
  { sev: 'ok',   txt: 'Nova Systems v2.4.1 deployed',     meta: 'us-east-1 · 03:42:18' },
  { sev: 'info', txt: 'Atlas Workspace module booted',     meta: 'eu-west-2 · 03:39:54' },
  { sev: 'ok',   txt: 'Orion block #482,113 finalized',    meta: 'global · 03:38:02' },
  { sev: 'warn', txt: 'Web4 Commerce · review pending',    meta: 'eu-central · 03:28:47' },
  { sev: 'ok',   txt: 'Support Pilot · context scaled',    meta: 'us-west-2 · 03:22:11' },
  { sev: 'info', txt: 'Auto-scale +4 instances',           meta: 'ap-south-1 · 03:14:50' },
];
const EventsList = () => {
  const app = useApp();
  return (
    <div className="dash-events">
      {EVENTS.map((e, i) => (
        <button key={i} className="dash-event" onClick={() => app.toast({ msg: e.txt, tone: e.sev === 'warn' ? 'warn' : 'ok' })}>
          <span className={"dash-event-sev " + e.sev}/>
          <span className="dash-event-txt">{e.txt}</span>
          <span className="dash-event-meta dash-mono">{e.meta}</span>
        </button>
      ))}
    </div>
  );
};

/* ===== Projects ===== */
const PROJECTS = [
  { name: 'Nova Systems',     kind: 'SaaS',   status: 'live',    lead: 'Alex Morgan',   prog: 94, region: 'us-east-1' },
  { name: 'Atlas Workspace',  kind: 'WEB4',   status: 'live',    lead: 'Maya Stone',    prog: 88, region: 'eu-west-2' },
  { name: 'Orion Control',    kind: 'L1',     status: 'syncing', lead: 'Ethan Carter',  prog: 72, region: 'global' },
  { name: 'Web4 Commerce',    kind: 'INVEST', status: 'live',    lead: 'Sofia Lane',    prog: 91, region: 'eu-central' },
  { name: 'Support Pilot',    kind: 'AI',     status: 'live',    lead: 'Alex Morgan',   prog: 96, region: 'us-west-2' },
  { name: 'GameHub Demo',     kind: 'GAMING', status: 'live',    lead: 'Ethan Carter',  prog: 99, region: 'global' },
];
const ViewProjects = () => {
  const app = useApp();
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all');
  const filtered = PROJECTS.filter(p =>
    (filter === 'all' || p.status === filter || p.kind.toLowerCase() === filter) &&
    p.name.toLowerCase().includes(q.toLowerCase())
  );
  return (
    <div className="view-pad">
      <div className="view-toolbar">
        <div className="view-search">
          <IconSearch size={12}/>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search projects…"/>
        </div>
        <div className="view-filters">
          {['all', 'live', 'syncing', 'ai', 'web4'].map(f => (
            <button key={f} className={"view-chip" + (filter === f ? ' active' : '')} onClick={() => setFilter(f)}>{f}</button>
          ))}
        </div>
        <button className="view-cta" onClick={() => app.openModal({ kind: 'newproj' })}>
          <IconPlus size={11}/> New project
        </button>
      </div>
      <div className="dash-modules" style={{padding:'0', marginTop: 12}}>
        {filtered.map(p => (
          <ModuleCard key={p.name} name={p.name} tag={p.kind + ' · ' + p.region} status={p.status === 'live' ? 'healthy' : 'syncing'} metric={`Lead: ${p.lead}`} accent={p.kind === 'AI' ? '#22d3ee' : p.kind === 'WEB4' ? '#5eead4' : p.kind === 'L1' ? '#7c5cff' : p.kind === 'GAMING' ? '#fb7185' : '#fbbf24'} progress={p.prog}/>
        ))}
      </div>
    </div>
  );
};

/* ===== AI Systems ===== */
const AGENTS = [
  { name: 'Nova Assistant',  role: 'Support · bilingual',  reqs: 12481, model: 'haiku-4-5' },
  { name: 'Atlas Writer',     role: 'Docs · summarization', reqs: 8421,  model: 'sonnet-4-5' },
  { name: 'Orion Verifier',   role: 'Tx validation',        reqs: 5104,  model: 'sonnet-4-5' },
  { name: 'Data Sentinel',    role: 'Anomaly detection',    reqs: 3094,  model: 'haiku-4-5' },
];
const ViewAI = () => {
  const app = useApp();
  return (
    <div className="view-pad">
      <div className="view-header">
        <div>
          <div className="dash-card-eyebrow">AI SYSTEMS</div>
          <div className="dash-card-title">Active agents</div>
        </div>
        <button className="view-cta" onClick={() => app.toast({ title: 'New agent', msg: 'Wizard opened (demo)' })}>
          <IconPlus size={11}/> New agent
        </button>
      </div>
      <div className="agent-grid">
        {AGENTS.map(a => <AgentCard key={a.name} {...a}/>)}
      </div>
    </div>
  );
};
const AgentCard = ({ name, role, reqs, model }) => {
  const app = useApp();
  const live = useLiveNumber(reqs, { delta: 30, min: reqs - 200, max: reqs + 200, interval: 900 });
  return (
    <button className="agent-card" onClick={() => app.toast({ title: name, msg: 'Agent dashboard (demo)' })}>
      <div className="agent-head">
        <div className="agent-avatar"><IconSparkle size={14}/></div>
        <div>
          <div className="agent-name">{name}</div>
          <div className="agent-role">{role}</div>
        </div>
        <span className="dash-pill-status live"><span className="dot"/>online</span>
      </div>
      <div className="agent-stat">
        <div>
          <div className="agent-stat-label">Requests · live</div>
          <div className="agent-stat-val live">{fmt(live)}</div>
        </div>
        <div>
          <div className="agent-stat-label">Model</div>
          <div className="agent-stat-val dash-mono" style={{fontSize: 12}}>{model}</div>
        </div>
      </div>
    </button>
  );
};

/* ===== Blockchain ===== */
const CHAINS = [
  { name: 'Orion Mainnet',  block: 482113, tps: 412, val: '124.8M', tag: 'L1', accent: '#7c5cff' },
  { name: 'Atlas L2',       block: 182041, tps: 1240, val: '42.1M', tag: 'L2', accent: '#5eead4' },
  { name: 'Nova Side',      block: 30481,  tps: 84,   val: '8.4M',  tag: 'SIDE', accent: '#22d3ee' },
];
const ViewBlockchain = () => (
  <div className="view-pad">
    <div className="view-header">
      <div>
        <div className="dash-card-eyebrow">BLOCKCHAIN</div>
        <div className="dash-card-title">Networks</div>
      </div>
    </div>
    <div className="chain-grid">
      {CHAINS.map(c => <ChainCard key={c.name} {...c}/>)}
    </div>
  </div>
);
const ChainCard = ({ name, block, tps, val, tag, accent }) => {
  const app = useApp();
  const lblock = useLiveNumber(block, { delta: 1, min: block, max: block + 500, interval: 1800 });
  const ltps = useLiveNumber(tps, { delta: tps * 0.08, min: tps * 0.6, max: tps * 1.4, interval: 1100 });
  return (
    <button className="chain-card" style={{'--c': accent}} onClick={() => app.toast({ title: name, msg: 'Network explorer (demo)' })}>
      <div className="chain-head">
        <div className="chain-mark">{tag}</div>
        <div className="chain-name">{name}</div>
        <span className="dash-pill-status live"><span className="dot"/>live</span>
      </div>
      <div className="chain-grid-stats">
        <div>
          <div className="chain-label">Block</div>
          <div className="chain-val live dash-mono">#{fmt(lblock)}</div>
        </div>
        <div>
          <div className="chain-label">TPS</div>
          <div className="chain-val live dash-mono">{fmt(Math.round(ltps))}</div>
        </div>
        <div>
          <div className="chain-label">Value locked</div>
          <div className="chain-val">${val}</div>
        </div>
      </div>
    </button>
  );
};

/* ===== Infra ===== */
const SERVERS = [
  { id: 'us-east-1-a',  cpu: 42, mem: 64, status: 'live' },
  { id: 'us-east-1-b',  cpu: 38, mem: 58, status: 'live' },
  { id: 'eu-west-2-a',  cpu: 71, mem: 82, status: 'live' },
  { id: 'eu-west-2-b',  cpu: 55, mem: 60, status: 'live' },
  { id: 'ap-south-1-a', cpu: 89, mem: 91, status: 'syncing' },
  { id: 'us-west-2-a',  cpu: 32, mem: 44, status: 'live' },
];
const ViewInfra = () => (
  <div className="view-pad">
    <div className="view-header">
      <div>
        <div className="dash-card-eyebrow">INFRASTRUCTURE</div>
        <div className="dash-card-title">Regions · instances</div>
      </div>
    </div>
    <div className="server-grid">
      {SERVERS.map(s => <ServerCard key={s.id} {...s}/>)}
    </div>
  </div>
);
const ServerCard = ({ id, cpu, mem, status }) => {
  const app = useApp();
  const lcpu = useLiveNumber(cpu, { delta: 4, min: Math.max(10, cpu - 20), max: Math.min(99, cpu + 20) });
  const lmem = useLiveNumber(mem, { delta: 3, min: Math.max(10, mem - 15), max: Math.min(99, mem + 15) });
  return (
    <button className="server-card" onClick={() => app.toast({ title: id, msg: 'SSH session opened (demo)' })}>
      <div className="server-head">
        <span className="server-id dash-mono">{id}</span>
        <span className={"dash-pill-status " + status}><span className="dot"/>{status}</span>
      </div>
      <div className="server-meter">
        <span>CPU</span>
        <div className="server-bar"><i style={{width: lcpu + '%'}}/></div>
        <span className="dash-mono live">{lcpu}%</span>
      </div>
      <div className="server-meter">
        <span>MEM</span>
        <div className="server-bar"><i style={{width: lmem + '%'}}/></div>
        <span className="dash-mono live">{lmem}%</span>
      </div>
    </button>
  );
};

/* ===== Data ===== */
const ViewData = () => {
  const app = useApp();
  return (
    <div className="view-pad">
      <div className="view-header">
        <div>
          <div className="dash-card-eyebrow">DATA INTELLIGENCE</div>
          <div className="dash-card-title">Pipelines · dashboards</div>
        </div>
      </div>
      <div className="view-empty">
        <IconChart size={28}/>
        <h4>3 dashboards configured</h4>
        <p>Connect a data source to start streaming analytics into your panel.</p>
        <button className="view-cta" onClick={() => app.toast({ title: 'Connect source', msg: 'Snowflake wizard (demo)' })}>Connect source</button>
      </div>
    </div>
  );
};

/* ===== Automation ===== */
const AUTOMATIONS = [
  { name: 'Deploy on push',     trig: 'GitHub · main',    runs: 184 },
  { name: 'Alert on failure',   trig: 'Sentry · error',   runs: 22  },
  { name: 'Weekly KPI digest',  trig: 'Cron · Mon 09:00', runs: 18  },
  { name: 'Auto-scale infra',   trig: 'Load > 80%',       runs: 96  },
];
const ViewAutomation = () => {
  const app = useApp();
  return (
    <div className="view-pad">
      <div className="view-header">
        <div>
          <div className="dash-card-eyebrow">AUTOMATION</div>
          <div className="dash-card-title">Workflows</div>
        </div>
        <button className="view-cta" onClick={() => app.toast('New workflow (demo)')}><IconPlus size={11}/> New workflow</button>
      </div>
      <div className="auto-list">
        {AUTOMATIONS.map(a => (
          <div key={a.name} className="auto-row">
            <span className="auto-ico"><IconBolt size={13}/></span>
            <div className="auto-c">
              <strong>{a.name}</strong>
              <span>Trigger · {a.trig}</span>
            </div>
            <span className="dash-mono">{a.runs} runs</span>
            <button className="auto-toggle on" onClick={(e) => { e.stopPropagation(); e.currentTarget.classList.toggle('on'); }}><i/></button>
          </div>
        ))}
      </div>
    </div>
  );
};

/* ===== Execution ===== */
const ViewExecution = () => (
  <div className="view-pad">
    <div className="view-header">
      <div>
        <div className="dash-card-eyebrow">EXECUTION LAYER</div>
        <div className="dash-card-title">Core orchestration</div>
      </div>
    </div>
    <div className="exec-hero">
      <Brandmark size={56}/>
      <h3>All systems are healthy.</h3>
      <p>3 regions · 7 modules · 99.98% uptime · last incident 14d ago.</p>
    </div>
  </div>
);

Object.assign(window, {
  ViewOverview, ViewProjects, ViewAI, ViewBlockchain, ViewInfra,
  ViewData, ViewAutomation, ViewExecution,
  Kpi, ActionRow, LiveChart, DeploymentsTable, ModuleCard, EventsList,
  AgentCard, ChainCard, ServerCard
});
