wows_minimap_renderer 0.25.0

Library/CLI application for rendering World of Warships replay files as a minimap render "
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
use std::collections::HashMap;

use ab_glyph::Font;
use ab_glyph::FontArc;
use ab_glyph::PxScale;
use ab_glyph::ScaleFont;
use image::Rgb;
use image::RgbImage;
use image::RgbaImage;
use tiny_skia::BlendMode;
use tiny_skia::FillRule;
use tiny_skia::FilterQuality;
use tiny_skia::LineCap;
use tiny_skia::LineJoin;
use tiny_skia::Paint;
use tiny_skia::PathBuilder;
use tiny_skia::Pixmap;
use tiny_skia::PixmapPaint;
use tiny_skia::Stroke;
use tiny_skia::StrokeDash;
use tiny_skia::Transform;

use std::sync::Arc;

use crate::STATS_PANEL_WIDTH;
use crate::assets::GameFonts;
use crate::draw_command::ActivityFeedKind;
use crate::draw_command::ChatEntry;
use crate::draw_command::DrawCommand;
use crate::draw_command::FontHint;
use crate::draw_command::KillFeedEntry;
use crate::draw_command::RenderTarget;
use crate::draw_command::ShipVisibility;
use wows_replays::types::ElapsedClock;
use wt_translations::DefaultTextResolver;
use wt_translations::TextResolver;
use wt_translations::TranslatableText;

// ── Pixmap conversion helpers ──────────────────────────────────────────────

/// Convert an RGB image (no alpha) to a tiny-skia Pixmap (opaque RGBA, premultiplied).
fn rgb_to_pixmap(img: &RgbImage) -> Pixmap {
    let w = img.width();
    let h = img.height();
    let mut pm = Pixmap::new(w, h).expect("failed to create pixmap");
    let data = pm.data_mut();
    for y in 0..h {
        for x in 0..w {
            let px = img.get_pixel(x, y).0;
            let idx = (y * w + x) as usize * 4;
            data[idx] = px[0];
            data[idx + 1] = px[1];
            data[idx + 2] = px[2];
            data[idx + 3] = 255;
        }
    }
    pm
}

/// Convert a tiny-skia Pixmap (premultiplied RGBA) back to an RGB image.
fn pixmap_to_rgb(pm: &Pixmap) -> RgbImage {
    let w = pm.width();
    let h = pm.height();
    let data = pm.data();
    let mut img = RgbImage::new(w, h);
    for y in 0..h {
        for x in 0..w {
            let idx = (y * w + x) as usize * 4;
            let a = data[idx + 3] as f32 / 255.0;
            // Unpremultiply alpha
            let (r, g, b) = if a > 0.001 {
                (
                    (data[idx] as f32 / a).min(255.0) as u8,
                    (data[idx + 1] as f32 / a).min(255.0) as u8,
                    (data[idx + 2] as f32 / a).min(255.0) as u8,
                )
            } else {
                (0, 0, 0)
            };
            img.put_pixel(x, y, Rgb([r, g, b]));
        }
    }
    img
}

/// Convert an RGBA image to a tiny-skia Pixmap (premultiplied alpha).
fn rgba_to_pixmap(img: &RgbaImage) -> Pixmap {
    let w = img.width();
    let h = img.height();
    let mut pm = Pixmap::new(w, h).expect("failed to create pixmap");
    let data = pm.data_mut();
    for y in 0..h {
        for x in 0..w {
            let px = img.get_pixel(x, y).0;
            let idx = (y * w + x) as usize * 4;
            let a = px[3] as f32 / 255.0;
            // Premultiply
            data[idx] = (px[0] as f32 * a) as u8;
            data[idx + 1] = (px[1] as f32 * a) as u8;
            data[idx + 2] = (px[2] as f32 * a) as u8;
            data[idx + 3] = px[3];
        }
    }
    pm
}

// ── Paint helpers ──────────────────────────────────────────────────────────

/// Create a solid-color paint with the given RGBA values.
fn solid_paint(r: u8, g: u8, b: u8, a: u8) -> Paint<'static> {
    let mut paint = Paint::default();
    paint.set_color_rgba8(r, g, b, a);
    paint.anti_alias = true;
    paint
}

/// Create a solid-color paint from an [u8; 3] array with alpha.
fn color_paint(color: [u8; 3], alpha: f32) -> Paint<'static> {
    let a = (alpha.clamp(0.0, 1.0) * 255.0) as u8;
    solid_paint(color[0], color[1], color[2], a)
}

// ── Text rendering directly onto Pixmap ────────────────────────────────────

/// Draw anti-aliased text onto a Pixmap at (x, y) with the given color.
///
/// Uses ab_glyph's per-pixel coverage callback for proper anti-aliasing.
/// Coordinates are in pixel space (x = left edge, y = top edge of text).
fn draw_text(pm: &mut Pixmap, color: [u8; 3], x: i32, y: i32, scale: PxScale, font: &impl Font, text: &str) {
    let scaled = font.as_scaled(scale);
    let mut cursor_x = x as f32;
    let baseline_y = y as f32 + scaled.ascent();
    let w = pm.width() as i32;
    let h = pm.height() as i32;
    let data = pm.data_mut();

    let mut last_glyph_id = None;
    for c in text.chars() {
        let glyph_id = scaled.glyph_id(c);
        if let Some(last) = last_glyph_id {
            cursor_x += scaled.kern(last, glyph_id);
        }
        let glyph = glyph_id.with_scale_and_position(scale, ab_glyph::point(cursor_x, baseline_y));
        if let Some(outlined) = font.outline_glyph(glyph) {
            let bounds = outlined.px_bounds();
            outlined.draw(|gx, gy, coverage| {
                let px = gx as i32 + bounds.min.x as i32;
                let py = gy as i32 + bounds.min.y as i32;
                if px < 0 || px >= w || py < 0 || py >= h {
                    return;
                }
                let cov = coverage.clamp(0.0, 1.0);
                if cov < 0.01 {
                    return;
                }
                let idx = (py as usize * w as usize + px as usize) * 4;
                // Read existing premultiplied pixel
                let bg_r = data[idx] as f32;
                let bg_g = data[idx + 1] as f32;
                let bg_b = data[idx + 2] as f32;
                let bg_a = data[idx + 3] as f32;
                // Source color (premultiplied by coverage)
                let src_r = color[0] as f32 * cov;
                let src_g = color[1] as f32 * cov;
                let src_b = color[2] as f32 * cov;
                let src_a = 255.0 * cov;
                // Source-over compositing
                let inv_a = 1.0 - cov;
                data[idx] = (src_r + bg_r * inv_a).min(255.0) as u8;
                data[idx + 1] = (src_g + bg_g * inv_a).min(255.0) as u8;
                data[idx + 2] = (src_b + bg_b * inv_a).min(255.0) as u8;
                data[idx + 3] = (src_a + bg_a * inv_a).min(255.0) as u8;
            });
        }
        cursor_x += scaled.h_advance(glyph_id);
        last_glyph_id = Some(glyph_id);
    }
}

/// Measure the width and height of text at the given scale.
fn text_size(scale: PxScale, font: &impl Font, text: &str) -> (u32, u32) {
    let scaled = font.as_scaled(scale);
    let mut w = 0.0f32;
    let mut last_glyph_id = None;
    for c in text.chars() {
        let glyph_id = scaled.glyph_id(c);
        if let Some(last) = last_glyph_id {
            w += scaled.kern(last, glyph_id);
        }
        w += scaled.h_advance(glyph_id);
        last_glyph_id = Some(glyph_id);
    }
    let h = scaled.ascent() - scaled.descent();
    (w.ceil() as u32, h.ceil() as u32)
}

/// Draw text with a shadow (black offset by +1,+1).
fn draw_text_shadow(pm: &mut Pixmap, color: [u8; 3], x: i32, y: i32, scale: PxScale, font: &impl Font, text: &str) {
    draw_text(pm, [0, 0, 0], x + 1, y + 1, scale, font, text);
    draw_text(pm, color, x, y, scale, font, text);
}

// ── Drawing primitives ─────────────────────────────────────────────────────

/// Draw an anti-aliased line.
fn draw_line(pm: &mut Pixmap, x1: f32, y1: f32, x2: f32, y2: f32, color: [u8; 3], alpha: f32, width: f32) {
    let mut pb = PathBuilder::new();
    pb.move_to(x1, y1);
    pb.line_to(x2, y2);
    let Some(path) = pb.finish() else { return };
    let paint = color_paint(color, alpha);
    let stroke = Stroke { width, line_cap: LineCap::Round, line_join: LineJoin::Round, miter_limit: 4.0, dash: None };
    pm.stroke_path(&path, &paint, &stroke, Transform::identity(), None);
}

/// Draw an anti-aliased filled circle.
fn draw_filled_circle(pm: &mut Pixmap, cx: f32, cy: f32, radius: f32, color: [u8; 3], alpha: f32) {
    let Some(path) = PathBuilder::from_circle(cx, cy, radius) else {
        return;
    };
    let paint = color_paint(color, alpha);
    pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);
}

/// Draw an anti-aliased circle outline.
fn draw_circle_outline(pm: &mut Pixmap, cx: f32, cy: f32, radius: f32, color: [u8; 3], alpha: f32, width: f32) {
    let Some(path) = PathBuilder::from_circle(cx, cy, radius) else {
        return;
    };
    let paint = color_paint(color, alpha);
    let stroke = Stroke { width, line_cap: LineCap::Butt, line_join: LineJoin::Miter, miter_limit: 4.0, dash: None };
    pm.stroke_path(&path, &paint, &stroke, Transform::identity(), None);
}

/// Draw an anti-aliased dashed circle outline.
fn draw_dashed_circle(pm: &mut Pixmap, cx: f32, cy: f32, radius: f32, color: [u8; 3], alpha: f32, width: f32) {
    let Some(path) = PathBuilder::from_circle(cx, cy, radius) else {
        return;
    };
    let paint = color_paint(color, alpha);
    // Dash pattern: 8px on, 8px off
    let dash = StrokeDash::new(vec![8.0, 8.0], 0.0);
    let stroke = Stroke { width, line_cap: LineCap::Butt, line_join: LineJoin::Miter, miter_limit: 4.0, dash };
    pm.stroke_path(&path, &paint, &stroke, Transform::identity(), None);
}

/// Draw a filled rectangle.
fn draw_filled_rect(pm: &mut Pixmap, x: f32, y: f32, w: f32, h: f32, color: [u8; 3], alpha: f32) {
    let Some(rect) = tiny_skia::Rect::from_xywh(x, y, w, h) else {
        return;
    };
    let paint = color_paint(color, alpha);
    pm.fill_rect(rect, &paint, Transform::identity(), None);
}

fn draw_rounded_rect(pm: &mut Pixmap, x: f32, y: f32, w: f32, h: f32, radius: f32, color: [u8; 3], alpha: f32) {
    if w <= 0.0 || h <= 0.0 {
        return;
    }
    let r = radius.min(w / 2.0).min(h / 2.0);
    let mut pb = PathBuilder::new();
    pb.move_to(x + r, y);
    pb.line_to(x + w - r, y);
    pb.quad_to(x + w, y, x + w, y + r);
    pb.line_to(x + w, y + h - r);
    pb.quad_to(x + w, y + h, x + w - r, y + h);
    pb.line_to(x + r, y + h);
    pb.quad_to(x, y + h, x, y + h - r);
    pb.line_to(x, y + r);
    pb.quad_to(x, y, x + r, y);
    pb.close();
    let Some(path) = pb.finish() else {
        return;
    };
    let paint = color_paint(color, alpha);
    pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);
}

// ── Composite drawing functions ────────────────────────────────────────────

