/**
 * 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 = 120 }: TrendChartProps) {
  if (data.length === 0) return null;

  const chartWidth = Math.max(420, data.length * 26);
  const padding = { top: 12, right: 14, bottom: 28, left: 14 };
  const plotWidth = chartWidth - padding.left - padding.right;
  const chartHeight = Math.max(60, height - padding.top - padding.bottom);
  const barWidth = Math.min(16, Math.max(7, (plotWidth / data.length) * 0.62));
  const gap = Math.max(4, (plotWidth - barWidth * data.length) / Math.max(data.length + 1, 1));

  return (
    <div className="w-full overflow-x-auto rounded-xl bg-white">
      <svg
        viewBox={`0 0 ${chartWidth} ${height}`}
        className="block min-w-full"
        style={{ width: '100%', minWidth: `${chartWidth}px`, height: `${height}px` }}
        aria-label="Tendencia de ventas"
        role="img"
      >
        {/* Y-axis baseline */}
        <line
          x1={padding.left}
          y1={padding.top + chartHeight}
          x2={chartWidth - padding.right}
          y2={padding.top + chartHeight}
          stroke="#e5e7eb"
          strokeWidth="1"
        />

        {data.map((point, i) => {
          const barH = maxValue > 0 ? (point.value / maxValue) * chartHeight : 0;
          const x = padding.left + gap + i * (barWidth + gap);
          const y = padding.top + 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="3"
                className="transition-all duration-200 hover:fill-[#245a42]"
              />
              {data.length <= 31 && (
                <text
                  x={x + barWidth / 2}
                  y={height - 8}
                  textAnchor="middle"
                  fontSize="11"
                  fontWeight="500"
                  fill="#9ca3af"
                >
                  {point.label.slice(5, 10)}
                </text>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}
