/* kpi-strip.jsx — sticky KPI strip + coin heat-rail */
function Sparkline({ data, color = "currentColor", height = 18, width = 80, fill = false, strokeWidth = 1 }) {
  if (!data || data.length < 2) return null;
  const min = Math.min(...data), max = Math.max(...data);
  const rng = max - min || 1;
  const step = width / (data.length - 1);
  const pts = data.map((v, i) => `${(i * step).toFixed(2)},${(height - ((v - min) / rng) * height).toFixed(2)}`);
  const path = `M ${pts.join(" L ")}`;
  const fillPath = `${path} L ${width},${height} L 0,${height} Z`;
  return (
    <svg width={width} height={height} style={{ display: "block", overflow: "visible" }}>
      {fill && (
        <path d={fillPath} fill={color} opacity="0.12" />
      )}
      <path d={path} fill="none" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function KpiStrip() {
  const [, force] = React.useState(0);
  React.useEffect(() => {
    return window.NTData.subscribe((evt) => {
      if (evt.type === "price") force(t => t + 1);
    });
  }, []);

  const agg = window.NTData.aggregates();
  const { fmtUSD, fmtPct } = window.NTData;
  const signals = window.NTData.getSignals();
  const phist = window.NTData.getPriceHistory();

  // KPI definitions
  const kpis = [
    {
      label: "Portfolio NAV",
      value: fmtUSD(agg.totalNAV),
      sub: <span><span className={agg.dayPnl >= 0 ? "fg-gain" : "fg-loss"}>{fmtPct(agg.dayPnlPct)}</span> <span className="fg-dim">today</span></span>,
      spark: agg.navHist,
      sparkColor: "var(--gain)",
    },
    {
      label: "Day P&L",
      value: fmtUSD(agg.dayPnl),
      sub: <span className="fg-dim">vs $128.4K avg</span>,
      gauge: { val: 0.71, of: 1, color: "var(--gain)", label: "of monthly" },
    },
    {
      label: "VaR(95)",
      value: fmtUSD(agg.var95),
      sub: <span><span className="fg-warn">{agg.var95Pct.toFixed(2)}%</span> <span className="fg-dim">limit {agg.var95Limit.toFixed(2)}%</span></span>,
      gauge: { val: agg.var95Pct / agg.var95Limit, of: 1, color: "var(--warn)", label: "of limit" },
    },
    {
      label: "Margin Used",
      value: `${(agg.marginUsed * 100).toFixed(1)}%`,
      sub: <span><span className="fg-info">{fmtUSD(agg.totalNAV * agg.marginUsed)}</span> <span className="fg-dim">of {fmtUSD(agg.totalNAV)}</span></span>,
      gauge: { val: agg.marginUsed, of: 1, color: "var(--info)", label: "" },
    },
    {
      label: "Open Pos / Orders",
      value: `${agg.openPositions} / ${agg.activeOrders}`,
      sub: <span className="fg-dim">across 4 venues</span>,
    },
    {
      label: "Active Signals",
      value: `${agg.signalsCount}`,
      sub: (
        <span style={{ display: "inline-flex", gap: 6 }}>
          <span className="fg-gain">{agg.buyCount} BUY</span>
          <span className="fg-dim">·</span>
          <span className="fg-warn">{agg.holdCount} HOLD</span>
          <span className="fg-dim">·</span>
          <span className="fg-loss">{agg.sellCount} SELL</span>
        </span>
      ),
    },
  ];

  return (
    <div className="kpi-strip">
      <style>{`
        .kpi-strip {
          display: grid;
          grid-template-columns: 1fr 360px;
          gap: 1px;
          background: var(--border);
          border-bottom: 1px solid var(--border);
          flex-shrink: 0;
        }
        .kpi-grid {
          display: grid;
          grid-template-columns: repeat(6, 1fr);
          gap: 1px;
          background: var(--border);
        }
        .kpi {
          background: var(--bg-elev);
          padding: 8px 12px;
          display: flex;
          flex-direction: column;
          gap: 3px;
          min-width: 0;
          position: relative;
        }
        .kpi__label {
          font-family: var(--font-mono); font-size: 9.5px;
          color: var(--fg-dim); letter-spacing: 0.12em; text-transform: uppercase;
          display: flex; align-items: center; justify-content: space-between; gap: 6px;
        }
        .kpi__value {
          font-family: var(--font-display); font-size: 19px;
          color: var(--fg); font-weight: 600; letter-spacing: -0.02em;
          line-height: 1.1;
          font-variant-numeric: tabular-nums;
        }
        .kpi__sub {
          font-family: var(--font-mono); font-size: 10px;
          color: var(--fg-muted);
          margin-top: 1px;
        }
        .kpi__spark {
          position: absolute; bottom: 4px; right: 8px; opacity: 0.7;
        }
        .kpi__gauge {
          display: flex; align-items: center; gap: 6px; margin-top: 4px;
        }
        .kpi__gauge-track {
          flex: 1; height: 3px; background: var(--bg-subtle); border-radius: 1px; overflow: hidden;
          position: relative;
        }
        .kpi__gauge-fill {
          height: 100%; border-radius: 1px;
          transition: width .4s ease;
        }
        .kpi__gauge-label {
          font-family: var(--font-mono); font-size: 9px;
          color: var(--fg-dim); letter-spacing: 0.06em;
        }

        /* Heat rail */
        .heatrail {
          background: var(--bg-elev);
          padding: 6px 12px;
          display: flex; flex-direction: column; gap: 4px;
        }
        .heatrail__header {
          display: flex; align-items: center; justify-content: space-between;
          font-family: var(--font-mono); font-size: 9.5px;
          color: var(--fg-dim); letter-spacing: 0.12em; text-transform: uppercase;
        }
        .heatrail__grid {
          display: grid;
          grid-template-columns: repeat(8, 1fr);
          gap: 2px;
        }
        .heatcell {
          padding: 4px 5px;
          border-radius: 2px;
          background: var(--bg-panel);
          border: 1px solid var(--border);
          display: flex; flex-direction: column; gap: 1px;
          cursor: pointer;
          transition: transform .12s, border-color .12s;
          min-width: 0;
        }
        .heatcell:hover { transform: translateY(-1px); border-color: var(--accent); }
        .heatcell__sym {
          font-family: var(--font-mono); font-size: 9px; font-weight: 700;
          color: var(--fg-2); letter-spacing: 0.06em;
          display: flex; align-items: center; gap: 3px;
        }
        .heatcell__dot {
          width: 4px; height: 4px; border-radius: 50%;
        }
        .heatcell__price {
          font-family: var(--font-mono); font-size: 10px; font-weight: 600;
          color: var(--fg); font-variant-numeric: tabular-nums;
          white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
        }
        .heatcell__pct {
          font-family: var(--font-mono); font-size: 8.5px;
          font-weight: 600;
          letter-spacing: 0;
        }
      `}</style>

      <div className="kpi-grid">
        {kpis.map((k, i) => (
          <div className="kpi" key={i}>
            <div className="kpi__label">
              <span>{k.label}</span>
            </div>
            <div className="kpi__value">{k.value}</div>
            <div className="kpi__sub">{k.sub}</div>
            {k.gauge && (
              <div className="kpi__gauge">
                <div className="kpi__gauge-track">
                  <div className="kpi__gauge-fill" style={{ width: `${Math.min(100, k.gauge.val * 100)}%`, background: k.gauge.color }} />
                </div>
              </div>
            )}
            {k.spark && (
              <div className="kpi__spark">
                <Sparkline data={k.spark} color={k.sparkColor} width={70} height={16} fill />
              </div>
            )}
          </div>
        ))}
      </div>

      <div className="heatrail">
        <div className="heatrail__header">
          <span>Tracked · 24h</span>
          <span className="fg-faint">{window.NTData.COINS.length} coins</span>
        </div>
        <div className="heatrail__grid">
          {window.NTData.COINS.map(c => {
            const hist = phist[c.symbol];
            const cur = hist[hist.length - 1];
            const prev = hist[Math.max(0, hist.length - 24)];
            const pct = ((cur - prev) / prev) * 100;
            const intensity = Math.min(1, Math.abs(pct) / 6);
            const pos = pct >= 0;
            const bgColor = pos
              ? `color-mix(in srgb, var(--gain) ${intensity * 40}%, var(--bg-panel))`
              : `color-mix(in srgb, var(--loss) ${intensity * 40}%, var(--bg-panel))`;
            const priceStr = cur < 1 ? `$${cur.toFixed(4)}` : cur < 100 ? `$${cur.toFixed(2)}` : `$${cur.toLocaleString(undefined, { maximumFractionDigits: 0 })}`;
            return (
              <div className="heatcell" key={c.symbol} style={{ background: bgColor }}>
                <div className="heatcell__sym">
                  <span className="heatcell__dot" style={{ background: c.chainColor }} />
                  {c.symbol}
                </div>
                <div className="heatcell__price">{priceStr}</div>
                <div className="heatcell__pct" style={{ color: pos ? "var(--gain)" : "var(--loss)" }}>
                  {pos ? "▲" : "▼"} {Math.abs(pct).toFixed(2)}%
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.KpiStrip = KpiStrip;
window.Sparkline = Sparkline;