/// Draw a capture point zone: filled circle + progress pie + outline + label.
fn draw_capture_point(
    pm: &mut Pixmap,
    x: f32,
    y: f32,
    radius: f32,
    color: [u8; 3],
    alpha: f32,
    label: &str,
    progress: f32,
    invader_color: Option<[u8; 3]>,
    flag_icon: Option<&RgbaImage>,
    fonts: &GameFonts,
) {
    // Base filled circle with owner's color
    draw_filled_circle(pm, x, y, radius, color, alpha);

    // If capture in progress, draw a pie-slice fill in the invader's color
    if progress > 0.001
        && let Some(inv_color) = invader_color
    {
        let fill_alpha = alpha + 0.10;
        // Pie-slice from top (-PI/2), sweeping clockwise by progress * 2*PI
        let start_angle = -std::f32::consts::FRAC_PI_2;
        let sweep = progress * std::f32::consts::TAU;

        let mut pb = PathBuilder::new();
        pb.move_to(x, y);
        // Starting point on circle
        let sx = x + radius * (start_angle).cos();
        let sy = y + radius * (start_angle).sin();
        pb.line_to(sx, sy);

        // Approximate the arc with line segments (smooth enough at this scale)
        let steps = ((sweep / std::f32::consts::TAU) * 64.0).max(4.0) as i32;
        for i in 1..=steps {
            let t = i as f32 / steps as f32;
            let angle = start_angle + sweep * t;
            let px = x + radius * angle.cos();
            let py = y + radius * angle.sin();
            pb.line_to(px, py);
        }
        pb.close();

        if let Some(path) = pb.finish() {
            let paint = color_paint(inv_color, fill_alpha);
            pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);
        }
    }

    // Circle outline
    let outline_color = if let Some(ic) = invader_color
        && progress > 0.001
    {
        ic
    } else {
        color
    };
    draw_circle_outline(pm, x, y, radius, outline_color, 0.6, 2.0);

    // Centered label: icon for base-type, text for domination
    if let Some(icon) = flag_icon {
        draw_icon(pm, icon, x as i32, y as i32);
    } else {
        let scale = fonts.scale(16.0);
        let (tw, th) = text_size(scale, &fonts.primary, label);
        let tx = x as i32 - tw as i32 / 2;
        let ty = y as i32 - th as i32 / 2;
        draw_text_shadow(pm, [255, 255, 255], tx, ty, scale, &fonts.primary, label);
    }
}

/// Draw player name and/or ship name labels centered above a ship icon.
fn draw_ship_labels(
    pm: &mut Pixmap,
    x: i32,
    y: i32,
    player_name: Option<&str>,
    ship_name: Option<&str>,
    name_color: Option<[u8; 3]>,
    fonts: &GameFonts,
) {
    let line_height = 12i32;
    let line_count = player_name.is_some() as i32 + ship_name.is_some() as i32;
    if line_count == 0 {
        return;
    }

    // Apply armament color to ship_name if shown, otherwise player_name
    let color_on_ship = ship_name.is_some();

    // Position lines above the icon (icon radius ~12px)
    let base_y = y - 14 - line_count * line_height;
    let mut cur_y = base_y;

    if let Some(name) = player_name {
        let (font, scale) = fonts.font_and_scale(name, 10.0);
        let color = if !color_on_ship { name_color.unwrap_or([255, 255, 255]) } else { [255, 255, 255] };
        let (w, _) = text_size(scale, font, name);
        let tx = x - w as i32 / 2;
        draw_text_shadow(pm, color, tx, cur_y, scale, font, name);
        cur_y += line_height;
    }
    if let Some(name) = ship_name {
        let (font, scale) = fonts.font_and_scale(name, 10.0);
        let color = name_color.unwrap_or([255, 255, 255]);
        let (w, _) = text_size(scale, font, name);
        let tx = x - w as i32 / 2;
        draw_text_shadow(pm, color, tx, cur_y, scale, font, name);
    }
}

/// Draw a health bar below a ship icon.
fn draw_health_bar(
    pm: &mut Pixmap,
    x: i32,
    y: i32,
    fraction: f32,
    fill_color: [u8; 3],
    bg_color: [u8; 3],
    bg_alpha: f32,
) {
    let bar_w = 20.0f32;
    let bar_h = 3.0f32;
    let bar_x = x as f32 - bar_w / 2.0;
    let bar_y = y as f32 + 10.0;

    let fill_w = (fraction.clamp(0.0, 1.0) * bar_w).round();

    // Background portion
    if fill_w < bar_w {
        draw_filled_rect(pm, bar_x + fill_w, bar_y, bar_w - fill_w, bar_h, bg_color, bg_alpha);
    }
    // Filled portion
    if fill_w > 0.0 {
        draw_filled_rect(pm, bar_x, bar_y, fill_w, bar_h, fill_color, 1.0);
    }
}

/// Draw a ship icon rotated by yaw, with optional team-color tinting.
///
/// Uses tiny-skia's bilinear-filtered transform compositing for smooth rotation.
fn draw_ship_icon(pm: &mut Pixmap, icon: &RgbaImage, x: i32, y: i32, yaw: f32, color: Option<[u8; 3]>, opacity: f32) {
    let iw = icon.width();
    let ih = icon.height();
    let cx = iw as f32 / 2.0;
    let cy = ih as f32 / 2.0;

    // Create a tinted copy of the icon as a Pixmap
    let mut icon_pm = Pixmap::new(iw, ih).expect("failed to create icon pixmap");
    let data = icon_pm.data_mut();
    for iy in 0..ih {
        for ix in 0..iw {
            let px = icon.get_pixel(ix, iy).0;
            let idx = (iy * iw + ix) as usize * 4;
            let a = px[3] as f32 / 255.0;
            if a < 0.01 {
                continue;
            }
            let (r, g, b) = if let Some(c) = color {
                // Tint: use luminance as intensity
                let luminance = (px[0] as f32 * 0.299 + px[1] as f32 * 0.587 + px[2] as f32 * 0.114) / 255.0;
                ((c[0] as f32 * luminance) as u8, (c[1] as f32 * luminance) as u8, (c[2] as f32 * luminance) as u8)
            } else {
                (px[0], px[1], px[2])
            };
            // Premultiply
            data[idx] = (r as f32 * a) as u8;
            data[idx + 1] = (g as f32 * a) as u8;
            data[idx + 2] = (b as f32 * a) as u8;
            data[idx + 3] = px[3];
        }
    }

    // The SVG icons point upward (north = -Y). In game coordinates,
    // yaw=0 means east and increases counter-clockwise.
    // Screen rotation: R = PI/2 - yaw, converted to degrees for tiny-skia.
    let angle_deg = (std::f32::consts::FRAC_PI_2 - yaw).to_degrees();

    // Build transform: translate icon center to destination, then rotate
    let tx = x as f32 - cx;
    let ty = y as f32 - cy;
    let transform = Transform::from_translate(tx, ty).post_rotate_at(angle_deg, x as f32, y as f32);

    let paint = PixmapPaint { opacity, blend_mode: BlendMode::SourceOver, quality: FilterQuality::Bilinear };

    pm.draw_pixmap(0, 0, icon_pm.as_ref(), &paint, transform, None);
}

/// Draw an outline around a ship icon's shape.
///
/// Draws the icon at slightly larger scale with outline color, then the normal icon on top.
fn draw_ship_icon_outline(
    pm: &mut Pixmap,
    icon: &RgbaImage,
    x: i32,
    y: i32,
    yaw: f32,
    outline_color: [u8; 3],
    outline_opacity: f32,
    thickness: i32,
) {
    // Draw outline by rendering the icon shifted in 8 directions
    let offsets: &[(i32, i32)] = &[
        (-thickness, 0),
        (thickness, 0),
        (0, -thickness),
        (0, thickness),
        (-thickness, -thickness),
        (thickness, -thickness),
        (-thickness, thickness),
        (thickness, thickness),
    ];
    for (dx, dy) in offsets {
        draw_ship_icon(pm, icon, x + dx, y + dy, yaw, Some(outline_color), outline_opacity);
    }
}

/// Draw a plane/consumable icon (pre-colored RGBA, no rotation).
fn draw_icon(pm: &mut Pixmap, icon: &RgbaImage, x: i32, y: i32) {
    let iw = icon.width();
    let ih = icon.height();
    let icon_pm = rgba_to_pixmap(icon);
    let tx = x - iw as i32 / 2;
    let ty = y - ih as i32 / 2;
    let paint = PixmapPaint { opacity: 1.0, blend_mode: BlendMode::SourceOver, quality: FilterQuality::Bilinear };
    pm.draw_pixmap(tx, ty, icon_pm.as_ref(), &paint, Transform::identity(), None);
}

/// Draw the team score bar at the top of the frame.
///
/// Two independent progress bars growing toward the center. Each bar represents
/// progress toward 1000 points. Team 0 (friendly) grows left→center,
/// team 1 (enemy) grows right→center.
fn draw_score_bar(
    pm: &mut Pixmap,
    team0_score: i32,
    team1_score: i32,
    team0_color: [u8; 3],
    team1_color: [u8; 3],
    max_score: i32,
    team0_timer: Option<&str>,
    team1_timer: Option<&str>,
    advantage_label: &str,
    advantage_team: i32,
    fonts: &GameFonts,
    map_width: u32,
) {
    let width = map_width as f32;
    let bar_height = crate::HUD_HEIGHT as f32;
    let max_score = max_score as f32;
    let half = width / 2.0;
    let center_gap = 2.0f32; // small gap between the two bars

    // Dark background for the entire bar area
    draw_filled_rect(pm, 0.0, 0.0, width, bar_height, [30, 30, 30], 0.8);

    // Team 0 progress: grows from left edge toward center
    let t0_frac = (team0_score as f32 / max_score).clamp(0.0, 1.0);
    let t0_width = t0_frac * (half - center_gap);
    if t0_width > 0.0 {
        draw_filled_rect(pm, 0.0, 0.0, t0_width, bar_height, team0_color, 1.0);
    }

    // Team 1 progress: grows from right edge toward center
    let t1_frac = (team1_score as f32 / max_score).clamp(0.0, 1.0);
    let t1_width = t1_frac * (half - center_gap);
    if t1_width > 0.0 {
        draw_filled_rect(pm, width - t1_width, 0.0, t1_width, bar_height, team1_color, 1.0);
    }

    let font = &fonts.primary;
    let timer_color: [u8; 3] = [200, 200, 200];
    let pill_pad_x = 4.0f32;
    let pill_pad_y = 1.0f32;
    let pill_margin = 2.0f32;
    let pill_radius = 3.0f32;
    let pill_color: [u8; 3] = [0, 0, 0];
    let pill_alpha = 0.55f32;

    let score_scale = fonts.scale(14.0);
    let timer_scale = fonts.scale(12.0);
    let advantage_scale = fonts.scale(11.0);

    let t0 = format!("{}", team0_score);
    let t1 = format!("{}", team1_score);
    let (t0w, t0h) = text_size(score_scale, font, &t0);
    let (t1w, _) = text_size(score_scale, font, &t1);

    let pill_h = (t0h as f32 + pill_pad_y * 2.0).min(bar_height - pill_margin * 2.0);
    let pill_y = (bar_height - pill_h) / 2.0;
    let text_y = pill_y as i32 + pill_pad_y as i32;

    // ── Measure team 0 pill width ──
    let mut t0_total_w = t0w as f32;
    if let Some(timer) = team0_timer {
        let (tw, _) = text_size(timer_scale, font, timer);
        t0_total_w += 4.0 + tw as f32;
    }
    if advantage_team == 0 && !advantage_label.is_empty() {
        let (aw, _) = text_size(advantage_scale, font, advantage_label);
        t0_total_w += 6.0 + aw as f32;
    }

    // ── Measure team 1 pill width ──
    let mut t1_total_w = t1w as f32;
    if let Some(timer) = team1_timer {
        let (tw, _) = text_size(timer_scale, font, timer);
        t1_total_w += 4.0 + tw as f32;
    }
    if advantage_team == 1 && !advantage_label.is_empty() {
        let (aw, _) = text_size(advantage_scale, font, advantage_label);
        t1_total_w += 6.0 + aw as f32;
    }

    // ── Draw team 0 pill background + text ──
    let t0_pill_x = 8.0 - pill_pad_x;
    draw_rounded_rect(
        pm,
        t0_pill_x,
        pill_y,
        t0_total_w + pill_pad_x * 2.0,
        pill_h,
        pill_radius,
        pill_color,
        pill_alpha,
    );

    let mut t0_cursor = 8i32;
    draw_text(pm, [255, 255, 255], t0_cursor, text_y, score_scale, font, &t0);
    t0_cursor += t0w as i32;
    if let Some(timer) = team0_timer {
        t0_cursor += 4;
        draw_text(pm, timer_color, t0_cursor, text_y + 1, timer_scale, font, timer);
        let (tw, _) = text_size(timer_scale, font, timer);
        t0_cursor += tw as i32;
    }
    if advantage_team == 0 && !advantage_label.is_empty() {
        t0_cursor += 6;
        draw_text(pm, [255, 255, 255], t0_cursor, text_y + 2, advantage_scale, font, advantage_label);
    }

    // ── Draw team 1 pill background + text ──
    let t1_pill_x = width - 8.0 - t1_total_w - pill_pad_x;
    draw_rounded_rect(
        pm,
        t1_pill_x,
        pill_y,
        t1_total_w + pill_pad_x * 2.0,
        pill_h,
        pill_radius,
        pill_color,
        pill_alpha,
    );

    // Team 1 draws right-to-left: [advantage] [timer] [score]
    let mut t1_cursor = (width - 8.0) as i32; // right edge of score
    // Score (rightmost)
    let t1_x = t1_cursor - t1w as i32;
    draw_text(pm, [255, 255, 255], t1_x, text_y, score_scale, font, &t1);
    t1_cursor = t1_x;
    // Timer (left of score)
    if let Some(timer) = team1_timer {
        let (tw, _) = text_size(timer_scale, font, timer);
        t1_cursor -= 4;
        let tx = t1_cursor - tw as i32;
        draw_text(pm, timer_color, tx, text_y + 1, timer_scale, font, timer);
        t1_cursor = tx;
    }
    // Advantage (leftmost)
    if advantage_team == 1 && !advantage_label.is_empty() {
        let (aw, _) = text_size(advantage_scale, font, advantage_label);
        t1_cursor -= 6;
        let ax = t1_cursor - aw as i32;
        draw_text(pm, [255, 255, 255], ax, text_y + 2, advantage_scale, font, advantage_label);
    }
}

