/**
 * F-148 — TrendChart: SVG bar chart for sales over time.
 */

interface TrendDataPoint {
  label: string;
  value: number; // cents
}

interface TrendChartProps {
  data: TrendDataPoint[];
  maxValue: number;
  height?: number;
}

export function TrendChart({ data, maxValue, height = 200 }: TrendChartProps) {
  if (data.length === 0) return null;

  const width = 100; // percentage-based SVG
  const barWidth = Math.min(3, (width * 0.9) / data.length);
  const gap = Math.max(0.2, (width - barWidth * data.length) / (data.length + 1));
  const chartHeight = height - 40; // leave room for labels

  return (
    <div className="w-full overflow-x-auto">
      <svg
        viewBox={`0 0 ${width} ${height}`}
        className="w-full"
        style={{ minWidth: `${Math.max(300, data.length * 8)}px` }}
        aria-label="Tendencia de ventas"
        role="img"
      >
        {/* Y-axis baseline */}
        <line x1="0" y1={chartHeight} x2={width} y2={chartHeight} stroke="#e5e7eb" strokeWidth="0.5" />

        {data.map((point, i) => {
          const barH = maxValue > 0 ? (point.value / maxValue) * chartHeight : 0;
          const x = gap + i * (barWidth + gap);
          const y = chartHeight - barH;

          return (
            <g key={i} className="group">
              <title>{`${point.label}: €${(point.value / 100).toFixed(2)}`}</title>
              <rect
                x={x}
                y={y}
                width={barWidth}
                height={barH}
                fill="#2D6A4F"
                rx="1"
                className="transition-all duration-200 hover:fill-[#245a42]"
              />
              {/* Label (show every ~7 bars or if narrow) */}
              {data.length <= 31 && (
                <text
                  x={x + barWidth / 2}
                  y={height - 2}
                  textAnchor="middle"
                  fontSize="2.5"
                  fill="#9ca3af"
                >
                  {point.label.slice(5, 10)}
                </text>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}
