'use client';

import { cn } from '@/lib/cn';

export interface SparklineProps {
  points: number[];
  'aria-label': string;
  className?: string;
  tone?: 'default' | 'success' | 'warning' | 'danger';
}

const strokeToneClass: Record<NonNullable<SparklineProps['tone']>, string> = {
  default: 'stroke-text-muted',
  success: 'stroke-success-600',
  warning: 'stroke-warning-600',
  danger: 'stroke-danger-600',
};

function buildPolyline(points: number[]): string {
  if (points.length < 2) return '';

  const min = Math.min(...points);
  const max = Math.max(...points);
  const range = max - min || 1;

  return points
    .map((point, index) => {
      const x = (index / (points.length - 1)) * 100;
      const y = 100 - ((point - min) / range) * 100;
      return `${x},${y}`;
    })
    .join(' ');
}

export function Sparkline({
  points,
  'aria-label': ariaLabel,
  className,
  tone = 'default',
}: SparklineProps) {
  const polyline = buildPolyline(points);

  return (
    <svg
      viewBox="0 0 100 100"
      role="img"
      aria-label={ariaLabel}
      preserveAspectRatio="none"
      className={cn('h-10 w-full overflow-visible', className)}
    >
      {polyline ? (
        <polyline
          fill="none"
          strokeWidth="6"
          strokeLinecap="round"
          strokeLinejoin="round"
          points={polyline}
          className={strokeToneClass[tone]}
        />
      ) : (
        <line
          x1="0"
          y1="50"
          x2="100"
          y2="50"
          strokeWidth="6"
          strokeLinecap="round"
          className={strokeToneClass[tone]}
        />
      )}
    </svg>
  );
}
