/**
 * Sparkline — tiny inline trend line for stat tiles (Sorbet Studio).
 *
 * Pure SVG, no axes or labels: it shows shape, not values (the tile's number
 * carries the value). Stretches to its container via preserveAspectRatio=none,
 * so strokes use vector-effect to stay crisp.
 */
import React from "react";

interface SparklineProps {
  data: number[];
  color: string;
  /** rgba fill for an area under the line (featured tiles) */
  fill?: string;
  /** Tooltip text, e.g. "Last 30 days" */
  title?: string;
  className?: string;
}

const W = 100;
const H = 32;
const PAD = 3;

const Sparkline: React.FC<SparklineProps> = ({ data, color, fill, title, className }) => {
  if (!data || data.length < 2) return null;

  const max = Math.max(...data);
  const min = Math.min(...data);
  const span = max - min || 1;
  const pts = data.map((v, i) => [
    PAD + (i * (W - 2 * PAD)) / (data.length - 1),
    PAD + ((max - v) * (H - 2 * PAD)) / span,
  ]);
  const d = pts
    .map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(1)} ${p[1].toFixed(1)}`)
    .join(" ");
  const [ex, ey] = pts[pts.length - 1];

  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      preserveAspectRatio="none"
      className={className}
      style={{ display: "block", width: "100%", height: "100%" }}
      aria-hidden="true"
    >
      {title && <title>{title}</title>}
      {fill && (
        <path
          d={`${d} L${ex.toFixed(1)} ${H - PAD} L${PAD} ${H - PAD} Z`}
          fill={fill}
        />
      )}
      <path
        d={d}
        fill="none"
        stroke={color}
        strokeWidth={2}
        strokeLinejoin="round"
        strokeLinecap="round"
        vectorEffect="non-scaling-stroke"
      />
      <circle cx={ex.toFixed(1)} cy={ey.toFixed(1)} r={2.4} fill={color} />
    </svg>
  );
};

export default Sparkline;
