FilamentTrends.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. import { useMemo, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import {
  4. AreaChart,
  5. Area,
  6. XAxis,
  7. YAxis,
  8. CartesianGrid,
  9. Tooltip,
  10. ResponsiveContainer,
  11. PieChart,
  12. Pie,
  13. Cell,
  14. } from 'recharts';
  15. import type { ArchiveSlim } from '../api/client';
  16. import { MetricToggle, type Metric } from './MetricToggle';
  17. import { parseUTCDate } from '../utils/date';
  18. import { formatWeight } from '../utils/weight';
  19. interface FilamentTrendsProps {
  20. archives: ArchiveSlim[];
  21. currency?: string;
  22. dateFrom?: string;
  23. dateTo?: string;
  24. }
  25. const COLORS = ['#00ae42', '#3b82f6', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#14b8a6', '#f97316'];
  26. const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  27. const HOUR_SUFFIXES = ['12am', '1am', '2am', '3am', '4am', '5am', '6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm', '9pm', '10pm', '11pm'];
  28. export function FilamentTrends({ archives, currency = '$', dateFrom, dateTo }: FilamentTrendsProps) {
  29. const { t } = useTranslation();
  30. const [filamentTypeMetric, setFilamentTypeMetric] = useState<Metric>('weight');
  31. const [colorMetric, setColorMetric] = useState<Metric>('weight');
  32. // Calculate daily usage data
  33. const dailyData = useMemo(() => {
  34. const dataMap = new Map<string, { date: string; filament: number; cost: number; energy: number; prints: number }>();
  35. archives.forEach(archive => {
  36. const date = parseUTCDate(archive.completed_at || archive.created_at) || new Date();
  37. // Use local date string for grouping
  38. const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  39. const existing = dataMap.get(key) || { date: key, filament: 0, cost: 0, energy: 0, prints: 0 };
  40. existing.filament += archive.filament_used_grams || 0;
  41. existing.cost += archive.cost || 0;
  42. existing.energy += archive.energy_kwh || 0;
  43. existing.prints += archive.quantity ?? 1;
  44. dataMap.set(key, existing);
  45. });
  46. return Array.from(dataMap.values())
  47. .sort((a, b) => a.date.localeCompare(b.date))
  48. .map(d => ({
  49. ...d,
  50. dateLabel: new Date(d.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
  51. }));
  52. }, [archives]);
  53. // Compute effective span in days from props or archive spread
  54. const spanDays = useMemo(() => {
  55. if (dateFrom && dateTo) {
  56. return Math.max((new Date(dateTo).getTime() - new Date(dateFrom).getTime()) / 86400000, 0) + 1;
  57. }
  58. if (dateFrom) {
  59. return Math.max((Date.now() - new Date(dateFrom).getTime()) / 86400000, 0) + 1;
  60. }
  61. if (archives.length < 2) return 0;
  62. const times = archives.map(a => new Date(a.completed_at || a.created_at).getTime());
  63. return (Math.max(...times) - Math.min(...times)) / 86400000;
  64. }, [archives, dateFrom, dateTo]);
  65. // Calculate hourly data for short timeframes (≤ 7 days)
  66. const hourlyData = useMemo(() => {
  67. if (spanDays > 7) return [];
  68. const dataMap = new Map<string, { date: string; filament: number; cost: number; energy: number; prints: number }>();
  69. const multiDay = spanDays > 1;
  70. archives.forEach(archive => {
  71. const date = parseUTCDate(archive.completed_at || archive.created_at) || new Date();
  72. const h = date.getHours();
  73. const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}T${String(h).padStart(2, '0')}`;
  74. const existing = dataMap.get(key) || { date: key, filament: 0, cost: 0, energy: 0, prints: 0 };
  75. existing.filament += archive.filament_used_grams || 0;
  76. existing.cost += archive.cost || 0;
  77. existing.energy += archive.energy_kwh || 0;
  78. existing.prints += archive.quantity ?? 1;
  79. dataMap.set(key, existing);
  80. });
  81. return Array.from(dataMap.values())
  82. .sort((a, b) => a.date.localeCompare(b.date))
  83. .map(d => {
  84. const [datePart, hourPart] = d.date.split('T');
  85. const dt = new Date(datePart);
  86. const h = parseInt(hourPart, 10);
  87. const label = multiDay
  88. ? `${DAY_NAMES[dt.getDay()]} ${HOUR_SUFFIXES[h]}`
  89. : HOUR_SUFFIXES[h];
  90. return { ...d, dateLabel: label };
  91. });
  92. }, [archives, spanDays]);
  93. // Calculate weekly aggregated data when there are many daily points
  94. const weeklyData = useMemo(() => {
  95. if (dailyData.length <= 60) return dailyData;
  96. const dataMap = new Map<string, { week: string; filament: number; cost: number; energy: number; prints: number }>();
  97. dailyData.forEach(day => {
  98. const date = new Date(day.date);
  99. const weekStart = new Date(date);
  100. weekStart.setDate(date.getDate() - date.getDay());
  101. const key = `${weekStart.getFullYear()}-${String(weekStart.getMonth() + 1).padStart(2, '0')}-${String(weekStart.getDate()).padStart(2, '0')}`;
  102. const existing = dataMap.get(key) || { week: key, filament: 0, cost: 0, energy: 0, prints: 0 };
  103. existing.filament += day.filament;
  104. existing.cost += day.cost;
  105. existing.energy += day.energy;
  106. existing.prints += day.prints;
  107. dataMap.set(key, existing);
  108. });
  109. return Array.from(dataMap.values())
  110. .sort((a, b) => a.week.localeCompare(b.week))
  111. .map(d => ({
  112. date: d.week,
  113. dateLabel: `Week of ${new Date(d.week).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`,
  114. ...d,
  115. }));
  116. }, [dailyData]);
  117. // Usage by filament type
  118. const filamentTypeData = useMemo(() => {
  119. const dataMap = new Map<string, number>();
  120. archives.forEach(archive => {
  121. const type = archive.filament_type || 'Unknown';
  122. // Handle multiple types (e.g., "PLA, PETG")
  123. const types = type.split(', ');
  124. types.forEach(t => {
  125. const grams = (archive.filament_used_grams || 0) / types.length;
  126. dataMap.set(t, (dataMap.get(t) || 0) + grams);
  127. });
  128. });
  129. return Array.from(dataMap.entries())
  130. .map(([name, value]) => ({ name, value: Math.round(value) }))
  131. .sort((a, b) => b.value - a.value);
  132. }, [archives]);
  133. // Usage by filament type (print count)
  134. const filamentTypePrintData = useMemo(() => {
  135. const dataMap = new Map<string, number>();
  136. archives.forEach(archive => {
  137. const type = archive.filament_type || 'Unknown';
  138. const types = type.split(', ');
  139. types.forEach(t => {
  140. dataMap.set(t, (dataMap.get(t) || 0) + 1);
  141. });
  142. });
  143. return Array.from(dataMap.entries())
  144. .map(([name, value]) => ({ name, value }))
  145. .sort((a, b) => b.value - a.value);
  146. }, [archives]);
  147. // Usage by filament type (print time in hours)
  148. const filamentTypeTimeData = useMemo(() => {
  149. const dataMap = new Map<string, number>();
  150. archives.forEach(archive => {
  151. const type = archive.filament_type || 'Unknown';
  152. const types = type.split(', ');
  153. const seconds = (archive.actual_time_seconds || archive.print_time_seconds || 0) / types.length;
  154. types.forEach(t => {
  155. dataMap.set(t, (dataMap.get(t) || 0) + seconds);
  156. });
  157. });
  158. return Array.from(dataMap.entries())
  159. .map(([name, seconds]) => ({ name, value: Math.round((seconds / 3600) * 10) / 10 }))
  160. .sort((a, b) => b.value - a.value);
  161. }, [archives]);
  162. // Success rate by filament type
  163. const filamentSuccessData = useMemo(() => {
  164. const map = new Map<string, { completed: number; failed: number }>();
  165. archives.forEach(a => {
  166. if (a.status !== 'completed' && a.status !== 'failed') return;
  167. const types = (a.filament_type || 'Unknown').split(', ');
  168. types.forEach(type => {
  169. const entry = map.get(type) || { completed: 0, failed: 0 };
  170. if (a.status === 'completed') entry.completed++;
  171. else entry.failed++;
  172. map.set(type, entry);
  173. });
  174. });
  175. return Array.from(map.entries())
  176. .filter(([, v]) => v.completed + v.failed >= 2)
  177. .map(([name, v]) => {
  178. const total = v.completed + v.failed;
  179. const rate = Math.round((v.completed / total) * 100);
  180. return { name, rate, total };
  181. })
  182. .sort((a, b) => b.rate - a.rate);
  183. }, [archives]);
  184. // Color distribution
  185. const colorData = useMemo(() => {
  186. const colorMap = new Map<string, { count: number; weight: number }>();
  187. archives.forEach(a => {
  188. if (!a.filament_color) return;
  189. const colors = a.filament_color.split(',').map(c => c.trim());
  190. const weightPerColor = (a.filament_used_grams || 0) / colors.length;
  191. colors.forEach(hex => {
  192. const entry = colorMap.get(hex) || { count: 0, weight: 0 };
  193. entry.count++;
  194. entry.weight += weightPerColor;
  195. colorMap.set(hex, entry);
  196. });
  197. });
  198. return Array.from(colorMap.entries())
  199. .map(([hex, data]) => ({
  200. hex,
  201. value: colorMetric === 'prints' ? data.count : Math.round(data.weight),
  202. }))
  203. .sort((a, b) => b.value - a.value);
  204. }, [archives, colorMetric]);
  205. const activeFilamentTypeData =
  206. filamentTypeMetric === 'weight' ? filamentTypeData :
  207. filamentTypeMetric === 'prints' ? filamentTypePrintData :
  208. filamentTypeTimeData;
  209. const chartData = spanDays <= 7 && hourlyData.length > 0 ? hourlyData : weeklyData;
  210. const totalFilament = archives.reduce((sum, a) => sum + (a.filament_used_grams || 0), 0);
  211. const totalCost = archives.reduce((sum, a) => sum + (a.cost || 0), 0);
  212. const totalEnergy = archives.reduce((sum, a) => sum + (a.energy_kwh || 0), 0);
  213. const totalEnergyCost = archives.reduce((sum, a) => sum + (a.energy_cost || 0), 0);
  214. // `??`, not `||`: an archive edited down to 0 produced nothing (#3051), and
  215. // `0 || 1` would count the ruined plate as one print here while the project
  216. // page correctly counts none.
  217. const totalPrints = archives.reduce((sum, a) => sum + (a.quantity ?? 1), 0);
  218. const printerCount = new Set(archives.map(a => a.printer_id).filter(Boolean)).size;
  219. return (
  220. <div className="space-y-4">
  221. {/* Summary Cards */}
  222. <div className="grid grid-cols-3 gap-2 max-[640px]:grid-cols-1">
  223. <div className="bg-bambu-dark rounded-lg p-4">
  224. <div className="flex items-center justify-between gap-2">
  225. <p className="text-sm text-bambu-gray leading-none">{t('stats.periodFilament')}</p>
  226. <p className="text-2xl font-bold text-white leading-none">{formatWeight(totalFilament)}</p>
  227. </div>
  228. <p className="text-xs text-bambu-gray">{printerCount} {t('nav.printers').toLowerCase()}</p>
  229. </div>
  230. <div className="bg-bambu-dark rounded-lg p-4">
  231. <div className="flex items-center justify-between gap-2">
  232. <p className="text-sm text-bambu-gray leading-none">{t('stats.periodCost')}</p>
  233. <p className="text-2xl font-bold text-white leading-none">{currency}{totalCost.toFixed(2)}</p>
  234. </div>
  235. <p className="text-xs text-bambu-gray">{totalPrints} {t('common.prints')}</p>
  236. </div>
  237. <div className="bg-bambu-dark rounded-lg p-4">
  238. <div className="flex items-center justify-between gap-2">
  239. <p className="text-sm text-bambu-gray leading-none">{t('stats.avgPerPrint')}</p>
  240. <p className="text-2xl font-bold text-white leading-none">
  241. {totalPrints > 0
  242. ? (totalFilament / totalPrints).toFixed(0)
  243. : 0}g
  244. </p>
  245. </div>
  246. <p className="text-xs text-bambu-gray">
  247. {currency}{totalPrints > 0 ? (totalCost / totalPrints).toFixed(2) : '0.00'} avg
  248. </p>
  249. </div>
  250. </div>
  251. {/* Usage Over Time Chart */}
  252. {chartData.length > 0 ? (
  253. <div className="bg-bambu-dark rounded-lg p-4">
  254. <h4 className="text-sm font-medium text-bambu-gray mb-4">{t('stats.usageOverTime')}</h4>
  255. <ResponsiveContainer width="100%" height={250}>
  256. <AreaChart data={chartData}>
  257. <defs>
  258. <linearGradient id="colorFilament" x1="0" y1="0" x2="0" y2="1">
  259. <stop offset="5%" stopColor="#00ae42" stopOpacity={0.3}/>
  260. <stop offset="95%" stopColor="#00ae42" stopOpacity={0}/>
  261. </linearGradient>
  262. </defs>
  263. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  264. <XAxis
  265. dataKey="dateLabel"
  266. stroke="#9ca3af"
  267. tick={{ fontSize: 12 }}
  268. interval="preserveStartEnd"
  269. />
  270. <YAxis
  271. stroke="#9ca3af"
  272. tick={{ fontSize: 12 }}
  273. tickFormatter={(value) => `${value}g`}
  274. />
  275. <Tooltip
  276. contentStyle={{
  277. backgroundColor: '#2d2d2d',
  278. border: '1px solid #3d3d3d',
  279. borderRadius: '8px',
  280. }}
  281. labelStyle={{ color: '#fff' }}
  282. formatter={(value) => [`${Number(value ?? 0).toFixed(0)}g`, 'Filament']}
  283. />
  284. <Area
  285. type="monotone"
  286. dataKey="filament"
  287. stroke="#00ae42"
  288. strokeWidth={2}
  289. fillOpacity={1}
  290. fill="url(#colorFilament)"
  291. />
  292. </AreaChart>
  293. </ResponsiveContainer>
  294. </div>
  295. ) : (
  296. <div className="bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray">
  297. {t('stats.noPrintDataInRange')}
  298. </div>
  299. )}
  300. {/* Energy Over Time Chart (#1432) — only when smart-plug per-print data exists */}
  301. {totalEnergy > 0 && chartData.length > 0 && (
  302. <div className="bg-bambu-dark rounded-lg p-4">
  303. <div className="flex items-center justify-between mb-4">
  304. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.energyOverTime')}</h4>
  305. <span className="text-xs text-bambu-gray">
  306. {totalEnergy.toFixed(3)} kWh · {currency}{totalEnergyCost.toFixed(2)}
  307. </span>
  308. </div>
  309. <ResponsiveContainer width="100%" height={250}>
  310. <AreaChart data={chartData}>
  311. <defs>
  312. <linearGradient id="colorEnergy" x1="0" y1="0" x2="0" y2="1">
  313. <stop offset="5%" stopColor="#f59e0b" stopOpacity={0.3}/>
  314. <stop offset="95%" stopColor="#f59e0b" stopOpacity={0}/>
  315. </linearGradient>
  316. </defs>
  317. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  318. <XAxis
  319. dataKey="dateLabel"
  320. stroke="#9ca3af"
  321. tick={{ fontSize: 12 }}
  322. interval="preserveStartEnd"
  323. />
  324. <YAxis
  325. stroke="#9ca3af"
  326. tick={{ fontSize: 12 }}
  327. tickFormatter={(value) => `${value}kWh`}
  328. />
  329. <Tooltip
  330. contentStyle={{
  331. backgroundColor: '#2d2d2d',
  332. border: '1px solid #3d3d3d',
  333. borderRadius: '8px',
  334. }}
  335. labelStyle={{ color: '#fff' }}
  336. formatter={(value) => [`${Number(value ?? 0).toFixed(3)} kWh`, t('stats.energyUsed')]}
  337. />
  338. <Area
  339. type="monotone"
  340. dataKey="energy"
  341. stroke="#f59e0b"
  342. strokeWidth={2}
  343. fillOpacity={1}
  344. fill="url(#colorEnergy)"
  345. />
  346. </AreaChart>
  347. </ResponsiveContainer>
  348. </div>
  349. )}
  350. {/* Bottom Charts */}
  351. <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
  352. {/* Filament Type Distribution */}
  353. <div className="bg-bambu-dark rounded-lg p-4">
  354. <div className="flex items-center justify-between mb-4">
  355. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.byMaterial')}</h4>
  356. <MetricToggle value={filamentTypeMetric} onChange={setFilamentTypeMetric} />
  357. </div>
  358. {activeFilamentTypeData.length > 0 ? (
  359. <div className="flex items-center gap-4">
  360. <ResponsiveContainer width={160} height={160}>
  361. <PieChart>
  362. <Pie
  363. data={activeFilamentTypeData}
  364. cx="50%"
  365. cy="50%"
  366. innerRadius={40}
  367. outerRadius={70}
  368. paddingAngle={2}
  369. dataKey="value"
  370. >
  371. {activeFilamentTypeData.map((_, index) => (
  372. <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
  373. ))}
  374. </Pie>
  375. <Tooltip
  376. contentStyle={{
  377. backgroundColor: '#2d2d2d',
  378. border: '1px solid #3d3d3d',
  379. borderRadius: '8px',
  380. }}
  381. formatter={(value) => [
  382. filamentTypeMetric === 'weight' ? formatWeight(Number(value ?? 0)) :
  383. filamentTypeMetric === 'time' ? `${Number(value ?? 0)}h` :
  384. `${value ?? 0}`,
  385. filamentTypeMetric === 'weight' ? 'Usage' : filamentTypeMetric === 'time' ? 'Time' : 'Prints',
  386. ]}
  387. />
  388. </PieChart>
  389. </ResponsiveContainer>
  390. <div className="flex-1 space-y-2 overflow-hidden">
  391. {activeFilamentTypeData.map((entry, index) => {
  392. const total = activeFilamentTypeData.reduce((sum, e) => sum + e.value, 0);
  393. const percent = total > 0 ? ((entry.value / total) * 100).toFixed(0) : 0;
  394. return (
  395. <div key={entry.name} className="flex items-center gap-2 text-sm">
  396. <div
  397. className="w-3 h-3 rounded-sm flex-shrink-0"
  398. style={{ backgroundColor: COLORS[index % COLORS.length] }}
  399. />
  400. <span className="text-white truncate flex-1">{entry.name}</span>
  401. <span className="text-bambu-gray flex-shrink-0">
  402. {filamentTypeMetric === 'weight' ? formatWeight(entry.value) :
  403. filamentTypeMetric === 'time' ? `${entry.value}h` :
  404. entry.value} · {percent}%
  405. </span>
  406. </div>
  407. );
  408. })}
  409. </div>
  410. </div>
  411. ) : (
  412. <div className="h-[160px] flex items-center justify-center text-bambu-gray">
  413. {t('stats.noFilamentData')}
  414. </div>
  415. )}
  416. </div>
  417. {/* Success by Material */}
  418. <div className="bg-bambu-dark rounded-lg p-4">
  419. <h4 className="text-sm font-medium text-bambu-gray mb-4">{t('stats.filamentSuccess')}</h4>
  420. {filamentSuccessData.length > 0 ? (
  421. <div className="space-y-1.5">
  422. {filamentSuccessData.map(d => (
  423. <div key={d.name} className="flex items-center gap-2 text-sm">
  424. <span className="text-white truncate w-20 flex-shrink-0">{d.name}</span>
  425. <div className="flex-1 h-1.5 bg-bambu-dark-secondary rounded-full">
  426. <div
  427. className={`h-full rounded-full transition-all ${
  428. d.rate >= 90 ? 'bg-status-ok' : d.rate >= 70 ? 'bg-status-warning' : 'bg-status-error'
  429. }`}
  430. style={{ width: `${d.rate}%` }}
  431. />
  432. </div>
  433. <span className={`font-medium flex-shrink-0 tabular-nums ${
  434. d.rate >= 90 ? 'text-status-ok' : d.rate >= 70 ? 'text-status-warning' : 'text-status-error'
  435. }`}>
  436. {d.rate}%
  437. </span>
  438. <span className="text-bambu-gray flex-shrink-0 text-xs">({d.total})</span>
  439. </div>
  440. ))}
  441. </div>
  442. ) : (
  443. <div className="h-[160px] flex items-center justify-center text-bambu-gray">
  444. {t('stats.noArchiveData')}
  445. </div>
  446. )}
  447. </div>
  448. {/* Color Distribution */}
  449. <div className="bg-bambu-dark rounded-lg p-4">
  450. <div className="flex items-center justify-between mb-4">
  451. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.colorDistribution')}</h4>
  452. <MetricToggle value={colorMetric} onChange={setColorMetric} exclude={['time']} />
  453. </div>
  454. {colorData.length > 0 ? (() => {
  455. const colorTotal = colorData.reduce((sum, e) => sum + e.value, 0);
  456. return (
  457. <div>
  458. <div className="relative mx-auto" style={{ width: 160, height: 160 }}>
  459. <ResponsiveContainer width="100%" height="100%">
  460. <PieChart>
  461. <Pie
  462. data={colorData}
  463. cx="50%"
  464. cy="50%"
  465. innerRadius={45}
  466. outerRadius={70}
  467. paddingAngle={2}
  468. dataKey="value"
  469. >
  470. {colorData.map((entry, index) => (
  471. <Cell key={`color-${index}`} fill={entry.hex} stroke="#1a1a1a" strokeWidth={1} />
  472. ))}
  473. </Pie>
  474. <Tooltip
  475. contentStyle={{
  476. backgroundColor: '#2d2d2d',
  477. border: '1px solid #3d3d3d',
  478. borderRadius: '8px',
  479. }}
  480. formatter={(value) => [
  481. colorMetric === 'weight' ? formatWeight(Number(value ?? 0)) : `${value ?? 0}`,
  482. colorMetric === 'weight' ? t('stats.filamentByWeight') : t('stats.filamentByPrints'),
  483. ]}
  484. />
  485. </PieChart>
  486. </ResponsiveContainer>
  487. <div className="absolute inset-0 flex flex-col items-center justify-center">
  488. <span className="text-lg font-bold text-white">
  489. {colorMetric === 'weight' ? formatWeight(colorTotal) : colorTotal}
  490. </span>
  491. <span className="text-[10px] text-bambu-gray">
  492. {colorData.length} {colorData.length === 1 ? 'color' : 'colors'}
  493. </span>
  494. </div>
  495. </div>
  496. <div className="grid grid-cols-2 gap-x-3 gap-y-1 mt-2">
  497. {colorData.slice(0, 8).map((entry) => {
  498. const percent = colorTotal > 0 ? ((entry.value / colorTotal) * 100).toFixed(0) : 0;
  499. return (
  500. <div key={entry.hex} className="flex items-center gap-1.5 text-xs min-w-0">
  501. <div className="w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20"
  502. style={{ backgroundColor: entry.hex }} />
  503. <span className="text-bambu-gray truncate">
  504. {percent}%
  505. </span>
  506. </div>
  507. );
  508. })}
  509. </div>
  510. {colorData.length > 8 && (
  511. <p className="text-[10px] text-bambu-gray mt-1 text-center">+{colorData.length - 8} more</p>
  512. )}
  513. </div>
  514. );
  515. })() : (
  516. <div className="h-[160px] flex items-center justify-center text-bambu-gray">
  517. {t('stats.noColorData')}
  518. </div>
  519. )}
  520. </div>
  521. </div>
  522. </div>
  523. );
  524. }