/** Dependency-free SVG bar chart. Real data only; a visually-hidden table gives screen readers the same numbers. */
export function BarChart({ title, data, height = 160 }: { title: string; data: ReadonlyArray<{ label: string; value: number }>; height?: number }) {
  const max = Math.max(1, ...data.map((d) => d.value));
  const width = Math.max(data.length * 22, 240);
  const barW = Math.max(6, Math.floor(width / Math.max(data.length, 1)) - 6);
  const every = Math.max(1, Math.ceil(data.length / 8));
  return (
    <figure className="space-y-2">
      <figcaption className="text-sm font-medium">{title}</figcaption>
      {data.length === 0 || data.every((d) => d.value === 0) ? <p className="text-sm text-muted-foreground">No data in this period.</p> : (
        <>
          <svg role="img" aria-label={`${title}. Highest value ${max}.`} viewBox={`0 0 ${width} ${height + 20}`} className="h-auto w-full max-w-2xl text-primary">
            {data.map((d, i) => {
              const h = Math.round((d.value / max) * height);
              const x = i * (width / data.length) + 3;
              return (
                <g key={d.label}>
                  <rect x={x} y={height - h} width={barW} height={h} rx={2} fill="currentColor"><title>{`${d.label}: ${d.value}`}</title></rect>
                  {i % every === 0 ? <text x={x + barW / 2} y={height + 14} textAnchor="middle" fontSize="9" fill="currentColor" className="text-muted-foreground">{d.label.length > 5 ? d.label.slice(5) : d.label}</text> : null}
                </g>
              );
            })}
          </svg>
          <table className="sr-only"><caption>{title}</caption><thead><tr><th>Label</th><th>Value</th></tr></thead><tbody>{data.map((d) => <tr key={d.label}><td>{d.label}</td><td>{d.value}</td></tr>)}</tbody></table>
        </>
      )}
    </figure>
  );
}
