// BarChart — data: [{ label, value, color }]
function BarChart({ data, height = 220, formatter = fmt$ }) {
  const ref = React.useRef(null);
  const { w } = useSize(ref);
  const padL = 56, padR = 16, padT = 12, padB = 32;
  const innerW = Math.max(100, w - padL - padR);
  const innerH = height - padT - padB;
  const max = Math.max(...data.map(d => d.value), 1);
  const ticks = 4;
  const tickVals = Array.from({ length: ticks + 1 }, (_, i) => (max / ticks) * i);
  const niceMax = Math.ceil(max / 1000) * 1000;
  const barW = innerW / data.length * 0.56;
  const gap = innerW / data.length;

  return (
    <div ref={ref} style={{ width: '100%', height }}>
      <svg width="100%" height={height} style={{ display: 'block' }}>
        {/* gridlines */}
        {tickVals.map((v, i) => {
          const y = padT + innerH - (v / niceMax) * innerH;
          return (
            <g key={i}>
              <line x1={padL} x2={w - padR} y1={y} y2={y} stroke="var(--border)" strokeWidth="1"/>
              <text x={padL - 8} y={y + 3} fontSize="10" fill="var(--text-tertiary)" textAnchor="end">
                {formatter(v, { compact: true })}
              </text>
            </g>
          );
        })}
        {/* bars */}
        {data.map((d, i) => {
          const x = padL + gap * i + (gap - barW) / 2;
          const h = (d.value / niceMax) * innerH;
          const y = padT + innerH - h;
          return (
            <g key={i}>
              <rect x={x} y={y} width={barW} height={h} fill={d.color || 'var(--accent)'} rx="3"/>
              <text x={x + barW / 2} y={padT + innerH + 18} fontSize="11" fill="var(--text-tertiary)" textAnchor="middle">{d.label}</text>
              <text x={x + barW / 2} y={y - 6} fontSize="10.5" fill="var(--text-secondary)" textAnchor="middle" fontWeight="500">
                {formatter(d.value, { compact: true })}
              </text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

Object.assign(window, { BarChart });
