const { useState: useStateM, useMemo: useMemoM } = React;
const {
  IconSearch: IconSearchM, IconChevDown: IconChevDownM, IconClock: IconClockM,
  IconRefresh: IconRefreshM, IconChart: IconChartM, IconHistogram: IconHistogramM,
  IconPlus: IconPlusM, IconShare: IconShareM, IconMenu: IconMenuM, IconSave: IconSaveM,
} = window.Icons;

// ─── Deterministic series for metric panels
function rng(seed) {
  let s = seed;
  return () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
}

function metricSeries(seed, len, opts = {}) {
  const r = rng(seed);
  const { trend = 0, base = 50, noise = 12, spikeAt = -1, spike = 40 } = opts;
  return Array.from({ length: len }, (_, i) => {
    const trended = base + trend * i;
    const noisy = trended + Math.sin(i * 0.35) * noise * 0.7 + (r() - 0.5) * noise;
    const spiked = i === spikeAt ? noisy + spike : noisy;
    return Math.max(0, Math.round(spiked * 10) / 10);
  });
}

// 8 metric panels — AI inference platform
const PANELS = [
  { id: "tps",   title: "LLM requests / sec",       unit: " req/s",   color: "var(--accent)",   data: metricSeries(1, 60, { base: 847, trend: 2.1, noise: 84, spikeAt: 38, spike: 420 }) },
  { id: "err",   title: "Error rate",               unit: "%",         color: "var(--err)",      data: metricSeries(2, 60, { base: 0.31, trend: 0.002, noise: 0.09, spikeAt: 41, spike: 2.8 }) },
  { id: "p99",   title: "P99 inference latency",    unit: " ms",       color: "var(--warn)",     data: metricSeries(3, 60, { base: 1847, trend: 3.2, noise: 220, spikeAt: 41, spike: 2800 }) },
  { id: "tok",   title: "Token throughput",         unit: " tok/s",    color: "var(--accent)",   data: metricSeries(4, 60, { base: 142000, trend: 420, noise: 12000, spikeAt: 38, spike: 38000 }) },
  { id: "gpu",   title: "GPU utilization",          unit: "%",         color: "var(--hist-2)",   data: metricSeries(5, 60, { base: 84, trend: 0.08, noise: 7, spikeAt: 38, spike: 14 }) },
  { id: "cost",  title: "Cost / hour",              unit: " USD",      color: "var(--warn)",     data: metricSeries(6, 60, { base: 28.4, trend: 0.06, noise: 3.2, spikeAt: 38, spike: 8.4 }) },
  { id: "emb",   title: "Embedding QPS",            unit: " req/s",    color: "var(--ok)",       data: metricSeries(7, 60, { base: 3200, trend: 6, noise: 280, spikeAt: 56, spike: 1800 }) },
  { id: "cache", title: "Cache hit rate",           unit: "%",         color: "var(--hist)",     data: metricSeries(8, 60, { base: 64, trend: 0.04, noise: 4.2 }) },
];

