aprender-test-lib 0.34.0

Probar: Rust-native testing framework with pixel coverage, TUI snapshots, and visual regression
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
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
//! Heatmap Rendering for Pixel Coverage
//!
//! Renders coverage data as visual heatmaps for terminal and web output.

use super::tracker::{CoverageCell, PixelCoverageTracker};
use serde::{Deserialize, Serialize};

/// RGB color
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rgb {
    /// Red component (0-255)
    pub r: u8,
    /// Green component (0-255)
    pub g: u8,
    /// Blue component (0-255)
    pub b: u8,
}

impl Rgb {
    /// Create a new RGB color
    #[must_use]
    pub const fn new(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b }
    }

    /// Create color from hex value
    #[must_use]
    pub const fn from_hex(hex: u32) -> Self {
        Self {
            r: ((hex >> 16) & 0xFF) as u8,
            g: ((hex >> 8) & 0xFF) as u8,
            b: (hex & 0xFF) as u8,
        }
    }
}

/// Color palette for heatmap rendering
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColorPalette {
    /// Color for 0% coverage
    pub zero: Rgb,
    /// Color for 25% coverage
    pub low: Rgb,
    /// Color for 50% coverage
    pub medium: Rgb,
    /// Color for 75% coverage
    pub high: Rgb,
    /// Color for 100% coverage
    pub full: Rgb,
}

impl Default for ColorPalette {
    fn default() -> Self {
        Self::viridis()
    }
}

impl ColorPalette {
    /// Viridis color palette (colorblind-friendly)
    #[must_use]
    pub fn viridis() -> Self {
        Self {
            zero: Rgb::from_hex(0x440154),   // Dark purple
            low: Rgb::from_hex(0x3B528B),    // Blue
            medium: Rgb::from_hex(0x21918C), // Teal
            high: Rgb::from_hex(0x5DC863),   // Green
            full: Rgb::from_hex(0xFDE725),   // Yellow
        }
    }

    /// Red-Yellow-Green palette (traffic light)
    #[must_use]
    pub fn traffic_light() -> Self {
        Self {
            zero: Rgb::from_hex(0xFF0000),   // Red
            low: Rgb::from_hex(0xFF6600),    // Orange
            medium: Rgb::from_hex(0xFFFF00), // Yellow
            high: Rgb::from_hex(0x99FF00),   // Yellow-green
            full: Rgb::from_hex(0x00FF00),   // Green
        }
    }

    /// Get color for coverage value
    #[must_use]
    pub fn color_for_coverage(&self, coverage: f32) -> Rgb {
        match coverage {
            c if c <= 0.0 => self.zero,
            c if c <= 0.25 => self.low,
            c if c <= 0.50 => self.medium,
            c if c <= 0.75 => self.high,
            _ => self.full,
        }
    }
}

/// Terminal heatmap renderer
#[derive(Debug, Clone)]
pub struct TerminalHeatmap {
    cells: Vec<Vec<f32>>,
    palette: ColorPalette,
    use_color: bool,
}

impl TerminalHeatmap {
    /// Create from coverage tracker
    #[must_use]
    pub fn from_tracker(tracker: &PixelCoverageTracker) -> Self {
        let cells = tracker
            .cells()
            .iter()
            .map(|row| row.iter().map(|c| c.coverage).collect())
            .collect();

        Self {
            cells,
            palette: ColorPalette::default(),
            use_color: true,
        }
    }

    /// Create from raw coverage values
    #[must_use]
    pub fn from_values(cells: Vec<Vec<f32>>) -> Self {
        Self {
            cells,
            palette: ColorPalette::default(),
            use_color: true,
        }
    }

    /// Set color palette
    #[must_use]
    pub fn with_palette(mut self, palette: ColorPalette) -> Self {
        self.palette = palette;
        self
    }

    /// Disable ANSI color output
    #[must_use]
    pub fn without_color(mut self) -> Self {
        self.use_color = false;
        self
    }

    /// Render to string
    #[must_use]
    pub fn render(&self) -> String {
        let mut output = String::new();

        for row in &self.cells {
            for &coverage in row {
                let char = Self::coverage_to_char(coverage);

                if self.use_color {
                    let color = self.palette.color_for_coverage(coverage);
                    output.push_str(&format!(
                        "\x1b[38;2;{};{};{}m{}\x1b[0m",
                        color.r, color.g, color.b, char
                    ));
                } else {
                    output.push(char);
                }
            }
            output.push('\n');
        }

        output
    }

    /// Render with border
    #[must_use]
    pub fn render_with_border(&self) -> String {
        let width = self.cells.first().map_or(0, Vec::len);
        let mut output = String::new();

        // Top border
        output.push('');
        for _ in 0..width {
            output.push('');
        }
        output.push_str("\n");

        // Content
        for row in &self.cells {
            output.push('');
            for &coverage in row {
                let char = Self::coverage_to_char(coverage);

                if self.use_color {
                    let color = self.palette.color_for_coverage(coverage);
                    output.push_str(&format!(
                        "\x1b[38;2;{};{};{}m{}\x1b[0m",
                        color.r, color.g, color.b, char
                    ));
                } else {
                    output.push(char);
                }
            }
            output.push_str("\n");
        }

        // Bottom border
        output.push('');
        for _ in 0..width {
            output.push('');
        }
        output.push('');

        output
    }

    /// Convert coverage value to Unicode block character
    fn coverage_to_char(coverage: f32) -> char {
        match coverage {
            c if c <= 0.0 => ' ',  // Empty
            c if c <= 0.25 => '', // Light shade
            c if c <= 0.50 => '', // Medium shade
            c if c <= 0.75 => '', // Dark shade
            _ => '',              // Full block
        }
    }

    /// Render legend
    #[must_use]
    pub fn legend(&self) -> String {
        let mut legend = String::from("Legend:\n");

        if self.use_color {
            let c = &self.palette;
            legend.push_str(&format!(
                "  \x1b[38;2;{};{};{}m \x1b[0m = 0% (untested)\n",
                c.zero.r, c.zero.g, c.zero.b
            ));
            legend.push_str(&format!(
                "  \x1b[38;2;{};{};{}m░\x1b[0m = 1-25%\n",
                c.low.r, c.low.g, c.low.b
            ));
            legend.push_str(&format!(
                "  \x1b[38;2;{};{};{}m▒\x1b[0m = 26-50%\n",
                c.medium.r, c.medium.g, c.medium.b
            ));
            legend.push_str(&format!(
                "  \x1b[38;2;{};{};{}m▓\x1b[0m = 51-75%\n",
                c.high.r, c.high.g, c.high.b
            ));
            legend.push_str(&format!(
                "  \x1b[38;2;{};{};{}m█\x1b[0m = 76-100%\n",
                c.full.r, c.full.g, c.full.b
            ));
        } else {
            legend.push_str("    = 0% (untested)\n");
            legend.push_str("  ░ = 1-25%\n");
            legend.push_str("  ▒ = 26-50%\n");
            legend.push_str("  ▓ = 51-75%\n");
            legend.push_str("  █ = 76-100%\n");
        }

        legend
    }
}

/// Heatmap renderer trait for extensibility
pub trait HeatmapRenderer {
    /// Render heatmap to string
    fn render(&self, cells: &[Vec<CoverageCell>]) -> String;
}

/// PNG heatmap export with trueno-viz style output
#[derive(Debug, Clone)]
pub struct PngHeatmap {
    /// Output width in pixels
    width: u32,
    /// Output height in pixels
    height: u32,
    /// Color palette
    palette: ColorPalette,
    /// Show legend color bar
    show_legend: bool,
    /// Highlight gaps with red outline
    highlight_gaps: bool,
    /// Show cell borders
    show_borders: bool,
    /// Border color (gray by default)
    border_color: Rgb,
    /// Title text
    title: Option<String>,
    /// Subtitle text (below title)
    subtitle: Option<String>,
    /// Margin around the heatmap (trueno-viz style)
    margin: u32,
    /// Background color
    background: Rgb,
    /// Stats panel for combined coverage display
    pub stats_panel: Option<StatsPanel>,
}

impl Default for PngHeatmap {
    fn default() -> Self {
        Self::new(800, 600)
    }
}

