// Interactive K8s Host Metrics dashboard (rendered inside O2 Assistant + as a real screen)
const { useState: useStateDk, useMemo: useMemoDk } = React;

// 18 deterministic time series for "CPU Usage per Node (cores/sec)"
// Each line is a node with a base level + sustained spikes
const NODES = [
  { id: "aks-workers-18063413",    color: "#7E5DC4", base: 0.8 },
  { id: "ip-10-1-2-11.us-east",    color: "#D9CE57", base: 5.0, peak: { from: 18, to: 36, lift: 2.2 } },
  { id: "aks-o2aks1-np-sqkmr",     color: "#509FE0", base: 2.2 },
  { id: "aks-o2aks1-np-xddpd",     color: "#E5B450", base: 4.6, peak: { from: 24, to: 38, lift: 3.0 } },
  { id: "ip-10-125-151-47.eu-c",   color: "#D9CE57", base: 3.2 },
  { id: "ip-10-0-31-197.us-eas",   color: "#509FE0", base: 1.5 },
  { id: "aks-o2aks1-np-4dcqp",     color: "#5AAE5E", base: 3.6, peak: { from: 12, to: 22, lift: 1.4 } },
  { id: "aks-system-32873377-v",   color: "#D9CE57", base: 6.0 },
  { id: "ip-10-1-61-230.us-eas",   color: "#509FE0", base: 1.2 },
  { id: "ip-10-2-12-240.us-eas",   color: "#E25264", base: 1.0 },
  { id: "ip-10-0-63-70.us-eas",    color: "#7E5DC4", base: 2.0 },
  { id: "ip-10-0-81-231.us-eas",   color: "#A7C758", base: 1.6 },
  { id: "ip-10-1-1-160.us-eas",    color: "#D9CE57", base: 2.4 },
  { id: "ip-10-1-1-193.us-eas",    color: "#509FE0", base: 1.8 },
  { id: "aks-o2aks1-np-knc2l",     color: "#D45AB8", base: 2.0 },
  { id: "ip-10-2-179-138.us-ea",   color: "#E07B3C", base: 2.6 },
  { id: "ip-10-1-1-225.us-east",   color: "#5AAE5E", base: 1.7 },
  { id: "aks-o2aks1-np-dlch7",     color: "#3CADD9", base: 3.0 },
  { id: "aks-o2aks1-np-rjh2k",     color: "#D45AB8", base: 1.4 },
];

function rngK(seed) {
  let s = seed;
  return () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
}

function buildNodeSeries(node, n, idx) {
  const r = rngK(node.id.length * 13 + idx);
  return Array.from({ length: n }, (_, i) => {
    let v = node.base;
    if (node.peak && i >= node.peak.from && i <= node.peak.to) {
      v += node.peak.lift * (0.6 + Math.sin((i - node.peak.from) * 0.6) * 0.4);
    }
    // step-like fluctuations
    if (i % 4 === 0) v += (r() - 0.5) * 0.8;
    v += (r() - 0.5) * 0.3;
    return Math.max(0.05, v);
  });
}

const TIME_LABELS_DASH = ["12:10","12:12","12:14","12:16","12:18","12:20","12:22","12:24"];

