/* Charts — minimal SVG charts: line, bar, radar, donut, heatmap, sparkline */

const palette = {
  primary: '#4F46E5',
  violet: '#8B5CF6',
  sky: '#38BDF8',
  mint: '#14B8A6',
  amber: '#F59E0B',
  rose: '#EF4444',
  emerald: '#10B981',
  slate: '#94A3B8',
};

/* LineChart — multi-series */
const LineChart = ({ data, series, height = 220, showArea = true }) => {
  // data: [{ x: 'Mon', s1: 12, s2: 8 }, ...]
  const W = 600, H = height;
  const padL = 36, padR = 12, padT = 16, padB = 28;
  const innerW = W - padL - padR;
  const innerH = H - padT - padB;
  const allVals = data.flatMap(d => series.map(s => d[s.key]));
  const maxY = Math.max(...allVals) * 1.15;
  const minY = 0;

  const xStep = innerW / (data.length - 1 || 1);
  const yScale = (v) => padT + innerH - (v - minY) / (maxY - minY) * innerH;

  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(t => minY + (maxY - minY) * t);

  return (
    <svg className="chart-svg" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      {/* gridlines */}
      <g className="chart-grid">
        {yTicks.map((t, i) => (
          <line key={i} x1={padL} x2={W - padR} y1={yScale(t)} y2={yScale(t)} />
        ))}
      </g>
      {/* y labels */}
      {yTicks.map((t, i) => (
        <text key={i} x={padL - 6} y={yScale(t) + 3} fontSize="10" textAnchor="end" fill="#9197B3">
          {Math.round(t)}
        </text>
      ))}
      {/* x labels */}
      {data.map((d, i) => (
        <text key={i} x={padL + i * xStep} y={H - 8} fontSize="10" textAnchor="middle" fill="#9197B3">
          {d.x}
        </text>
      ))}
      {/* series */}
      {series.map((s, si) => {
        const pts = data.map((d, i) => `${padL + i * xStep},${yScale(d[s.key])}`).join(' ');
        const areaPath = `M ${padL},${yScale(0)} L ${data.map((d, i) => `${padL + i * xStep},${yScale(d[s.key])}`).join(' L ')} L ${padL + (data.length - 1) * xStep},${yScale(0)} Z`;
        const color = s.color || Object.values(palette)[si];
        return (
          <g key={s.key}>
            {showArea && si === 0 && (
              <>
                <defs>
                  <linearGradient id={`grad-${s.key}`} x1="0" x2="0" y1="0" y2="1">
                    <stop offset="0%" stopColor={color} stopOpacity="0.18"/>
                    <stop offset="100%" stopColor={color} stopOpacity="0"/>
                  </linearGradient>
                </defs>
                <path d={areaPath} fill={`url(#grad-${s.key})`} />
              </>
            )}
            <polyline points={pts} fill="none" stroke={color} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
            {data.map((d, i) => (
              <circle key={i} cx={padL + i * xStep} cy={yScale(d[s.key])} r="3" fill="white" stroke={color} strokeWidth="2"/>
            ))}
          </g>
        );
      })}
    </svg>
  );
};