impl PngHeatmap {
    /// Create new PNG exporter with specified dimensions
    #[must_use]
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            palette: ColorPalette::default(),
            show_legend: false,
            highlight_gaps: false,
            show_borders: true,
            border_color: Rgb::new(80, 80, 80),
            title: None,
            subtitle: None,
            margin: 40,
            background: Rgb::new(255, 255, 255),
            stats_panel: None,
        }
    }

    /// Set margin around the heatmap (trueno-viz style)
    #[must_use]
    pub fn with_margin(mut self, margin: u32) -> Self {
        self.margin = margin;
        self
    }

    /// Set background color
    #[must_use]
    pub fn with_background(mut self, color: Rgb) -> Self {
        self.background = color;
        self
    }

    /// Set border color
    #[must_use]
    pub fn with_border_color(mut self, color: Rgb) -> Self {
        self.border_color = color;
        self
    }

    /// Set color palette
    #[must_use]
    pub fn with_palette(mut self, palette: ColorPalette) -> Self {
        self.palette = palette;
        self
    }

    /// Enable legend overlay
    #[must_use]
    pub fn with_legend(mut self) -> Self {
        self.show_legend = true;
        self
    }

    /// Enable gap highlighting (red outline for 0% coverage cells)
    #[must_use]
    pub fn with_gap_highlighting(mut self) -> Self {
        self.highlight_gaps = true;
        self
    }

    /// Enable or disable cell borders
    #[must_use]
    pub fn with_borders(mut self, show: bool) -> Self {
        self.show_borders = show;
        self
    }

    /// Set title text
    #[must_use]
    pub fn with_title(mut self, title: &str) -> Self {
        self.title = Some(title.to_string());
        self
    }

    /// Set subtitle text (displayed below title)
    #[must_use]
    pub fn with_subtitle(mut self, subtitle: &str) -> Self {
        self.subtitle = Some(subtitle.to_string());
        self
    }

    /// Set combined coverage stats panel
    #[must_use]
    pub fn with_combined_stats(mut self, report: &super::tracker::CombinedCoverageReport) -> Self {
        self.stats_panel = Some(StatsPanel {
            line_coverage: report.line_coverage.element_coverage * 100.0,
            pixel_coverage: report.pixel_coverage.overall_coverage * 100.0,
            overall_score: report.overall_score * 100.0,
            line_details: (
                report.line_coverage.covered_elements,
                report.line_coverage.total_elements,
            ),
            pixel_details: (
                report.pixel_coverage.covered_cells,
                report.pixel_coverage.total_cells,
            ),
            meets_threshold: report.meets_threshold,
        });
        self
    }

    /// Export to PNG bytes (trueno-viz style with margins)
    #[cfg(feature = "media")]
    pub fn export(&self, cells: &[Vec<CoverageCell>]) -> Result<Vec<u8>, std::io::Error> {
        use image::{ImageBuffer, Rgb as ImageRgb, RgbImage};
        use std::io::Cursor;

        let rows = cells.len();
        let cols = cells.first().map_or(0, Vec::len);

        if rows == 0 || cols == 0 {
            // Return minimal 1x1 PNG
            let img: RgbImage = ImageBuffer::new(1, 1);
            let mut buffer = Cursor::new(Vec::new());
            img.write_to(&mut buffer, image::ImageFormat::Png)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
            return Ok(buffer.into_inner());
        }

        // Create image buffer and fill with background color
        let mut img: RgbImage = ImageBuffer::new(self.width, self.height);
        let bg = ImageRgb([self.background.r, self.background.g, self.background.b]);
        for pixel in img.pixels_mut() {
            *pixel = bg;
        }

        let font = BitmapFont::default();
        let text_color = Rgb::new(0, 0, 0); // Black text

        // Calculate title space
        let title_space = if self.title.is_some() {
            if self.subtitle.is_some() {
                24 // Title + subtitle
            } else {
                12 // Title only
            }
        } else {
            0
        };

        // Calculate stats panel space
        let stats_space = if self.stats_panel.is_some() { 50 } else { 0 };

        // Calculate plot area (with margins, trueno-viz style)
        let legend_space = if self.show_legend { 30 } else { 0 };
        let plot_width = self.width.saturating_sub(2 * self.margin);
        let plot_height = self
            .height
            .saturating_sub(2 * self.margin + legend_space + title_space + stats_space);

        // Render title if present
        let content_y_offset = self.margin + title_space;
        if let Some(title) = &self.title {
            if !title.is_empty() {
                let title_width = font.text_width(title);
                let title_x = (self.width.saturating_sub(title_width)) / 2;
                font.render_text(&mut img, title, title_x, self.margin / 2, text_color);
            }
        }

        // Render subtitle if present
        if let Some(subtitle) = &self.subtitle {
            if !subtitle.is_empty() {
                let subtitle_width = font.text_width(subtitle);
                let subtitle_x = (self.width.saturating_sub(subtitle_width)) / 2;
                let subtitle_y = self.margin / 2 + 10;
                font.render_text(&mut img, subtitle, subtitle_x, subtitle_y, text_color);
            }
        }

        // Calculate cell dimensions within the plot area
        let cell_width = plot_width / cols as u32;
        let cell_height = plot_height / rows as u32;

        let border_rgb = ImageRgb([
            self.border_color.r,
            self.border_color.g,
            self.border_color.b,
        ]);

        // Fill cells within the plot area
        for (row_idx, row) in cells.iter().enumerate() {
            for (col_idx, cell) in row.iter().enumerate() {
                let x_start = self.margin + col_idx as u32 * cell_width;
                let y_start = content_y_offset + row_idx as u32 * cell_height;
                let x_end = (x_start + cell_width).min(self.margin + plot_width);
                let y_end = (y_start + cell_height).min(content_y_offset + plot_height);

                let color = self.palette.interpolate(cell.coverage);
                let cell_rgb = ImageRgb([color.r, color.g, color.b]);

                // Fill cell
                for y in y_start..y_end {
                    for x in x_start..x_end {
                        if x < self.width && y < self.height {
                            img.put_pixel(x, y, cell_rgb);
                        }
                    }
                }

                // Draw border if enabled
                if self.show_borders {
                    // Top border
                    for x in x_start..x_end {
                        if y_start < self.height {
                            img.put_pixel(x, y_start, border_rgb);
                        }
                    }
                    // Left border
                    for y in y_start..y_end {
                        if x_start < self.width {
                            img.put_pixel(x_start, y, border_rgb);
                        }
                    }
                    // Right border (last column)
                    if col_idx == cols - 1 {
                        for y in y_start..y_end {
                            if x_end > 0 && x_end <= self.width {
                                img.put_pixel(x_end - 1, y, border_rgb);
                            }
                        }
                    }
                    // Bottom border (last row)
                    if row_idx == rows - 1 {
                        for x in x_start..x_end {
                            if y_end > 0 && y_end <= self.height {
                                img.put_pixel(x, y_end - 1, border_rgb);
                            }
                        }
                    }
                }

                // Highlight gaps with red outline if enabled
                if self.highlight_gaps && cell.coverage <= 0.0 {
                    let gap_color = ImageRgb([255, 0, 0]);
                    // Draw thicker red border for gaps (3 pixels)
                    for thickness in 0..3 {
                        // Top border
                        for x in x_start..x_end {
                            if y_start + thickness < self.height {
                                img.put_pixel(x, y_start + thickness, gap_color);
                            }
                        }
                        // Bottom border
                        if y_end > thickness {
                            let y_bottom = y_end - 1 - thickness;
                            for x in x_start..x_end {
                                if y_bottom < self.height {
                                    img.put_pixel(x, y_bottom, gap_color);
                                }
                            }
                        }
                        // Left border
                        for y in y_start..y_end {
                            if x_start + thickness < self.width {
                                img.put_pixel(x_start + thickness, y, gap_color);
                            }
                        }
                        // Right border
                        if x_end > thickness {
                            let x_right = x_end - 1 - thickness;
                            for y in y_start..y_end {
                                if x_right < self.width {
                                    img.put_pixel(x_right, y, gap_color);
                                }
                            }
                        }
                    }
                }
            }
        }

        // Draw legend color bar if enabled
        if self.show_legend {
            let legend_height = 20;
            let legend_y = self
                .height
                .saturating_sub(self.margin / 2 + legend_height + stats_space);
            let legend_width = plot_width;
            let legend_x_start = self.margin;

            // Draw legend bar
            for x in legend_x_start..(legend_x_start + legend_width) {
                let coverage = (x - legend_x_start) as f32 / legend_width as f32;
                let color = self.palette.interpolate(coverage);
                for y in legend_y..(legend_y + legend_height).min(self.height) {
                    img.put_pixel(x, y, ImageRgb([color.r, color.g, color.b]));
                }
            }

            // Draw legend labels
            font.render_text(
                &mut img,
                "0%",
                legend_x_start,
                legend_y + legend_height + 2,
                text_color,
            );
            let label_100 = "100%";
            let label_width = font.text_width(label_100);
            font.render_text(
                &mut img,
                label_100,
                legend_x_start + legend_width - label_width,
                legend_y + legend_height + 2,
                text_color,
            );
        }

        // Draw stats panel if present
        if let Some(stats) = &self.stats_panel {
            let stats_y = self.height.saturating_sub(stats_space + self.margin / 4);
            let stats_x = self.margin;

            // Line coverage
            let line_text = format!(
                "Line: {:.1}% ({}/{})",
                stats.line_coverage, stats.line_details.0, stats.line_details.1
            );
            font.render_text(&mut img, &line_text, stats_x, stats_y, text_color);

            // Pixel coverage
            let pixel_text = format!(
                "Pixel: {:.1}% ({}/{})",
                stats.pixel_coverage, stats.pixel_details.0, stats.pixel_details.1
            );
            font.render_text(&mut img, &pixel_text, stats_x, stats_y + 12, text_color);

            // Overall score
            let overall_text = format!("Overall: {:.1}%", stats.overall_score);
            let threshold_indicator = if stats.meets_threshold {
                " PASS"
            } else {
                " FAIL"
            };
            let full_text = format!("{}{}", overall_text, threshold_indicator);
            font.render_text(&mut img, &full_text, stats_x, stats_y + 24, text_color);
        }

        // Encode to PNG
        let mut buffer = Cursor::new(Vec::new());
        img.write_to(&mut buffer, image::ImageFormat::Png)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;

        Ok(buffer.into_inner())
    }

    /// Export to file
    #[cfg(feature = "media")]
    pub fn export_to_file(
        &self,
        cells: &[Vec<CoverageCell>],
        path: &std::path::Path,
    ) -> Result<(), std::io::Error> {
        let bytes = self.export(cells)?;
        std::fs::write(path, bytes)
    }
}