// ─── Multi-line CPU chart with hover
function CPUChart({ series, title, height = 250 }) {
  const W = 1400;
  const H = height;
  const padL = 40, padR = 20, padT = 20, padB = 22;
  const cw = W - padL - padR;
  const ch = H - padT - padB;
  const maxY = 8;
  const yTicks = [0, 2, 4, 6, 8];
  const n = series[0].data.length;

  const [hoverIdx, setHoverIdx] = useStateDk(null);

  function xFor(i) { return padL + (i / (n - 1)) * cw; }
  function yFor(v) { return padT + ch - (v / maxY) * ch; }

  return (
    <div style={{
      background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8,
      padding: "12px 14px 14px", boxShadow: "var(--shadow-1)",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)", display: "flex", alignItems: "center", gap: 6 }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--muted-2)" strokeWidth="2"><circle cx="9" cy="6" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="9" cy="18" r="1.5"/><circle cx="15" cy="6" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="15" cy="18" r="1.5"/></svg>
          {title}
        </span>
        <span style={{ fontSize: 11, color: "var(--muted)", display: "flex", alignItems: "center", gap: 4 }}>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--ok)" }}/> now
        </span>
      </div>

      <div style={{ position: "relative" }}
           onMouseMove={(e) => {
             const r = e.currentTarget.getBoundingClientRect();
             const x = ((e.clientX - r.left) / r.width) * W;
             if (x < padL || x > W - padR) { setHoverIdx(null); return; }
             const idx = Math.round(((x - padL) / cw) * (n - 1));
             setHoverIdx(Math.max(0, Math.min(n - 1, idx)));
           }}
           onMouseLeave={() => setHoverIdx(null)}>
        <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: "block" }}>
          {/* Y grid */}
          {yTicks.map(v => {
            const y = yFor(v);
            return (
              <g key={v}>
                <line x1={padL} y1={y} x2={W - padR} y2={y} stroke="var(--border)" strokeWidth="0.5" strokeDasharray="2 3"/>
                <text x={padL - 8} y={y + 3} textAnchor="end" fontSize="9.5" fontFamily="JetBrains Mono" fill="var(--muted)">{v.toFixed(2)}</text>
              </g>
            );
          })}
          {/* Lines */}
          {series.map((s, si) => {
            const d = s.data.map((v, i) => `${i === 0 ? "M" : "L"}${xFor(i).toFixed(1)} ${yFor(v).toFixed(1)}`).join(" ");
            return <path key={si} d={d} stroke={s.color} strokeWidth="1.1" fill="none" opacity={hoverIdx === null ? 0.85 : 0.45}/>;
          })}
          {/* Hover crosshair + dots */}
          {hoverIdx !== null && (
            <g>
              <line x1={xFor(hoverIdx)} y1={padT} x2={xFor(hoverIdx)} y2={padT + ch} stroke="var(--ink)" strokeWidth="0.6" strokeDasharray="2 2" opacity=".5"/>
              {series.map((s, si) => (
                <circle key={si} cx={xFor(hoverIdx)} cy={yFor(s.data[hoverIdx])} r="3"
                        fill={s.color} stroke="white" strokeWidth="1"/>
              ))}
            </g>
          )}
          {/* X labels */}
          {TIME_LABELS_DASH.map((t, i) => {
            const x = padL + (i / (TIME_LABELS_DASH.length - 1)) * cw;
            return <text key={t} x={x} y={H - 6} textAnchor="middle" fontSize="9.5" fontFamily="JetBrains Mono" fill="var(--muted)">{t}</text>;
          })}
        </svg>
        {/* Floating tooltip */}
        {hoverIdx !== null && (
          <div style={{
            position: "absolute",
            left: `${(xFor(hoverIdx) / W) * 100}%`,
            top: 10,
            transform: `translateX(${hoverIdx > n * 0.7 ? "-100%" : "12px"})`,
            background: "var(--ink)",
            color: "var(--canvas)",
            padding: "8px 12px", borderRadius: 6,
            fontSize: 11, fontFamily: "JetBrains Mono",
            pointerEvents: "none", whiteSpace: "nowrap",
            boxShadow: "0 4px 14px rgba(0,0,0,0.15)",
            zIndex: 3, minWidth: 220,
          }}>
            <div style={{ color: "var(--muted-2)", fontSize: 10, marginBottom: 4 }}>
              {TIME_LABELS_DASH[Math.round((hoverIdx / (n - 1)) * (TIME_LABELS_DASH.length - 1))]}
            </div>
            {series.slice(0, 6).map((s, si) => (
              <div key={si} style={{ display: "flex", alignItems: "center", gap: 6, padding: "1px 0" }}>
                <span style={{ width: 8, height: 2, background: s.color }}/>
                <span style={{ flex: 1, color: "var(--muted-2)", overflow: "hidden", textOverflow: "ellipsis" }}>
                  {s.node.slice(0, 24)}…
                </span>
                <strong style={{ fontWeight: 600 }}>{s.data[hoverIdx].toFixed(2)}</strong>
              </div>
            ))}
            {series.length > 6 && (
              <div style={{ color: "var(--muted-2)", fontSize: 10, paddingTop: 2 }}>+ {series.length - 6} more</div>
            )}
          </div>
        )}
      </div>
      {/* Legend */}
      <div style={{
        display: "flex", flexWrap: "nowrap", gap: 14,
        overflowX: "auto",
        padding: "10px 0 0", fontSize: 11, color: "var(--ink-2)",
        scrollbarWidth: "thin",
      }}>
        {series.map((s, si) => (
          <span key={si} style={{ display: "flex", alignItems: "center", gap: 5, whiteSpace: "nowrap" }}>
            <svg width="16" height="8" viewBox="0 0 16 8">
              <line x1="0" y1="4" x2="16" y2="4" stroke={s.color} strokeWidth="1.5"/>
              <circle cx="8" cy="4" r="2.6" fill="var(--surface)" stroke={s.color} strokeWidth="1.6"/>
            </svg>
            <span style={{ color: "var(--ink-2)" }}>{s.node.slice(0, 22)}…</span>
          </span>
        ))}
        <button className="icon-btn" style={{ width: 16, height: 16 }}>
          <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="M9 6l6 6-6 6V6z"/></svg>
        </button>
      </div>
    </div>
  );
}