function Spark({ data, color, h = 60 }) {
  const W = 240, H = h;
  const max = Math.max(...data) * 1.05;
  const min = Math.min(...data) * 0.95;
  const span = max - min || 1;
  const stepX = W / (data.length - 1);
  const pts = data.map((v, i) => [i * stepX, H - ((v - min) / span) * H]);
  const path = pts.map((p, i) => `${i === 0 ? "M" : "L"}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(" ");
  const area = `${path} L ${W} ${H} L 0 ${H} Z`;
  return (
    <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: "block" }}>
      <path d={area} fill={color} opacity=".15"/>
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" />
    </svg>
  );
}

function MetricCard({ panel }) {
  const cur = panel.data[panel.data.length - 1];
  const prev = panel.data[Math.max(0, panel.data.length - 8)];
  const delta = ((cur - prev) / prev) * 100;
  const up = delta > 0;
  const isErrUp = panel.id === "err" && up;
  return (
    <div style={{
      background: "var(--surface)", border: "1px solid var(--border)",
      borderRadius: 8, padding: 14, display: "flex", flexDirection: "column", gap: 8,
      boxShadow: "var(--shadow-1)",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink)" }}>{panel.title}</span>
        <span className="mono pill" style={{
          background: isErrUp ? "var(--err-bg)" : "var(--canvas)",
          color: isErrUp ? "var(--err)" : (up ? "var(--ok)" : "var(--muted)"),
          border: "1px solid var(--border)",
        }}>
          {up ? "▲" : "▼"} {Math.abs(delta).toFixed(1)}%
        </span>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
        <span className="mono" style={{ fontSize: 22, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.01em" }}>
          {typeof cur === "number" && cur >= 1000 ? cur.toLocaleString() : cur}
        </span>
        <span style={{ fontSize: 11, color: "var(--muted)" }}>{panel.unit}</span>
      </div>
      <Spark data={panel.data} color={panel.color} />
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: -4 }}>
        <span className="mono" style={{ fontSize: 9, color: "var(--muted)" }}>1h ago</span>
        <span className="mono" style={{ fontSize: 9, color: "var(--muted)" }}>now</span>
      </div>
    </div>
  );
}

function MetricsToolbar({ stream, onStream }) {
  return (
    <div style={{
      height: 48, flexShrink: 0,
      display: "flex", alignItems: "center", gap: 10,
      padding: "0 16px",
      background: "var(--canvas)",
      borderBottom: "1px solid var(--border)",
    }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        background: "var(--surface)", border: "1px solid var(--border)",
        borderRadius: 6, padding: "0 12px", height: 32, minWidth: 220,
      }}>
        <IconSearchM size={13} style={{ color: "var(--muted)" }}/>
        <input placeholder="Search metrics..." style={{
          border: "none", background: "transparent", outline: "none",
          fontSize: 12, color: "var(--ink)", flex: 1, fontFamily: "inherit",
        }}/>
      </div>

      <button className="btn" style={{ minWidth: 180, justifyContent: "space-between" }}>
        <span>ai_inference · us-east-1</span><IconChevDownM size={12}/>
      </button>

      <div style={{ flex: 1 }} />

      <button className="btn" style={{ height: 32 }}>
        <IconClockM size={13}/><span>Past 1 Hour</span><IconChevDownM size={12}/>
      </button>
      <button className="btn" style={{ height: 32 }}>
        <IconRefreshM size={13}/><span>30s</span><IconChevDownM size={12}/>
      </button>
      <button className="btn-primary" style={{ height: 32, padding: "0 14px" }}>
        <IconPlusM size={13}/><span>Add panel</span>
      </button>
    </div>
  );
}

function MetricsBreadcrumb() {
  return (
    <div style={{
      padding: "10px 16px 4px",
      display: "flex", alignItems: "center", gap: 8,
    }}>
      <span style={{ fontSize: 18, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.01em" }}>
        AI inference health
      </span>
      <span className="mono pill" style={{
        background: "var(--accent-bg)", color: "var(--accent-fg)",
        border: "1px solid var(--accent-line)",
      }}>
        live
      </span>
      <span style={{ fontSize: 11, color: "var(--muted)" }}>
        Auto-refreshing every 30 seconds
      </span>
    </div>
  );
}

function MetricsScreen() {
  return (
    <div style={{
      flex: 1, display: "flex", flexDirection: "column", minHeight: 0,
      background: "var(--bg)",
    }}>
      <MetricsToolbar />
      <div style={{
        flex: 1, overflow: "auto",
        padding: "0 16px 16px",
      }}>
        <MetricsBreadcrumb />
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))",
          gap: 12,
          paddingTop: 12,
        }}>
          {PANELS.map(p => <MetricCard key={p.id} panel={p} />)}
        </div>
      </div>
    </div>
  );
}

window.MetricsScreen = MetricsScreen;
