"use client";

/**
 * Sparkline — minimal SVG line chart used in StatCard backgrounds
 * and inline next to numbers. No recharts dependency: a single
 * <svg> + two <path> elements (area fill + stroke) so it stays
 * cheap on the dozens-of-charts dashboard surface.
 *
 * Designed to render at 60-100px wide × 20-32px tall. preserveAspectRatio
 * is "none" so the same component scales smoothly into a card hero
 * background without distorting the data shape.
 */

import { useMemo } from "react";

interface Props {
  /** Numeric series — the actual data, not normalized. We scale
   *  internally against the max so the line always fills the box. */
  points: number[];
  /** Stroke + fill base color. Defaults to brand violet for visual
   *  consistency across the dashboard. */
  color?: string;
  /** Render as a filled area (default) vs a stroke-only line. The
   *  area mode reads as "background hint"; line mode reads as
   *  "primary chart". */
  variant?: "area" | "line";
  className?: string;
  /** Aspect ratio source — affects internal viewBox only. The CSS
   *  className (w-/h-) controls actual rendered size. */
  width?: number;
  height?: number;
}

export function Sparkline({
  points,
  color = "#6366F1",
  variant = "area",
  className = "w-full h-full",
  width = 100,
  height = 24,
}: Props) {
  const { linePath, areaPath, hasData } = useMemo(() => {
    if (points.length === 0) return { linePath: "", areaPath: "", hasData: false };
    const max = Math.max(...points, 1);
    const step = points.length > 1 ? width / (points.length - 1) : 0;
    const line = points.map((p, i) => {
      const x = i * step;
      const y = height - (p / max) * height;
      return `${i === 0 ? "M" : "L"}${x.toFixed(2)},${y.toFixed(2)}`;
    }).join(" ");
    const area = `${line} L${width},${height} L0,${height} Z`;
    return { linePath: line, areaPath: area, hasData: true };
  }, [points, width, height]);

  if (!hasData) return null;
  return (
    <svg
      viewBox={`0 0 ${width} ${height}`}
      className={className}
      preserveAspectRatio="none"
      aria-hidden
    >
      {variant === "area" && (
        <path d={areaPath} fill={color} fillOpacity={0.12} />
      )}
      <path d={linePath} stroke={color} strokeWidth={1.5} fill="none" />
    </svg>
  );
}