/// Draw the game timer.
fn draw_timer(pm: &mut Pixmap, time_remaining: Option<i64>, elapsed: ElapsedClock, fonts: &GameFonts, map_width: u32) {
    let font = &fonts.primary;
    let center_x = map_width as i32 / 2;
    let main_scale = fonts.scale(16.0);
    let small_scale = fonts.scale(11.0);

    if let Some(remaining) = time_remaining {
        // Show time remaining as main timer (centered)
        let r_mins = remaining / 60;
        let r_secs = remaining % 60;
        let remaining_text = format!("{:02}:{:02}", r_mins, r_secs);
        let (rw, _) = text_size(main_scale, font, &remaining_text);
        let rx = center_x - rw as i32 / 2;
        draw_text_shadow(pm, [255, 255, 255], rx, 2, main_scale, font, &remaining_text);

        // Show elapsed as smaller text below
        let e_mins = (elapsed.seconds() as i32) / 60;
        let e_secs = (elapsed.seconds() as i32) % 60;
        let elapsed_text = format!("+{:02}:{:02}", e_mins, e_secs);
        let (ew, _) = text_size(small_scale, font, &elapsed_text);
        let ex = center_x - ew as i32 / 2;
        draw_text_shadow(pm, [180, 180, 180], ex, 18, small_scale, font, &elapsed_text);
    } else {
        // Fallback: just show elapsed time centered (no timeLeft data yet)
        let mins = (elapsed.seconds() as i32) / 60;
        let secs = (elapsed.seconds() as i32) % 60;
        let text = format!("{:02}:{:02}", mins, secs);
        let (w, _) = text_size(main_scale, font, &text);
        let x = center_x - w as i32 / 2;
        draw_text_shadow(pm, [255, 255, 255], x, 2, main_scale, font, &text);
    }
}

fn draw_pre_battle_countdown(
    pm: &mut Pixmap,
    seconds: i64,
    fonts: &GameFonts,
    resolver: &dyn TextResolver,
    map_width: u32,
) {
    let text = format!("{}", seconds);
    let subtitle = resolver.resolve(&TranslatableText::PreBattleLabel);
    let glow_color: [u8; 3] = [255, 200, 50]; // gold
    draw_battle_result_overlay(pm, &text, Some(&subtitle), glow_color, true, fonts, map_width);
}

/// Map a DeathCause to the icon key used in the death_cause_icons HashMap.
///
/// Keys correspond to the base name portion of `icon_frag_{key}.png` files
/// in `gui/battle_hud/icon_frag/`.
fn death_cause_icon_key(
    cause: &wows_replays::analyzer::decoder::Recognized<wows_replays::analyzer::decoder::DeathCause>,
) -> &'static str {
    use wows_replays::analyzer::decoder::DeathCause;
    match cause.known() {
        Some(DeathCause::Artillery | DeathCause::ApShell | DeathCause::HeShell | DeathCause::CsShell) => "main_caliber",
        Some(DeathCause::Secondaries) => "atba",
        Some(DeathCause::Torpedo | DeathCause::AerialTorpedo) => "torpedo",
        Some(DeathCause::Fire) => "burning",
        Some(DeathCause::Flooding) => "flood",
        Some(DeathCause::DiveBomber) => "bomb",
        Some(DeathCause::SkipBombs) => "skip",
        Some(DeathCause::AerialRocket) => "rocket",
        Some(DeathCause::Detonation) => "detonate",
        Some(DeathCause::Ramming) => "ram",
        Some(DeathCause::DepthCharge | DeathCause::AerialDepthCharge) => "depthbomb",
        Some(DeathCause::Missile) => "missile",
        _ => "main_caliber",
    }
}

/// Draw rich kill feed entries in the top-right corner.
///
/// Layout per line (right-aligned):
/// `KILLER_NAME [icon] ship_name  [cause]  VICTIM_NAME [icon] ship_name`
fn draw_kill_feed(
    pm: &mut Pixmap,
    entries: &[KillFeedEntry],
    fonts: &GameFonts,
    ship_icons: &HashMap<String, ShipIcon>,
    death_cause_icons: &HashMap<String, RgbaImage>,
    map_width: u32,
) {
    let default_font = &fonts.primary;
    let default_name_scale = fonts.scale(12.0);
    let line_height = 20i32;
    let right_margin = 4i32;
    let icon_size = crate::assets::ICON_SIZE as i32;
    let cause_icon_size = icon_size;
    let gap = 2i32; // gap between elements
    let width = map_width as i32;

    let (_, text_h) = text_size(default_name_scale, default_font, "Ag");
    let text_h = text_h as i32;

    for (i, entry) in entries.iter().take(5).enumerate() {
        let y = crate::HUD_HEIGHT as i32 + i as i32 * line_height;
        let icon_y = y + (text_h - icon_size) / 2;

        // Get death cause icon key
        let cause_key = death_cause_icon_key(&entry.cause);
        let has_cause_icon = death_cause_icons.contains_key(cause_key);
        let cause_w = if has_cause_icon { cause_icon_size } else { 0 } as u32;

        // Pick appropriate fonts for each text segment
        let (killer_name_font, killer_name_scale) = fonts.font_and_scale(&entry.killer_name, 12.0);
        let (victim_name_font, victim_name_scale) = fonts.font_and_scale(&entry.victim_name, 12.0);
        let killer_ship = entry.killer_ship_name.as_deref().unwrap_or("");
        let victim_ship = entry.victim_ship_name.as_deref().unwrap_or("");
        let (killer_ship_font, killer_ship_scale) = fonts.font_and_scale(killer_ship, 12.0);
        let (victim_ship_font, victim_ship_scale) = fonts.font_and_scale(victim_ship, 12.0);

        // Measure all text segments
        let (killer_name_w, _) = text_size(killer_name_scale, killer_name_font, &entry.killer_name);
        let (killer_ship_w, _) =
            if !killer_ship.is_empty() { text_size(killer_ship_scale, killer_ship_font, killer_ship) } else { (0, 0) };
        let (victim_name_w, _) = text_size(victim_name_scale, victim_name_font, &entry.victim_name);
        let (victim_ship_w, _) =
            if !victim_ship.is_empty() { text_size(victim_ship_scale, victim_ship_font, victim_ship) } else { (0, 0) };

        // Determine if we have icons
        let has_killer_icon =
            entry.killer_species.is_some() && ship_icons.contains_key(entry.killer_species.as_ref().unwrap());
        let has_victim_icon =
            entry.victim_species.is_some() && ship_icons.contains_key(entry.victim_species.as_ref().unwrap());

        // Total width calculation:
        // killer_name [gap icon gap] killer_ship gap cause gap victim_name [gap icon gap] victim_ship
        let mut total_w = killer_name_w as i32;
        if has_killer_icon {
            total_w += gap + icon_size + gap;
        } else if killer_ship_w > 0 {
            total_w += gap;
        }
        if killer_ship_w > 0 {
            total_w += killer_ship_w as i32;
        }
        total_w += gap * 2 + cause_w as i32 + gap * 2;
        total_w += victim_name_w as i32;
        if has_victim_icon {
            total_w += gap + icon_size + gap;
        } else if victim_ship_w > 0 {
            total_w += gap;
        }
        if victim_ship_w > 0 {
            total_w += victim_ship_w as i32;
        }

        // Draw a semi-transparent background for readability
        let bg_x = (width - total_w - right_margin * 2) as f32;
        let bg_y = y as f32 - 1.0;
        draw_filled_rect(pm, bg_x, bg_y, (total_w + right_margin * 2) as f32, (line_height) as f32, [0, 0, 0], 0.5);

        let mut x = width - total_w - right_margin;

        // Killer name (team-colored)
        draw_text_shadow(pm, entry.killer_color, x, y, killer_name_scale, killer_name_font, &entry.killer_name);
        x += killer_name_w as i32;

        // Killer ship icon (friendly=left, enemy=right)
        if has_killer_icon {
            x += gap;
            let icon = &ship_icons[entry.killer_species.as_ref().unwrap()];
            draw_kill_feed_icon(pm, icon, x, icon_y, icon_size, entry.killer_color, !entry.killer_is_friendly);
            x += icon_size + gap;
        } else if killer_ship_w > 0 {
            x += gap;
        }

        // Killer ship name
        if killer_ship_w > 0 {
            draw_text_shadow(pm, entry.killer_color, x, y, killer_ship_scale, killer_ship_font, killer_ship);
            x += killer_ship_w as i32;
        }

        // Death cause icon (or fallback gap)
        x += gap * 2;
        if let Some(cause_icon) = death_cause_icons.get(cause_key) {
            let cause_center_y = icon_y + cause_icon_size / 2;
            draw_icon(pm, cause_icon, x + cause_icon_size / 2, cause_center_y);
        }
        x += cause_w as i32 + gap * 2;

        // Victim name (team-colored)
        draw_text_shadow(pm, entry.victim_color, x, y, victim_name_scale, victim_name_font, &entry.victim_name);
        x += victim_name_w as i32;

        // Victim ship icon (friendly=left, enemy=right)
        if has_victim_icon {
            x += gap;
            let icon = &ship_icons[entry.victim_species.as_ref().unwrap()];
            draw_kill_feed_icon(pm, icon, x, icon_y, icon_size, entry.victim_color, !entry.victim_is_friendly);
            x += icon_size + gap;
        } else if victim_ship_w > 0 {
            x += gap;
        }

        // Victim ship name
        if victim_ship_w > 0 {
            draw_text_shadow(pm, entry.victim_color, x, y, victim_ship_scale, victim_ship_font, victim_ship);
        }
    }
}

