/* risk-pane.jsx — VaR radial gauge, exposure stacked bar, drawdown sparkline, margin headroom */
function RadialGauge({ value, limit, label, color, size = 130, sublabel }) {
  const r = size / 2 - 12;
  const cx = size / 2, cy = size / 2;
  const sweep = 0.78; // 280°
  const startAngle = 135 + 90; // we'll handle via rotate
  const circ = 2 * Math.PI * r;
  const dashLen = circ * sweep;
  const ratio = Math.min(1, value / limit);
  const fillLen = dashLen * ratio;

  // tick marks
  const tickCount = 11;
  const ticks = Array.from({ length: tickCount }, (_, i) => {
    const a = -225 + (i * 280) / (tickCount - 1); // degrees from top
    const rad = (a * Math.PI) / 180;
    const inner = r - 4, outer = r + 4;
    return {
      x1: cx + Math.cos(rad) * inner, y1: cy + Math.sin(rad) * inner,
      x2: cx + Math.cos(rad) * outer, y2: cy + Math.sin(rad) * outer,
      lit: i / (tickCount - 1) <= ratio,
    };
  });

  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        {/* base arc */}
        <circle cx={cx} cy={cy} r={r}
                fill="none" stroke="var(--bg-subtle)" strokeWidth="6"
                strokeDasharray={`${dashLen} ${circ}`}
                strokeLinecap="round"
                transform={`rotate(135 ${cx} ${cy})`} />
        {/* filled arc */}
        <circle cx={cx} cy={cy} r={r}
                fill="none" stroke={color} strokeWidth="6"
                strokeDasharray={`${fillLen} ${circ}`}
                strokeLinecap="round"
                transform={`rotate(135 ${cx} ${cy})`}
                style={{ filter: `drop-shadow(0 0 4px ${color})` }} />
        {/* ticks */}
        {ticks.map((t, i) => (
          <line key={i} x1={t.x1} y1={t.y1} x2={t.x2} y2={t.y2}
                stroke={t.lit ? color : "var(--border)"}
                strokeWidth={t.lit ? "1.5" : "1"}
                opacity={t.lit ? 1 : 0.5} />
        ))}
        {/* center text */}
        <text x={cx} y={cy - 5} textAnchor="middle"
              style={{ font: "600 9px var(--font-mono)", fill: "var(--fg-dim)", letterSpacing: "0.12em" }}>
          {label}
        </text>
        <text x={cx} y={cy + 12} textAnchor="middle"
              style={{ font: "600 18px var(--font-display)", fill: "var(--fg)", letterSpacing: "-0.02em" }}>
          {value.toFixed(2)}%
        </text>
        <text x={cx} y={cy + 25} textAnchor="middle"
              style={{ font: "500 8.5px var(--font-mono)", fill: "var(--fg-dim)", letterSpacing: "0.08em" }}>
          LIMIT {limit.toFixed(2)}%
        </text>
      </svg>
      {sublabel && (
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--fg-muted)", letterSpacing: "0.08em" }}>
          {sublabel}
        </div>
      )}
    </div>
  );
}

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

  const agg = window.NTData.aggregates();
  const { fmtUSD, fmtPct } = window.NTData;

  // drawdown synthetic series
  const ddSeries = Array.from({ length: 60 }, (_, i) => {
    const base = -1.4 + Math.sin(i / 5) * 0.6 + Math.cos(i / 9) * 0.4;
    return +(base + (Math.random() - 0.5) * 0.2).toFixed(2);
  });

  const exposure = agg.exposure;
  const total = exposure.reduce((s, e) => s + e.value, 0);

  return (
    <div className="panel">
      <style>{`
        .risk-body {
          padding: 12px;
          display: flex; flex-direction: column;
          gap: 14px;
          height: 100%;
          overflow-y: auto;
        }
        .risk-gauges {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 8px;
          align-items: center;
        }
        .risk-section-title {
          font-family: var(--font-mono); font-size: 9px;
          color: var(--fg-dim); letter-spacing: 0.14em; text-transform: uppercase;
          font-weight: 600;
          display: flex; align-items: center; justify-content: space-between;
        }
        .risk-section-meta {
          font-family: var(--font-mono); font-size: 9px;
          color: var(--fg-muted); letter-spacing: 0.06em;
        }
        .exposure-bar {
          display: flex; height: 14px; border-radius: 2px; overflow: hidden;
          gap: 1px;
          margin-top: 6px;
          background: var(--bg-inset);
        }
        .exposure-seg {
          position: relative; min-width: 0;
          transition: filter .12s;
        }
        .exposure-seg:hover { filter: brightness(1.2); }
        .exposure-list {
          display: flex; flex-direction: column;
          margin-top: 6px;
        }
        .exposure-row {
          display: grid;
          grid-template-columns: 8px 36px 1fr 60px 60px;
          gap: 8px;
          align-items: center;
          padding: 3px 0;
          font-family: var(--font-mono); font-size: 10px;
        }
        .exposure-row__dot {
          width: 8px; height: 8px; border-radius: 50%;
        }
        .exposure-row__coin { color: var(--fg-2); font-weight: 600; letter-spacing: 0.04em; }
        .exposure-row__bar {
          height: 4px; border-radius: 1px; background: var(--bg-inset); position: relative; overflow: hidden;
        }
        .exposure-row__bar-fill {
          position: absolute; left: 0; top: 0; bottom: 0;
          border-radius: 1px;
        }
        .exposure-row__val { text-align: right; color: var(--fg); font-variant-numeric: tabular-nums; }
        .exposure-row__delta { text-align: right; font-variant-numeric: tabular-nums; }

        .dd-wrap {
          background: var(--bg-inset);
          border: 1px solid var(--border);
          border-radius: 3px;
          padding: 8px 10px;
        }
        .dd-meta {
          display: flex; justify-content: space-between; align-items: baseline;
        }
        .dd-current {
          font-family: var(--font-display); font-size: 18px; font-weight: 600;
          color: var(--loss); letter-spacing: -0.02em;
        }
        .margin-bars {
          display: flex; flex-direction: column; gap: 6px;
        }
        .margin-bar-row {
          display: flex; flex-direction: column; gap: 3px;
        }
        .margin-bar-label {
          display: flex; justify-content: space-between;
          font-family: var(--font-mono); font-size: 9px;
          color: var(--fg-muted); letter-spacing: 0.04em;
        }
        .margin-bar {
          height: 6px; border-radius: 2px; background: var(--bg-inset);
          position: relative; overflow: hidden;
        }
        .margin-bar-fill {
          position: absolute; left: 0; top: 0; bottom: 0;
          border-radius: 2px;
        }
        .margin-bar-mark {
          position: absolute; top: -2px; bottom: -2px; width: 1px;
          background: var(--warn);
        }
        .scenarios {
          display: grid; grid-template-columns: 1fr 1fr; gap: 4px;
        }
        .scenario {
          padding: 5px 8px;
          background: var(--bg-inset);
          border: 1px solid var(--border);
          border-radius: 3px;
          display: flex; flex-direction: column; gap: 2px;
        }
        .scenario__head {
          font-family: var(--font-mono); font-size: 8.5px;
          color: var(--fg-dim); letter-spacing: 0.1em; text-transform: uppercase;
        }
        .scenario__impact {
          font-family: var(--font-mono); font-size: 11px;
          font-weight: 700;
          font-variant-numeric: tabular-nums;
        }
      `}</style>

      <div className="panel__head">
        <span className="panel__title panel__title-accent">Risk · Live</span>
        <div className="panel__meta">
          <span className="live-dot"></span>
          <span>10s</span>
        </div>
      </div>

      <div className="risk-body">

        {/* gauges */}
        <div className="risk-gauges">
          <RadialGauge value={agg.var95Pct} limit={agg.var95Limit}
                       label="VaR(95)" color="#f5b744"
                       sublabel={`${fmtUSD(agg.var95)} @ 95%`} />
          <RadialGauge value={agg.drawdown} limit={agg.drawdownMax}
                       label="DRAWDOWN" color="#f47272"
                       sublabel={`peak -${agg.drawdownMax.toFixed(2)}% (30d)`} />
        </div>

        {/* drawdown sparkline */}
        <div className="dd-wrap">
          <div className="dd-meta">
            <span className="risk-section-title">Drawdown · 60min</span>
            <span className="dd-current">-{agg.drawdown.toFixed(2)}%</span>
          </div>
          <div style={{ marginTop: 4 }}>
            <Sparkline data={ddSeries.map(v => -v)} color="#f47272" width={260} height={28} fill strokeWidth={1.2} />
          </div>
        </div>

        {/* exposure */}
        <div>
          <div className="risk-section-title">
            <span>Exposure by coin</span>
            <span className="risk-section-meta">{fmtUSD(total)} gross</span>
          </div>
          <div className="exposure-bar">
            {exposure.map(e => (
              <div key={e.coin} className="exposure-seg"
                   style={{ flex: e.value, background: e.color }}
                   title={`${e.coin} · ${(e.pct * 100).toFixed(1)}%`} />
            ))}
          </div>
          <div className="exposure-list">
            {exposure.map(e => (
              <div className="exposure-row" key={e.coin}>
                <span className="exposure-row__dot" style={{ background: e.color }} />
                <span className="exposure-row__coin">{e.coin}</span>
                <div className="exposure-row__bar">
                  <div className="exposure-row__bar-fill" style={{ width: `${e.pct * 100}%`, background: e.color, opacity: 0.7 }} />
                </div>
                <span className="exposure-row__val">{fmtUSD(e.value)}</span>
                <span className="exposure-row__delta" style={{ color: e.delta >= 0 ? "var(--gain)" : "var(--loss)" }}>
                  {fmtPct(e.delta * 100, 2)}
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* margin */}
        <div>
          <div className="risk-section-title">
            <span>Margin & headroom</span>
            <span className="risk-section-meta">62% available</span>
          </div>
          <div className="margin-bars" style={{ marginTop: 6 }}>
            <div className="margin-bar-row">
              <div className="margin-bar-label">
                <span>Initial margin</span>
                <span className="fg-2">{fmtUSD(agg.totalNAV * 0.28)} · 28%</span>
              </div>
              <div className="margin-bar">
                <div className="margin-bar-fill" style={{ width: "28%", background: "var(--info)" }} />
                <div className="margin-bar-mark" style={{ left: "75%" }} />
              </div>
            </div>
            <div className="margin-bar-row">
              <div className="margin-bar-label">
                <span>Maintenance margin</span>
                <span className="fg-2">{fmtUSD(agg.totalNAV * 0.17)} · 17%</span>
              </div>
              <div className="margin-bar">
                <div className="margin-bar-fill" style={{ width: "17%", background: "var(--gain)" }} />
              </div>
            </div>
            <div className="margin-bar-row">
              <div className="margin-bar-label">
                <span>Net delta (long-short)</span>
                <span className="fg-gain">+{fmtUSD(agg.totalNAV * 0.12)} · long-biased</span>
              </div>
              <div className="margin-bar" style={{ background: "var(--bg-inset)", display: "flex" }}>
                <div style={{ width: "50%", display: "flex", justifyContent: "flex-end" }}>
                  <div style={{ width: "24%", height: "100%", background: "var(--loss)", opacity: 0.55, borderRadius: "2px 0 0 2px" }} />
                </div>
                <div style={{ width: "50%" }}>
                  <div style={{ width: "48%", height: "100%", background: "var(--gain)", borderRadius: "0 2px 2px 0" }} />
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* stress scenarios */}
        <div>
          <div className="risk-section-title">
            <span>Stress scenarios</span>
            <span className="risk-section-meta">backtest · 90d</span>
          </div>
          <div className="scenarios" style={{ marginTop: 6 }}>
            <div className="scenario">
              <span className="scenario__head">BTC -20%</span>
              <span className="scenario__impact fg-loss">-{fmtUSD(agg.totalNAV * 0.072)}</span>
            </div>
            <div className="scenario">
              <span className="scenario__head">ETH -25%</span>
              <span className="scenario__impact fg-loss">-{fmtUSD(agg.totalNAV * 0.058)}</span>
            </div>
            <div className="scenario">
              <span className="scenario__head">All alts -40%</span>
              <span className="scenario__impact fg-loss">-{fmtUSD(agg.totalNAV * 0.123)}</span>
            </div>
            <div className="scenario">
              <span className="scenario__head">USD funding +30%</span>
              <span className="scenario__impact fg-warn">-{fmtUSD(agg.totalNAV * 0.014)}</span>
            </div>
          </div>
        </div>

      </div>
    </div>
  );
}

window.RiskPane = RiskPane;
