import { scaleLinear, svgText, CHART_COLORS, escapeXml } from './chart-utils.js';
const PADDING = { top: 40, right: 20, bottom: 60, left: 50 };
/** Build a responsive SVG bar chart. Returns empty string when data is empty. */
export function buildSvgBarChart(data, options) {
    if (data.length === 0) {
        return '';
    }
    const vbW = options?.width ?? 500;
    const vbH = options?.height ?? 300;
    const title = options?.title ?? '';
    const innerW = vbW - PADDING.left - PADDING.right;
    const innerH = vbH - PADDING.top - PADDING.bottom;
    const maxVal = Math.max(...data.map((d) => d.value), 1);
    const yScale = scaleLinear([0, maxVal], [innerH, 0]);
    const barW = Math.max(2, Math.floor(innerW / data.length) - 4);
    const bars = data.map((d, i) => {
        const x = PADDING.left + i * (innerW / data.length) + (innerW / data.length - barW) / 2;
        const barH = innerH - yScale(d.value);
        const y = PADDING.top + yScale(d.value);
        const color = d.color ?? CHART_COLORS[i % CHART_COLORS.length] ?? '#e94560';
        const labelX = x + barW / 2;
        const labelY = vbH - PADDING.bottom + 16;
        const shortLabel = d.label.length > 10 ? d.label.slice(0, 9) + '…' : d.label;
        return `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${barW}" height="${Math.max(0, barH).toFixed(1)}" fill="${escapeXml(color)}" rx="2"/>
${svgText(labelX, labelY, shortLabel, { fontSize: 10, anchor: 'middle', fill: '#6b7280' })}
${svgText(labelX, y - 4, String(d.value), { fontSize: 10, anchor: 'middle', fill: '#2d3436' })}`;
    });
    const yTicks = buildYTicks(maxVal, vbW, PADDING, innerH, yScale);
    const titleEl = title
        ? svgText(vbW / 2, 20, title, { fontSize: 13, anchor: 'middle', fill: '#1a1a2e' })
        : '';
    return `<svg viewBox="0 0 ${vbW} ${vbH}" xmlns="http://www.w3.org/2000/svg" style="width:100%;max-width:${vbW}px">
  ${titleEl}
  ${yTicks}
  ${bars.join('\n  ')}
  <line x1="${PADDING.left}" y1="${PADDING.top}" x2="${PADDING.left}" y2="${PADDING.top + innerH}" stroke="#e9ecef" stroke-width="1"/>
  <line x1="${PADDING.left}" y1="${PADDING.top + innerH}" x2="${PADDING.left + innerW}" y2="${PADDING.top + innerH}" stroke="#e9ecef" stroke-width="1"/>
</svg>`;
}
function buildYTicks(maxVal, vbW, padding, _innerH, yScale) {
    const tickCount = 4;
    return Array.from({ length: tickCount + 1 }, (_, i) => {
        const val = (maxVal / tickCount) * i;
        const y = padding.top + yScale(val);
        const label = Number.isInteger(val) ? String(val) : val.toFixed(1);
        return `<line x1="${padding.left}" y1="${y.toFixed(1)}" x2="${padding.left + (vbW - padding.left - padding.right)}" y2="${y.toFixed(1)}" stroke="#f3f4f6" stroke-width="1"/>
${svgText(padding.left - 6, y + 4, label, { fontSize: 9, anchor: 'end', fill: '#9ca3af' })}`;
    }).join('\n  ');
}
//# sourceMappingURL=bar-chart.js.map