/// Draw a small ship icon for the kill feed, tinted with team color.
/// If `flip` is true, the icon faces left (horizontally mirrored).
fn draw_kill_feed_icon(pm: &mut Pixmap, icon: &RgbaImage, x: i32, y: i32, size: i32, color: [u8; 3], flip: bool) {
    let iw = icon.width();
    let ih = icon.height();
    let scale = size as f32 / iw.max(ih) as f32;

    // Create a tinted icon pixmap
    let mut icon_pm = Pixmap::new(iw, ih).expect("failed to create icon pixmap");
    let data = icon_pm.data_mut();
    for iy in 0..ih {
        for ix in 0..iw {
            let px = icon.get_pixel(ix, iy).0;
            let idx = (iy * iw + ix) as usize * 4;
            let a = px[3] as f32 / 255.0;
            if a < 0.01 {
                continue;
            }
            let luminance = (px[0] as f32 * 0.299 + px[1] as f32 * 0.587 + px[2] as f32 * 0.114) / 255.0;
            let r = (color[0] as f32 * luminance) as u8;
            let g = (color[1] as f32 * luminance) as u8;
            let b = (color[2] as f32 * luminance) as u8;
            // Premultiply
            data[idx] = (r as f32 * a) as u8;
            data[idx + 1] = (g as f32 * a) as u8;
            data[idx + 2] = (b as f32 * a) as u8;
            data[idx + 3] = px[3];
        }
    }

    // The ship icons point up (north). For kill feed we want them pointing
    // right (victim) or left (killer). Rotate 90° CW for right, 90° CCW for left.
    let angle_deg = if flip { -90.0 } else { 90.0 };

    let cx = iw as f32 / 2.0;
    let cy = ih as f32 / 2.0;
    // Center the icon at (x + size/2, y + size/2) with scaling
    let dest_cx = x as f32 + size as f32 / 2.0;
    let dest_cy = y as f32 + size as f32 / 2.0;

    let transform = Transform::from_translate(dest_cx - cx * scale, dest_cy - cy * scale)
        .pre_scale(scale, scale)
        .post_rotate_at(angle_deg, dest_cx, dest_cy);

    let paint = PixmapPaint { opacity: 1.0, blend_mode: BlendMode::SourceOver, quality: FilterQuality::Bilinear };

    pm.draw_pixmap(0, 0, icon_pm.as_ref(), &paint, transform, None);
}

/// Word-wrap text to fit within `max_width` pixels, breaking on word boundaries.
///
/// Returns a vector of lines. Each line fits within `max_width` when rendered at `scale`.
fn word_wrap(text: &str, max_width: u32, scale: PxScale, font: &impl Font) -> Vec<String> {
    let mut lines = Vec::new();
    let mut current_line = String::new();

    for word in text.split_whitespace() {
        if current_line.is_empty() {
            // First word on the line — force-break if it alone exceeds max_width
            let (w, _) = text_size(scale, font, word);
            if w > max_width {
                force_break_word(word, max_width, scale, font, &mut lines);
                current_line = lines.pop().unwrap_or_default();
            } else {
                current_line = word.to_string();
            }
        } else {
            let candidate = format!("{} {}", current_line, word);
            let (w, _) = text_size(scale, font, &candidate);
            if w > max_width {
                // Push the current line and start a new one
                lines.push(current_line);
                // The new word itself might also be too wide
                let (ww, _) = text_size(scale, font, word);
                if ww > max_width {
                    force_break_word(word, max_width, scale, font, &mut lines);
                    current_line = lines.pop().unwrap_or_default();
                } else {
                    current_line = word.to_string();
                }
            } else {
                current_line = candidate;
            }
        }
    }
    if !current_line.is_empty() {
        lines.push(current_line);
    }
    if lines.is_empty() {
        lines.push(String::new());
    }
    lines
}

/// Break a single word into lines that each fit within `max_width`.
/// Completed lines are pushed to `lines`; the last (possibly partial) segment
/// is also pushed so the caller can pop it to continue accumulating.
fn force_break_word(word: &str, max_width: u32, scale: PxScale, font: &impl Font, lines: &mut Vec<String>) {
    let mut segment = String::new();
    for ch in word.chars() {
        let candidate = format!("{}{}", segment, ch);
        let (w, _) = text_size(scale, font, &candidate);
        if w > max_width && !segment.is_empty() {
            lines.push(segment);
            segment = ch.to_string();
        } else {
            segment = candidate;
        }
    }
    if !segment.is_empty() {
        lines.push(segment);
    }
}

/// Truncate `text` with ellipsis so it fits within `max_width` pixels.
/// Returns the original string if it already fits.
fn truncate_to_fit(text: &str, max_width: u32, scale: PxScale, font: &impl Font) -> String {
    let (w, _) = text_size(scale, font, text);
    if w <= max_width {
        return text.to_string();
    }
    let ellipsis = "..";
    let (ew, _) = text_size(scale, font, ellipsis);
    if ew >= max_width {
        return ellipsis.to_string();
    }
    let target = max_width - ew;
    let mut truncated = String::new();
    for ch in text.chars() {
        let candidate = format!("{}{}", truncated, ch);
        let (cw, _) = text_size(scale, font, &candidate);
        if cw > target {
            break;
        }
        truncated = candidate;
    }
    format!("{}{}", truncated, ellipsis)
}

/// Draw the chat overlay on the left side of the minimap.
///
/// Each entry shows:
///   Line 1: `[CLAN] PlayerName` (truncated to fit)
///   Line 2: `<ship_icon> ShipName:`
///   Line 3+: message text, word-wrapped
/// The whole thing sits in a semi-translucent dark box.
fn draw_chat_overlay(
    pm: &mut Pixmap,
    entries: &[ChatEntry],
    fonts: &GameFonts,
    ship_icons: &HashMap<String, ShipIcon>,
    y_offset: u32,
) {
    let font = &fonts.primary;
    if entries.is_empty() {
        return;
    }

    let minimap_w = crate::MINIMAP_SIZE;
    let max_box_width = (minimap_w / 4) as i32; // 1/4 of minimap = 192px
    let margin = 6i32;
    let inner_width = (max_box_width - margin * 2) as u32;
    let header_scale = fonts.scale(11.0);
    let msg_scale = fonts.scale(11.0);
    let line_height = 14i32;
    let entry_gap = 6i32;
    let icon_size = 12i32;

    // Pre-compute layout for each entry
    struct EntryLayout {
        /// Line 1: truncated "[CLAN] PlayerName"
        name_line: String,
        /// Color for clan tag portion (if present)
        clan_color: Option<[u8; 3]>,
        /// Length of clan tag prefix (including brackets and space), 0 if none
        clan_prefix_len: usize,
        /// Line 2: ship species key for icon + ship name
        ship_line: Option<String>,
        ship_species: Option<String>,
        /// Message lines (word-wrapped)
        msg_lines: Vec<String>,
        total_height: i32,
    }

    let mut layouts: Vec<EntryLayout> = Vec::new();
    let mut total_height = margin; // top padding

    for entry in entries {
        // Line 1: "[CLAN] PlayerName" -- pick font based on player name
        let clan_prefix = if !entry.clan_tag.is_empty() { format!("[{}] ", entry.clan_tag) } else { String::new() };
        let full_name_line = format!("{}{}", clan_prefix, entry.player_name);
        let (name_font, name_font_scale) = fonts.font_and_scale(&entry.player_name, 11.0);
        let name_line = truncate_to_fit(&full_name_line, inner_width, name_font_scale, name_font);
        let clan_color =
            if !entry.clan_tag.is_empty() { Some(entry.clan_color.unwrap_or(entry.team_color)) } else { None };

        // Line 2: ship icon + ship name (if available)
        let has_ship_line = entry.ship_name.is_some();
        let ship_line = entry.ship_name.as_ref().map(|name| {
            let (sf, ss) = fonts.font_and_scale(name, 11.0);
            let icon_reserved = (icon_size + 2) as u32;
            let available = inner_width.saturating_sub(icon_reserved);
            truncate_to_fit(name, available, ss, sf)
        });

        // Message lines (word-wrapped), using the font selected by font_hint
        let msg_font = match entry.font_hint {
            FontHint::Primary => &fonts.primary,
            FontHint::Fallback(i) => fonts.fallbacks.get(i).unwrap_or(&fonts.primary),
        };
        let entry_msg_scale = fonts.scale_for_hint(11.0, entry.font_hint);
        let msg_lines = word_wrap(&entry.message, inner_width, entry_msg_scale, msg_font);

        let line_count = 1 + has_ship_line as i32 + msg_lines.len() as i32;
        let entry_height = line_count * line_height;

        total_height += entry_height + entry_gap;
        layouts.push(EntryLayout {
            name_line,
            clan_color,
            clan_prefix_len: clan_prefix.len(),
            ship_line,
            ship_species: entry.ship_species.clone(),
            msg_lines,
            total_height: entry_height,
        });
    }
    total_height -= entry_gap; // remove trailing gap
    total_height += margin; // bottom padding

    // Position: middle-left of the minimap area
    let box_x = 0i32;
    let map_mid_y = y_offset as i32 + (minimap_w as i32) / 2;
    let box_y = map_mid_y - total_height / 2;

    // Find the overall max opacity for the background alpha
    let max_opacity = entries.iter().map(|e| e.opacity).fold(0.0f32, f32::max);

    // Draw semi-translucent background
    draw_filled_rect(
        pm,
        box_x as f32,
        box_y as f32,
        max_box_width as f32,
        total_height as f32,
        [0, 0, 0],
        0.35 * max_opacity,
    );

    // Draw each entry
    let mut cur_y = box_y + margin;
    for (entry, layout) in entries.iter().zip(layouts.iter()) {
        let opacity = entry.opacity;
        if opacity < 0.01 {
            cur_y += layout.total_height + entry_gap;
            continue;
        }

        let apply_opacity = |color: [u8; 3], op: f32| -> [u8; 3] {
            [(color[0] as f32 * op) as u8, (color[1] as f32 * op) as u8, (color[2] as f32 * op) as u8]
        };

        // Line 1: [CLAN] PlayerName
        let x = box_x + margin;
        if let Some(clan_rgb) = layout.clan_color {
            // Draw clan prefix in clan color, rest in team color
            let clan_text: String = layout.name_line.chars().take(layout.clan_prefix_len).collect();
            let name_text: String = layout.name_line.chars().skip(layout.clan_prefix_len).collect();
            let (cw, _) = text_size(header_scale, font, &clan_text);
            draw_text(pm, apply_opacity(clan_rgb, opacity), x, cur_y, header_scale, font, &clan_text);
            draw_text(
                pm,
                apply_opacity(entry.team_color, opacity),
                x + cw as i32,
                cur_y,
                header_scale,
                font,
                &name_text,
            );
        } else {
            draw_text(pm, apply_opacity(entry.team_color, opacity), x, cur_y, header_scale, font, &layout.name_line);
        }
        cur_y += line_height;

        // Line 2: ship icon + ship name
        if let Some(ref ship_name) = layout.ship_line {
            let mut sx = x;
            if let Some(ref species_key) = layout.ship_species {
                if let Some(icon) = ship_icons.get(species_key) {
                    let icon_y = cur_y + (line_height - icon_size) / 2;
                    draw_kill_feed_icon(
                        pm,
                        icon,
                        sx,
                        icon_y,
                        icon_size,
                        apply_opacity(entry.team_color, opacity),
                        false,
                    );
                }
                sx += icon_size + 2;
            }
            draw_text(pm, apply_opacity(entry.team_color, opacity), sx, cur_y, header_scale, font, ship_name);
            cur_y += line_height;
        }

        // Message lines (using font selected by font_hint)
        let msg_font: &FontArc = match entry.font_hint {
            FontHint::Primary => &fonts.primary,
            FontHint::Fallback(i) => fonts.fallbacks.get(i).unwrap_or(&fonts.primary),
        };
        let msg_color = apply_opacity(entry.message_color, opacity);
        for line in &layout.msg_lines {
            draw_text(pm, msg_color, box_x + margin, cur_y, msg_scale, msg_font, line);
            cur_y += line_height;
        }

        cur_y += entry_gap;
    }
}