/* BarChart — vertical, grouped optional */
const BarChart = ({ data, series, height = 220, horizontal = false }) => {
  const W = 600, H = height;
  const padL = horizontal ? 110 : 36, padR = 12, padT = 12, padB = 28;
  const innerW = W - padL - padR;
  const innerH = H - padT - padB;
  const allVals = data.flatMap(d => series.map(s => d[s.key]));
  const maxY = Math.max(...allVals) * 1.1;

  if (horizontal) {
    const rowH = innerH / data.length;
    const barH = Math.min(18, rowH * 0.55);
    return (
      <svg className="chart-svg" viewBox={`0 0 ${W} ${H}`}>
        {data.map((d, i) => {
          const y = padT + i * rowH + rowH / 2 - barH / 2;
          const v = d[series[0].key];
          const w = (v / maxY) * innerW;
          const color = d.color || series[0].color || palette.primary;
          return (
            <g key={i}>
              <text x={padL - 10} y={y + barH / 2 + 4} fontSize="11" textAnchor="end" fill="#4B5071">{d.x}</text>
              <rect x={padL} y={y} width={innerW} height={barH} rx={barH/2} fill="#ECEEF6"/>
              <rect x={padL} y={y} width={w} height={barH} rx={barH/2} fill={color}/>
              <text x={padL + w + 6} y={y + barH / 2 + 4} fontSize="11" fill="#4B5071" fontWeight="600">{v}{series[0].suffix || ''}</text>
            </g>
          );
        })}
      </svg>
    );
  }

  const groupW = innerW / data.length;
  const barW = Math.min(28, groupW / (series.length + 1));
  const yScale = (v) => padT + innerH - (v / maxY) * innerH;

  return (
    <svg className="chart-svg" viewBox={`0 0 ${W} ${H}`}>
      <g className="chart-grid">
        {[0.25, 0.5, 0.75, 1].map(t => (
          <line key={t} x1={padL} x2={W - padR} y1={yScale(maxY * t)} y2={yScale(maxY * t)} />
        ))}
      </g>
      {[0, 0.5, 1].map(t => (
        <text key={t} x={padL - 6} y={yScale(maxY * t) + 3} fontSize="10" textAnchor="end" fill="#9197B3">
          {Math.round(maxY * t)}
        </text>
      ))}
      {data.map((d, i) => {
        const cx = padL + i * groupW + groupW / 2;
        return (
          <g key={i}>
            {series.map((s, si) => {
              const v = d[s.key];
              const h = (v / maxY) * innerH;
              const x = cx - (series.length * barW) / 2 + si * barW + 2;
              const color = s.color || Object.values(palette)[si];
              return (
                <rect key={si} x={x} y={yScale(v)} width={barW - 4} height={h} rx="4" fill={color}/>
              );
            })}
            <text x={cx} y={H - 8} fontSize="10" textAnchor="middle" fill="#9197B3">{d.x}</text>
          </g>
        );
      })}
    </svg>
  );
};

/* RadarChart */
const RadarChart = ({ axes, series, size = 260 }) => {
  // axes: ['Communication', 'Teamwork', ...]
  // series: [{ key, name, color, values: [4.2, 4.0, ...] }]
  const cx = size / 2, cy = size / 2;
  const r = size * 0.38;
  const N = axes.length;
  const maxV = 5;

  const pt = (i, v) => {
    const a = (-Math.PI / 2) + (i * 2 * Math.PI) / N;
    const rr = (v / maxV) * r;
    return [cx + rr * Math.cos(a), cy + rr * Math.sin(a)];
  };

  const ringLevels = [1, 2, 3, 4, 5];

  return (
    <svg className="chart-svg" viewBox={`0 0 ${size} ${size}`} style={{ maxWidth: size }}>
      {/* rings */}
      {ringLevels.map(lv => {
        const pts = axes.map((_, i) => pt(i, lv).join(',')).join(' ');
        return <polygon key={lv} points={pts} fill="none" stroke="#E7E9F2" strokeDasharray={lv === 5 ? '0' : '2 4'}/>;
      })}
      {/* axes */}
      {axes.map((ax, i) => {
        const [x, y] = pt(i, maxV);
        return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="#E7E9F2"/>;
      })}
      {/* series */}
      {series.map((s, si) => {
        const pts = axes.map((_, i) => pt(i, s.values[i]).join(',')).join(' ');
        return (
          <g key={si}>
            <polygon points={pts} fill={s.color} fillOpacity="0.18" stroke={s.color} strokeWidth="2"/>
            {axes.map((_, i) => {
              const [x, y] = pt(i, s.values[i]);
              return <circle key={i} cx={x} cy={y} r="3" fill="white" stroke={s.color} strokeWidth="2"/>;
            })}
          </g>
        );
      })}
      {/* labels */}
      {axes.map((ax, i) => {
        const [x, y] = pt(i, maxV + 0.6);
        return (
          <text key={i} x={x} y={y} fontSize="10" textAnchor="middle" dominantBaseline="middle" fill="#4B5071" fontWeight="600">
            {ax}
          </text>
        );
      })}
    </svg>
  );
};