impl ColorPalette {
    /// Magma color palette (dark to bright)
    #[must_use]
    pub fn magma() -> Self {
        Self {
            zero: Rgb::from_hex(0x000004),   // Almost black
            low: Rgb::from_hex(0x51127C),    // Dark purple
            medium: Rgb::from_hex(0xB63679), // Magenta
            high: Rgb::from_hex(0xFB8861),   // Orange
            full: Rgb::from_hex(0xFCFDBF),   // Light yellow
        }
    }

    /// Heat color palette (black-red-yellow-white)
    #[must_use]
    pub fn heat() -> Self {
        Self {
            zero: Rgb::from_hex(0x000000),   // Black
            low: Rgb::from_hex(0x8B0000),    // Dark red
            medium: Rgb::from_hex(0xFF4500), // Orange red
            high: Rgb::from_hex(0xFFD700),   // Gold
            full: Rgb::from_hex(0xFFFFFF),   // White
        }
    }

    /// Interpolate color for any coverage value 0.0-1.0
    /// Returns smooth gradient instead of discrete steps
    #[must_use]
    pub fn interpolate(&self, coverage: f32) -> Rgb {
        let coverage = coverage.clamp(0.0, 1.0);

        // Define color stops
        let stops: [(f32, Rgb); 5] = [
            (0.0, self.zero),
            (0.25, self.low),
            (0.5, self.medium),
            (0.75, self.high),
            (1.0, self.full),
        ];

        // Find the two stops to interpolate between
        for i in 0..stops.len() - 1 {
            let (t0, c0) = stops[i];
            let (t1, c1) = stops[i + 1];

            if coverage >= t0 && coverage <= t1 {
                let t = (coverage - t0) / (t1 - t0);
                return Rgb::lerp(c0, c1, t);
            }
        }

        // Fallback to full coverage color
        self.full
    }
}

impl Rgb {
    /// Linear interpolation between two colors
    #[must_use]
    pub fn lerp(c0: Rgb, c1: Rgb, t: f32) -> Rgb {
        let t = t.clamp(0.0, 1.0);
        Rgb {
            r: (f32::from(c0.r) + (f32::from(c1.r) - f32::from(c0.r)) * t) as u8,
            g: (f32::from(c0.g) + (f32::from(c1.g) - f32::from(c0.g)) * t) as u8,
            b: (f32::from(c0.b) + (f32::from(c1.b) - f32::from(c0.b)) * t) as u8,
        }
    }
}

// =============================================================================
// Bitmap Font for Text Rendering
// =============================================================================

/// Simple 5x7 bitmap font for PNG text rendering
/// Each character is represented as a 7-element array of u8 (5 bits per row)
#[derive(Debug, Clone)]
pub struct BitmapFont {
    /// Character width in pixels
    char_width: u32,
    /// Character height in pixels
    char_height: u32,
    /// Spacing between characters
    spacing: u32,
}

impl Default for BitmapFont {
    fn default() -> Self {
        Self {
            char_width: 5,
            char_height: 7,
            spacing: 1,
        }
    }
}

impl BitmapFont {
    /// Get character width
    #[must_use]
    pub const fn char_width(&self) -> u32 {
        self.char_width
    }

    /// Get character height
    #[must_use]
    pub const fn char_height(&self) -> u32 {
        self.char_height
    }

    /// Get spacing between characters
    #[must_use]
    pub const fn spacing(&self) -> u32 {
        self.spacing
    }

    /// Get text width in pixels
    #[must_use]
    pub fn text_width(&self, text: &str) -> u32 {
        let len = text.chars().count() as u32;
        if len == 0 {
            return 0;
        }
        len * self.char_width + (len - 1) * self.spacing
    }

    /// Get glyph bitmap for a character (5x7 bits as Vec<bool>)
    #[must_use]
    pub fn glyph(&self, c: char) -> Vec<bool> {
        let bitmap = Self::char_bitmap(c);
        let mut result = Vec::with_capacity(35);
        for row in &bitmap {
            for bit in 0..5 {
                result.push((row >> (4 - bit)) & 1 == 1);
            }
        }
        result
    }

    /// Get raw bitmap data for character (7 rows, each u8 represents 5 bits)
    #[must_use]
    const fn char_bitmap(c: char) -> [u8; 7] {
        match c {
            // Uppercase letters
            'A' => [
                0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
            ],
            'B' => [
                0b11110, 0b10001, 0b11110, 0b10001, 0b10001, 0b10001, 0b11110,
            ],
            'C' => [
                0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
            ],
            'D' => [
                0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110,
            ],
            'E' => [
                0b11111, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000, 0b11111,
            ],
            'F' => [
                0b11111, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000, 0b10000,
            ],
            'G' => [
                0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110,
            ],
            'H' => [
                0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001, 0b10001,
            ],
            'I' => [
                0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
            ],
            'J' => [
                0b00111, 0b00010, 0b00010, 0b00010, 0b10010, 0b10010, 0b01100,
            ],
            'K' => [
                0b10001, 0b10010, 0b11100, 0b10010, 0b10001, 0b10001, 0b10001,
            ],
            'L' => [
                0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
            ],
            'M' => [
                0b10001, 0b11011, 0b10101, 0b10001, 0b10001, 0b10001, 0b10001,
            ],
            'N' => [
                0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
            ],
            'O' => [
                0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
            ],
            'P' => [
                0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000,
            ],
            'Q' => [
                0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b01110, 0b00001,
            ],
            'R' => [
                0b11110, 0b10001, 0b10001, 0b11110, 0b10010, 0b10001, 0b10001,
            ],
            'S' => [
                0b01110, 0b10001, 0b10000, 0b01110, 0b00001, 0b10001, 0b01110,
            ],
            'T' => [
                0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
            ],
            'U' => [
                0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
            ],
            'V' => [
                0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100,
            ],
            'W' => [
                0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001,
            ],
            'X' => [
                0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001,
            ],
            'Y' => [
                0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100,
            ],
            'Z' => [
                0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111,
            ],
            // Lowercase (map to uppercase for simplicity)
            'a'..='z' => Self::char_bitmap((c as u8 - 32) as char),
            // Digits
            '0' => [
                0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
            ],
            '1' => [
                0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
            ],
            '2' => [
                0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111,
            ],
            '3' => [
                0b01110, 0b10001, 0b00001, 0b00110, 0b00001, 0b10001, 0b01110,
            ],
            '4' => [
                0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
            ],
            '5' => [
                0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
            ],
            '6' => [
                0b01110, 0b10000, 0b11110, 0b10001, 0b10001, 0b10001, 0b01110,
            ],
            '7' => [
                0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
            ],
            '8' => [
                0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
            ],
            '9' => [
                0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00001, 0b01110,
            ],
            // Punctuation and symbols
            ' ' => [
                0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000,
            ],
            '.' => [
                0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100,
            ],
            ',' => [
                0b00000, 0b00000, 0b00000, 0b00000, 0b00110, 0b00100, 0b01000,
            ],
            ':' => [
                0b00000, 0b01100, 0b01100, 0b00000, 0b01100, 0b01100, 0b00000,
            ],
            '-' => [
                0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000,
            ],
            '_' => [
                0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111,
            ],
            '/' => [
                0b00001, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b10000,
            ],
            '%' => [
                0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011,
            ],
            '(' => [
                0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010,
            ],
            ')' => [
                0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000,
            ],
            '=' => [
                0b00000, 0b00000, 0b11111, 0b00000, 0b11111, 0b00000, 0b00000,
            ],
            '+' => [
                0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000,
            ],
            '*' => [
                0b00000, 0b10101, 0b01110, 0b11111, 0b01110, 0b10101, 0b00000,
            ],
            '!' => [
                0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100,
            ],
            '?' => [
                0b01110, 0b10001, 0b00001, 0b00110, 0b00100, 0b00000, 0b00100,
            ],
            // Default: empty
            _ => [
                0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000,
            ],
        }
    }

    /// Render text to an image buffer at the specified position
    #[cfg(feature = "media")]
    pub fn render_text(&self, img: &mut image::RgbImage, text: &str, x: u32, y: u32, color: Rgb) {
        use image::Rgb as ImageRgb;

        let text_color = ImageRgb([color.r, color.g, color.b]);
        let mut cursor_x = x;

        for c in text.chars() {
            let bitmap = Self::char_bitmap(c);

            for (row_idx, &row) in bitmap.iter().enumerate() {
                for bit in 0..5 {
                    if (row >> (4 - bit)) & 1 == 1 {
                        let px = cursor_x + bit;
                        let py = y + row_idx as u32;
                        if px < img.width() && py < img.height() {
                            img.put_pixel(px, py, text_color);
                        }
                    }
                }
            }

            cursor_x += self.char_width + self.spacing;
        }
    }
}

/// Stats panel content for combined coverage display
#[derive(Debug, Clone)]
pub struct StatsPanel {
    /// Line coverage percentage
    pub line_coverage: f32,
    /// Pixel coverage percentage
    pub pixel_coverage: f32,
    /// Overall score
    pub overall_score: f32,
    /// Line coverage details (covered/total)
    pub line_details: (usize, usize),
    /// Pixel coverage details (covered/total)
    pub pixel_details: (u32, u32),
    /// Whether threshold is met
    pub meets_threshold: bool,
}

/// SVG heatmap export
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct SvgHeatmap {
    width: u32,
    height: u32,
    palette: ColorPalette,
}

