"use client";

import { useId } from "react";

export type SparkColor = "primary" | "cyan" | "green" | "pink" | "amber" | "red";

type SparkProps = {
  values: number[];
  color?: SparkColor;
  height?: number;
  fill?: boolean;
};

const COLOR_VAR: Record<SparkColor, string> = {
  primary: "var(--v5-primary)",
  cyan: "rgb(var(--v5-cyan-rgb))",
  green: "rgb(var(--v5-green-rgb))",
  pink: "rgb(var(--v5-pink-rgb))",
  amber: "rgb(var(--v5-amber-rgb))",
  red: "rgb(var(--v5-red-rgb))",
};

export function Spark({ values, color = "primary", height = 36, fill = true }: SparkProps) {
  const id = useId().replace(/:/g, "");
  if (!values || values.length === 0) return null;

  const max = Math.max(...values);
  const min = Math.min(...values);
  const range = max - min || 1;
  const stepX = 100 / Math.max(1, values.length - 1);

  const points = values.map((v, i) => {
    const x = i * stepX;
    const y = 100 - ((v - min) / range) * 100;
    return `${x.toFixed(2)},${y.toFixed(2)}`;
  });

  const linePath = `M ${points.join(" L ")}`;
  const areaPath = `${linePath} L 100,100 L 0,100 Z`;
  const stroke = COLOR_VAR[color];

  return (
    <svg
      className="v5-spark"
      viewBox="0 0 100 100"
      preserveAspectRatio="none"
      style={{ height }}
      aria-hidden
    >
      <defs>
        <linearGradient id={`sg-${id}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"   style={{ stopColor: stroke, stopOpacity: 0.35 }} />
          <stop offset="100%" style={{ stopColor: stroke, stopOpacity: 0 }} />
        </linearGradient>
      </defs>
      {fill && <path d={areaPath} fill={`url(#sg-${id})`} />}
      <path d={linePath} fill="none" stroke={stroke} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
    </svg>
  );
}