/* Donut chart */
const DonutChart = ({ data, size = 200, thickness = 28 }) => {
  // data: [{ label, value, color }]
  const total = data.reduce((s, d) => s + d.value, 0);
  const cx = size / 2, cy = size / 2;
  const r = (size - thickness) / 2;
  let acc = 0;
  const arcs = data.map(d => {
    const frac = d.value / total;
    const start = acc * 2 * Math.PI - Math.PI / 2;
    acc += frac;
    const end = acc * 2 * Math.PI - Math.PI / 2;
    const x1 = cx + r * Math.cos(start);
    const y1 = cy + r * Math.sin(start);
    const x2 = cx + r * Math.cos(end);
    const y2 = cy + r * Math.sin(end);
    const large = frac > 0.5 ? 1 : 0;
    return { d, path: `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2}` };
  });
  return (
    <svg className="chart-svg" viewBox={`0 0 ${size} ${size}`} style={{ maxWidth: size }}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="#ECEEF6" strokeWidth={thickness}/>
      {arcs.map((a, i) => (
        <path key={i} d={a.path} fill="none" stroke={a.d.color} strokeWidth={thickness} strokeLinecap="butt"/>
      ))}
      <text x={cx} y={cy - 2} fontSize="22" fontWeight="700" textAnchor="middle" fill="#0F1226">{total}</text>
      <text x={cx} y={cy + 16} fontSize="10" textAnchor="middle" fill="#6A6F8E">RATERS</text>
    </svg>
  );
};

/* Heatmap */
const Heatmap = ({ rows, cols, values, max = 5, min = 1 }) => {
  // values[rowIdx][colIdx]
  const colorFor = (v) => {
    const t = (v - min) / (max - min);
    // gradient from soft to deep indigo
    const c1 = [238, 240, 255]; // primary-50
    const c2 = [67, 56, 202];   // primary-600
    const r = Math.round(c1[0] + (c2[0] - c1[0]) * t);
    const g = Math.round(c1[1] + (c2[1] - c1[1]) * t);
    const b = Math.round(c1[2] + (c2[2] - c1[2]) * t);
    return `rgb(${r}, ${g}, ${b})`;
  };
  const textColor = (v) => ((v - min) / (max - min) > 0.55 ? 'white' : 'var(--ink-900)');

  return (
    <div style={{ display: 'grid', gridTemplateColumns: `160px repeat(${cols.length}, 1fr)`, gap: 4, fontSize: 11 }}>
      <div></div>
      {cols.map(c => (
        <div key={c} style={{ fontSize: 10.5, color: 'var(--ink-500)', textAlign: 'center', padding: '4px 2px', fontWeight: 600, lineHeight: 1.2 }}>{c}</div>
      ))}
      {rows.map((row, ri) => (
        <React.Fragment key={ri}>
          <div style={{ fontSize: 11.5, color: 'var(--ink-700)', padding: '6px 0', fontWeight: 500, display: 'flex', alignItems: 'center' }}>{row}</div>
          {cols.map((_, ci) => {
            const v = values[ri][ci];
            return (
              <div key={ci} className="heat-cell" style={{ background: colorFor(v), color: textColor(v) }}>
                {v.toFixed(1)}
              </div>
            );
          })}
        </React.Fragment>
      ))}
    </div>
  );
};

/* Sparkline */
const Sparkline = ({ values, color = '#4F46E5', height = 32, width = 90 }) => {
  const max = Math.max(...values);
  const min = Math.min(...values);
  const range = max - min || 1;
  const pts = values.map((v, i) => `${(i / (values.length - 1)) * width},${height - ((v - min) / range) * height}`).join(' ');
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
};

/* Stacked horizontal score bar (Self vs Manager vs Peer comparison row) */
const ScoreBar = ({ value, max = 5, color = '#4F46E5', width = '100%' }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 8, width }}>
    <div style={{ flex: 1, height: 8, background: '#ECEEF6', borderRadius: 999, overflow: 'hidden' }}>
      <div style={{ width: `${(value / max) * 100}%`, height: '100%', background: color, borderRadius: 999 }}></div>
    </div>
    <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-700)', minWidth: 28, textAlign: 'right' }}>{value.toFixed(1)}</span>
  </div>
);

Object.assign(window, { LineChart, BarChart, RadarChart, DonutChart, Heatmap, Sparkline, ScoreBar, chartPalette: palette });