#[allow(dead_code)]
impl SvgHeatmap {
    /// Create new SVG exporter
    #[must_use]
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            palette: ColorPalette::default(),
        }
    }

    /// Set color palette
    #[must_use]
    pub fn with_palette(mut self, palette: ColorPalette) -> Self {
        self.palette = palette;
        self
    }

    /// Export to SVG string
    #[must_use]
    pub fn export(&self, cells: &[Vec<CoverageCell>]) -> String {
        let rows = cells.len();
        let cols = cells.first().map_or(0, Vec::len);

        if rows == 0 || cols == 0 {
            return String::from("<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>");
        }

        let cell_width = self.width / cols as u32;
        let cell_height = self.height / rows as u32;

        let mut svg = format!(
            r#"<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}" viewBox="0 0 {} {}">"#,
            self.width, self.height, self.width, self.height
        );

        svg.push_str("\n  <style>.cell { stroke: #333; stroke-width: 0.5; }</style>\n");

        for (row_idx, row) in cells.iter().enumerate() {
            for (col_idx, cell) in row.iter().enumerate() {
                let x = col_idx as u32 * cell_width;
                let y = row_idx as u32 * cell_height;
                let color = self.palette.color_for_coverage(cell.coverage);

                svg.push_str(&format!(
                    r#"  <rect class="cell" x="{}" y="{}" width="{}" height="{}" fill="rgb({},{},{})"/>"#,
                    x, y, cell_width, cell_height, color.r, color.g, color.b
                ));
                svg.push('\n');
            }
        }

        svg.push_str("</svg>");
        svg
    }
}

// =============================================================================
// Visual Regression Testing Infrastructure
// =============================================================================

/// Visual regression testing utilities for PNG heatmap output
#[cfg(test)]
pub mod visual_regression {
    use super::*;
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    /// Reference checksum for deterministic PNG output
    #[allow(dead_code)]
    #[derive(Debug, Clone)]
    pub struct ReferenceChecksum {
        /// Hash of the PNG bytes
        pub checksum: u64,
        /// Description of the reference
        pub description: &'static str,
        /// Width of the reference image
        pub width: u32,
        /// Height of the reference image
        pub height: u32,
    }

    /// Result of visual comparison
    #[derive(Debug)]
    pub struct ComparisonResult {
        /// Whether images match within tolerance
        pub matches: bool,
        /// Percentage of pixels that differ
        pub diff_percentage: f32,
        /// Maximum color difference found
        pub max_diff: u8,
        /// Number of differing pixels
        pub diff_count: usize,
        /// Total pixels compared
        #[allow(dead_code)]
        pub total_pixels: usize,
    }

    /// Compare two PNG images pixel-by-pixel with tolerance
    ///
    /// # Arguments
    /// * `reference` - Reference PNG bytes
    /// * `generated` - Generated PNG bytes
    /// * `tolerance` - Per-channel color tolerance (0-255)
    ///
    /// # Returns
    /// `ComparisonResult` with match status and diff statistics
    pub fn compare_png_with_tolerance(
        reference: &[u8],
        generated: &[u8],
        tolerance: u8,
    ) -> Result<ComparisonResult, String> {
        use image::GenericImageView;

        let ref_img = image::load_from_memory(reference)
            .map_err(|e| format!("Failed to load reference image: {}", e))?;
        let gen_img = image::load_from_memory(generated)
            .map_err(|e| format!("Failed to load generated image: {}", e))?;

        // Check dimensions match
        if ref_img.dimensions() != gen_img.dimensions() {
            return Ok(ComparisonResult {
                matches: false,
                diff_percentage: 100.0,
                max_diff: 255,
                diff_count: (ref_img.width() * ref_img.height()) as usize,
                total_pixels: (ref_img.width() * ref_img.height()) as usize,
            });
        }

        let (width, height) = ref_img.dimensions();
        let total_pixels = (width * height) as usize;
        let mut diff_count = 0;
        let mut max_diff: u8 = 0;

        for y in 0..height {
            for x in 0..width {
                let ref_pixel = ref_img.get_pixel(x, y);
                let gen_pixel = gen_img.get_pixel(x, y);

                // Compare RGB channels (ignore alpha)
                let diff_r = (ref_pixel[0] as i16 - gen_pixel[0] as i16).unsigned_abs() as u8;
                let diff_g = (ref_pixel[1] as i16 - gen_pixel[1] as i16).unsigned_abs() as u8;
                let diff_b = (ref_pixel[2] as i16 - gen_pixel[2] as i16).unsigned_abs() as u8;

                let channel_max = diff_r.max(diff_g).max(diff_b);
                max_diff = max_diff.max(channel_max);

                if channel_max > tolerance {
                    diff_count += 1;
                }
            }
        }

        let diff_percentage = (diff_count as f32 / total_pixels as f32) * 100.0;
        let matches = diff_count == 0 || diff_percentage < 0.1; // Allow 0.1% variance

        Ok(ComparisonResult {
            matches,
            diff_percentage,
            max_diff,
            diff_count,
            total_pixels,
        })
    }

    /// Compute deterministic checksum for PNG bytes
    pub fn compute_checksum(png_bytes: &[u8]) -> u64 {
        let mut hasher = DefaultHasher::new();
        png_bytes.hash(&mut hasher);
        hasher.finish()
    }

    /// Generate reference cells for testing (deterministic pattern)
    pub fn reference_gradient_cells(rows: usize, cols: usize) -> Vec<Vec<CoverageCell>> {
        let mut cells = Vec::with_capacity(rows);
        for row in 0..rows {
            let mut row_cells = Vec::with_capacity(cols);
            for col in 0..cols {
                let coverage = (row as f32 / (rows - 1).max(1) as f32
                    + col as f32 / (cols - 1).max(1) as f32)
                    / 2.0;
                row_cells.push(CoverageCell {
                    coverage,
                    hit_count: (coverage * 10.0) as u64,
                });
            }
            cells.push(row_cells);
        }
        cells
    }

    /// Generate reference cells with gaps (deterministic pattern)
    pub fn reference_gap_cells(rows: usize, cols: usize) -> Vec<Vec<CoverageCell>> {
        let mut cells = reference_gradient_cells(rows, cols);
        // Add deterministic gaps
        if rows > 2 && cols > 2 {
            cells[rows / 2][cols / 2] = CoverageCell {
                coverage: 0.0,
                hit_count: 0,
            };
        }
        if rows > 4 && cols > 4 {
            cells[rows / 4][cols / 4] = CoverageCell {
                coverage: 0.0,
                hit_count: 0,
            };
        }
        cells
    }

    /// Generate uniform cells for testing
    pub fn reference_uniform_cells(
        rows: usize,
        cols: usize,
        coverage: f32,
    ) -> Vec<Vec<CoverageCell>> {
        vec![
            vec![
                CoverageCell {
                    coverage,
                    hit_count: (coverage * 10.0) as u64,
                };
                cols
            ];
            rows
        ]
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::float_cmp)]
mod tests {
    use super::*;

    #[test]
    fn test_rgb_from_hex() {
        let red = Rgb::from_hex(0xFF0000);
        assert_eq!(red.r, 255);
        assert_eq!(red.g, 0);
        assert_eq!(red.b, 0);

        let white = Rgb::from_hex(0xFFFFFF);
        assert_eq!(white.r, 255);
        assert_eq!(white.g, 255);
        assert_eq!(white.b, 255);
    }

    #[test]
    fn test_color_palette_viridis() {
        let palette = ColorPalette::viridis();
        assert_ne!(palette.zero, palette.full);
    }

    #[test]
    fn test_color_for_coverage() {
        let palette = ColorPalette::traffic_light();

        assert_eq!(palette.color_for_coverage(0.0), palette.zero);
        assert_eq!(palette.color_for_coverage(0.1), palette.low);
        assert_eq!(palette.color_for_coverage(0.4), palette.medium);
        assert_eq!(palette.color_for_coverage(0.6), palette.high);
        assert_eq!(palette.color_for_coverage(1.0), palette.full);
    }

    #[test]
    fn test_terminal_heatmap_render() {
        let cells = vec![vec![0.0, 0.25, 0.5], vec![0.75, 1.0, 0.0]];

        let heatmap = TerminalHeatmap::from_values(cells).without_color();
        let rendered = heatmap.render();

        assert!(rendered.contains(' ')); // 0% coverage
        assert!(rendered.contains('')); // 100% coverage
    }

    #[test]
    fn test_terminal_heatmap_with_border() {
        let cells = vec![vec![1.0, 1.0], vec![0.0, 0.0]];

        let heatmap = TerminalHeatmap::from_values(cells).without_color();
        let rendered = heatmap.render_with_border();

        assert!(rendered.contains(''));
        assert!(rendered.contains(''));
        assert!(rendered.contains(''));
    }

    #[test]
    fn test_coverage_to_char() {
        assert_eq!(TerminalHeatmap::coverage_to_char(0.0), ' ');
        assert_eq!(TerminalHeatmap::coverage_to_char(0.1), '');
        assert_eq!(TerminalHeatmap::coverage_to_char(0.3), '');
        assert_eq!(TerminalHeatmap::coverage_to_char(0.6), '');
        assert_eq!(TerminalHeatmap::coverage_to_char(1.0), '');
    }

    #[test]
    fn test_svg_export() {
        let cells = vec![vec![CoverageCell {
            hit_count: 1,
            coverage: 1.0,
        }]];

        let svg = SvgHeatmap::new(100, 100).export(&cells);

        assert!(svg.starts_with("<svg"));
        assert!(svg.contains("<rect"));
        assert!(svg.ends_with("</svg>"));
    }

