// Lightweight inline-SVG charts: Sparkline, AreaChart, BarsChart, EquityChart.

function pathFromPoints(points, w, h, padX = 0, padY = 4) {
  const min = Math.min(...points), max = Math.max(...points);
  const range = max - min || 1;
  const n = points.length;
  const x = (i) => padX + (i / (n - 1)) * (w - padX * 2);
  const y = (v) => padY + (1 - (v - min) / range) * (h - padY * 2);
  let d = "";
  points.forEach((p, i) => {
    d += (i === 0 ? "M" : "L") + x(i).toFixed(2) + " " + y(p).toFixed(2) + " ";
  });
  return { d: d.trim(), x, y, min, max };
}

// Catmull–Rom-ish smoothed path
function smoothPathFromPoints(points, w, h, padX = 0, padY = 4) {
  const { x, y, min, max } = pathFromPoints(points, w, h, padX, padY);
  const pts = points.map((p, i) => [x(i), y(p)]);
  if (pts.length < 2) return { d: "", min, max, x, y };
  let d = `M${pts[0][0]} ${pts[0][1]}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[i - 1] || pts[i];
    const p1 = pts[i];
    const p2 = pts[i + 1];
    const p3 = pts[i + 2] || p2;
    const c1x = p1[0] + (p2[0] - p0[0]) / 6;
    const c1y = p1[1] + (p2[1] - p0[1]) / 6;
    const c2x = p2[0] - (p3[0] - p1[0]) / 6;
    const c2y = p2[1] - (p3[1] - p1[1]) / 6;
    d += ` C ${c1x.toFixed(2)} ${c1y.toFixed(2)}, ${c2x.toFixed(2)} ${c2y.toFixed(2)}, ${p2[0].toFixed(2)} ${p2[1].toFixed(2)}`;
  }
  return { d, min, max, x, y, pts };
}

function Sparkline({ data, width = 80, height = 24, stroke = "currentColor", fill = false, strokeWidth = 1.5 }) {
  const { d } = smoothPathFromPoints(data, width, height, 1, 2);
  const id = React.useId();
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} className="overflow-visible">
      <defs>
        <linearGradient id={`sf-${id}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"   stopColor={stroke} stopOpacity="0.25" />
          <stop offset="100%" stopColor={stroke} stopOpacity="0" />
        </linearGradient>
      </defs>
      {fill && <path d={`${d} L ${width} ${height} L 0 ${height} Z`} fill={`url(#sf-${id})`} />}
      <path d={d} fill="none" stroke={stroke} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function AreaChart({ data, width = 720, height = 220, stroke = "hsl(var(--primary))", baseline, gridLines = 4, label, showAxis = true }) {
  const { d, min, max, x, y, pts } = smoothPathFromPoints(data, width, height, 8, 14);
  const id = React.useId();
  const grid = [];
  for (let i = 0; i <= gridLines; i++) {
    const gy = 14 + (i / gridLines) * (height - 28);
    grid.push(gy);
  }
  return (
    <svg width="100%" viewBox={`0 0 ${width} ${height}`} className="block">
      <defs>
        <linearGradient id={`area-${id}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"   stopColor={stroke} stopOpacity="0.32" />
          <stop offset="60%"  stopColor={stroke} stopOpacity="0.08" />
          <stop offset="100%" stopColor={stroke} stopOpacity="0" />
        </linearGradient>
      </defs>
      {grid.map((g, i) => (
        <line key={i} x1={0} x2={width} y1={g} y2={g} stroke="hsl(var(--border-2))" strokeWidth="1" strokeDasharray="3 4" />
      ))}
      <path d={`${d} L ${width - 8} ${height - 14} L 8 ${height - 14} Z`} fill={`url(#area-${id})`} />
      <path d={d} fill="none" stroke={stroke} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      {showAxis && (
        <>
          <text x="8" y="12" className="font-mono" fontSize="10" fill="hsl(var(--subtle-fg))">{label ?? `$${Math.round(max).toLocaleString()}`}</text>
          <text x="8" y={height - 2} className="font-mono" fontSize="10" fill="hsl(var(--subtle-fg))">${Math.round(min).toLocaleString()}</text>
        </>
      )}
      {/* last-point dot */}
      {pts && pts.length > 0 && (
        <g>
          <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="4" fill={stroke} />
          <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="8" fill={stroke} opacity="0.18" />
        </g>
      )}
    </svg>
  );
}

function BarsChart({ data, width = 480, height = 160, gap = 4, label }) {
  // data = [{m, v}]
  const max = Math.max(...data.map(d => Math.abs(d.v)));
  const w = (width - gap * (data.length - 1)) / data.length;
  const mid = height / 2;
  const scale = (Math.abs(max) / (height / 2 - 8)) || 1;
  return (
    <svg width="100%" viewBox={`0 0 ${width} ${height + 22}`} className="block">
      <line x1={0} x2={width} y1={mid} y2={mid} stroke="hsl(var(--border-2))" />
      {data.map((d, i) => {
        const x = i * (w + gap);
        const h = Math.abs(d.v) / scale;
        const positive = d.v >= 0;
        const y = positive ? mid - h : mid;
        return (
          <g key={i}>
            <rect x={x} y={y} width={w} height={h} rx="2"
              fill={positive ? "hsl(var(--positive))" : "hsl(var(--negative))"}
              opacity="0.85" />
            <text x={x + w / 2} y={height + 14} fontSize="10" textAnchor="middle"
              fill="hsl(var(--subtle-fg))" className="font-mono">{d.m}</text>
          </g>
        );
      })}
    </svg>
  );
}

// EquityChart with optional overlay line (e.g. unrealized)
function EquityChart({ data, width = 760, height = 260, stroke = "hsl(var(--primary))", overlay, overlayStroke = "hsl(var(--info))" }) {
  const { d, min, max, pts } = smoothPathFromPoints(data, width, height, 12, 16);
  const overlayPath = overlay ? smoothPathFromPoints(overlay, width, height, 12, 16) : null;
  const id = React.useId();
  return (
    <svg width="100%" viewBox={`0 0 ${width} ${height}`} className="block">
      <defs>
        <linearGradient id={`eq-${id}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"   stopColor={stroke} stopOpacity="0.35" />
          <stop offset="60%"  stopColor={stroke} stopOpacity="0.08" />
          <stop offset="100%" stopColor={stroke} stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0, 0.25, 0.5, 0.75, 1].map((p, i) => {
        const y = 16 + p * (height - 32);
        return <line key={i} x1={0} x2={width} y1={y} y2={y} stroke="hsl(var(--border-2))" strokeWidth="1" strokeDasharray="3 5" />;
      })}
      <path d={`${d} L ${width - 12} ${height - 16} L 12 ${height - 16} Z`} fill={`url(#eq-${id})`} />
      <path d={d} fill="none" stroke={stroke} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      {overlayPath && <path d={overlayPath.d} fill="none" stroke={overlayStroke} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="2 4" />}
      {pts && (
        <g>
          <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="4" fill={stroke} />
          <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="9" fill={stroke} opacity="0.18" />
        </g>
      )}
      <text x="14" y="14" fontSize="10" fill="hsl(var(--subtle-fg))" className="font-mono">${Math.round(max).toLocaleString()}</text>
      <text x="14" y={height - 4} fontSize="10" fill="hsl(var(--subtle-fg))" className="font-mono">${Math.round(min).toLocaleString()}</text>
    </svg>
  );
}

Object.assign(window, { Sparkline, AreaChart, BarsChart, EquityChart, pathFromPoints, smoothPathFromPoints });
