import React, { useMemo } from 'react';

// Fix #10: Memoized graph with computed max
const MiniGraph = React.memo(({ data }) => {
  const maxVal = useMemo(() => {
    let m = 10;
    for (let i = 0; i < data.length; i++) {
      if (data[i].baseline > m) m = data[i].baseline;
      if (data[i].memory > m) m = data[i].memory;
    }
    return m;
  }, [data]);

  if (data.length < 2) {
    return (
      <div className="h-full w-full flex items-center justify-center text-slate-700 text-xs font-mono">
        WAITING FOR DATA...
      </div>
    );
  }

  const width = 100;
  const height = 100;

  const makePath = (key) => {
    let points = '';
    for (let i = 0; i < data.length; i++) {
      const x = (i / (data.length - 1)) * width;
      const y = height - (data[i][key] / maxVal) * height;
      if (i > 0) points += ' ';
      points += `${x},${y}`;
    }
    return points;
  };

  return (
    <svg viewBox={`0 0 ${width} ${height}`} className="w-full h-full overflow-visible" role="img" aria-label="Throughput comparison graph">
      <line x1="0" y1="25" x2="100" y2="25" stroke="#334155" strokeWidth="0.5" strokeDasharray="2" />
      <line x1="0" y1="50" x2="100" y2="50" stroke="#334155" strokeWidth="0.5" strokeDasharray="2" />
      <line x1="0" y1="75" x2="100" y2="75" stroke="#334155" strokeWidth="0.5" strokeDasharray="2" />
      <polyline
        points={makePath('baseline')}
        fill="none" stroke="#06b6d4" strokeWidth="2"
        vectorEffect="non-scaling-stroke"
        style={{ filter: 'drop-shadow(0 0 3px rgba(6,182,212,0.8))' }}
      />
      <polyline
        points={makePath('memory')}
        fill="none" stroke="#d946ef" strokeWidth="2"
        vectorEffect="non-scaling-stroke"
        style={{ filter: 'drop-shadow(0 0 3px rgba(217,70,239,0.8))' }}
      />
    </svg>
  );
});

MiniGraph.displayName = 'MiniGraph';
export default MiniGraph;
