import { useMemo } from 'react'; import { SEGMENT_COLORS } from '../../lib/consts'; import { formatValue, roundedPercentages } from '../../lib/format'; interface Segment { name: string; value: number; } interface StackedBarChartProps { segments: Segment[]; total: number; /** Optional custom colors keyed by segment name. Falls back to SEGMENT_COLORS. */ colorMap?: Record; } /** Strip common suffixes/prefixes to produce short legend labels */ function shortenLabel(name: string): string { return name .replace(' (avg/yr)', '') .replace(/^% /, '') .replace('and sexual offences', '') .replace('and arson', '') .replace('from the person', '') .replace('Possession of weapons', 'Weapons') .replace('Anti-social behaviour', 'Anti-social') .replace('Criminal damage', 'Damage') .trim(); } export default function StackedBarChart({ segments, total, colorMap }: StackedBarChartProps) { const sortedSegments = useMemo(() => [...segments].sort((a, b) => b.value - a.value), [segments]); const roundedPcts = useMemo( () => roundedPercentages(sortedSegments.map((s) => s.value), total, 1), [sortedSegments, total] ); if (total === 0) { return
No data
; } return (
{/* Stacked bar */}
{sortedSegments.map((segment, i) => { const pct = (segment.value / total) * 100; if (pct < 0.5) return null; return (
); })}
{/* Legend */}
{sortedSegments.map((segment, i) => (
{shortenLabel(segment.name)} {formatValue(segment.value)}
))}
); }