/// Draw the 10x10 grid overlay with labels.
fn draw_grid(pm: &mut Pixmap, minimap_size: u32, y_off: u32, fonts: &GameFonts) {
    let font = &fonts.primary;
    let cell = minimap_size as f32 / 10.0;
    let grid_color = [180, 180, 180];
    let alpha = 0.25f32;
    let label_scale = fonts.scale(11.0);

    // Draw 9 interior lines in each direction
    for i in 1..10 {
        let pos = (i as f32 * cell).round();
        // Vertical line
        draw_line(pm, pos, y_off as f32, pos, (y_off + minimap_size) as f32, grid_color, alpha, 1.0);
        // Horizontal line
        draw_line(pm, 0.0, pos + y_off as f32, minimap_size as f32, pos + y_off as f32, grid_color, alpha, 1.0);
    }

    // Labels: numbers 1-10 across the top, letters A-J down the left
    for i in 0..10 {
        let label = format!("{}", i + 1);
        let x = (i as f32 * cell + cell / 2.0 - 3.0) as i32;
        let y = y_off as i32 + 2;
        draw_text_shadow(pm, [255, 255, 255], x, y, label_scale, font, &label);
    }
    let labels_row = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
    for (i, &ch) in labels_row.iter().enumerate() {
        let label = ch.to_string();
        let x = 3i32;
        let y = y_off as i32 + (i as f32 * cell + cell / 2.0 - 5.0) as i32;
        draw_text_shadow(pm, [255, 255, 255], x, y, label_scale, font, &label);
    }
}

/// Draw a large centered battle result text with a colored glow effect.
///
/// The glow is created by drawing the text multiple times at increasing offsets
/// with decreasing opacity in the glow color, creating a soft halo effect.
fn draw_battle_result_overlay(
    pm: &mut Pixmap,
    text: &str,
    subtitle: Option<&str>,
    glow_color: [u8; 3],
    subtitle_above: bool,
    fonts: &GameFonts,
    map_width: u32,
) {
    let font = &fonts.primary;
    let w = map_width;
    let h = pm.height();

    let font_height = w as f32 / 8.0;
    let scale = fonts.scale(font_height);
    let (tw, th) = text_size(scale, font, text);

    let sub_scale = fonts.scale(font_height / 4.0);
    let sub_height = subtitle.map(|s| text_size(sub_scale, font, s).1).unwrap_or(0);
    let gap = if subtitle.is_some() { 8 } else { 0 };
    let total_height = th + gap as u32 + sub_height;

    let x = (w as i32 - tw as i32) / 2;
    let center_y = (h as i32 - total_height as i32) / 2;

    // When subtitle is above, subtitle comes first then main text;
    // when below, main text comes first then subtitle.
    let (main_y, sub_y) = if subtitle_above {
        (center_y + sub_height as i32 + gap, center_y)
    } else {
        (center_y, center_y + th as i32 + gap)
    };

    // Dark shadow behind text for contrast, then colored glow, then white text
    let glow_layers: &[(i32, [u8; 3], f32)] = &[
        (8, [0, 0, 0], 0.15),
        (6, [0, 0, 0], 0.25),
        (4, glow_color, 0.30),
        (3, glow_color, 0.45),
        (2, glow_color, 0.60),
        (1, glow_color, 0.80),
    ];
    let offsets: &[(i32, i32)] = &[(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, -1), (-1, 1), (1, 1)];
    for &(dist, color, opacity) in glow_layers {
        let c =
            [(color[0] as f32 * opacity) as u8, (color[1] as f32 * opacity) as u8, (color[2] as f32 * opacity) as u8];
        for &(dx, dy) in offsets {
            draw_text(pm, c, x + dx * dist, main_y + dy * dist, scale, font, text);
        }
    }
    draw_text(pm, [255, 255, 255], x, main_y, scale, font, text);

    // Subtitle
    if let Some(sub) = subtitle {
        let (sw, _) = text_size(sub_scale, font, sub);
        let sx = (w as i32 - sw as i32) / 2;
        // Subtle dark outline for readability
        for &(dx, dy) in offsets {
            draw_text(pm, [0, 0, 0], sx + dx * 2, sub_y + dy * 2, sub_scale, font, sub);
        }
        draw_text(pm, [200, 200, 200], sx, sub_y, sub_scale, font, sub);
    }
}

// ── Stats panel helpers ─────────────────────────────────────────────────────

/// Tint a silhouette image (alpha-masked) with a solid color.
fn tint_silhouette(img: &RgbaImage, color: [u8; 3]) -> RgbaImage {
    let mut out = img.clone();
    for px in out.pixels_mut() {
        let a = px.0[3];
        if a > 0 {
            px.0[0] = color[0];
            px.0[1] = color[1];
            px.0[2] = color[2];
            // Keep original alpha
        }
    }
    out
}

/// HP bar color lerp: green (>66%) → yellow (33-66%) → red (<33%).
fn hp_bar_color_lerp(fraction: f32) -> [u8; 3] {
    if fraction > 0.66 {
        [0, 255, 0] // green
    } else if fraction > 0.33 {
        let t = (fraction - 0.33) / 0.33;
        [(255.0 * (1.0 - t)) as u8, 255, 0]
    } else {
        let t = fraction / 0.33;
        [255, (255.0 * t) as u8, 0]
    }
}

/// Draw an RGBA image at a non-centered position (top-left corner).
fn draw_icon_at(pm: &mut Pixmap, icon: &RgbaImage, x: i32, y: i32) {
    let icon_pm = rgba_to_pixmap(icon);
    pm.draw_pixmap(x, y, icon_pm.as_ref(), &PixmapPaint::default(), Transform::identity(), None);
}

/// Format a number with thousands separators (e.g. 12345 → "12,345").
fn format_number(n: i64) -> String {
    if n < 0 {
        return format!("-{}", format_number(-n));
    }
    let s = n.to_string();
    let mut result = String::with_capacity(s.len() + s.len() / 3);
    for (i, c) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.push(',');
        }
        result.push(c);
    }
    result.chars().rev().collect()
}

/// Short display name for a ribbon variant (for the compact stats panel).
fn damage_label_color_rgb(label: &str) -> [u8; 3] {
    match label {
        "AP" => [255, 200, 80],
        "HE" => [255, 140, 50],
        "SAP" => [200, 180, 255],
        "MAIN" => [255, 200, 80],
        "SEC" => [255, 170, 60],
        "TORP" => [100, 200, 255],
        "FIRE" => [255, 120, 50],
        "FLOOD" => [80, 160, 255],
        "BOMB" => [220, 180, 100],
        "ROCKET" => [230, 150, 80],
        "DC" => [160, 200, 160],
        "RAM" => [200, 100, 100],
        "MISSILE" => [220, 130, 220],
        _ => [180, 180, 180],
    }
}

// ── ImageTarget (RenderTarget implementation) ──────────────────────────────

use crate::CANVAS_HEIGHT;
use crate::HUD_HEIGHT;
use crate::MINIMAP_SIZE;

/// Pre-rasterized ship icon (RGBA, white/alpha mask to be tinted at draw time).
pub type ShipIcon = RgbaImage;

/// Software renderer that draws to a tiny-skia `Pixmap` for anti-aliased output.
///
/// Owns the map image, font, ship icons, plane icons, and consumable icons.
/// Implements `RenderTarget` by dispatching `DrawCommand`s to tiny-skia primitives.
pub struct ImageTarget {
    canvas: Pixmap,
    /// Pre-built background: map image + grid overlay. Cloned at start of each frame.
    base_canvas: Pixmap,
    /// Width of the minimap area (excludes the stats panel).
    /// HUD elements (score bar, timer, kill feed) are confined to this width.
    map_width: u32,
    fonts: GameFonts,
    ship_icons: HashMap<String, ShipIcon>,
    plane_icons: HashMap<String, RgbaImage>,
    building_icons: HashMap<String, RgbaImage>,
    consumable_icons: HashMap<String, RgbaImage>,
    death_cause_icons: HashMap<String, RgbaImage>,
    powerup_icons: HashMap<String, RgbaImage>,
    /// Bounding rects [x, y, w, h] of previously placed config-circle labels in the current frame.
    placed_labels: Vec<[i32; 4]>,
    /// Resolves translatable game text (battle results, advantage labels, etc.)
    text_resolver: Arc<dyn TextResolver>,
}

impl ImageTarget {
    pub fn new(
        map_image: Option<RgbImage>,
        fonts: GameFonts,
        ship_icons: HashMap<String, ShipIcon>,
        plane_icons: HashMap<String, RgbaImage>,
        building_icons: HashMap<String, RgbaImage>,
        consumable_icons: HashMap<String, RgbaImage>,
        death_cause_icons: HashMap<String, RgbaImage>,
        powerup_icons: HashMap<String, RgbaImage>,
    ) -> Self {
        Self::with_stats_panel(
            map_image,
            fonts,
            ship_icons,
            plane_icons,
            building_icons,
            consumable_icons,
            death_cause_icons,
            powerup_icons,
            false,
        )
    }

    pub fn with_stats_panel(
        map_image: Option<RgbImage>,
        fonts: GameFonts,
        ship_icons: HashMap<String, ShipIcon>,
        plane_icons: HashMap<String, RgbaImage>,
        building_icons: HashMap<String, RgbaImage>,
        consumable_icons: HashMap<String, RgbaImage>,
        death_cause_icons: HashMap<String, RgbaImage>,
        powerup_icons: HashMap<String, RgbaImage>,
        stats_panel: bool,
    ) -> Self {
        let map = map_image.unwrap_or_else(|| RgbImage::from_pixel(MINIMAP_SIZE, MINIMAP_SIZE, Rgb([30, 40, 60])));

        let canvas_width = if stats_panel { MINIMAP_SIZE + STATS_PANEL_WIDTH } else { MINIMAP_SIZE };

        // Pre-build the base canvas: dark background + map + grid
        let mut base_rgb = RgbImage::from_pixel(canvas_width, CANVAS_HEIGHT, Rgb([20, 25, 35]));
        for y in 0..map.height().min(MINIMAP_SIZE) {
            for x in 0..map.width().min(MINIMAP_SIZE) {
                base_rgb.put_pixel(x, y + HUD_HEIGHT, *map.get_pixel(x, y));
            }
        }
        let mut base = rgb_to_pixmap(&base_rgb);
        draw_grid(&mut base, MINIMAP_SIZE, HUD_HEIGHT, &fonts);

        Self {
            canvas: Pixmap::new(canvas_width, CANVAS_HEIGHT).unwrap(),
            base_canvas: base,
            map_width: MINIMAP_SIZE,
            fonts,
            ship_icons,
            plane_icons,
            building_icons,
            consumable_icons,
            death_cause_icons,
            powerup_icons,
            placed_labels: Vec::new(),
            text_resolver: Arc::new(DefaultTextResolver),
        }
    }