// ─── User & System rate chart (subset of nodes, smaller)
function CPURateChart() {
  const subset = NODES.slice(2, 7);
  const series = subset.map((node, i) => ({
    color: node.color, node: "user: " + node.id,
    data: Array.from({ length: 24 }, (_, j) => {
      let v = node.base * 0.4;
      if (j >= 4 && j <= 13) v += Math.sin((j - 4) * 0.5) * 1.6 + 0.8;
      return Math.max(0.1, v + (Math.sin(j + i) * 0.2));
    }),
  }));
  const W = 700, H = 220;
  const padL = 36, padR = 12, padT = 16, padB = 26;
  const cw = W - padL - padR, ch = H - padT - padB;
  const maxY = 7;
  const yTicks = [0, 1, 2, 3, 4, 5, 6, 7];

  return (
    <div style={{
      background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8,
      padding: "12px 14px 14px", boxShadow: "var(--shadow-1)",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>
          CPU Usage Rate — User &amp; System Modes per Node
        </span>
        <span style={{ fontSize: 11, color: "var(--muted)", display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--ok)" }}/> now
          <button className="icon-btn" style={{ width: 18, height: 18 }}><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M21 12a9 9 0 1 1-3-6.7"/></svg></button>
        </span>
      </div>
      <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: "block" }}>
        {yTicks.map(v => {
          const y = padT + ch - (v / maxY) * ch;
          return (
            <g key={v}>
              <line x1={padL} y1={y} x2={W - padR} y2={y} stroke="var(--border)" strokeWidth="0.5" strokeDasharray="2 3"/>
              <text x={padL - 6} y={y + 3} textAnchor="end" fontSize="9" fontFamily="JetBrains Mono" fill="var(--muted)">{v.toFixed(2)}</text>
            </g>
          );
        })}
        {series.map((s, si) => {
          const d = s.data.map((v, i) =>
            `${i === 0 ? "M" : "L"}${(padL + (i / (s.data.length - 1)) * cw).toFixed(1)} ${(padT + ch - (v / maxY) * ch).toFixed(1)}`
          ).join(" ");
          return <path key={si} d={d} stroke={s.color} strokeWidth="1.1" fill="none" opacity=".85"/>;
        })}
        {TIME_LABELS_DASH.slice(0, 7).map((t, i) => (
          <text key={t} x={padL + (i / 6) * cw} y={H - 8} textAnchor="middle" fontSize="9" fontFamily="JetBrains Mono" fill="var(--muted)">{t}</text>
        ))}
      </svg>
      <div style={{ display: "flex", alignItems: "center", gap: 12, paddingTop: 8, fontSize: 11, color: "var(--ink-2)", flexWrap: "wrap" }}>
        {series.map((s, si) => (
          <span key={si} style={{ display: "flex", alignItems: "center", gap: 5 }}>
            <svg width="14" height="6" viewBox="0 0 14 6"><line x1="0" y1="3" x2="14" y2="3" stroke={s.color} strokeWidth="1.5"/><circle cx="7" cy="3" r="2.4" fill="var(--surface)" stroke={s.color} strokeWidth="1.6"/></svg>
            <span>user: {s.node.slice(6, 24)}…</span>
          </span>
        ))}
        <span style={{ display: "inline-flex", alignItems: "center", gap: 3, color: "var(--muted)" }}>
          <button className="icon-btn" style={{ width: 14, height: 14 }}><svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="M15 6l-6 6 6 6V6z"/></svg></button>
          <span className="mono">1/12</span>
          <button className="icon-btn" style={{ width: 14, height: 14 }}><svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="M9 6l6 6-6 6V6z"/></svg></button>
        </span>
      </div>
    </div>
  );
}

// ─── Idle rate chart (right column)
function IdleRateChart() {
  const subset = NODES.slice(5, 13);
  const series = subset.map((node, i) => ({
    color: node.color, node: node.id,
    data: Array.from({ length: 24 }, () => 3 + (node.base * 1.8) + (Math.random() - 0.5) * 0.6),
  }));
  const W = 700, H = 220;
  const padL = 36, padR = 12, padT = 16, padB = 26;
  const cw = W - padL - padR, ch = H - padT - padB;
  const maxY = 18;
  const yTicks = [0, 3, 6, 9, 12, 15, 18];

  return (
    <div style={{
      background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8,
      padding: "12px 14px 14px", boxShadow: "var(--shadow-1)",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>CPU Idle Rate per Node</span>
        <span style={{ fontSize: 11, color: "var(--muted)" }}>now</span>
      </div>
      <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: "block" }}>
        {yTicks.map(v => {
          const y = padT + ch - (v / maxY) * ch;
          return (
            <g key={v}>
              <line x1={padL} y1={y} x2={W - padR} y2={y} stroke="var(--border)" strokeWidth="0.5" strokeDasharray="2 3"/>
              <text x={padL - 6} y={y + 3} textAnchor="end" fontSize="9" fontFamily="JetBrains Mono" fill="var(--muted)">{v.toFixed(2)}</text>
            </g>
          );
        })}
        {series.map((s, si) => {
          const d = s.data.map((v, i) =>
            `${i === 0 ? "M" : "L"}${(padL + (i / (s.data.length - 1)) * cw).toFixed(1)} ${(padT + ch - (v / maxY) * ch).toFixed(1)}`
          ).join(" ");
          return <path key={si} d={d} stroke={s.color} strokeWidth="1.1" fill="none" opacity=".85"/>;
        })}
        {["12:10","12:12","12:14","12:16","12:18"].map((t, i) => (
          <text key={t} x={padL + (i / 4) * cw} y={H - 8} textAnchor="middle" fontSize="9" fontFamily="JetBrains Mono" fill="var(--muted)">{t}</text>
        ))}
      </svg>
      <div style={{ display: "flex", alignItems: "center", gap: 12, paddingTop: 8, fontSize: 11, color: "var(--ink-2)", flexWrap: "wrap" }}>
        {series.slice(0, 4).map((s, si) => (
          <span key={si} style={{ display: "flex", alignItems: "center", gap: 5 }}>
            <svg width="14" height="6" viewBox="0 0 14 6"><line x1="0" y1="3" x2="14" y2="3" stroke={s.color} strokeWidth="1.5"/><circle cx="7" cy="3" r="2.4" fill="var(--surface)" stroke={s.color} strokeWidth="1.6"/></svg>
            <span>{s.node.slice(0, 18)}…</span>
          </span>
        ))}
      </div>
    </div>
  );
}

// ─── Bar chart "CPU Usage — Latest Snapshot per Node"
function CPUSnapshotChart() {
  const groups = 240;
  const colors = ["#D9CE57","#E5B450","#5AAE5E","#D45AB8","#E07B3C","#A7C758","#3CADD9","#D45AB8","#7E5DC4"];
  const bars = Array.from({ length: groups }, (_, i) => {
    const c = colors[i % colors.length];
    const base = 1.8 + Math.sin(i * 0.04) * 0.6;
    let v = base + (Math.random() - 0.3) * 1.2;
    if (i > 30 && i < 56 && Math.random() > 0.5) v += 1 + Math.random() * 5;
    return { color: c, v: Math.max(0.1, v) };
  });
  const W = 1400, H = 220;
  const padL = 36, padR = 12, padT = 16, padB = 26;
  const cw = W - padL - padR, ch = H - padT - padB;
  const barW = cw / groups - 0.5;
  const maxY = 8;

  return (
    <div style={{
      background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8,
      padding: "12px 14px 14px", boxShadow: "var(--shadow-1)",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>CPU Usage — Latest Snapshot per Node</span>
        <span style={{ fontSize: 11, color: "var(--muted)" }}>now</span>
      </div>
      <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: "block" }}>
        {[0, 2, 4, 6, 8].map(v => {
          const y = padT + ch - (v / maxY) * ch;
          return (
            <g key={v}>
              <line x1={padL} y1={y} x2={W - padR} y2={y} stroke="var(--border)" strokeWidth="0.5" strokeDasharray="2 3"/>
              <text x={padL - 6} y={y + 3} textAnchor="end" fontSize="9" fontFamily="JetBrains Mono" fill="var(--muted)">{v.toFixed(2)}</text>
            </g>
          );
        })}
        {bars.map((b, i) => {
          const x = padL + (i / groups) * cw;
          const h = (b.v / maxY) * ch;
          return (
            <rect key={i} x={x} y={padT + ch - h} width={barW} height={h} fill={b.color} opacity=".88"/>
          );
        })}
        {TIME_LABELS_DASH.map((t, i) => (
          <text key={t} x={padL + (i / (TIME_LABELS_DASH.length - 1)) * cw} y={H - 8} textAnchor="middle" fontSize="9" fontFamily="JetBrains Mono" fill="var(--muted)">{t}</text>
        ))}
      </svg>
    </div>
  );
}

// ─── Dashboard tabs (CPU / Memory / Disk)
function K8sHostDashboard({ inline = false, onBack }) {
  const [tab, setTab] = useStateDk("cpu");

  const cpuSeries = useMemoDk(() => NODES.map((node, i) => ({
    color: node.color, node: node.id,
    data: buildNodeSeries(node, 40, i),
  })), []);

  return (
    <div style={{
      flex: inline ? "" : 1, display: "flex", flexDirection: "column",
      minHeight: 0, background: "var(--bg)",
      borderRadius: inline ? 8 : 0,
      border: inline ? "1px solid var(--border)" : "none",
      overflow: "hidden",
    }}>
      {/* Header */}
      <div style={{
        height: inline ? 44 : 56, flexShrink: 0,
        display: "flex", alignItems: "center", gap: 12,
        padding: "0 16px",
        borderBottom: "1px solid var(--border)",
        background: "var(--canvas)",
      }}>
        {!inline && onBack && (
          <button className="icon-btn" onClick={onBack} title="Back">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
          </button>
        )}
        <span style={{ fontSize: 12, color: "var(--muted)" }}>default</span>
        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="var(--muted-2)" strokeWidth="1.6"><path d="m9 6 6 6-6 6"/></svg>
        <span style={{ fontSize: inline ? 14 : 18, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.01em" }}>
          K8s Host Metrics — CPU, Memory &amp; Disk per Node
        </span>
        <div style={{ flex: 1 }}/>
        <button className="btn" style={{ height: 28 }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>
          Past 15 Minutes <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="m6 9 6 6 6-6"/></svg>
        </button>
        <button className="btn" style={{ height: 28 }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M21 12a9 9 0 1 1-3-6.7"/></svg>
          Off <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="m6 9 6 6 6-6"/></svg>
        </button>
      </div>

      {/* Tabs */}
      <div style={{
        display: "flex", gap: 18, padding: "8px 18px",
        borderBottom: "1px solid var(--border)", background: "var(--surface)",
        flexShrink: 0,
      }}>
        {["cpu","memory","disk"].map(k => (
          <button key={k} onClick={() => setTab(k)}
            className={`tab-underline ${tab === k ? "active" : ""}`}
            style={{
              background: "none", border: "none", padding: "4px 4px",
              cursor: "pointer", textTransform: "capitalize", fontSize: 13,
            }}>
            {k}
          </button>
        ))}
      </div>

      {/* Body */}
      <div style={{
        flex: 1, overflowY: "auto", padding: 14, display: "flex", flexDirection: "column", gap: 14,
        minHeight: 0,
      }}>
        {tab === "cpu" && (
          <>
            <CPUChart series={cpuSeries} title="CPU Usage per Node (cores/sec)" height={250}/>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <CPURateChart/>
              <IdleRateChart/>
            </div>
            <CPUSnapshotChart/>
          </>
        )}
        {tab === "memory" && <DashEmpty label="Memory metrics"/>}
        {tab === "disk"   && <DashEmpty label="Disk metrics"/>}
      </div>
    </div>
  );
}

function DashEmpty({ label }) {
  return (
    <div style={{
      padding: 60, textAlign: "center", color: "var(--muted)",
      background: "var(--surface)", border: "1px dashed var(--border)", borderRadius: 8,
    }}>
      {label} — switch to the CPU tab for the live demo.
    </div>
  );
}

window.K8sHostDashboard = K8sHostDashboard;
