import { useMemo, type CSSProperties } from 'react';

export interface BarSparklineProps {
  data: number[];
  width?: number;
  height?: number;
  color?: string;
  /** Color for the maximum bar. Defaults to `color`. */
  highlightMax?: string;
  /** Spacing between bars as a fraction of bar width. Default 0.25. */
  gap?: number;
  ariaLabel?: string;
  className?: string;
  style?: CSSProperties;
}

/**
 * `<BarSparkline>` — inline mini-bar chart. Pairs well with KPI cards
 * where a line sparkline doesn't fit (e.g. discrete daily counts).
 */
export function BarSparkline({
  data,
  width = 120,
  height = 36,
  color = 'var(--bl-accent, #6366f1)',
  highlightMax,
  gap = 0.25,
  ariaLabel,
  className,
  style,
}: BarSparklineProps) {
  const { bars, maxIdx } = useMemo(() => {
    if (data.length === 0) return { bars: [], maxIdx: -1 };
    const max = Math.max(...data, 1);
    const slot = width / data.length;
    const barW = slot * (1 - gap);
    const offset = slot * (gap / 2);
    const maxIdx = data.indexOf(Math.max(...data));
    const bars = data.map((v, i) => {
      const h = Math.max(2, (v / max) * height);
      return { x: i * slot + offset, y: height - h, w: barW, h };
    });
    return { bars, maxIdx };
  }, [data, width, height, gap]);

  const peak = highlightMax ?? color;

  return (
    <svg
      data-testid="bl-bar-sparkline"
      role="img"
      aria-label={ariaLabel ?? 'Bar sparkline'}
      width={width}
      height={height}
      viewBox={`0 0 ${width} ${height}`}
      className={className}
      style={style}
    >
      {bars.map((b, i) => (
        <rect
          key={i}
          x={b.x}
          y={b.y}
          width={b.w}
          height={b.h}
          rx={1.5}
          fill={i === maxIdx ? peak : color}
          opacity={i === maxIdx ? 1 : 0.55}
        />
      ))}
    </svg>
  );
}
