// ─── Dashboard Page ──────────────────────────────────────────────────────────
const { useState: uDS, useEffect: uDE, useRef: uDR } = React;

function useMetricsHistory(key, interval = 3000) {
  const [history, setHistory] = uDS(Array(60).fill(0));
  const metrics = usePolling('/api/system/metrics', interval);
  uDE(() => {
    if (!metrics) return;
    const val = key === 'cpu' ? metrics.cpu_pct : metrics.ram_pct;
    setHistory(prev => [...prev.slice(-59), val]);
  }, [metrics]);
  return [history, metrics];
}

function useNetHistory(interval = 3000) {
  const [prevCounters, setPrev] = uDS(null);
  const [inHistory, setIn] = uDS(Array(60).fill(0));
  const [outHistory, setOut] = uDS(Array(60).fill(0));
  const net = usePolling('/api/system/network', interval);
  uDE(() => {
    if (!net) return;
    if (prevCounters) {
      const inMBps = Math.max(0, (net.bytes_recv - prevCounters.bytes_recv) / 1e6 / (interval / 1000));
      const outMBps = Math.max(0, (net.bytes_sent - prevCounters.bytes_sent) / 1e6 / (interval / 1000));
      setIn(prev => [...prev.slice(-59), +inMBps.toFixed(2)]);
      setOut(prev => [...prev.slice(-59), +outMBps.toFixed(2)]);
    }
    setPrev(net);
  }, [net]);
  return [inHistory, outHistory];
}