    /// Set a custom text resolver for translating game text.
    pub fn set_text_resolver(&mut self, resolver: Arc<dyn TextResolver>) {
        self.text_resolver = resolver;
    }

    /// Access the current frame as an RGB image (converted from Pixmap).
    pub fn frame(&self) -> RgbImage {
        pixmap_to_rgb(&self.canvas)
    }

    /// Canvas dimensions.
    pub fn canvas_size(&self) -> (u32, u32) {
        (self.canvas.width(), self.canvas.height())
    }
}

impl RenderTarget for ImageTarget {
    fn begin_frame(&mut self) {
        self.canvas = self.base_canvas.clone();
        self.placed_labels.clear();
    }

    fn draw(&mut self, cmd: &DrawCommand) {
        let y_off = HUD_HEIGHT as f32;
        match cmd {
            DrawCommand::ShotTracer { from, to, color } => {
                draw_line(
                    &mut self.canvas,
                    from.x as f32,
                    from.y as f32 + y_off,
                    to.x as f32,
                    to.y as f32 + y_off,
                    *color,
                    1.0,
                    1.5,
                );
            }
            DrawCommand::Torpedo { pos, color } => {
                draw_filled_circle(&mut self.canvas, pos.x as f32, pos.y as f32 + y_off, 2.5, *color, 1.0);
            }
            DrawCommand::Smoke { pos, radius, color, alpha } => {
                draw_filled_circle(
                    &mut self.canvas,
                    pos.x as f32,
                    pos.y as f32 + y_off,
                    *radius as f32,
                    *color,
                    *alpha,
                );
            }
            DrawCommand::BuffZone { pos, radius, color, alpha, marker_name } => {
                let cx = pos.x as f32;
                let cy = pos.y as f32 + y_off;
                let r = *radius as f32;
                // Filled circle
                draw_filled_circle(&mut self.canvas, cx, cy, r, *color, *alpha);
                // Border ring
                draw_circle_outline(&mut self.canvas, cx, cy, r, *color, 0.6, 1.5);
                // Draw powerup icon centered on zone
                if let Some(name) = marker_name
                    && let Some(icon) = self.powerup_icons.get(name.as_str())
                {
                    draw_icon(&mut self.canvas, icon, cx as i32, cy as i32);
                }
            }
            DrawCommand::CapturePoint { pos, radius, color, alpha, label, progress, invader_color, flag_icon } => {
                draw_capture_point(
                    &mut self.canvas,
                    pos.x as f32,
                    pos.y as f32 + y_off,
                    *radius as f32,
                    *color,
                    *alpha,
                    label,
                    *progress,
                    *invader_color,
                    flag_icon.as_ref(),
                    &self.fonts,
                );
            }
            DrawCommand::TurretDirection { pos, yaw, color, length, .. } => {
                let x = pos.x as f32;
                let y = pos.y as f32 + y_off;
                let dx = *length as f32 * yaw.cos();
                let dy = -*length as f32 * yaw.sin();
                draw_line(&mut self.canvas, x, y, x + dx, y + dy, *color, 0.7, 1.0);
            }
            DrawCommand::Building { pos, color, icon_type, relation, .. } => {
                // Try to render an icon; fall back to a dot if no icon is available
                let icon_key = icon_type.map(|t| format!("{}_{}", t.icon_name(), relation.icon_suffix()));
                let icon = icon_key.as_ref().and_then(|k| self.building_icons.get(k));
                if let Some(icon) = icon {
                    draw_icon(&mut self.canvas, icon, pos.x, pos.y + y_off as i32);
                } else {
                    draw_filled_circle(&mut self.canvas, pos.x as f32, pos.y as f32 + y_off, 2.5, *color, 1.0);
                }
            }
            DrawCommand::WeatherZone { pos, radius } => {
                // Semi-transparent light gray circle for weather zones (squalls/storms)
                draw_filled_circle(
                    &mut self.canvas,
                    pos.x as f32,
                    pos.y as f32 + y_off,
                    *radius as f32,
                    [255, 255, 255],
                    0.25,
                );
            }
            DrawCommand::Ship {
                pos,
                yaw,
                species,
                color,
                visibility,
                opacity,
                is_self,
                player_name,
                ship_name,
                is_detected_teammate,
                name_color,
                ..
            } => {
                let x = pos.x;
                let y = pos.y + y_off as i32;

                let fallback_key = match (*visibility, *is_self) {
                    (ShipVisibility::Visible, true) => "Auxiliary_self",
                    (ShipVisibility::Visible, false) => "Auxiliary",
                    (ShipVisibility::MinimapOnly | ShipVisibility::Undetected, _) => "Auxiliary_invisible",
                };
                let icon = if let Some(sp) = species.as_ref() {
                    let variant_key = match (*visibility, *is_self) {
                        (ShipVisibility::Visible, true) => format!("{}_self", sp),
                        (ShipVisibility::Visible, false) => sp.clone(),
                        (ShipVisibility::MinimapOnly, _) => format!("{}_invisible", sp),
                        (ShipVisibility::Undetected, _) => format!("{}_invisible", sp),
                    };
                    self.ship_icons
                        .get(&variant_key)
                        .or_else(|| self.ship_icons.get(sp))
                        .or_else(|| self.ship_icons.get(fallback_key))
                } else {
                    self.ship_icons.get(fallback_key)
                };

                let Some(icon) = icon else {
                    return;
                };

                // Draw outline for detected teammates
                if *is_detected_teammate {
                    draw_ship_icon_outline(&mut self.canvas, icon, x, y, *yaw, [255, 215, 0], 0.9, 2);
                }

                draw_ship_icon(&mut self.canvas, icon, x, y, *yaw, color.map(|c| c), *opacity);
                draw_ship_labels(
                    &mut self.canvas,
                    x,
                    y,
                    player_name.as_deref(),
                    ship_name.as_deref(),
                    *name_color,
                    &self.fonts,
                );
            }
            DrawCommand::HealthBar { pos, fraction, fill_color, background_color, background_alpha, .. } => {
                draw_health_bar(
                    &mut self.canvas,
                    pos.x,
                    pos.y + y_off as i32,
                    *fraction,
                    *fill_color,
                    *background_color,
                    *background_alpha,
                );
            }
            DrawCommand::DeadShip { pos, yaw, species, color, is_self, .. } => {
                let x = pos.x;
                let y = pos.y + y_off as i32;

                let fallback_key = if *is_self { "Auxiliary_dead_self" } else { "Auxiliary_dead" };
                let icon = if let Some(sp) = species.as_ref() {
                    let variant_key = if *is_self { format!("{}_dead_self", sp) } else { format!("{}_dead", sp) };
                    self.ship_icons
                        .get(&variant_key)
                        .or_else(|| self.ship_icons.get(sp))
                        .or_else(|| self.ship_icons.get(fallback_key))
                } else {
                    self.ship_icons.get(fallback_key)
                };

                let Some(icon) = icon else {
                    return;
                };

                draw_ship_icon(&mut self.canvas, icon, x, y, *yaw, color.map(|c| c), 1.0);
            }
            DrawCommand::Plane { pos, icon_key, player_name, ship_name, .. } => {
                let x = pos.x;
                let y = pos.y + y_off as i32;
                let Some(icon) = self.plane_icons.get(icon_key) else {
                    tracing::warn!(icon_key, "Missing plane icon, skipping");
                    return;
                };
                draw_icon(&mut self.canvas, icon, x, y);
                draw_ship_labels(
                    &mut self.canvas,
                    x,
                    y,
                    player_name.as_deref(),
                    ship_name.as_deref(),
                    None,
                    &self.fonts,
                );
            }
            DrawCommand::ConsumableRadius { pos, radius_px, color, alpha, .. } => {
                let x = pos.x as f32;
                let y = pos.y as f32 + y_off;
                // Semi-transparent filled circle
                draw_filled_circle(&mut self.canvas, x, y, *radius_px as f32, *color, *alpha);
                // Outline for visibility
                draw_circle_outline(&mut self.canvas, x, y, *radius_px as f32, *color, 0.5, 2.0);
            }
            DrawCommand::PatrolRadius { pos, radius_px, color, alpha, .. } => {
                let x = pos.x as f32;
                let y = pos.y as f32 + y_off;
                // Filled circle only, no outline
                draw_filled_circle(&mut self.canvas, x, y, *radius_px as f32, *color, *alpha);
            }
            DrawCommand::ConsumableIcons { pos, icon_keys, has_hp_bar, .. } => {
                let x = pos.x;
                let y = pos.y + y_off as i32;
                let base_y = if *has_hp_bar { y + 28 } else { y + 26 };
                let icon_size = 28i32;
                let gap = 1i32;
                let count = icon_keys.len() as i32;
                let total_w = count * icon_size + (count - 1) * gap;
                let start_x = x - total_w / 2 + icon_size / 2;
                for (i, icon_key) in icon_keys.iter().enumerate() {
                    if let Some(icon) = self.consumable_icons.get(icon_key) {
                        let ix = start_x + i as i32 * (icon_size + gap);
                        draw_icon(&mut self.canvas, icon, ix, base_y);
                    }
                }
            }
            DrawCommand::ScoreBar {
                team0,
                team1,
                team0_color,
                team1_color,
                max_score,
                team0_timer,
                team1_timer,
                advantage,
            } => {
                let advantage_label = advantage
                    .map(|(level, _)| self.text_resolver.resolve(&TranslatableText::Advantage(level)))
                    .unwrap_or_default();
                let advantage_team = advantage.map(|(_, team)| team as i32).unwrap_or(-1);
                draw_score_bar(
                    &mut self.canvas,
                    *team0,
                    *team1,
                    *team0_color,
                    *team1_color,
                    *max_score,
                    team0_timer.as_deref(),
                    team1_timer.as_deref(),
                    &advantage_label,
                    advantage_team,
                    &self.fonts,
                    self.map_width,
                );
            }
            DrawCommand::TeamAdvantage { .. } => {
                // Advantage is now rendered inline in the score bar;
                // this command is retained for consumers that want the breakdown data.
            }
            DrawCommand::Timer { time_remaining, elapsed } => {
                draw_timer(&mut self.canvas, *time_remaining, *elapsed, &self.fonts, self.map_width);
            }
            DrawCommand::PreBattleCountdown { seconds } => {
                draw_pre_battle_countdown(
                    &mut self.canvas,
                    *seconds,
                    &self.fonts,
                    &*self.text_resolver,
                    self.map_width,
                );
            }
            DrawCommand::TeamBuffs { friendly_buffs, enemy_buffs } => {
                let icon_size = 16i32;
                let gap = 2i32;
                let buff_y = HUD_HEIGHT as i32;
                let count_scale = self.fonts.scale(10.0);

                // Friendly buffs: left side, starting from x=4
                let mut x = 4i32;
                for (marker, count) in friendly_buffs {
                    if let Some(icon) = self.powerup_icons.get(marker.as_str()) {
                        let resized = image::imageops::resize(
                            icon,
                            icon_size as u32,
                            icon_size as u32,
                            image::imageops::FilterType::Nearest,
                        );
                        draw_icon(&mut self.canvas, &resized, x + icon_size / 2, buff_y + icon_size / 2);
                        if *count > 1 {
                            let label = format!("{}", count);
                            draw_text_shadow(
                                &mut self.canvas,
                                [255, 255, 255],
                                x + icon_size,
                                buff_y + 4,
                                count_scale,
                                &self.fonts.primary,
                                &label,
                            );
                            let (tw, _) = text_size(count_scale, &self.fonts.primary, &label);
                            x += icon_size + tw as i32 + gap;
                        } else {
                            x += icon_size + gap;
                        }
                    }
                }

                // Enemy buffs: right side, starting from right edge of map area
                let width = self.map_width as i32;
                let mut x = width - 4;
                for (marker, count) in enemy_buffs {
                    if let Some(icon) = self.powerup_icons.get(marker.as_str()) {
                        let resized = image::imageops::resize(
                            icon,
                            icon_size as u32,
                            icon_size as u32,
                            image::imageops::FilterType::Nearest,
                        );
                        if *count > 1 {
                            let label = format!("{}", count);
                            let (tw, _) = text_size(count_scale, &self.fonts.primary, &label);
                            x -= tw as i32;
                            draw_text_shadow(
                                &mut self.canvas,
                                [255, 255, 255],
                                x,
                                buff_y + 4,
                                count_scale,
                                &self.fonts.primary,
                                &label,
                            );
                            x -= icon_size;
                        } else {
                            x -= icon_size;
                        }
                        draw_icon(&mut self.canvas, &resized, x + icon_size / 2, buff_y + icon_size / 2);
                        x -= gap;
                    }
                }
            }
            DrawCommand::PositionTrail { points, .. } => {
                let y_off_i = y_off as i32;
                for (pos, color) in points {
                    draw_filled_circle(&mut self.canvas, pos.x as f32, (pos.y + y_off_i) as f32, 1.0, *color, 1.0);
                }
            }
            DrawCommand::ShipConfigCircle { pos, radius_px, color, alpha, dashed, label, .. } => {
                let x = pos.x as f32;
                let y = pos.y as f32 + y_off;
                let r = *radius_px;
                if *dashed {
                    draw_dashed_circle(&mut self.canvas, x, y, r, *color, *alpha, 1.0);
                } else {
                    draw_circle_outline(&mut self.canvas, x, y, r, *color, *alpha, 1.0);
                }
                if let Some(text) = label {
                    let font = self.fonts.font_for_text(text);
                    let scale = self.fonts.scale(11.0);
                    let (tw, th) = text_size(scale, font, text);
                    let tw = tw as i32;
                    let th = th as i32;
                    let cx = x as i32;
                    let cy = y as i32;
                    let ri = *radius_px as i32;
                    let gap = 3;

                    // 8 candidate angles: top, top-right, right, bottom-right, bottom, bottom-left, left, top-left
                    let candidates: [(f32, f32); 8] = [
                        (0.0, -1.0),      // top
                        (0.707, -0.707),  // top-right
                        (1.0, 0.0),       // right
                        (0.707, 0.707),   // bottom-right
                        (0.0, 1.0),       // bottom
                        (-0.707, 0.707),  // bottom-left
                        (-1.0, 0.0),      // left
                        (-0.707, -0.707), // top-left
                    ];

                    let compute_rect = |cos: f32, sin: f32| -> [i32; 4] {
                        let ax = cx + ((ri + gap) as f32 * cos) as i32;
                        let ay = cy + ((ri + gap) as f32 * sin) as i32;
                        let lx = if cos < -0.3 {
                            ax - tw
                        } else if cos > 0.3 {
                            ax
                        } else {
                            ax - tw / 2
                        };
                        let ly = if sin < -0.3 {
                            ay - th
                        } else if sin > 0.3 {
                            ay
                        } else {
                            ay - th / 2
                        };
                        [lx, ly, tw, th]
                    };

                    let rects_overlap = |a: &[i32; 4], b: &[i32; 4]| -> bool {
                        a[0] < b[0] + b[2] && a[0] + a[2] > b[0] && a[1] < b[1] + b[3] && a[1] + a[3] > b[1]
                    };

                    let mut best = compute_rect(candidates[0].0, candidates[0].1);
                    for &(cos, sin) in &candidates {
                        let rect = compute_rect(cos, sin);
                        let overlaps = self.placed_labels.iter().any(|prev| rects_overlap(prev, &rect));
                        if !overlaps {
                            best = rect;
                            break;
                        }
                    }

                    self.placed_labels.push(best);
                    draw_text_shadow(&mut self.canvas, *color, best[0], best[1], scale, font, text);
                }
            }
            DrawCommand::KillFeed { entries } => {
                draw_kill_feed(
                    &mut self.canvas,
                    entries,
                    &self.fonts,
                    &self.ship_icons,
                    &self.death_cause_icons,
                    self.map_width,
                );
            }
            DrawCommand::ChatOverlay { entries } => {
                draw_chat_overlay(&mut self.canvas, entries, &self.fonts, &self.ship_icons, HUD_HEIGHT);
            }
            DrawCommand::BattleResultOverlay { result, finish_type, color, subtitle_above } => {
                let text = self.text_resolver.resolve(&TranslatableText::BattleResult(*result));
                let subtitle = finish_type
                    .as_ref()
                    .map(|ft| self.text_resolver.resolve(&TranslatableText::FinishType(ft.clone())).to_uppercase());
                draw_battle_result_overlay(
                    &mut self.canvas,
                    &text,
                    subtitle.as_deref(),
                    *color,
                    *subtitle_above,
                    &self.fonts,
                    self.map_width,
                );
            }
            DrawCommand::StatsPanel { x, width } => {
                // Dark background for the stats panel area
                draw_filled_rect(
                    &mut self.canvas,
                    *x as f32,
                    0.0,
                    *width as f32,
                    CANVAS_HEIGHT as f32,
                    [30, 34, 42],
                    0.96,
                );
                // Subtle left border
                draw_line(&mut self.canvas, *x as f32, 0.0, *x as f32, CANVAS_HEIGHT as f32, [55, 60, 72], 0.8, 1.0);
            }
            DrawCommand::StatsSilhouette {
                x,
                y,
                width,
                height,
                ship_param_id: _,
                hp_fraction,
                hp_current,
                hp_max,
                player_name,
                clan_tag,
                clan_color,
                ship_name,
                silhouette,
            } => {
                let padding = 8;
                let inner_x = *x + padding;
                let inner_w = *width - padding * 2;

                // Draw clan tag + player name, and ship name above the silhouette
                let _name_scale = self.fonts.scale(12.0);
                let _small_scale = self.fonts.scale(10.0);
                let mut label_y = *y + 2;

                if player_name.is_some() || clan_tag.as_ref().is_some_and(|t| !t.is_empty()) {
                    let clan_prefix = clan_tag.as_ref().filter(|t| !t.is_empty()).map(|t| format!("[{t}] "));
                    let name_part = player_name.as_deref().unwrap_or("");

                    let (name_font, name_font_scale) = self.fonts.font_and_scale(name_part, 12.0);

                    // Measure total width for centering
                    let clan_w =
                        clan_prefix.as_ref().map(|cp| text_size(name_font_scale, name_font, cp).0).unwrap_or(0);
                    let name_w =
                        if !name_part.is_empty() { text_size(name_font_scale, name_font, name_part).0 } else { 0 };
                    let total_w = clan_w + name_w;
                    let mut cx = inner_x + (inner_w - total_w as i32) / 2;

                    if let Some(ref cp) = clan_prefix {
                        let cc = clan_color.unwrap_or([255, 255, 255]);
                        draw_text_shadow(&mut self.canvas, cc, cx, label_y, name_font_scale, name_font, cp);
                        cx += clan_w as i32;
                    }
                    if !name_part.is_empty() {
                        draw_text_shadow(
                            &mut self.canvas,
                            [255, 255, 255],
                            cx,
                            label_y,
                            name_font_scale,
                            name_font,
                            name_part,
                        );
                    }
                    label_y += 14;
                }
                if let Some(name) = ship_name {
                    let (ship_font, ship_font_scale) = self.fonts.font_and_scale(name, 10.0);
                    let (tw, _) = text_size(ship_font_scale, ship_font, name);
                    let tx = inner_x + (inner_w - tw as i32) / 2;
                    draw_text_shadow(&mut self.canvas, [180, 180, 180], tx, label_y, ship_font_scale, ship_font, name);
                    label_y += 14;
                }

                // Draw silhouette (gray base + yellow HP overlay)
                let sil_y = label_y + 2;
                let sil_h = (*y + *height - 18 - sil_y).max(20);
                if let Some(sil_img) = silhouette {
                    // Scale silhouette to fit the available area
                    let aspect = sil_img.width() as f32 / sil_img.height() as f32;
                    let fit_w = inner_w as u32;
                    let fit_h = sil_h as u32;
                    let (draw_w, draw_h) = if aspect > (fit_w as f32 / fit_h as f32) {
                        (fit_w, (fit_w as f32 / aspect) as u32)
                    } else {
                        ((fit_h as f32 * aspect) as u32, fit_h)
                    };
                    let draw_w = draw_w.max(1);
                    let draw_h = draw_h.max(1);

                    // Gray silhouette (background / lost HP)
                    let gray_sil = tint_silhouette(sil_img, [200, 200, 200]);
                    let resized_gray =
                        image::imageops::resize(&gray_sil, draw_w, draw_h, image::imageops::FilterType::Triangle);
                    let sil_x = inner_x + (inner_w - draw_w as i32) / 2;
                    let sil_cy = sil_y + (sil_h - draw_h as i32) / 2;
                    draw_icon_at(&mut self.canvas, &resized_gray, sil_x, sil_cy);

                    // Yellow HP overlay: mask to hp_fraction width
                    let hp_color = hp_bar_color_lerp(*hp_fraction);
                    let hp_sil = tint_silhouette(sil_img, hp_color);
                    let resized_hp =
                        image::imageops::resize(&hp_sil, draw_w, draw_h, image::imageops::FilterType::Triangle);
                    let hp_px = (draw_w as f32 * hp_fraction) as u32;
                    if hp_px > 0 {
                        let cropped = image::imageops::crop_imm(&resized_hp, 0, 0, hp_px, draw_h).to_image();
                        draw_icon_at(&mut self.canvas, &cropped, sil_x, sil_cy);
                    }
                }

                // HP text: "12,345 / 42,750"
                let hp_text = format!("{} / {}", format_number(*hp_current as i64), format_number(*hp_max as i64));
                let hp_scale = self.fonts.scale(14.0);
                let (tw, _) = text_size(hp_scale, &self.fonts.primary, &hp_text);
                let hp_text_x = inner_x + (inner_w - tw as i32) / 2;
                draw_text_shadow(
                    &mut self.canvas,
                    [220, 220, 220],
                    hp_text_x,
                    *y + *height - 14,
                    hp_scale,
                    &self.fonts.primary,
                    &hp_text,
                );
            }
            DrawCommand::StatsDamage {
                x,
                y,
                width,
                breakdowns,
                damage_spotting,
                spotting_breakdowns,
                damage_potential,
                potential_breakdowns,
            } => {
                let padding = 8;
                let inner_x = *x + padding;
                let indent_x = inner_x + 12;
                let header_scale = self.fonts.scale(16.0);
                let breakdown_scale = self.fonts.scale(13.0);
                let header_row_h = 22;
                let breakdown_row_h = 18;
                let right_x = *x + *width - padding;

                let mut cur_y = *y + 4;

                // Total enemy damage header
                let total_damage: f64 = breakdowns.iter().map(|e| e.damage).sum();
                draw_text_shadow(
                    &mut self.canvas,
                    [200, 200, 200],
                    inner_x,
                    cur_y,
                    header_scale,
                    &self.fonts.primary,
                    "DMG",
                );
                let total_str = format_number(total_damage as i64);
                let (tw, _) = text_size(header_scale, &self.fonts.primary, &total_str);
                draw_text_shadow(
                    &mut self.canvas,
                    [255, 220, 100],
                    right_x - tw as i32,
                    cur_y,
                    header_scale,
                    &self.fonts.primary,
                    &total_str,
                );
                cur_y += header_row_h;

                // Indented breakdown rows
                for entry in breakdowns.iter() {
                    let color = damage_label_color_rgb(&entry.label);
                    draw_text_shadow(
                        &mut self.canvas,
                        [140, 140, 140],
                        indent_x,
                        cur_y,
                        breakdown_scale,
                        &self.fonts.primary,
                        &entry.label,
                    );
                    let val_str = format_number(entry.damage as i64);
                    let (tw, _) = text_size(breakdown_scale, &self.fonts.primary, &val_str);
                    draw_text_shadow(
                        &mut self.canvas,
                        color,
                        right_x - tw as i32,
                        cur_y,
                        breakdown_scale,
                        &self.fonts.primary,
                        &val_str,
                    );
                    cur_y += breakdown_row_h;
                }

                // Spotting + Potential with sub-breakdowns
                let summary_sections: [(&str, f64, &[_], [u8; 3]); 2] = [
                    ("SPOT", *damage_spotting, spotting_breakdowns, [120u8, 200, 255]),
                    ("POT", *damage_potential, potential_breakdowns, [180, 180, 180]),
                ];
                for (label, total, sub_breakdowns, color) in &summary_sections {
                    // Header row
                    draw_text_shadow(
                        &mut self.canvas,
                        [140, 140, 140],
                        inner_x,
                        cur_y,
                        breakdown_scale,
                        &self.fonts.primary,
                        label,
                    );
                    let val_str = format_number(*total as i64);
                    let (tw, _) = text_size(breakdown_scale, &self.fonts.primary, &val_str);
                    draw_text_shadow(
                        &mut self.canvas,
                        *color,
                        right_x - tw as i32,
                        cur_y,
                        breakdown_scale,
                        &self.fonts.primary,
                        &val_str,
                    );
                    cur_y += breakdown_row_h;

                    // Sub-breakdown rows
                    for entry in sub_breakdowns.iter() {
                        let sub_color = damage_label_color_rgb(&entry.label);
                        draw_text_shadow(
                            &mut self.canvas,
                            [140, 140, 140],
                            indent_x,
                            cur_y,
                            breakdown_scale,
                            &self.fonts.primary,
                            &entry.label,
                        );
                        let sub_val_str = format_number(entry.damage as i64);
                        let (tw, _) = text_size(breakdown_scale, &self.fonts.primary, &sub_val_str);
                        draw_text_shadow(
                            &mut self.canvas,
                            sub_color,
                            right_x - tw as i32,
                            cur_y,
                            breakdown_scale,
                            &self.fonts.primary,
                            &sub_val_str,
                        );
                        cur_y += breakdown_row_h;
                    }
                }
            }
            DrawCommand::StatsRibbons { x, y, width, ribbons } => {
                let padding = 8;
                let inner_x = *x + padding;
                let inner_w = *width - padding * 2;
                let col_w = inner_w / 2;
                let row_h = 20;
                let scale = self.fonts.scale(14.0);

                for (i, rc) in ribbons.iter().take(12).enumerate() {
                    let col = i % 2;
                    let row = i / 2;
                    let rx = inner_x + col as i32 * col_w;
                    let ry = *y + row as i32 * row_h;

                    let count_str = format!("x{}", rc.count);
                    draw_text_shadow(
                        &mut self.canvas,
                        [180, 180, 180],
                        rx,
                        ry,
                        scale,
                        &self.fonts.primary,
                        &rc.display_name,
                    );
                    let (tw, _) = text_size(scale, &self.fonts.primary, &count_str);
                    draw_text_shadow(
                        &mut self.canvas,
                        [255, 220, 100],
                        rx + col_w - tw as i32,
                        ry,
                        scale,
                        &self.fonts.primary,
                        &count_str,
                    );
                }
            }
            DrawCommand::StatsActivityFeed { x, y, width, height, entries } => {
                let padding = 8;
                let inner_x = *x + padding;
                let inner_w = *width - padding * 2;
                let name_scale = self.fonts.scale(14.0);
                let msg_scale = self.fonts.scale(13.0);
                let kill_row_h = 20i32;
                let chat_header_h = 18i32;
                let chat_line_h = 17i32;
                let icon_size = 16i32;
                let gap = 2i32;
                let font = &self.fonts.primary;

                // Fixed-size box background
                draw_filled_rect(
                    &mut self.canvas,
                    *x as f32,
                    *y as f32,
                    *width as f32,
                    *height as f32,
                    [24, 28, 36],
                    0.8,
                );
                // Top border
                draw_line(
                    &mut self.canvas,
                    *x as f32 + 4.0,
                    *y as f32,
                    (*x + *width - 4) as f32,
                    *y as f32,
                    [55, 60, 72],
                    0.6,
                    1.0,
                );

                // Pre-compute entry heights
                let mut entry_heights: Vec<i32> = Vec::new();
                for entry in entries.iter() {
                    let h = match &entry.kind {
                        ActivityFeedKind::Kill(_) => kill_row_h,
                        ActivityFeedKind::Chat(chat) => {
                            let msg_font = match chat.font_hint {
                                FontHint::Primary => &self.fonts.primary,
                                FontHint::Fallback(i) => self.fonts.fallbacks.get(i).unwrap_or(&self.fonts.primary),
                            };
                            let msg_lines = word_wrap(&chat.message, inner_w as u32, msg_scale, msg_font);
                            chat_header_h + msg_lines.len().max(1) as i32 * chat_line_h + 2
                        }
                    };
                    entry_heights.push(h);
                }

                // Show most recent entries that fit
                let total_h = *height;
                let mut consumed = 0i32;
                let mut start_idx = entries.len();
                for i in (0..entries.len()).rev() {
                    let needed = consumed + entry_heights[i];
                    if needed > total_h - 4 {
                        break;
                    }
                    consumed = needed;
                    start_idx = i;
                }

                let mut ey = *y + 4;
                for entry in entries.iter().skip(start_idx) {
                    if ey >= *y + *height {
                        break;
                    }
                    match &entry.kind {
                        ActivityFeedKind::Kill(kill) => {
                            let (_, text_h) = text_size(name_scale, font, "Ag");
                            let icon_y = ey + (text_h as i32 - icon_size) / 2;
                            let mut cx = inner_x;

                            // Kill prefix
                            let prefix = " | ";
                            draw_text_shadow(&mut self.canvas, [140, 140, 140], cx, ey, name_scale, font, prefix);
                            let (pw, _) = text_size(name_scale, font, prefix);
                            cx += pw as i32;

                            // Killer name
                            let (kf, ks) = self.fonts.font_and_scale(&kill.killer_name, 14.0);
                            draw_text_shadow(&mut self.canvas, kill.killer_color, cx, ey, ks, kf, &kill.killer_name);
                            let (kw, _) = text_size(ks, kf, &kill.killer_name);
                            cx += kw as i32 + gap;

                            // Killer ship icon (friendly=left, enemy=right)
                            if let Some(ref species) = kill.killer_species
                                && let Some(icon) = self.ship_icons.get(species)
                            {
                                draw_kill_feed_icon(
                                    &mut self.canvas,
                                    icon,
                                    cx,
                                    icon_y,
                                    icon_size,
                                    kill.killer_color,
                                    !kill.killer_is_friendly,
                                );
                                cx += icon_size + gap;
                            }

                            // Death cause icon
                            let cause_key = death_cause_icon_key(&kill.cause);
                            if let Some(cause_icon) = self.death_cause_icons.get(cause_key) {
                                let cause_center_y = icon_y + icon_size / 2;
                                draw_icon(&mut self.canvas, cause_icon, cx + icon_size / 2, cause_center_y);
                                cx += icon_size + gap;
                            }

                            // Victim name
                            let (vf, vs) = self.fonts.font_and_scale(&kill.victim_name, 14.0);
                            draw_text_shadow(&mut self.canvas, kill.victim_color, cx, ey, vs, vf, &kill.victim_name);
                            let (vw, _) = text_size(vs, vf, &kill.victim_name);
                            cx += vw as i32 + gap;

                            // Victim ship icon (friendly=left, enemy=right)
                            if let Some(ref species) = kill.victim_species
                                && let Some(icon) = self.ship_icons.get(species)
                            {
                                draw_kill_feed_icon(
                                    &mut self.canvas,
                                    icon,
                                    cx,
                                    icon_y,
                                    icon_size,
                                    kill.victim_color,
                                    !kill.victim_is_friendly,
                                );
                            }

                            ey += kill_row_h;
                        }
                        ActivityFeedKind::Chat(chat) => {
                            let mut cx = inner_x;

                            // Clan tag + Player name (use same font for both)
                            let (chat_name_font, chat_name_scale) = self.fonts.font_and_scale(&chat.player_name, 14.0);
                            if !chat.clan_tag.is_empty() {
                                let clan_color = chat.clan_color.unwrap_or(chat.team_color);
                                let clan_text = format!("[{}] ", chat.clan_tag);
                                draw_text_shadow(
                                    &mut self.canvas,
                                    clan_color,
                                    cx,
                                    ey,
                                    chat_name_scale,
                                    chat_name_font,
                                    &clan_text,
                                );
                                let (cw, _) = text_size(chat_name_scale, chat_name_font, &clan_text);
                                cx += cw as i32;
                            }

                            // Player name
                            draw_text_shadow(
                                &mut self.canvas,
                                chat.team_color,
                                cx,
                                ey,
                                chat_name_scale,
                                chat_name_font,
                                &chat.player_name,
                            );
                            let (nw, text_h) = text_size(chat_name_scale, chat_name_font, &chat.player_name);
                            cx += nw as i32 + gap;

                            // Ship icon
                            let icon_y = ey + (text_h as i32 - icon_size) / 2;
                            if let Some(ref species) = chat.ship_species
                                && let Some(icon) = self.ship_icons.get(species.as_str())
                            {
                                draw_kill_feed_icon(
                                    &mut self.canvas,
                                    icon,
                                    cx,
                                    icon_y,
                                    icon_size,
                                    chat.team_color,
                                    false,
                                );
                                cx += icon_size + gap;
                            }

                            // Ship name
                            if let Some(ref ship_name) = chat.ship_name {
                                draw_text_shadow(
                                    &mut self.canvas,
                                    chat.team_color,
                                    cx,
                                    ey,
                                    name_scale,
                                    font,
                                    ship_name,
                                );
                            }

                            ey += chat_header_h;

                            // Message lines (word-wrapped)
                            let msg_font = match chat.font_hint {
                                FontHint::Primary => &self.fonts.primary,
                                FontHint::Fallback(idx) => self.fonts.fallbacks.get(idx).unwrap_or(&self.fonts.primary),
                            };
                            let msg_lines = word_wrap(&chat.message, inner_w as u32, msg_scale, msg_font);
                            for line in &msg_lines {
                                draw_text_shadow(
                                    &mut self.canvas,
                                    chat.message_color,
                                    inner_x,
                                    ey,
                                    msg_scale,
                                    msg_font,
                                    line,
                                );
                                ey += chat_line_h;
                            }
                            if msg_lines.is_empty() {
                                ey += chat_line_h;
                            }
                            ey += 2; // small gap after chat
                        }
                    }
                }
            }
        }
    }

    fn end_frame(&mut self) {
        // No-op — frame is ready to read via frame()
    }
}