    #[test]
    fn test_svg_empty_cells() {
        let cells: Vec<Vec<CoverageCell>> = vec![];
        let svg = SvgHeatmap::new(100, 100).export(&cells);
        assert!(svg.contains("</svg>"));
    }

    #[test]
    fn test_legend() {
        let cells = vec![vec![1.0]];
        let heatmap = TerminalHeatmap::from_values(cells).without_color();
        let legend = heatmap.legend();

        assert!(legend.contains("Legend:"));
        assert!(legend.contains(""));
        assert!(legend.contains(""));
    }

    // =========================================================================
    // PNG Heatmap Tests (H₀-PNG-XX)
    // =========================================================================

    #[test]
    fn h0_png_01_basic_render() {
        let cells = vec![vec![CoverageCell {
            coverage: 0.5,
            hit_count: 5,
        }]];
        let png = PngHeatmap::new(100, 100).export(&cells).unwrap();
        assert!(!png.is_empty());
        // Verify PNG header bytes
        assert_eq!(&png[0..8], &[137, 80, 78, 71, 13, 10, 26, 10]);
    }

    #[test]
    fn h0_png_02_color_interpolation() {
        let palette = ColorPalette::viridis();
        let color_0 = palette.interpolate(0.0);
        let color_50 = palette.interpolate(0.5);
        let color_100 = palette.interpolate(1.0);

        // Should be distinct colors
        assert_ne!(color_0, color_50);
        assert_ne!(color_50, color_100);
    }

    #[test]
    fn h0_png_03_gap_highlighting() {
        let mut cells = vec![
            vec![
                CoverageCell {
                    coverage: 1.0,
                    hit_count: 10,
                };
                10
            ];
            10
        ];
        cells[5][5] = CoverageCell {
            coverage: 0.0,
            hit_count: 0,
        }; // Gap

        let png = PngHeatmap::new(100, 100)
            .with_gap_highlighting()
            .export(&cells)
            .unwrap();

        // Should render successfully with gap highlighted
        assert!(!png.is_empty());
        // Verify PNG header
        assert_eq!(&png[0..8], &[137, 80, 78, 71, 13, 10, 26, 10]);
    }

    #[test]
    fn h0_png_04_magma_palette() {
        let palette = ColorPalette::magma();
        assert_ne!(palette.zero, palette.full);
        // Magma starts nearly black
        assert!(palette.zero.r < 10);
        assert!(palette.zero.g < 10);
    }

    #[test]
    fn h0_png_05_heat_palette() {
        let palette = ColorPalette::heat();
        assert_ne!(palette.zero, palette.full);
        // Heat starts at black
        assert_eq!(palette.zero, Rgb::new(0, 0, 0));
        // Heat ends at white
        assert_eq!(palette.full, Rgb::new(255, 255, 255));
    }

    #[test]
    fn h0_png_06_rgb_lerp() {
        let black = Rgb::new(0, 0, 0);
        let white = Rgb::new(255, 255, 255);

        let mid = Rgb::lerp(black, white, 0.5);
        assert_eq!(mid.r, 127);
        assert_eq!(mid.g, 127);
        assert_eq!(mid.b, 127);

        // Extremes
        assert_eq!(Rgb::lerp(black, white, 0.0), black);
        assert_eq!(Rgb::lerp(black, white, 1.0), white);
    }

    #[test]
    fn h0_png_07_interpolate_boundaries() {
        let palette = ColorPalette::viridis();

        // Exactly at boundaries
        let c0 = palette.interpolate(0.0);
        let c25 = palette.interpolate(0.25);
        let c50 = palette.interpolate(0.5);
        let c75 = palette.interpolate(0.75);
        let c100 = palette.interpolate(1.0);

        assert_eq!(c0, palette.zero);
        assert_eq!(c25, palette.low);
        assert_eq!(c50, palette.medium);
        assert_eq!(c75, palette.high);
        assert_eq!(c100, palette.full);
    }

    #[test]
    fn h0_png_08_interpolate_clamping() {
        let palette = ColorPalette::viridis();

        // Out of range values should be clamped
        let below = palette.interpolate(-0.5);
        let above = palette.interpolate(1.5);

        assert_eq!(below, palette.zero);
        assert_eq!(above, palette.full);
    }

    #[test]
    fn h0_png_09_empty_cells() {
        let cells: Vec<Vec<CoverageCell>> = vec![];
        let png = PngHeatmap::new(100, 100).export(&cells).unwrap();
        // Should still produce valid PNG (1x1 fallback)
        assert!(!png.is_empty());
        assert_eq!(&png[0..8], &[137, 80, 78, 71, 13, 10, 26, 10]);
    }

