import { svgText, escapeXml } from './chart-utils.js';
/**
 * Build a responsive SVG pie chart.
 * Returns empty string when slices array is empty or all values are zero.
 */
export function buildSvgPieChart(slices, size) {
    if (slices.length === 0) {
        return '';
    }
    const total = slices.reduce((s, p) => s + p.value, 0);
    if (total === 0) {
        return '';
    }
    const vbSize = size ?? 220;
    const cx = vbSize / 2;
    const cy = vbSize / 2;
    const r = (vbSize / 2) * 0.65;
    let startAngle = -Math.PI / 2; // start at top
    const paths = [];
    for (const slice of slices) {
        const angle = (slice.value / total) * 2 * Math.PI;
        const endAngle = startAngle + angle;
        const largeArc = angle > Math.PI ? 1 : 0;
        const x1 = cx + r * Math.cos(startAngle);
        const y1 = cy + r * Math.sin(startAngle);
        const x2 = cx + r * Math.cos(endAngle);
        const y2 = cy + r * Math.sin(endAngle);
        const d = [
            `M ${cx.toFixed(1)} ${cy.toFixed(1)}`,
            `L ${x1.toFixed(2)} ${y1.toFixed(2)}`,
            `A ${r.toFixed(1)} ${r.toFixed(1)} 0 ${largeArc} 1 ${x2.toFixed(2)} ${y2.toFixed(2)}`,
            'Z',
        ].join(' ');
        paths.push(`<path d="${d}" fill="${escapeXml(slice.color)}" stroke="white" stroke-width="1.5"/>`);
        startAngle = endAngle;
    }
    // Legend below the pie
    const legendItems = slices.map((s, i) => {
        const lx = 8;
        const ly = vbSize + 14 + i * 16;
        const pct = ((s.value / total) * 100).toFixed(1);
        const short = s.label.length > 20 ? s.label.slice(0, 19) + '…' : s.label;
        return `<rect x="${lx}" y="${ly - 9}" width="10" height="10" fill="${escapeXml(s.color)}" rx="2"/>
${svgText(lx + 14, ly, `${short}: ${pct}%`, { fontSize: 10, anchor: 'start', fill: '#4b5563' })}`;
    });
    const totalHeight = vbSize + 14 + slices.length * 16;
    return `<svg viewBox="0 0 ${vbSize} ${totalHeight}" xmlns="http://www.w3.org/2000/svg" style="width:100%;max-width:${vbSize}px">
  ${paths.join('\n  ')}
  ${legendItems.join('\n  ')}
</svg>`;
}
//# sourceMappingURL=pie-chart.js.map