import React, { useMemo } from 'react';

interface Props {
  series: number[];
  label?: string;
  height?: number;
}

function sparkPath(values: number[], w: number, h: number): string {
  if (values.length < 2) return '';
  const lo = Math.min(...values);
  const hi = Math.max(...values);
  const range = hi - lo || 1;
  return values.map((v, i) => {
    const x = (i / (values.length - 1)) * w;
    const y = h - 8 - ((v - lo) / range) * (h - 16);
    return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
}

export default function DashboardSparkChart({ series, label, height = 140 }: Props) {
  const w = 480;
  const path = useMemo(() => sparkPath(series, w, height), [series, height]);
  const area = path ? `${path} L ${w},${height} L 0,${height} Z` : '';
  const last = series.length ? series[series.length - 1] : 0;

  return (
    <div className="gc-spark-chart">
      {label && (
        <div className="gc-spark-chart-head">
          <span>{label}</span>
          <strong>{last.toFixed(1)}/s</strong>
        </div>
      )}
      <svg viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none" className="gc-spark-chart-svg">
        <defs>
          <linearGradient id="gcSparkGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#22d3ee" stopOpacity="0.55" />
            <stop offset="100%" stopColor="#6366f1" stopOpacity="0.05" />
          </linearGradient>
        </defs>
        {area && <path d={area} fill="url(#gcSparkGrad)" />}
        {path && (
          <path d={path} fill="none" stroke="#22d3ee" strokeWidth="2" style={{ filter: 'drop-shadow(0 0 4px rgba(34,211,238,0.5))' }} />
        )}
      </svg>
    </div>
  );
}