function formatUptime(seconds) {
  const d = Math.floor(seconds / 86400);
  const h = Math.floor((seconds % 86400) / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  return [String(d).padStart(2,'0'), String(h).padStart(2,'0'), String(m).padStart(2,'0')];
}

function DashboardPage() {
  const [cpuHistory, metrics] = useMetricsHistory('cpu', 3000);
  const [ramHistory]          = useMetricsHistory('ram', 3000);
  const [netInHistory, netOutHistory] = useNetHistory(3000);
  const disks     = usePolling('/api/system/disks', 10000);
  const processes = usePolling('/api/system/processes', 5000);

  const cpu = metrics ? metrics.cpu_pct : 0;
  const ram = metrics ? metrics.ram_pct : 0;
  const ramUsed  = metrics ? metrics.ram_used_gb : 0;
  const ramTotal = metrics ? metrics.ram_total_gb : 0;
  const uptimeParts = metrics ? formatUptime(metrics.uptime_seconds) : ['--','--','--'];
  const loadAvg = metrics ? metrics.load_avg.map(v => v.toFixed(2)).join(' / ') : '—';
  const kernel   = metrics ? metrics.kernel   : '—';
  const os_name  = metrics ? metrics.os       : '—';
  const hostname = metrics ? metrics.hostname : '—';

  const diskRows = disks || [];
  const procRows = (processes || []).slice(0, 6).map(p => ({ ...p, cpu: p.cpu_pct, mem: p.mem_pct }));

  const netIn  = netInHistory[netInHistory.length - 1] || 0;
  const netOut = netOutHistory[netOutHistory.length - 1] || 0;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gridTemplateRows: 'auto auto auto auto', gap: 8, padding: 10, height: '100%', boxSizing: 'border-box', overflow: 'auto' }}>

      {/* CPU */}
      <Panel title="CPU USAGE" style={{ gridColumn: '1', gridRow: '1' }}>
        <div style={{ padding: '12px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <RadialGauge value={cpu} max={100} color="#00c8ff" size={110} label="cpu" warning={70} critical={90} />
          <LineChart data={cpuHistory} color="#00c8ff" height={50} />
          <div style={{ padding: '4px 12px 8px', width: '100%', boxSizing: 'border-box' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, color: 'rgba(0,200,255,0.4)', fontFamily: "'Share Tech Mono',monospace" }}>
              <span>LOAD {loadAvg}</span>
            </div>
          </div>
        </div>
      </Panel>

      {/* RAM */}
      <Panel title="MEMORY" style={{ gridColumn: '2', gridRow: '1' }}>
        <div style={{ padding: '12px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <RadialGauge value={ram} max={100} color="#00ff88" size={110} label="ram" warning={75} critical={90} />
          <LineChart data={ramHistory} color="#00ff88" height={50} />
          <div style={{ padding: '4px 12px 8px', width: '100%', boxSizing: 'border-box' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, color: 'rgba(0,255,136,0.4)', fontFamily: "'Share Tech Mono',monospace" }}>
              <span>{ramUsed.toFixed(1)} GB USED</span><span>{ramTotal.toFixed(0)} GB TOTAL</span>
            </div>
          </div>
        </div>
      </Panel>

      {/* Uptime & System */}
      <Panel title="UPTIME & SYSTEM" style={{ gridColumn: '3', gridRow: '1' }}>
        <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <div style={{ fontSize: 11, color: 'rgba(0,200,255,0.4)', letterSpacing: '0.2em', fontFamily: "'Share Tech Mono',monospace", marginBottom: 10 }}>UPTIME</div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
              {[['DAYS', 0], ['HRS', 1], ['MIN', 2]].map(([l, i]) => (
                <div key={l} style={{ textAlign: 'center', flex: 1, background: 'rgba(0,200,255,0.05)', border: '1px solid rgba(0,200,255,0.12)', padding: '8px 4px' }}>
                  <div style={{ fontSize: 28, fontWeight: 700, color: '#00c8ff', fontFamily: "'Share Tech Mono',monospace", lineHeight: 1, textShadow: '0 0 8px #00c8ff' }}>{uptimeParts[i]}</div>
                  <div style={{ fontSize: 11, color: 'rgba(0,200,255,0.4)', letterSpacing: '0.1em', fontFamily: "'Share Tech Mono',monospace", marginTop: 3 }}>{l}</div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ borderTop: '1px solid rgba(0,200,255,0.1)', paddingTop: 12, display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13, fontFamily: "'Share Tech Mono',monospace" }}>
            {[['KERNEL', kernel, '#00c8ff'], ['OS', os_name, '#00c8ff'], ['HOSTNAME', hostname, '#ffd700']].map(([k, v, c]) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ color: 'rgba(0,200,255,0.4)' }}>{k}</span>
                <span style={{ color: c, maxWidth: 150, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v}</span>
              </div>
            ))}
          </div>
        </div>
      </Panel>

      {/* Network Overview */}
      <Panel title="NETWORK I/O" style={{ gridColumn: '4', gridRow: '1' }}>
        <div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <DonutChart segments={[{ value: Math.max(netIn,0.1), color: '#00c8ff' }, { value: Math.max(netOut,0.1), color: '#00ff88' }]} size={90} value={(netIn+netOut).toFixed(1)} label="mb/s" />
          <div style={{ marginTop: 4 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
              <span style={{ fontSize: 14, color: '#00c8ff', fontFamily: "'Share Tech Mono',monospace" }}>↑ IN: {netIn.toFixed(2)} MB/s</span>
              <span style={{ fontSize: 14, color: '#00ff88', fontFamily: "'Share Tech Mono',monospace" }}>↓ OUT: {netOut.toFixed(2)} MB/s</span>
            </div>
            <LineChart data={netInHistory} color="#00c8ff" height={35} />
            <LineChart data={netOutHistory} color="#00ff88" height={35} />
          </div>
        </div>
      </Panel>

      {/* Disk */}
      <Panel title="DISK & STORAGE" style={{ gridColumn: '1 / 3', gridRow: '2' }}>
        <div style={{ padding: 12 }}>
          {diskRows.length === 0
            ? <div style={{ color: 'rgba(0,200,255,0.3)', fontFamily: "'Share Tech Mono',monospace", fontSize: 13 }}>Loading...</div>
            : diskRows.map(d => (
                <HorizontalBar key={d.mount} label={d.mount} sublabel={`${d.used_gb} GB / ${d.total_gb} GB`}
                  value={d.used_gb} max={d.total_gb}
                  color={d.pct > 85 ? '#ff2244' : d.pct > 70 ? '#ffd700' : '#00c8ff'} height={8} />
              ))
          }
        </div>
      </Panel>

      {/* Process Table */}
      <Panel title="TOP PROCESSES" style={{ gridColumn: '3 / 5', gridRow: '2' }}>
        <div style={{ padding: '8px 0', overflow: 'auto' }}>
          <DataTable
            columns={[
              { key: 'pid',  label: 'PID' },
              { key: 'name', label: 'NAME' },
              { key: 'cpu',  label: 'CPU %', render: r => <span style={{ color: r.cpu > 5 ? '#ffd700' : '#00ff88' }}>{(r.cpu||0).toFixed(1)}</span> },
              { key: 'mem',  label: 'MEM %', render: r => <span style={{ color: '#00c8ff' }}>{(r.mem||0).toFixed(1)}</span> },
              { key: 'status', label: 'STATUS', render: r => <StatusBadge status={r.status} /> },
            ]}
            rows={procRows}
          />
        </div>
      </Panel>

      {/* System Events */}
      <Panel title="SYSTEM EVENTS" style={{ gridColumn: '1 / 5', gridRow: '3' }}>
        <SystemEventFeed />
      </Panel>
    </div>
  );
}

function SystemEventFeed() {
  const events = usePolling('/api/system/events', 15000) || [];
  const levelColor = { info: '#00c8ff', warning: '#ffd700', error: '#ff2244', INFO: '#00c8ff', WARNING: '#ffd700', ERROR: '#ff2244' };

  return (
    <div style={{ padding: '4px 0', overflow: 'auto', maxHeight: 180 }}>
      {events.length === 0
        ? <div style={{ padding: '10px 14px', color: 'rgba(0,200,255,0.3)', fontFamily: "'Share Tech Mono',monospace", fontSize: 13 }}>Loading events...</div>
        : events.map((e, i) => {
            const color = levelColor[e.level] || '#00c8ff';
            return (
              <div key={i} style={{ display: 'flex', gap: 10, padding: '6px 12px', borderBottom: '1px solid rgba(0,200,255,0.05)', alignItems: 'flex-start' }}>
                <span style={{ fontSize: 13, color: 'rgba(0,200,255,0.35)', fontFamily: "'Share Tech Mono',monospace", flexShrink: 0, marginTop: 1 }}>{e.ts}</span>
                <span style={{ width: 4, height: 4, borderRadius: '50%', background: color, boxShadow: `0 0 4px ${color}`, marginTop: 5, flexShrink: 0 }} />
                <span style={{ fontSize: 13, color: color === '#00c8ff' ? 'rgba(220,240,255,0.7)' : color, fontFamily: "'Share Tech Mono',monospace", overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.msg}</span>
              </div>
            );
          })
      }
    </div>
  );
}

Object.assign(window, { DashboardPage });