    #[test]
    fn h0_png_10_with_legend() {
        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.0,
                    hit_count: 0,
                },
                CoverageCell {
                    coverage: 1.0,
                    hit_count: 10,
                },
            ],
            vec![
                CoverageCell {
                    coverage: 0.5,
                    hit_count: 5,
                },
                CoverageCell {
                    coverage: 0.75,
                    hit_count: 8,
                },
            ],
        ];

        let png = PngHeatmap::new(200, 200)
            .with_legend()
            .with_palette(ColorPalette::magma())
            .export(&cells)
            .unwrap();

        assert!(!png.is_empty());
        assert_eq!(&png[0..8], &[137, 80, 78, 71, 13, 10, 26, 10]);
    }

    #[test]
    fn h0_png_11_builder_pattern() {
        let heatmap = PngHeatmap::new(800, 600)
            .with_palette(ColorPalette::heat())
            .with_legend()
            .with_gap_highlighting()
            .with_borders(false)
            .with_title("Test Heatmap");

        // Verify settings applied (indirectly through export working)
        let cells = vec![vec![CoverageCell {
            coverage: 0.5,
            hit_count: 5,
        }]];
        let png = heatmap.export(&cells).unwrap();
        assert!(!png.is_empty());
    }

    #[test]
    fn h0_png_12_export_to_file() {
        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.0,
                    hit_count: 0,
                },
                CoverageCell {
                    coverage: 0.5,
                    hit_count: 5,
                },
                CoverageCell {
                    coverage: 1.0,
                    hit_count: 10,
                },
            ];
            3
        ];

        let temp_dir = std::env::temp_dir();
        let path = temp_dir.join("test_heatmap.png");

        PngHeatmap::new(300, 300)
            .with_gap_highlighting()
            .export_to_file(&cells, &path)
            .unwrap();

        // Verify file exists and is valid PNG
        let bytes = std::fs::read(&path).unwrap();
        assert_eq!(&bytes[0..8], &[137, 80, 78, 71, 13, 10, 26, 10]);

        // Cleanup
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn h0_png_13_default() {
        let heatmap = PngHeatmap::default();
        let cells = vec![vec![CoverageCell {
            coverage: 0.5,
            hit_count: 5,
        }]];
        let png = heatmap.export(&cells).unwrap();
        assert!(!png.is_empty());
    }

    // =========================================================================
    // Title/Metadata Text Rendering Tests (H₀-TXT-XX)
    // =========================================================================

    #[test]
    fn h0_txt_01_title_renders() {
        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.5,
                    hit_count: 5,
                };
                5
            ];
            5
        ];

        let png = PngHeatmap::new(400, 300)
            .with_title("Test Coverage")
            .export(&cells)
            .unwrap();

        assert!(!png.is_empty());
        assert_eq!(&png[0..8], &[137, 80, 78, 71, 13, 10, 26, 10]);
    }

    #[test]
    fn h0_txt_02_title_with_legend() {
        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 1.0,
                    hit_count: 10,
                };
                3
            ];
            3
        ];

        let png = PngHeatmap::new(400, 300)
            .with_title("Coverage Heatmap")
            .with_legend()
            .export(&cells)
            .unwrap();

        assert!(!png.is_empty());
    }

    #[test]
    fn h0_txt_03_bitmap_font_basic() {
        // Test that bitmap font renders without panics
        let font = BitmapFont::default();
        let glyph = font.glyph('A');
        assert!(!glyph.is_empty());
    }

    #[test]
    fn h0_txt_04_bitmap_font_digits() {
        let font = BitmapFont::default();
        for c in '0'..='9' {
            let glyph = font.glyph(c);
            assert!(!glyph.is_empty(), "Digit {} should have a glyph", c);
        }
    }

    #[test]
    fn h0_txt_05_bitmap_font_text_width() {
        let font = BitmapFont::default();
        let width = font.text_width("Hello");
        assert!(width > 0);
        assert_eq!(
            width,
            5 * (font.char_width() + font.spacing()) - font.spacing()
        );
    }

    #[test]
    fn h0_txt_06_metadata_subtitle() {
        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.75,
                    hit_count: 8,
                };
                4
            ];
            4
        ];

        let png = PngHeatmap::new(500, 400)
            .with_title("Main Title")
            .with_subtitle("85% coverage")
            .export(&cells)
            .unwrap();

        assert!(!png.is_empty());
    }

    #[test]
    fn h0_txt_07_empty_title() {
        let cells = vec![vec![CoverageCell {
            coverage: 0.5,
            hit_count: 5,
        }]];

        // Empty title should not cause issues
        let png = PngHeatmap::new(200, 200)
            .with_title("")
            .export(&cells)
            .unwrap();

        assert!(!png.is_empty());
    }

    #[test]
    fn h0_txt_08_special_characters() {
        let font = BitmapFont::default();
        // Should return empty glyph for unknown chars
        let glyph = font.glyph('');
        assert!(glyph.is_empty() || glyph.iter().all(|&b| !b));
    }

    // =========================================================================
    // Combined PNG Tests (H₀-CMB-XX)
    // =========================================================================

    #[test]
    fn h0_cmb_01_combined_heatmap() {
        use super::super::tracker::{
            CombinedCoverageReport, LineCoverageReport, PixelCoverageReport,
        };

        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.8,
                    hit_count: 8,
                };
                10
            ];
            10
        ];

        let line_report = LineCoverageReport::new(0.90, 1.0, 0.80, 22, 20);
        let pixel_report = PixelCoverageReport {
            overall_coverage: 0.85,
            covered_cells: 85,
            total_cells: 100,
            ..Default::default()
        };
        let combined = CombinedCoverageReport::from_parts(line_report, pixel_report);

        let png = PngHeatmap::new(600, 500)
            .with_title("Combined Coverage")
            .with_legend()
            .with_combined_stats(&combined)
            .export(&cells)
            .unwrap();

        assert!(!png.is_empty());
    }

    #[test]
    fn h0_cmb_02_stats_panel_height() {
        // Stats panel should add extra height
        use super::super::tracker::{
            CombinedCoverageReport, LineCoverageReport, PixelCoverageReport,
        };

        let line_report = LineCoverageReport::new(0.90, 1.0, 0.80, 22, 20);
        let pixel_report = PixelCoverageReport::default();
        let combined = CombinedCoverageReport::from_parts(line_report, pixel_report);

        let heatmap = PngHeatmap::new(400, 300).with_combined_stats(&combined);

        // The stats panel should be stored
        assert!(heatmap.stats_panel.is_some());
    }

    // =========================================================================
    // Visual Regression Tests (H₀-VIS-XX)
    // =========================================================================

    #[test]
    fn h0_vis_01_deterministic_output() {
        use super::visual_regression::*;

        // Same input should produce identical output
        let cells = reference_gradient_cells(8, 10);

        let png1 = PngHeatmap::new(400, 300)
            .with_palette(ColorPalette::viridis())
            .export(&cells)
            .unwrap();

        let png2 = PngHeatmap::new(400, 300)
            .with_palette(ColorPalette::viridis())
            .export(&cells)
            .unwrap();

        // Byte-for-byte identical
        assert_eq!(png1.len(), png2.len());
        assert_eq!(compute_checksum(&png1), compute_checksum(&png2));
    }

    #[test]
    fn h0_vis_02_compare_identical_images() {
        use super::visual_regression::*;

        let cells = reference_uniform_cells(5, 5, 0.5);
        let png = PngHeatmap::new(200, 200).export(&cells).unwrap();

        let result = compare_png_with_tolerance(&png, &png, 0).unwrap();

        assert!(result.matches);
        assert_eq!(result.diff_count, 0);
        assert_eq!(result.max_diff, 0);
        assert!((result.diff_percentage - 0.0).abs() < 0.001);
    }

    #[test]
    fn h0_vis_03_compare_different_palettes() {
        use super::visual_regression::*;

        let cells = reference_gradient_cells(5, 5);

        let png_viridis = PngHeatmap::new(200, 200)
            .with_palette(ColorPalette::viridis())
            .export(&cells)
            .unwrap();

        let png_magma = PngHeatmap::new(200, 200)
            .with_palette(ColorPalette::magma())
            .export(&cells)
            .unwrap();

        // Different palettes should produce different output
        let result = compare_png_with_tolerance(&png_viridis, &png_magma, 0).unwrap();

        assert!(!result.matches || result.max_diff > 0);
    }

    #[test]
    fn h0_vis_04_gap_highlighting_visible() {
        use super::visual_regression::*;

        let cells = reference_gap_cells(8, 10);

        let png_no_gaps = PngHeatmap::new(400, 300).export(&cells).unwrap();

        let png_with_gaps = PngHeatmap::new(400, 300)
            .with_gap_highlighting()
            .export(&cells)
            .unwrap();

        // Gap highlighting should produce different output
        let result = compare_png_with_tolerance(&png_no_gaps, &png_with_gaps, 0).unwrap();

        // Should have some differences (the red gap borders)
        assert!(
            result.diff_count > 0,
            "Gap highlighting should produce visible differences"
        );
    }

    #[test]
    fn h0_vis_05_legend_visible() {
        use super::visual_regression::*;

        let cells = reference_gradient_cells(5, 5);

        let png_no_legend = PngHeatmap::new(300, 250).export(&cells).unwrap();

        let png_with_legend = PngHeatmap::new(300, 250)
            .with_legend()
            .export(&cells)
            .unwrap();

        // Legend should produce different output
        let result = compare_png_with_tolerance(&png_no_legend, &png_with_legend, 0).unwrap();

        assert!(
            result.diff_count > 0,
            "Legend should produce visible differences"
        );
    }

    #[test]
    fn h0_vis_06_title_visible() {
        use super::visual_regression::*;

        let cells = reference_uniform_cells(4, 4, 0.75);

        let png_no_title = PngHeatmap::new(300, 200).export(&cells).unwrap();

        let png_with_title = PngHeatmap::new(300, 200)
            .with_title("Test Title")
            .export(&cells)
            .unwrap();

        // Title should produce different output
        let result = compare_png_with_tolerance(&png_no_title, &png_with_title, 0).unwrap();

        assert!(
            result.diff_count > 0,
            "Title should produce visible differences"
        );
    }

    #[test]
    fn h0_vis_07_reference_viridis_gradient() {
        use super::visual_regression::*;

        // Generate reference gradient with Viridis palette
        let cells = reference_gradient_cells(10, 15);
        let png = PngHeatmap::new(800, 600)
            .with_palette(ColorPalette::viridis())
            .with_legend()
            .with_margin(40)
            .export(&cells)
            .unwrap();

        // Store checksum as reference (captured from known-good output)
        let checksum = compute_checksum(&png);

        // Verify we get a valid PNG
        assert!(!png.is_empty());
        assert_eq!(&png[0..8], &[137, 80, 78, 71, 13, 10, 26, 10]);

        // Re-generate and verify determinism
        let png2 = PngHeatmap::new(800, 600)
            .with_palette(ColorPalette::viridis())
            .with_legend()
            .with_margin(40)
            .export(&cells)
            .unwrap();

        assert_eq!(
            compute_checksum(&png2),
            checksum,
            "Output should be deterministic"
        );
    }

    #[test]
    fn h0_vis_08_reference_magma_gaps() {
        use super::visual_regression::*;

        // Generate reference with gaps and Magma palette
        let cells = reference_gap_cells(8, 12);
        let png = PngHeatmap::new(600, 400)
            .with_palette(ColorPalette::magma())
            .with_gap_highlighting()
            .with_legend()
            .export(&cells)
            .unwrap();

        let checksum = compute_checksum(&png);

        // Verify determinism
        let png2 = PngHeatmap::new(600, 400)
            .with_palette(ColorPalette::magma())
            .with_gap_highlighting()
            .with_legend()
            .export(&cells)
            .unwrap();

        assert_eq!(
            compute_checksum(&png2),
            checksum,
            "Magma gap output should be deterministic"
        );
    }

    #[test]
    fn h0_vis_09_reference_heat_with_title() {
        use super::visual_regression::*;

        // Generate reference with Heat palette and title
        let cells = reference_uniform_cells(6, 8, 0.65);
        let png = PngHeatmap::new(500, 400)
            .with_palette(ColorPalette::heat())
            .with_title("Heat Coverage")
            .with_subtitle("Reference Test")
            .with_legend()
            .export(&cells)
            .unwrap();

        let checksum = compute_checksum(&png);

        // Verify determinism
        let png2 = PngHeatmap::new(500, 400)
            .with_palette(ColorPalette::heat())
            .with_title("Heat Coverage")
            .with_subtitle("Reference Test")
            .with_legend()
            .export(&cells)
            .unwrap();

        assert_eq!(
            compute_checksum(&png2),
            checksum,
            "Heat title output should be deterministic"
        );
    }

    #[test]
    fn h0_vis_10_tolerance_comparison() {
        use super::visual_regression::*;

        let cells = reference_gradient_cells(5, 5);
        let png = PngHeatmap::new(200, 200).export(&cells).unwrap();

        // Exact match with 0 tolerance
        let result0 = compare_png_with_tolerance(&png, &png, 0).unwrap();
        assert!(result0.matches);
        assert_eq!(result0.diff_count, 0);

        // Also matches with higher tolerance
        let result10 = compare_png_with_tolerance(&png, &png, 10).unwrap();
        assert!(result10.matches);
        assert_eq!(result10.diff_count, 0);
    }

    #[test]
    fn h0_vis_11_combined_stats_determinism() {
        use super::super::tracker::{
            CombinedCoverageReport, LineCoverageReport, PixelCoverageReport,
        };
        use super::visual_regression::*;

        let cells = reference_gradient_cells(8, 10);

        let line_report = LineCoverageReport::new(0.85, 0.95, 0.90, 20, 17);
        let pixel_report = PixelCoverageReport {
            overall_coverage: 0.80,
            covered_cells: 64,
            total_cells: 80,
            ..Default::default()
        };
        let combined = CombinedCoverageReport::from_parts(line_report, pixel_report);

        let png1 = PngHeatmap::new(700, 600)
            .with_palette(ColorPalette::viridis())
            .with_title("Combined Report")
            .with_legend()
            .with_gap_highlighting()
            .with_combined_stats(&combined)
            .export(&cells)
            .unwrap();

        let checksum1 = compute_checksum(&png1);

        // Re-create with same parameters
        let line_report2 = LineCoverageReport::new(0.85, 0.95, 0.90, 20, 17);
        let pixel_report2 = PixelCoverageReport {
            overall_coverage: 0.80,
            covered_cells: 64,
            total_cells: 80,
            ..Default::default()
        };
        let combined2 = CombinedCoverageReport::from_parts(line_report2, pixel_report2);

        let png2 = PngHeatmap::new(700, 600)
            .with_palette(ColorPalette::viridis())
            .with_title("Combined Report")
            .with_legend()
            .with_gap_highlighting()
            .with_combined_stats(&combined2)
            .export(&cells)
            .unwrap();

        assert_eq!(
            compute_checksum(&png2),
            checksum1,
            "Combined stats output should be deterministic"
        );
    }

    #[test]
    fn h0_vis_12_dimension_mismatch() {
        use super::visual_regression::*;

        let cells_small = reference_uniform_cells(3, 3, 0.5);
        let cells_large = reference_uniform_cells(5, 5, 0.5);

        let png_small = PngHeatmap::new(100, 100).export(&cells_small).unwrap();
        let png_large = PngHeatmap::new(200, 200).export(&cells_large).unwrap();

        // Different dimensions should fail comparison
        let result = compare_png_with_tolerance(&png_small, &png_large, 255).unwrap();

        assert!(!result.matches, "Different dimensions should not match");
        assert_eq!(result.diff_percentage, 100.0);
    }

    // =========================================================================
    // Additional Coverage Tests (H₀-COV-XX)
    // =========================================================================

    #[test]
    fn h0_cov_01_terminal_from_tracker() {
        // Test TerminalHeatmap::from_tracker
        let tracker = super::super::tracker::PixelCoverageTracker::new(100, 100, 5, 5);
        let heatmap = TerminalHeatmap::from_tracker(&tracker);
        let rendered = heatmap.render();
        // Should render 5 rows
        assert_eq!(rendered.lines().count(), 5);
    }

    #[test]
    fn h0_cov_02_terminal_with_palette() {
        let cells = vec![vec![0.5, 1.0], vec![0.0, 0.25]];
        let heatmap = TerminalHeatmap::from_values(cells)
            .with_palette(ColorPalette::traffic_light())
            .without_color();
        let rendered = heatmap.render();
        assert!(rendered.contains('')); // 50% coverage
        assert!(rendered.contains('')); // 100% coverage
    }

    #[test]
    fn h0_cov_03_terminal_render_with_color() {
        let cells = vec![vec![0.0, 0.5, 1.0]];
        let heatmap = TerminalHeatmap::from_values(cells);
        // use_color is true by default
        let rendered = heatmap.render();
        // Should contain ANSI escape sequences
        assert!(rendered.contains("\x1b[38;2;"));
        assert!(rendered.contains("\x1b[0m"));
    }

    #[test]
    fn h0_cov_04_terminal_border_with_color() {
        let cells = vec![vec![0.5, 1.0]];
        let heatmap = TerminalHeatmap::from_values(cells);
        let rendered = heatmap.render_with_border();
        // Should contain border chars and ANSI sequences
        assert!(rendered.contains(''));
        assert!(rendered.contains("\x1b[38;2;"));
    }

    #[test]
    fn h0_cov_05_terminal_legend_with_color() {
        let cells = vec![vec![1.0]];
        let heatmap = TerminalHeatmap::from_values(cells);
        let legend = heatmap.legend();
        // Should contain ANSI escape sequences in legend
        assert!(legend.contains("\x1b[38;2;"));
        assert!(legend.contains("Legend:"));
    }

    #[test]
    fn h0_cov_06_terminal_empty_cells_border() {
        let cells: Vec<Vec<f32>> = vec![];
        let heatmap = TerminalHeatmap::from_values(cells).without_color();
        let rendered = heatmap.render_with_border();
        // Should still render borders with width 0
        assert!(rendered.contains(''));
        assert!(rendered.contains(''));
    }

    #[test]
    fn h0_cov_07_png_with_margin() {
        let cells = vec![vec![CoverageCell {
            coverage: 0.5,
            hit_count: 5,
        }]];
        let png = PngHeatmap::new(200, 200)
            .with_margin(60)
            .export(&cells)
            .unwrap();
        assert!(!png.is_empty());
        assert_eq!(&png[0..8], &[137, 80, 78, 71, 13, 10, 26, 10]);
    }

    #[test]
    fn h0_cov_08_png_with_background() {
        let cells = vec![vec![CoverageCell {
            coverage: 0.5,
            hit_count: 5,
        }]];
        let png = PngHeatmap::new(200, 200)
            .with_background(Rgb::new(0, 0, 0)) // Black background
            .export(&cells)
            .unwrap();
        assert!(!png.is_empty());
    }

    #[test]
    fn h0_cov_09_png_with_border_color() {
        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.5,
                    hit_count: 5,
                };
                3
            ];
            3
        ];
        let png = PngHeatmap::new(200, 200)
            .with_border_color(Rgb::new(255, 0, 0)) // Red borders
            .export(&cells)
            .unwrap();
        assert!(!png.is_empty());
    }

    #[test]
    fn h0_cov_10_bitmap_font_dimensions() {
        let font = BitmapFont::default();
        assert_eq!(font.char_width(), 5);
        assert_eq!(font.char_height(), 7);
        assert_eq!(font.spacing(), 1);
    }

    #[test]
    fn h0_cov_11_bitmap_font_empty_text_width() {
        let font = BitmapFont::default();
        assert_eq!(font.text_width(""), 0);
    }

    #[test]
    fn h0_cov_12_bitmap_font_single_char_width() {
        let font = BitmapFont::default();
        let width = font.text_width("A");
        assert_eq!(width, 5); // Just char_width, no spacing
    }

    #[test]
    fn h0_cov_13_bitmap_font_punctuation() {
        let font = BitmapFont::default();
        // Test all punctuation characters
        let chars = [
            '.', ',', ':', '-', '_', '/', '%', '(', ')', '=', '+', '*', '!', '?', ' ',
        ];
        for c in chars {
            let glyph = font.glyph(c);
            assert_eq!(glyph.len(), 35, "Glyph for '{}' should have 35 bits", c);
        }
    }

    #[test]
    fn h0_cov_14_bitmap_font_lowercase_to_uppercase() {
        let font = BitmapFont::default();
        // Lowercase should map to uppercase
        let upper = font.glyph('A');
        let lower = font.glyph('a');
        assert_eq!(upper, lower, "Lowercase should map to uppercase");
    }

    #[test]
    fn h0_cov_15_bitmap_font_all_uppercase() {
        let font = BitmapFont::default();
        for c in 'A'..='Z' {
            let glyph = font.glyph(c);
            // Each glyph should have some pixels set (not all false)
            assert!(
                glyph.iter().any(|&b| b),
                "Glyph for '{}' should have some pixels",
                c
            );
        }
    }

    #[test]
    fn h0_cov_16_rgb_lerp_clamping() {
        let black = Rgb::new(0, 0, 0);
        let white = Rgb::new(255, 255, 255);

        // Test clamping at negative values
        let below = Rgb::lerp(black, white, -1.0);
        assert_eq!(below, black);

        // Test clamping above 1.0
        let above = Rgb::lerp(black, white, 2.0);
        assert_eq!(above, white);
    }

    #[test]
    fn h0_cov_17_color_palette_default() {
        let default = ColorPalette::default();
        let viridis = ColorPalette::viridis();
        assert_eq!(default.zero, viridis.zero);
        assert_eq!(default.full, viridis.full);
    }

    #[test]
    fn h0_cov_18_svg_with_palette() {
        let cells = vec![vec![CoverageCell {
            coverage: 0.5,
            hit_count: 5,
        }]];
        let svg = SvgHeatmap::new(100, 100)
            .with_palette(ColorPalette::magma())
            .export(&cells);
        assert!(svg.contains("<svg"));
        assert!(svg.contains("</svg>"));
    }

    #[test]
    fn h0_cov_19_reference_gap_cells_small() {
        use super::visual_regression::*;
        // Test with small grid that won't have gaps at division points
        let cells = reference_gap_cells(2, 2);
        assert_eq!(cells.len(), 2);
        assert_eq!(cells[0].len(), 2);
    }

    #[test]
    fn h0_cov_20_reference_gap_cells_medium() {
        use super::visual_regression::*;
        // Test with grid large enough for first gap but not second
        let cells = reference_gap_cells(3, 3);
        // rows/2 = 1, cols/2 = 1 -> gap at (1,1)
        assert_eq!(cells[1][1].coverage, 0.0);
        assert_eq!(cells[1][1].hit_count, 0);
    }

    #[test]
    fn h0_cov_21_stats_panel_fields() {
        let panel = StatsPanel {
            line_coverage: 85.5,
            pixel_coverage: 90.2,
            overall_score: 87.85,
            line_details: (17, 20),
            pixel_details: (45, 50),
            meets_threshold: true,
        };
        assert!((panel.line_coverage - 85.5).abs() < 0.01);
        assert!((panel.pixel_coverage - 90.2).abs() < 0.01);
        assert!((panel.overall_score - 87.85).abs() < 0.01);
        assert_eq!(panel.line_details, (17, 20));
        assert_eq!(panel.pixel_details, (45, 50));
        assert!(panel.meets_threshold);
    }

    #[test]
    fn h0_cov_22_stats_panel_fail_threshold() {
        use super::super::tracker::{
            CombinedCoverageReport, LineCoverageReport, PixelCoverageReport,
        };

        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.3,
                    hit_count: 3,
                };
                5
            ];
            5
        ];

        // Create report that fails threshold
        let line_report = LineCoverageReport::new(0.5, 0.5, 0.5, 10, 5);
        let pixel_report = PixelCoverageReport {
            overall_coverage: 0.3,
            covered_cells: 15,
            total_cells: 50,
            ..Default::default()
        };
        let combined = CombinedCoverageReport::from_parts(line_report, pixel_report);

        let png = PngHeatmap::new(400, 400)
            .with_combined_stats(&combined)
            .export(&cells)
            .unwrap();

        assert!(!png.is_empty());
    }

    #[test]
    fn h0_cov_23_empty_subtitle() {
        let cells = vec![vec![CoverageCell {
            coverage: 0.5,
            hit_count: 5,
        }]];
        let png = PngHeatmap::new(200, 200)
            .with_subtitle("")
            .export(&cells)
            .unwrap();
        assert!(!png.is_empty());
    }

    #[test]
    fn h0_cov_24_title_and_subtitle() {
        let cells = vec![vec![CoverageCell {
            coverage: 0.5,
            hit_count: 5,
        }]];
        let png = PngHeatmap::new(400, 300)
            .with_title("Title")
            .with_subtitle("Subtitle")
            .export(&cells)
            .unwrap();
        assert!(!png.is_empty());
    }

    #[test]
    fn h0_cov_25_coverage_boundaries() {
        // Test exact boundary values for color_for_coverage
        let palette = ColorPalette::viridis();

        // Negative coverage
        assert_eq!(palette.color_for_coverage(-0.1), palette.zero);

        // Exactly 0.25
        assert_eq!(palette.color_for_coverage(0.25), palette.low);

        // Exactly 0.50
        assert_eq!(palette.color_for_coverage(0.50), palette.medium);

        // Exactly 0.75
        assert_eq!(palette.color_for_coverage(0.75), palette.high);

        // Above 0.75
        assert_eq!(palette.color_for_coverage(0.76), palette.full);
    }

    #[test]
    fn h0_cov_26_coverage_to_char_boundaries() {
        // Test exact boundary values
        assert_eq!(TerminalHeatmap::coverage_to_char(-0.1), ' ');
        assert_eq!(TerminalHeatmap::coverage_to_char(0.25), '');
        assert_eq!(TerminalHeatmap::coverage_to_char(0.26), '');
        assert_eq!(TerminalHeatmap::coverage_to_char(0.50), '');
        assert_eq!(TerminalHeatmap::coverage_to_char(0.51), '');
        assert_eq!(TerminalHeatmap::coverage_to_char(0.75), '');
        assert_eq!(TerminalHeatmap::coverage_to_char(0.76), '');
    }

    #[test]
    fn h0_cov_27_interpolate_mid_segment() {
        let palette = ColorPalette::viridis();

        // Test interpolation within a segment (not at boundaries)
        let c = palette.interpolate(0.125); // Middle of 0-0.25 segment
                                            // Should be between zero and low
        assert_ne!(c, palette.zero);
        assert_ne!(c, palette.low);
    }

    #[test]
    fn h0_cov_28_reference_gradient_single_cell() {
        use super::visual_regression::*;
        // Single cell grid (edge case with max(1) divisor)
        let cells = reference_gradient_cells(1, 1);
        assert_eq!(cells.len(), 1);
        assert_eq!(cells[0].len(), 1);
        // Coverage should be 0.0 (row=0, col=0, divided by max(1)=1)
        assert!((cells[0][0].coverage - 0.0).abs() < 0.01);
    }

    #[test]
    fn h0_cov_29_png_borders_disabled() {
        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.5,
                    hit_count: 5,
                };
                3
            ];
            3
        ];
        let png = PngHeatmap::new(200, 200)
            .with_borders(false)
            .export(&cells)
            .unwrap();
        assert!(!png.is_empty());
    }

    #[test]
    fn h0_cov_30_png_all_options() {
        use super::super::tracker::{
            CombinedCoverageReport, LineCoverageReport, PixelCoverageReport,
        };

        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.0,
                    hit_count: 0,
                },
                CoverageCell {
                    coverage: 0.5,
                    hit_count: 5,
                },
            ],
            vec![
                CoverageCell {
                    coverage: 1.0,
                    hit_count: 10,
                },
                CoverageCell {
                    coverage: 0.0,
                    hit_count: 0,
                },
            ],
        ];

        let line_report = LineCoverageReport::new(0.9, 0.95, 0.85, 20, 18);
        let pixel_report = PixelCoverageReport {
            overall_coverage: 0.5,
            covered_cells: 2,
            total_cells: 4,
            ..Default::default()
        };
        let combined = CombinedCoverageReport::from_parts(line_report, pixel_report);

        let png = PngHeatmap::new(600, 500)
            .with_palette(ColorPalette::traffic_light())
            .with_title("Full Options Test")
            .with_subtitle("All features enabled")
            .with_legend()
            .with_gap_highlighting()
            .with_borders(true)
            .with_margin(50)
            .with_background(Rgb::new(240, 240, 240))
            .with_border_color(Rgb::new(100, 100, 100))
            .with_combined_stats(&combined)
            .export(&cells)
            .unwrap();

        assert!(!png.is_empty());
        assert_eq!(&png[0..8], &[137, 80, 78, 71, 13, 10, 26, 10]);
    }

    #[test]
    fn h0_cov_31_rgb_new() {
        let color = Rgb::new(128, 64, 32);
        assert_eq!(color.r, 128);
        assert_eq!(color.g, 64);
        assert_eq!(color.b, 32);
    }

    #[test]
    fn h0_cov_32_comparison_result_fields() {
        use super::visual_regression::*;

        let cells = reference_uniform_cells(5, 5, 0.5);
        let png = PngHeatmap::new(200, 200).export(&cells).unwrap();
        let result = compare_png_with_tolerance(&png, &png, 0).unwrap();

        // Verify all fields are accessible
        assert!(result.matches);
        assert_eq!(result.diff_count, 0);
        assert_eq!(result.max_diff, 0);
        assert!((result.diff_percentage - 0.0).abs() < 0.001);
        assert!(result.total_pixels > 0);
    }

    #[test]
    fn h0_cov_33_checksum_determinism() {
        use super::visual_regression::*;

        let data1 = vec![1, 2, 3, 4, 5];
        let data2 = vec![1, 2, 3, 4, 5];
        let data3 = vec![5, 4, 3, 2, 1];

        assert_eq!(compute_checksum(&data1), compute_checksum(&data2));
        assert_ne!(compute_checksum(&data1), compute_checksum(&data3));
    }

    #[test]
    fn h0_cov_34_svg_multiple_cells() {
        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 0.0,
                    hit_count: 0,
                },
                CoverageCell {
                    coverage: 0.5,
                    hit_count: 5,
                },
                CoverageCell {
                    coverage: 1.0,
                    hit_count: 10,
                },
            ],
            vec![
                CoverageCell {
                    coverage: 0.25,
                    hit_count: 2,
                },
                CoverageCell {
                    coverage: 0.75,
                    hit_count: 7,
                },
                CoverageCell {
                    coverage: 0.5,
                    hit_count: 5,
                },
            ],
        ];

        let svg = SvgHeatmap::new(300, 200).export(&cells);

        // Should have 6 rect elements (2 rows x 3 cols)
        let rect_count = svg.matches("<rect").count();
        assert_eq!(rect_count, 6);
    }

    #[test]
    fn h0_cov_35_bitmap_font_render_bounds() {
        use image::{ImageBuffer, RgbImage};

        let font = BitmapFont::default();
        let mut img: RgbImage = ImageBuffer::new(10, 10);

        // Try to render text that would overflow bounds
        font.render_text(&mut img, "HELLO WORLD TEST", 5, 5, Rgb::new(0, 0, 0));

        // Should not panic - pixels outside bounds are simply skipped
    }

    #[test]
    fn h0_cov_36_interpolate_at_segment_boundaries() {
        let palette = ColorPalette::viridis();

        // Test values just below boundaries
        let c1 = palette.interpolate(0.249);
        let c2 = palette.interpolate(0.251);
        // These should be in different segments, producing different interpolations
        assert!(c1.r != c2.r || c1.g != c2.g || c1.b != c2.b);
    }

    #[test]
    fn h0_cov_37_heatmap_renderer_trait() {
        // Test that HeatmapRenderer trait is properly defined
        struct TestRenderer;
        impl HeatmapRenderer for TestRenderer {
            fn render(&self, cells: &[Vec<CoverageCell>]) -> String {
                format!("{}x{}", cells.len(), cells.first().map_or(0, Vec::len))
            }
        }

        let cells = vec![
            vec![
                CoverageCell {
                    coverage: 1.0,
                    hit_count: 10,
                };
                3
            ];
            2
        ];
        let renderer = TestRenderer;
        assert_eq!(renderer.render(&cells), "2x3");
    }

    #[test]
    fn h0_cov_38_terminal_multiple_rows() {
        let cells = vec![
            vec![0.0, 0.1, 0.2],
            vec![0.3, 0.4, 0.5],
            vec![0.6, 0.7, 0.8],
            vec![0.9, 1.0, 0.0],
        ];
        let heatmap = TerminalHeatmap::from_values(cells).without_color();
        let rendered = heatmap.render();

        // Should have 4 lines
        assert_eq!(rendered.lines().count(), 4);

        // Each line should have 3 characters
        for line in rendered.lines() {
            assert_eq!(line.chars().count(), 3);
        }
    }
}