/* global React */
const { useMemo } = React;

// Minimal SVG line chart with multi-series + grid + last-value label.
// props: series=[{key, color, points:[{x,y}]}], height, width, padding, formatY
function LineChart({ series, formatY, showGrid = true, showAxis = true }) {
  const W = 800, H = 280, P = { l: 50, r: 60, t: 14, b: 20 };
  const all = series.flatMap(s => s.points);
  if (!all.length) return null;
  const xs = all.map(p => p.x), ys = all.map(p => p.y);
  const xmin = Math.min(...xs), xmax = Math.max(...xs);
  const ymin = Math.min(...ys), ymax = Math.max(...ys);
  const pad = (ymax - ymin) * 0.08 || 1;
  const y0 = ymin - pad, y1 = ymax + pad;
  const sx = (x) => P.l + ((x - xmin) / (xmax - xmin || 1)) * (W - P.l - P.r);
  const sy = (y) => P.t + (1 - (y - y0) / (y1 - y0 || 1)) * (H - P.t - P.b);

  const fmt = formatY || ((y) => Math.round(y).toLocaleString());
  const ticks = 5;
  const yTicks = Array.from({ length: ticks }, (_, i) => y0 + ((y1 - y0) * i) / (ticks - 1));

  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      {showGrid && yTicks.map((t, i) => (
        <line key={i} x1={P.l} x2={W - P.r} y1={sy(t)} y2={sy(t)}
              stroke="#1f262f" strokeWidth="1" strokeDasharray="2 4" />
      ))}
      {showAxis && yTicks.map((t, i) => (
        <text key={`yl-${i}`} x={P.l - 6} y={sy(t) + 3}
              fontFamily="JetBrains Mono" fontSize="9" fill="#7d8590" textAnchor="end">
          {fmt(t)}
        </text>
      ))}
      {series.map(s => {
        const d = s.points.map((p, i) => `${i === 0 ? 'M' : 'L'}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join(' ');
        const area = s.fill ? `${d} L${sx(s.points[s.points.length-1].x)},${sy(y0)} L${sx(s.points[0].x)},${sy(y0)} Z` : null;
        return (
          <g key={s.key}>
            {area && <path d={area} fill={s.color} opacity="0.08" />}
            <path d={d} fill="none" stroke={s.color} strokeWidth="1.5" strokeLinejoin="round" />
            {s.points.length > 0 && (
              <g>
                <circle cx={sx(s.points[s.points.length-1].x)}
                        cy={sy(s.points[s.points.length-1].y)}
                        r="2.5" fill={s.color} />
                <text x={sx(s.points[s.points.length-1].x) + 6}
                      y={sy(s.points[s.points.length-1].y) + 3}
                      fontFamily="JetBrains Mono" fontSize="9" fill={s.color}>
                  {fmt(s.points[s.points.length-1].y)}
                </text>
              </g>
            )}
          </g>
        );
      })}
      {showAxis && (() => {
        // x labels (~6)
        const stride = Math.max(1, Math.floor(series[0].points.length / 6));
        return series[0].points.filter((_, i) => i % stride === 0).map((p, i) => (
          <text key={`xl-${i}`} x={sx(p.x)} y={H - 6}
                fontFamily="JetBrains Mono" fontSize="9" fill="#7d8590" textAnchor="middle">
            {p.label || p.x}
          </text>
        ));
      })()}
    </svg>
  );
}

function Sparkline({ values, color = '#7d8590', width = 60, height = 24 }) {
  if (!values || values.length < 2) return null;
  const min = Math.min(...values), max = Math.max(...values);
  const sx = (i) => (i / (values.length - 1)) * width;
  const sy = (v) => height - ((v - min) / (max - min || 1)) * height;
  const d = values.map((v, i) => `${i === 0 ? 'M' : 'L'}${sx(i).toFixed(1)},${sy(v).toFixed(1)}`).join(' ');
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
      <path d={d} fill="none" stroke={color} strokeWidth="1.2" />
    </svg>
  );
}

// Bar visualizer for strategy comparison
function StratBar({ value, max, color = 'var(--accent)' }) {
  const pct = Math.max(2, Math.min(100, (Math.abs(value) / max) * 100));
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <div style={{ flex: 1, height: 4, background: 'var(--bg-3)', position: 'relative' }}>
        <div style={{
          position: 'absolute', top: 0, bottom: 0, left: 0,
          width: `${pct}%`, background: color,
        }} />
      </div>
    </div>
  );
}

Object.assign(window, { LineChart, Sparkline, StratBar });
