FilamentTrends.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. const totalPrints = archives.reduce((sum, a) => sum + (a.quantity || 1), 0);
  215. const printerCount = new Set(archives.map(a => a.printer_id).filter(Boolean)).size;
  216. return (
  217. <div className="space-y-4">
  218. {/* Summary Cards */}
  219. <div className="grid grid-cols-3 gap-2 max-[640px]:grid-cols-1">
  220. <div className="bg-bambu-dark rounded-lg p-4">
  221. <div className="flex items-center justify-between gap-2">
  222. <p className="text-sm text-bambu-gray leading-none">{t('stats.periodFilament')}</p>
  223. <p className="text-2xl font-bold text-white leading-none">{formatWeight(totalFilament)}</p>
  224. </div>
  225. <p className="text-xs text-bambu-gray">{printerCount} {t('nav.printers').toLowerCase()}</p>
  226. </div>
  227. <div className="bg-bambu-dark rounded-lg p-4">
  228. <div className="flex items-center justify-between gap-2">
  229. <p className="text-sm text-bambu-gray leading-none">{t('stats.periodCost')}</p>
  230. <p className="text-2xl font-bold text-white leading-none">{currency}{totalCost.toFixed(2)}</p>
  231. </div>
  232. <p className="text-xs text-bambu-gray">{totalPrints} {t('common.prints')}</p>
  233. </div>
  234. <div className="bg-bambu-dark rounded-lg p-4">
  235. <div className="flex items-center justify-between gap-2">
  236. <p className="text-sm text-bambu-gray leading-none">{t('stats.avgPerPrint')}</p>
  237. <p className="text-2xl font-bold text-white leading-none">
  238. {totalPrints > 0
  239. ? (totalFilament / totalPrints).toFixed(0)
  240. : 0}g
  241. </p>
  242. </div>
  243. <p className="text-xs text-bambu-gray">
  244. {currency}{totalPrints > 0 ? (totalCost / totalPrints).toFixed(2) : '0.00'} avg
  245. </p>
  246. </div>
  247. </div>
  248. {/* Usage Over Time Chart */}
  249. {chartData.length > 0 ? (
  250. <div className="bg-bambu-dark rounded-lg p-4">
  251. <h4 className="text-sm font-medium text-bambu-gray mb-4">{t('stats.usageOverTime')}</h4>
  252. <ResponsiveContainer width="100%" height={250}>
  253. <AreaChart data={chartData}>
  254. <defs>
  255. <linearGradient id="colorFilament" x1="0" y1="0" x2="0" y2="1">
  256. <stop offset="5%" stopColor="#00ae42" stopOpacity={0.3}/>
  257. <stop offset="95%" stopColor="#00ae42" stopOpacity={0}/>
  258. </linearGradient>
  259. </defs>
  260. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  261. <XAxis
  262. dataKey="dateLabel"
  263. stroke="#9ca3af"
  264. tick={{ fontSize: 12 }}
  265. interval="preserveStartEnd"
  266. />
  267. <YAxis
  268. stroke="#9ca3af"
  269. tick={{ fontSize: 12 }}
  270. tickFormatter={(value) => `${value}g`}
  271. />
  272. <Tooltip
  273. contentStyle={{
  274. backgroundColor: '#2d2d2d',
  275. border: '1px solid #3d3d3d',
  276. borderRadius: '8px',
  277. }}
  278. labelStyle={{ color: '#fff' }}
  279. formatter={(value) => [`${Number(value ?? 0).toFixed(0)}g`, 'Filament']}
  280. />
  281. <Area
  282. type="monotone"
  283. dataKey="filament"
  284. stroke="#00ae42"
  285. strokeWidth={2}
  286. fillOpacity={1}
  287. fill="url(#colorFilament)"
  288. />
  289. </AreaChart>
  290. </ResponsiveContainer>
  291. </div>
  292. ) : (
  293. <div className="bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray">
  294. {t('stats.noPrintDataInRange')}
  295. </div>
  296. )}
  297. {/* Energy Over Time Chart (#1432) — only when smart-plug per-print data exists */}
  298. {totalEnergy > 0 && chartData.length > 0 && (
  299. <div className="bg-bambu-dark rounded-lg p-4">
  300. <div className="flex items-center justify-between mb-4">
  301. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.energyOverTime')}</h4>
  302. <span className="text-xs text-bambu-gray">
  303. {totalEnergy.toFixed(3)} kWh · {currency}{totalEnergyCost.toFixed(2)}
  304. </span>
  305. </div>
  306. <ResponsiveContainer width="100%" height={250}>
  307. <AreaChart data={chartData}>
  308. <defs>
  309. <linearGradient id="colorEnergy" x1="0" y1="0" x2="0" y2="1">
  310. <stop offset="5%" stopColor="#f59e0b" stopOpacity={0.3}/>
  311. <stop offset="95%" stopColor="#f59e0b" stopOpacity={0}/>
  312. </linearGradient>
  313. </defs>
  314. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  315. <XAxis
  316. dataKey="dateLabel"
  317. stroke="#9ca3af"
  318. tick={{ fontSize: 12 }}
  319. interval="preserveStartEnd"
  320. />
  321. <YAxis
  322. stroke="#9ca3af"
  323. tick={{ fontSize: 12 }}
  324. tickFormatter={(value) => `${value}kWh`}
  325. />
  326. <Tooltip
  327. contentStyle={{
  328. backgroundColor: '#2d2d2d',
  329. border: '1px solid #3d3d3d',
  330. borderRadius: '8px',
  331. }}
  332. labelStyle={{ color: '#fff' }}
  333. formatter={(value) => [`${Number(value ?? 0).toFixed(3)} kWh`, t('stats.energyUsed')]}
  334. />
  335. <Area
  336. type="monotone"
  337. dataKey="energy"
  338. stroke="#f59e0b"
  339. strokeWidth={2}
  340. fillOpacity={1}
  341. fill="url(#colorEnergy)"
  342. />
  343. </AreaChart>
  344. </ResponsiveContainer>
  345. </div>
  346. )}
  347. {/* Bottom Charts */}
  348. <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
  349. {/* Filament Type Distribution */}
  350. <div className="bg-bambu-dark rounded-lg p-4">
  351. <div className="flex items-center justify-between mb-4">
  352. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.byMaterial')}</h4>
  353. <MetricToggle value={filamentTypeMetric} onChange={setFilamentTypeMetric} />
  354. </div>
  355. {activeFilamentTypeData.length > 0 ? (
  356. <div className="flex items-center gap-4">
  357. <ResponsiveContainer width={160} height={160}>
  358. <PieChart>
  359. <Pie
  360. data={activeFilamentTypeData}
  361. cx="50%"
  362. cy="50%"
  363. innerRadius={40}
  364. outerRadius={70}
  365. paddingAngle={2}
  366. dataKey="value"
  367. >
  368. {activeFilamentTypeData.map((_, index) => (
  369. <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
  370. ))}
  371. </Pie>
  372. <Tooltip
  373. contentStyle={{
  374. backgroundColor: '#2d2d2d',
  375. border: '1px solid #3d3d3d',
  376. borderRadius: '8px',
  377. }}
  378. formatter={(value) => [
  379. filamentTypeMetric === 'weight' ? formatWeight(Number(value ?? 0)) :
  380. filamentTypeMetric === 'time' ? `${Number(value ?? 0)}h` :
  381. `${value ?? 0}`,
  382. filamentTypeMetric === 'weight' ? 'Usage' : filamentTypeMetric === 'time' ? 'Time' : 'Prints',
  383. ]}
  384. />
  385. </PieChart>
  386. </ResponsiveContainer>
  387. <div className="flex-1 space-y-2 overflow-hidden">
  388. {activeFilamentTypeData.map((entry, index) => {
  389. const total = activeFilamentTypeData.reduce((sum, e) => sum + e.value, 0);
  390. const percent = total > 0 ? ((entry.value / total) * 100).toFixed(0) : 0;
  391. return (
  392. <div key={entry.name} className="flex items-center gap-2 text-sm">
  393. <div
  394. className="w-3 h-3 rounded-sm flex-shrink-0"
  395. style={{ backgroundColor: COLORS[index % COLORS.length] }}
  396. />
  397. <span className="text-white truncate flex-1">{entry.name}</span>
  398. <span className="text-bambu-gray flex-shrink-0">
  399. {filamentTypeMetric === 'weight' ? formatWeight(entry.value) :
  400. filamentTypeMetric === 'time' ? `${entry.value}h` :
  401. entry.value} · {percent}%
  402. </span>
  403. </div>
  404. );
  405. })}
  406. </div>
  407. </div>
  408. ) : (
  409. <div className="h-[160px] flex items-center justify-center text-bambu-gray">
  410. {t('stats.noFilamentData')}
  411. </div>
  412. )}
  413. </div>
  414. {/* Success by Material */}
  415. <div className="bg-bambu-dark rounded-lg p-4">
  416. <h4 className="text-sm font-medium text-bambu-gray mb-4">{t('stats.filamentSuccess')}</h4>
  417. {filamentSuccessData.length > 0 ? (
  418. <div className="space-y-1.5">
  419. {filamentSuccessData.map(d => (
  420. <div key={d.name} className="flex items-center gap-2 text-sm">
  421. <span className="text-white truncate w-20 flex-shrink-0">{d.name}</span>
  422. <div className="flex-1 h-1.5 bg-bambu-dark-secondary rounded-full">
  423. <div
  424. className={`h-full rounded-full transition-all ${
  425. d.rate >= 90 ? 'bg-status-ok' : d.rate >= 70 ? 'bg-status-warning' : 'bg-status-error'
  426. }`}
  427. style={{ width: `${d.rate}%` }}
  428. />
  429. </div>
  430. <span className={`font-medium flex-shrink-0 tabular-nums ${
  431. d.rate >= 90 ? 'text-status-ok' : d.rate >= 70 ? 'text-status-warning' : 'text-status-error'
  432. }`}>
  433. {d.rate}%
  434. </span>
  435. <span className="text-bambu-gray flex-shrink-0 text-xs">({d.total})</span>
  436. </div>
  437. ))}
  438. </div>
  439. ) : (
  440. <div className="h-[160px] flex items-center justify-center text-bambu-gray">
  441. {t('stats.noArchiveData')}
  442. </div>
  443. )}
  444. </div>
  445. {/* Color Distribution */}
  446. <div className="bg-bambu-dark rounded-lg p-4">
  447. <div className="flex items-center justify-between mb-4">
  448. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.colorDistribution')}</h4>
  449. <MetricToggle value={colorMetric} onChange={setColorMetric} exclude={['time']} />
  450. </div>
  451. {colorData.length > 0 ? (() => {
  452. const colorTotal = colorData.reduce((sum, e) => sum + e.value, 0);
  453. return (
  454. <div>
  455. <div className="relative mx-auto" style={{ width: 160, height: 160 }}>
  456. <ResponsiveContainer width="100%" height="100%">
  457. <PieChart>
  458. <Pie
  459. data={colorData}
  460. cx="50%"
  461. cy="50%"
  462. innerRadius={45}
  463. outerRadius={70}
  464. paddingAngle={2}
  465. dataKey="value"
  466. >
  467. {colorData.map((entry, index) => (
  468. <Cell key={`color-${index}`} fill={entry.hex} stroke="#1a1a1a" strokeWidth={1} />
  469. ))}
  470. </Pie>
  471. <Tooltip
  472. contentStyle={{
  473. backgroundColor: '#2d2d2d',
  474. border: '1px solid #3d3d3d',
  475. borderRadius: '8px',
  476. }}
  477. formatter={(value) => [
  478. colorMetric === 'weight' ? formatWeight(Number(value ?? 0)) : `${value ?? 0}`,
  479. colorMetric === 'weight' ? t('stats.filamentByWeight') : t('stats.filamentByPrints'),
  480. ]}
  481. />
  482. </PieChart>
  483. </ResponsiveContainer>
  484. <div className="absolute inset-0 flex flex-col items-center justify-center">
  485. <span className="text-lg font-bold text-white">
  486. {colorMetric === 'weight' ? formatWeight(colorTotal) : colorTotal}
  487. </span>
  488. <span className="text-[10px] text-bambu-gray">
  489. {colorData.length} {colorData.length === 1 ? 'color' : 'colors'}
  490. </span>
  491. </div>
  492. </div>
  493. <div className="grid grid-cols-2 gap-x-3 gap-y-1 mt-2">
  494. {colorData.slice(0, 8).map((entry) => {
  495. const percent = colorTotal > 0 ? ((entry.value / colorTotal) * 100).toFixed(0) : 0;
  496. return (
  497. <div key={entry.hex} className="flex items-center gap-1.5 text-xs min-w-0">
  498. <div className="w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20"
  499. style={{ backgroundColor: entry.hex }} />
  500. <span className="text-bambu-gray truncate">
  501. {percent}%
  502. </span>
  503. </div>
  504. );
  505. })}
  506. </div>
  507. {colorData.length > 8 && (
  508. <p className="text-[10px] text-bambu-gray mt-1 text-center">+{colorData.length - 8} more</p>
  509. )}
  510. </div>
  511. );
  512. })() : (
  513. <div className="h-[160px] flex items-center justify-center text-bambu-gray">
  514. {t('stats.noColorData')}
  515. </div>
  516. )}
  517. </div>
  518. </div>
  519. </div>
  520. );
  521. }