// FundChart.jsx — big hero chart with area/bar style, interactive scrubber

function AreaChart({
  data, width = 360, height = 180, color = '#85FF86', negColor = '#FE4D5B',
  onHover, activeIdx, baselineIdx = 0,
}) {
  const pad = { t: 10, r: 4, b: 4, l: 4 };
  const w = width - pad.l - pad.r;
  const h = height - pad.t - pad.b;
  if (!data || data.length < 2) return null;

  const min = Math.min(...data);
  const max = Math.max(...data);
  const range = Math.max(max - min, 0.01);
  const padRange = range * 0.15;

  const xAt = i => pad.l + (i / (data.length - 1)) * w;
  const yAt = v => pad.t + h - ((v - (min - padRange)) / (range + padRange * 2)) * h;

  const baseline = data[baselineIdx];
  const isNeg = data[data.length - 1] < baseline;
  const strokeColor = isNeg ? negColor : color;

  // Path
  let d = '';
  data.forEach((v, i) => {
    d += (i === 0 ? 'M' : 'L') + xAt(i).toFixed(2) + ',' + yAt(v).toFixed(2) + ' ';
  });
  const areaD = d + `L${xAt(data.length - 1).toFixed(2)},${pad.t + h} L${xAt(0).toFixed(2)},${pad.t + h} Z`;

  const baselineY = yAt(baseline);

  const handlePointer = (e) => {
    if (!onHover) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX ?? e.touches?.[0]?.clientX) - rect.left) / rect.width * width;
    const idx = Math.max(0, Math.min(data.length - 1, Math.round(((x - pad.l) / w) * (data.length - 1))));
    onHover(idx);
  };

  const gradId = 'grad-' + Math.abs(color.charCodeAt(1)) + '-' + data.length;

  return (
    <svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: 'block', touchAction: 'none' }}
      onMouseMove={handlePointer} onMouseLeave={() => onHover && onHover(null)} onTouchMove={handlePointer} onTouchEnd={() => onHover && onHover(null)}>
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={strokeColor} stopOpacity="0.35"/>
          <stop offset="100%" stopColor={strokeColor} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {/* baseline */}
      <line x1={pad.l} x2={width - pad.r} y1={baselineY} y2={baselineY} stroke="rgba(255,255,255,0.08)" strokeWidth="1" strokeDasharray="3 4"/>
      {/* area */}
      <path d={areaD} fill={`url(#${gradId})`}/>
      {/* line */}
      <path d={d} fill="none" stroke={strokeColor} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
      {/* end dot */}
      <circle cx={xAt(data.length - 1)} cy={yAt(data[data.length - 1])} r="4" fill={strokeColor}/>
      <circle cx={xAt(data.length - 1)} cy={yAt(data[data.length - 1])} r="8" fill={strokeColor} opacity="0.2"/>
      {/* scrubber */}
      {activeIdx != null && activeIdx >= 0 && activeIdx < data.length && (
        <g>
          <line x1={xAt(activeIdx)} x2={xAt(activeIdx)} y1={pad.t} y2={pad.t + h} stroke="rgba(255,255,255,0.4)" strokeWidth="1"/>
          <circle cx={xAt(activeIdx)} cy={yAt(data[activeIdx])} r="5" fill="#fff" stroke={strokeColor} strokeWidth="2"/>
        </g>
      )}
    </svg>
  );
}

function BarChart({
  data, width = 360, height = 180, color = '#85FF86', negColor = '#FE4D5B',
  onHover, activeIdx, baselineIdx = 0,
}) {
  const pad = { t: 10, r: 4, b: 4, l: 4 };
  const w = width - pad.l - pad.r;
  const h = height - pad.t - pad.b;
  if (!data || data.length < 2) return null;

  const baseline = data[baselineIdx];
  // Use relative deltas
  const deltas = data.map(v => v - baseline);
  const maxAbs = Math.max(Math.abs(Math.min(...deltas)), Math.abs(Math.max(...deltas)), 0.01);

  const barW = w / data.length * 0.7;
  const gap = w / data.length * 0.3;
  const zeroY = pad.t + h / 2;

  const handlePointer = (e) => {
    if (!onHover) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX ?? e.touches?.[0]?.clientX) - rect.left) / rect.width * width;
    const idx = Math.max(0, Math.min(data.length - 1, Math.floor(((x - pad.l) / w) * data.length)));
    onHover(idx);
  };

  const isOverallNeg = data[data.length - 1] < baseline;
  const mainColor = isOverallNeg ? negColor : color;

  return (
    <svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: 'block', touchAction: 'none' }}
      onMouseMove={handlePointer} onMouseLeave={() => onHover && onHover(null)} onTouchMove={handlePointer} onTouchEnd={() => onHover && onHover(null)}>
      {/* zero line */}
      <line x1={pad.l} x2={width - pad.r} y1={zeroY} y2={zeroY} stroke="rgba(255,255,255,0.15)" strokeWidth="1"/>
      {deltas.map((d, i) => {
        const barH = (Math.abs(d) / maxAbs) * (h / 2 - 4);
        const y = d >= 0 ? zeroY - barH : zeroY;
        const c = d >= 0 ? color : negColor;
        const active = activeIdx === i;
        const x = pad.l + i * (w / data.length) + gap / 2;
        return (
          <rect key={i} x={x} y={y} width={barW} height={Math.max(barH, 1)} rx="1.5"
            fill={c} opacity={active ? 1 : (activeIdx == null ? 0.9 : 0.45)}/>
        );
      })}
    </svg>
  );
}

// Sparkline — tiny line for fund cards
function Sparkline({ data, color = '#85FF86', negColor = '#FE4D5B', width = 80, height = 30 }) {
  if (!data || data.length < 2) return null;
  const min = Math.min(...data), max = Math.max(...data);
  const range = Math.max(max - min, 0.01);
  const x = i => (i / (data.length - 1)) * width;
  const y = v => height - ((v - min) / range) * (height - 4) - 2;
  let d = '';
  data.forEach((v, i) => { d += (i === 0 ? 'M' : 'L') + x(i).toFixed(2) + ',' + y(v).toFixed(2) + ' '; });
  const isNeg = data[data.length - 1] < data[0];
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: 'block' }}>
      <path d={d} fill="none" stroke={isNeg ? negColor : color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// Donut — tiny allocation vis
function Donut({ parts, size = 80, thickness = 10 }) {
  const r = size / 2 - thickness / 2;
  const c = 2 * Math.PI * r;
  let acc = 0;
  const total = parts.reduce((s, p) => s + p.pct, 0);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth={thickness}/>
      {parts.map((p, i) => {
        const len = (p.pct / total) * c;
        const off = (acc / total) * c;
        acc += p.pct;
        return (
          <circle key={i} cx={size/2} cy={size/2} r={r} fill="none" stroke={p.color} strokeWidth={thickness}
            strokeDasharray={`${len} ${c - len}`} strokeDashoffset={-off}
            transform={`rotate(-90 ${size/2} ${size/2})`}/>
        );
      })}
    </svg>
  );
}

Object.assign(window, { AreaChart, BarChart, Sparkline, Donut });
