auditmysite 1.7.2

Resource-efficient WCAG 2.2 AA Accessibility Checker in Rust
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
//! Dark Mode Analysis
//!
//! Detects whether a site supports `prefers-color-scheme: dark` and audits
//! the quality of that implementation, including:
//!
//! - Static CSS detection (media queries, `color-scheme` declarations, meta tags)
//! - Dynamic contrast re-check after emulating dark mode via CDP
//! - Comparison of light-mode vs. dark-mode contrast violations
//! - Per-element contrast violation details for dark mode (selector, message, mode)

pub mod module;
pub use module::DarkModeModule;

use chromiumoxide::cdp::browser_protocol::emulation::{
    MediaFeature, SetEmulatedMediaParams, SetEmulatedVisionDeficiencyParams,
    SetEmulatedVisionDeficiencyType,
};
use chromiumoxide::Page;
use serde::{Deserialize, Serialize};
use tracing::warn;

use crate::cli::WcagLevel;
use crate::error::{AuditError, Result};
use crate::interaction::stability::settle;
use crate::wcag::rules::{check_use_of_color_with_page, ContrastRule};
use crate::wcag::Violation;

// ─── Public types ────────────────────────────────────────────────────────────

/// Complete dark mode analysis for a single page.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DarkModeAnalysis {
    /// Site declares `@media (prefers-color-scheme: dark)` CSS rules.
    pub supported: bool,
    /// Dark mode is implemented via CSS class toggle (html.dark / [data-theme="dark"])
    /// rather than @media (prefers-color-scheme: dark). Contrast testing via CDP is not
    /// possible in this mode.
    pub class_based_dark_mode: bool,
    /// Aggregate quality score 0–100.
    pub score: u32,
    /// Human-readable list of detected implementation methods.
    pub detection_methods: Vec<String>,
    /// `:root { color-scheme: ... }` or `html { color-scheme: ... }` present.
    pub color_scheme_css: bool,
    /// `<meta name="color-scheme" content="...">` value, if found.
    pub meta_color_scheme: Option<String>,
    /// `<meta name="theme-color" media="(prefers-color-scheme: dark)">` found.
    pub meta_theme_color_dark: bool,
    /// Number of CSS custom properties with color-related names on `:root`.
    pub css_custom_properties: u32,
    /// Contrast violations found while dark mode is active.
    pub dark_contrast_violations: u32,
    /// Contrast violations that exist in light mode but disappear in dark mode.
    pub light_only_violations: u32,
    /// New contrast violations that appear only in dark mode.
    pub dark_only_violations: u32,
    /// Per-element contrast violation details (light-and-dark, dark-only, light-only).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub contrast_violations: Vec<DarkContrastViolation>,
    /// Print stylesheet/readiness checks via CSS inspection and print media emulation.
    #[serde(default)]
    pub print: PrintStylesheetAnalysis,
    /// Forced-colors / Windows High Contrast readiness checks via media emulation.
    #[serde(default)]
    pub forced_colors: ForcedColorsAnalysis,
    /// Color vision deficiency simulation results via CDP.
    #[serde(default)]
    pub vision_deficiency: VisionDeficiencyAnalysis,
    /// Non-contrast issues (missing support, incomplete implementation, contrast summary).
    pub issues: Vec<DarkModeIssue>,
}

/// Print stylesheet and print-rendering readiness.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PrintStylesheetAnalysis {
    /// Any `@media print` rule or print stylesheet link was detected.
    pub stylesheet_detected: bool,
    /// Print media emulation succeeded through CDP.
    pub emulation_supported: bool,
    /// Navigation/header/footer interactive chrome appears hidden or reduced in print.
    pub interactive_chrome_hidden: bool,
    /// Main content appears unclipped under print media.
    pub content_not_clipped: bool,
    /// Number of potentially clipped visible elements after print emulation.
    pub clipped_elements: u32,
}

/// Forced-colors / Windows High Contrast readiness.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ForcedColorsAnalysis {
    /// Any `@media (forced-colors: active)` rule or `forced-color-adjust` usage was detected.
    pub stylesheet_detected: bool,
    /// Forced-colors media emulation succeeded through CDP.
    pub emulation_supported: bool,
    /// The emulated page reports `matchMedia('(forced-colors: active)').matches`.
    pub active_matches: bool,
    /// Number of elements using `forced-color-adjust`.
    pub forced_color_adjust_count: u32,
    /// Focusable controls have visible borders/outlines/background under forced colors.
    pub focus_indicators_visible: bool,
}

/// Color vision deficiency simulation summary.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VisionDeficiencyAnalysis {
    /// CDP vision-deficiency emulation succeeded for at least one mode.
    pub emulation_supported: bool,
    /// Per-mode results for protanopia/deuteranopia/tritanopia/achromatopsia.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub modes: Vec<VisionDeficiencyModeAnalysis>,
}

/// Per deficiency mode contrast/use-of-color result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisionDeficiencyModeAnalysis {
    pub mode: String,
    pub contrast_violations: u32,
    pub new_contrast_violations: u32,
    pub use_of_color_violations: u32,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub new_contrast_selectors: Vec<String>,
}

/// Per-element contrast violation detail from dark mode analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DarkContrastViolation {
    /// CSS selector identifying the affected element.
    pub selector: Option<String>,
    /// Human-readable contrast message (includes fg/bg colors when available).
    pub message: String,
    /// Which rendering mode(s) this violation appears in.
    pub mode: DarkContrastMode,
}

/// Which color scheme mode a contrast violation appears in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DarkContrastMode {
    /// Violation exists in both light and dark mode.
    LightAndDark,
    /// Violation only in dark mode — dark mode regression.
    DarkOnly,
    /// Violation only in light mode — dark mode fixes it.
    LightOnly,
}

/// A single dark-mode quality issue.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DarkModeIssue {
    pub kind: DarkModeIssueKind,
    pub description: String,
    pub severity: String,
    /// Affected CSS selectors (only populated for the contrast-regression kinds).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub selectors: Vec<String>,
}

/// Issue category for dark mode problems.
///
/// Carries the dynamic data (counts, flags, per-mode results) needed to
/// re-derive the human-readable text in any language via
/// [`dark_mode_issue_text`]. `description` on [`DarkModeIssue`] stores the
/// canonical-English rendering (baked at construction time); the PDF layer
/// re-derives localized text from `kind` + `selectors` at render time.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DarkModeIssueKind {
    NoDarkModeSupport,
    NoColorSchemeDeclaration,
    NoMetaColorScheme,
    /// Class-based dark mode detected (html.dark / [data-theme="dark"]) — contrast
    /// checking via CDP emulation is not possible for this implementation style.
    ClassBasedDarkModeDetected,
    /// Dark mode is implemented, but few color-related CSS custom properties were found.
    FewColorCustomProperties,
    NoPrintStylesheet,
    PrintLayoutRisk {
        chrome_hidden: bool,
        clipped_elements: u32,
    },
    NoForcedColorsSupport,
    ForcedColorsFocusRisk,
    ColorVisionDeficiencyContrastFailure {
        /// (mode label, new contrast violation count) pairs.
        affected_modes: Vec<(String, u32)>,
    },
    /// Elements that pass contrast in light mode but fail in dark mode.
    DarkOnlyContrastRegression {
        count: u32,
    },
    /// Elements with insufficient contrast in both light and dark mode.
    BothModesContrastFailure {
        count: u32,
    },
    /// Elements with contrast issues only in light mode (dark mode resolves them).
    LightOnlyContrastImproved {
        count: u32,
    },
}

/// The single source of truth for [`DarkModeIssue`] description text.
///
/// Returns the German or English sentence for the given `kind`. `selectors`
/// is only consulted for the contrast-regression kinds
/// (`DarkOnlyContrastRegression` / `BothModesContrastFailure`); pass an empty
/// slice for all other kinds. Analysis calls this with `en = true` to bake
/// canonical English into stored structs; the PDF layer calls it with the
/// run locale to re-derive localized text.
pub fn dark_mode_issue_text(kind: &DarkModeIssueKind, selectors: &[String], en: bool) -> String {
    match kind {
        DarkModeIssueKind::NoDarkModeSupport => if en {
            "No @media (prefers-color-scheme: dark) rules found. Users with system dark mode \
             enabled will receive the light view."
        } else {
            "Es wurden keine @media (prefers-color-scheme: dark)-Regeln gefunden. Nutzerinnen \
             und Nutzer mit aktiviertem System-Dunkelmodus erhalten weiterhin die helle Ansicht."
        }
        .to_string(),

        DarkModeIssueKind::NoColorSchemeDeclaration => if en {
            "No `color-scheme: dark light` declared on :root. The browser will not use native \
             dark mode colors for scrollbars, form controls, and other UI elements."
        } else {
            "Es ist kein `color-scheme: dark light` auf :root deklariert. Der Browser verwendet \
             dadurch keine nativen Dunkelmodus-Farben für Scrollbalken, Formularelemente und \
             andere UI-Komponenten."
        }
        .to_string(),

        DarkModeIssueKind::NoMetaColorScheme => if en {
            "No <meta name=\"color-scheme\"> found. Without this meta tag the browser cannot \
             optimize rendering behavior before the CSSOM is built."
        } else {
            "Es fehlt ein <meta name=\"color-scheme\">-Tag. Ohne dieses Tag kann der Browser das \
             Rendering-Verhalten nicht optimieren, bevor das CSSOM aufgebaut ist."
        }
        .to_string(),

        DarkModeIssueKind::ClassBasedDarkModeDetected => if en {
            "Class-based dark mode detected (html.dark / [data-theme=\"dark\"]). Contrast \
             checking in dark mode via CDP emulation is not possible — only \
             @media (prefers-color-scheme: dark) can be tested automatically."
        } else {
            "Es wurde ein klassenbasierter Dunkelmodus erkannt (html.dark / \
             [data-theme=\"dark\"]). Eine automatisierte Kontrastprüfung im Dunkelmodus ist \
             damit nicht möglich — testbar per CDP-Emulation ist nur \
             @media (prefers-color-scheme: dark)."
        }
        .to_string(),

        DarkModeIssueKind::FewColorCustomProperties => if en {
            "Few CSS custom properties for colors detected. Complete dark mode implementations \
             typically use CSS variables (--color-*) on :root and override them inside the \
             media query."
        } else {
            "Es wurden nur wenige CSS Custom Properties für Farben gefunden. Vollständige \
             Dunkelmodus-Implementierungen nutzen typischerweise CSS-Variablen (--color-*) auf \
             :root und überschreiben sie innerhalb der Media Query."
        }
        .to_string(),

        DarkModeIssueKind::NoPrintStylesheet => if en {
            "No print stylesheet rules detected. Printed or PDF-saved pages may unnecessarily \
             include navigation, cookie banners, or interactive elements."
        } else {
            "Es wurden keine Print-Stylesheet-Regeln gefunden. Gedruckte oder als PDF \
             gespeicherte Seiten enthalten dadurch möglicherweise unnötig Navigation, \
             Cookie-Banner oder interaktive Elemente."
        }
        .to_string(),

        DarkModeIssueKind::PrintLayoutRisk {
            chrome_hidden,
            clipped_elements,
        } => {
            if en {
                format!(
                    "Print stylesheet detected but the print layout appears risky: interactive \
                 chrome hidden = {}, potentially clipped elements = {}.",
                    if *chrome_hidden { "yes" } else { "no" },
                    clipped_elements
                )
            } else {
                format!(
                    "Ein Print-Stylesheet ist vorhanden, das Druck-Layout wirkt jedoch riskant: \
                 interaktive Bedienelemente ausgeblendet = {}, potenziell abgeschnittene \
                 Elemente = {}.",
                    if *chrome_hidden { "ja" } else { "nein" },
                    clipped_elements
                )
            }
        }

        DarkModeIssueKind::NoForcedColorsSupport => if en {
            "No targeted forced-colors rules detected. Windows high-contrast users may lose \
             focus indicators, borders, or status surfaces when colors are defined purely \
             visually."
        } else {
            "Es wurden keine gezielten Forced-Colors-Regeln gefunden. Nutzerinnen und Nutzer des \
             Windows-Hochkontrastmodus verlieren dadurch möglicherweise Fokusindikatoren, Rahmen \
             oder Statusflächen, wenn Farben rein visuell definiert sind."
        }
        .to_string(),

        DarkModeIssueKind::ForcedColorsFocusRisk => if en {
            "Forced-colors rules detected, but focusable elements do not consistently retain \
             visible borders, backgrounds, or outlines under emulation."
        } else {
            "Es sind Forced-Colors-Regeln vorhanden, fokussierbare Elemente behalten unter \
             Emulation jedoch nicht durchgängig sichtbare Rahmen, Hintergründe oder Outlines."
        }
        .to_string(),

        DarkModeIssueKind::ColorVisionDeficiencyContrastFailure { affected_modes } => {
            let joined = affected_modes
                .iter()
                .map(|(mode, count)| format!("{mode} ({count})"))
                .collect::<Vec<_>>()
                .join(", ");
            if en {
                format!(
                    "Additional contrast failures under color vision deficiency emulation: \
                     {joined}. Review these elements with non-color state cues and more robust \
                     color values."
                )
            } else {
                format!(
                    "Unter Simulation von Farbsehschwächen treten zusätzliche Kontrastausfälle \
                     auf: {joined}. Diese Elemente sollten zusätzliche, nicht-farbliche \
                     Zustandshinweise und robustere Farbwerte erhalten."
                )
            }
        }

        DarkModeIssueKind::DarkOnlyContrastRegression { count } => {
            let suffix = selector_suffix(selectors, en);
            let count = *count;
            if en {
                let noun = if count == 1 { "element" } else { "elements" };
                format!(
                    "{count} {noun} lose contrast in dark mode (dark mode regression). These \
                     elements pass in light mode but fall below the WCAG minimum contrast in \
                     dark mode.{suffix}"
                )
            } else if count == 1 {
                format!(
                    "1 Element verliert im Dunkelmodus an Kontrast (Dunkelmodus-Regression). Es \
                     liegt im hellen Modus im gültigen Bereich, unterschreitet im Dunkelmodus \
                     jedoch den WCAG-Mindestkontrast.{suffix}"
                )
            } else {
                format!(
                    "{count} Elemente verlieren im Dunkelmodus an Kontrast \
                     (Dunkelmodus-Regression). Sie liegen im hellen Modus im gültigen Bereich, \
                     unterschreiten im Dunkelmodus jedoch den WCAG-Mindestkontrast.{suffix}"
                )
            }
        }

        DarkModeIssueKind::BothModesContrastFailure { count } => {
            let suffix = selector_suffix(selectors, en);
            let count = *count;
            if en {
                let phrase = if count == 1 {
                    "element has"
                } else {
                    "elements have"
                };
                format!(
                    "{count} {phrase} insufficient contrast in both color modes (light and \
                     dark). The dark mode implementation does not adjust the colors of these \
                     elements sufficiently.{suffix}"
                )
            } else if count == 1 {
                format!(
                    "1 Element hat in beiden Farbmodi (hell und dunkel) unzureichenden Kontrast. \
                     Die Dunkelmodus-Implementierung passt die Farbe dieses Elements nicht \
                     ausreichend an.{suffix}"
                )
            } else {
                format!(
                    "{count} Elemente haben in beiden Farbmodi (hell und dunkel) unzureichenden \
                     Kontrast. Die Dunkelmodus-Implementierung passt die Farben dieser Elemente \
                     nicht ausreichend an.{suffix}"
                )
            }
        }

        DarkModeIssueKind::LightOnlyContrastImproved { count } => {
            let count = *count;
            if en {
                let phrase = if count == 1 {
                    "element has"
                } else {
                    "elements have"
                };
                format!(
                    "{count} {phrase} contrast issues only in light mode — dark mode resolves \
                     them. Consider adjusting the light mode colors accordingly."
                )
            } else if count == 1 {
                "1 Element hat nur im hellen Modus Kontrastprobleme — der Dunkelmodus behebt es. \
                 Die Farben im hellen Modus sollten entsprechend angepasst werden."
                    .to_string()
            } else {
                format!(
                    "{count} Elemente haben nur im hellen Modus Kontrastprobleme — der \
                     Dunkelmodus behebt sie. Die Farben im hellen Modus sollten entsprechend \
                     angepasst werden."
                )
            }
        }
    }
}

/// Format up to `max` selectors from an iterator as a locale-appropriate suffix string.
fn selector_suffix(selectors: &[String], en: bool) -> String {
    if selectors.is_empty() {
        return String::new();
    }
    let list = selectors.join(", ");
    if en {
        format!(" Affected elements: {list}.")
    } else {
        format!(" Betroffene Elemente: {list}.")
    }
}

// ─── Main entry point ────────────────────────────────────────────────────────

/// Analyse dark mode support and quality on the given already-loaded page.
///
/// Steps:
/// 1. Static JS detection: CSS media queries, `color-scheme`, meta tags, CSS vars.
/// 2. If dark mode is supported: emulate dark via CDP, re-run contrast, restore.
/// 3. Build per-element contrast violation list with mode classification.
/// 4. Build score and issue list.
pub async fn analyze_dark_mode(page: &Page, wcag_level: WcagLevel) -> Result<DarkModeAnalysis> {
    analyze_dark_mode_with_base_media(page, wcag_level, &[]).await
}

/// [`analyze_dark_mode`] on a page that already emulates media features —
/// the reduced motion of a `--display` mode (#653). Every emulation step here
/// replaces the page's whole feature list, so each one carries `base` along
/// and restores to it, instead of silently dropping the mode's preference
/// for the rest of the audit.
pub async fn analyze_dark_mode_with_base_media(
    page: &Page,
    wcag_level: WcagLevel,
    base: &[MediaFeature],
) -> Result<DarkModeAnalysis> {
    // ── 1. Static detection ─────────────────────────────────────────────────
    let static_info = detect_static_support(page).await?;
    let print = analyze_print_stylesheet(page, base)
        .await
        .unwrap_or_else(|e| {
            warn!("Print stylesheet analysis failed: {e}");
            PrintStylesheetAnalysis::default()
        });
    let forced_colors = analyze_forced_colors(page, base).await.unwrap_or_else(|e| {
        warn!("Forced-colors analysis failed: {e}");
        ForcedColorsAnalysis::default()
    });
    let vision_deficiency = analyze_vision_deficiency(page, wcag_level)
        .await
        .unwrap_or_else(|e| {
            warn!("Vision-deficiency analysis failed: {e}");
            VisionDeficiencyAnalysis::default()
        });

    // ── 2. Contrast comparison (only when dark mode CSS exists) ─────────────
    let (light_viols, dark_viols) = if static_info.has_dark_media_query
        && matches!(wcag_level, WcagLevel::AA | WcagLevel::AAA)
    {
        compare_contrast(page, wcag_level, base).await
    } else {
        (Vec::new(), Vec::new())
    };

    // ── 3. Classify per-element violations ───────────────────────────────────
    let contrast_violations = classify_contrast_violations(&light_viols, &dark_viols);

    let dark_contrast_count = dark_viols.len() as u32;
    let dark_only = contrast_violations
        .iter()
        .filter(|v| v.mode == DarkContrastMode::DarkOnly)
        .count() as u32;
    let light_only = contrast_violations
        .iter()
        .filter(|v| v.mode == DarkContrastMode::LightOnly)
        .count() as u32;

    // ── 4. Build issues list ──────────────────────────────────────────────────
    let issues = build_issues(
        &static_info,
        dark_contrast_count,
        dark_only,
        light_only,
        &contrast_violations,
        &print,
        &forced_colors,
        &vision_deficiency,
    );

    // ── 5. Score ─────────────────────────────────────────────────────────────
    let score = compute_score(
        &static_info,
        dark_contrast_count,
        dark_only,
        &print,
        &forced_colors,
        &vision_deficiency,
    );

    // ── 6. Detection methods ──────────────────────────────────────────────────
    // Only include signals that actually implement dark styling, not mere hints.
    // color-scheme CSS / meta_color_scheme tell the browser which scheme the site
    // prefers but do not apply dark styles — they stay as separate boolean fields.
    let mut detection_methods: Vec<String> = Vec::new();
    if static_info.has_dark_media_query {
        detection_methods.push("@media (prefers-color-scheme: dark)".to_string());
    }
    if static_info.has_class_based_dark_mode {
        detection_methods.push("CSS class-based (.dark / [data-theme=dark])".to_string());
    }
    if static_info.meta_theme_color_dark {
        detection_methods.push("<meta name=\"theme-color\" media dark>".to_string());
    }

    Ok(DarkModeAnalysis {
        supported: static_info.has_dark_media_query || static_info.has_class_based_dark_mode,
        class_based_dark_mode: static_info.has_class_based_dark_mode,
        score,
        detection_methods,
        color_scheme_css: static_info.color_scheme_css,
        meta_color_scheme: static_info.meta_color_scheme,
        meta_theme_color_dark: static_info.meta_theme_color_dark,
        css_custom_properties: static_info.css_custom_properties,
        dark_contrast_violations: dark_contrast_count,
        light_only_violations: light_only,
        dark_only_violations: dark_only,
        contrast_violations,
        print,
        forced_colors,
        vision_deficiency,
        issues,
    })
}

// ─── Issue generation ─────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn build_issues(
    info: &StaticDarkModeInfo,
    dark_contrast_count: u32,
    dark_only: u32,
    light_only: u32,
    contrast_violations: &[DarkContrastViolation],
    print: &PrintStylesheetAnalysis,
    forced_colors: &ForcedColorsAnalysis,
    vision_deficiency: &VisionDeficiencyAnalysis,
) -> Vec<DarkModeIssue> {
    let mut issues: Vec<DarkModeIssue> = Vec::new();

    if !info.has_dark_media_query && !info.has_class_based_dark_mode {
        let kind = DarkModeIssueKind::NoDarkModeSupport;
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "medium".to_string(),
            selectors: Vec::new(),
        });
    }

    if !info.has_dark_media_query && info.has_class_based_dark_mode {
        let kind = DarkModeIssueKind::ClassBasedDarkModeDetected;
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "low".to_string(),
            selectors: Vec::new(),
        });
    }

    // ── Structural best-practice issues ──────────────────────────────────────
    if (info.has_dark_media_query || info.has_class_based_dark_mode) && !info.color_scheme_css {
        let kind = DarkModeIssueKind::NoColorSchemeDeclaration;
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "low".to_string(),
            selectors: Vec::new(),
        });
    }
    if (info.has_dark_media_query || info.has_class_based_dark_mode)
        && info.meta_color_scheme.is_none()
    {
        let kind = DarkModeIssueKind::NoMetaColorScheme;
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "low".to_string(),
            selectors: Vec::new(),
        });
    }
    if (info.has_dark_media_query || info.has_class_based_dark_mode)
        && info.css_custom_properties < 3
    {
        let kind = DarkModeIssueKind::FewColorCustomProperties;
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "low".to_string(),
            selectors: Vec::new(),
        });
    }

    // ── Print and forced-colors issues (#436) ────────────────────────────────
    if !print.stylesheet_detected {
        let kind = DarkModeIssueKind::NoPrintStylesheet;
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "low".to_string(),
            selectors: Vec::new(),
        });
    } else if !print.interactive_chrome_hidden || !print.content_not_clipped {
        let kind = DarkModeIssueKind::PrintLayoutRisk {
            chrome_hidden: print.interactive_chrome_hidden,
            clipped_elements: print.clipped_elements,
        };
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: if print.content_not_clipped {
                "low"
            } else {
                "medium"
            }
            .to_string(),
            selectors: Vec::new(),
        });
    }

    if !forced_colors.stylesheet_detected {
        let kind = DarkModeIssueKind::NoForcedColorsSupport;
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "low".to_string(),
            selectors: Vec::new(),
        });
    } else if !forced_colors.focus_indicators_visible {
        let kind = DarkModeIssueKind::ForcedColorsFocusRisk;
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "medium".to_string(),
            selectors: Vec::new(),
        });
    }

    let affected_modes: Vec<(String, u32)> = vision_deficiency
        .modes
        .iter()
        .filter(|mode| mode.new_contrast_violations > 0)
        .map(|mode| (mode.mode.clone(), mode.new_contrast_violations))
        .collect();
    if !affected_modes.is_empty() {
        let kind = DarkModeIssueKind::ColorVisionDeficiencyContrastFailure { affected_modes };
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "medium".to_string(),
            selectors: Vec::new(),
        });
    }

    // ── Contrast issues ───────────────────────────────────────────────────────

    // Dark-only regressions: these elements were fine in light mode but break in dark mode
    if dark_only > 0 {
        let selectors = collect_selectors(
            contrast_violations
                .iter()
                .filter(|v| v.mode == DarkContrastMode::DarkOnly),
            5,
        );
        let kind = DarkModeIssueKind::DarkOnlyContrastRegression { count: dark_only };
        let description = dark_mode_issue_text(&kind, &selectors, true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "high".to_string(),
            selectors,
        });
    }

    // Violations present in both modes: dark mode doesn't fix the underlying problem
    let both = dark_contrast_count.saturating_sub(dark_only);
    if both > 0 {
        let selectors = collect_selectors(
            contrast_violations
                .iter()
                .filter(|v| v.mode == DarkContrastMode::LightAndDark),
            5,
        );
        let kind = DarkModeIssueKind::BothModesContrastFailure { count: both };
        let description = dark_mode_issue_text(&kind, &selectors, true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "high".to_string(),
            selectors,
        });
    }

    // Light-only: informational (dark mode actually improves these)
    if light_only > 0 {
        let kind = DarkModeIssueKind::LightOnlyContrastImproved { count: light_only };
        let description = dark_mode_issue_text(&kind, &[], true);
        issues.push(DarkModeIssue {
            kind,
            description,
            severity: "low".to_string(),
            selectors: Vec::new(),
        });
    }

    issues
}

/// Collect up to `max` non-empty selectors from an iterator of contrast violations.
fn collect_selectors<'a>(
    iter: impl Iterator<Item = &'a DarkContrastViolation>,
    max: usize,
) -> Vec<String> {
    iter.filter_map(|v| v.selector.as_deref())
        .filter(|s| !s.is_empty())
        .take(max)
        .map(|s| s.to_string())
        .collect()
}

// ─── Violation classification ─────────────────────────────────────────────────

/// Classify each violation from light and dark passes into light_and_dark / dark_only / light_only.
///
/// Dedup key: selector when present (stable across passes), otherwise message.
fn classify_contrast_violations(
    light: &[Violation],
    dark: &[Violation],
) -> Vec<DarkContrastViolation> {
    fn key(v: &Violation) -> String {
        v.selector
            .as_deref()
            .filter(|s| !s.is_empty())
            .map(|s| s.to_owned())
            .unwrap_or_else(|| v.message.clone())
    }

    use std::collections::HashMap;

    let light_map: HashMap<String, &Violation> = light.iter().map(|v| (key(v), v)).collect();
    let dark_map: HashMap<String, &Violation> = dark.iter().map(|v| (key(v), v)).collect();

    let mut result: Vec<DarkContrastViolation> = Vec::new();

    // Dark violations: dark_only or light_and_dark
    for (k, dv) in &dark_map {
        let mode = if light_map.contains_key(k) {
            DarkContrastMode::LightAndDark
        } else {
            DarkContrastMode::DarkOnly
        };
        result.push(DarkContrastViolation {
            selector: dv.selector.clone(),
            message: dv.message.clone(),
            mode,
        });
    }

    // Light-only violations (exist in light but not dark)
    for (k, lv) in &light_map {
        if !dark_map.contains_key(k) {
            result.push(DarkContrastViolation {
                selector: lv.selector.clone(),
                message: lv.message.clone(),
                mode: DarkContrastMode::LightOnly,
            });
        }
    }

    result
}

// ─── Static detection ────────────────────────────────────────────────────────

struct StaticDarkModeInfo {
    has_dark_media_query: bool,
    has_class_based_dark_mode: bool,
    color_scheme_css: bool,
    meta_color_scheme: Option<String>,
    meta_theme_color_dark: bool,
    css_custom_properties: u32,
}

async fn detect_static_support(page: &Page) -> Result<StaticDarkModeInfo> {
    let js = r#"
    (() => {
        const result = {
            hasDarkMediaQuery: false,
            hasClassBasedDarkMode: false,
            colorSchemeCss: false,
            metaColorScheme: null,
            metaThemeColorDark: false,
            cssCustomProperties: 0,
        };

        // 1. Scan stylesheets for @media (prefers-color-scheme: dark)
        try {
            for (const sheet of document.styleSheets) {
                let rules;
                try { rules = sheet.cssRules || sheet.rules; } catch (_) { continue; }
                if (!rules) continue;
                for (const rule of rules) {
                    if (rule instanceof CSSMediaRule) {
                        const text = rule.conditionText || rule.media?.mediaText || '';
                        if (text.includes('prefers-color-scheme') && text.includes('dark')) {
                            result.hasDarkMediaQuery = true;
                        }
                    }
                    if (rule instanceof CSSSupportsRule && rule.cssText &&
                        rule.cssText.includes('prefers-color-scheme')) {
                        result.hasDarkMediaQuery = true;
                    }
                }
            }
        } catch(e) {}

        // 2. Check color-scheme on :root / html
        try {
            const rootStyle = window.getComputedStyle(document.documentElement);
            const colorScheme = rootStyle.getPropertyValue('color-scheme').trim();
            if (colorScheme && colorScheme.length > 0) {
                result.colorSchemeCss = true;
            }
        } catch(e) {}

        // 3. Meta color-scheme tag
        try {
            const meta = document.querySelector('meta[name="color-scheme"]');
            if (meta) result.metaColorScheme = meta.getAttribute('content') || '';
        } catch(e) {}

        // 4. Meta theme-color with dark media
        try {
            const metas = document.querySelectorAll('meta[name="theme-color"]');
            for (const m of metas) {
                const media = m.getAttribute('media') || '';
                if (media.includes('prefers-color-scheme') && media.includes('dark')) {
                    result.metaThemeColorDark = true;
                }
            }
        } catch(e) {}

        // 5. Count CSS custom properties with color-related names on :root
        try {
            let count = 0;
            for (const sheet of document.styleSheets) {
                let rules;
                try { rules = sheet.cssRules || sheet.rules; } catch (_) { continue; }
                if (!rules) continue;
                for (const rule of rules) {
                    if (rule instanceof CSSStyleRule &&
                        (rule.selectorText === ':root' || rule.selectorText === 'html')) {
                        const style = rule.style;
                        for (let i = 0; i < style.length; i++) {
                            const prop = style[i];
                            if (prop.startsWith('--') && (
                                prop.includes('color') || prop.includes('bg') ||
                                prop.includes('background') || prop.includes('text') ||
                                prop.includes('foreground') || prop.includes('primary') ||
                                prop.includes('secondary') || prop.includes('accent') ||
                                prop.includes('surface') || prop.includes('on-')
                            )) {
                                count++;
                            }
                        }
                    }
                }
            }
            result.cssCustomProperties = count;
        } catch(e) {}

        // 6. Check for class-based dark mode in CSS selectors
        try {
            const darkClassPatterns = [
                'html.dark', 'body.dark', ':root.dark',
                '[data-theme="dark"]', "[data-theme='dark']",
                '.dark-mode', '.theme-dark'
            ];
            classLoop:
            for (const sheet of document.styleSheets) {
                let rules;
                try { rules = sheet.cssRules || sheet.rules; } catch (_) { continue; }
                if (!rules) continue;
                for (const rule of rules) {
                    if (rule instanceof CSSStyleRule) {
                        const sel = rule.selectorText || '';
                        for (const pattern of darkClassPatterns) {
                            if (sel.includes(pattern)) {
                                result.hasClassBasedDarkMode = true;
                                break classLoop;
                            }
                        }
                    }
                }
            }
        } catch(e) {}

        return JSON.stringify(result);
    })()
    "#;

    let js_result = page
        .evaluate(js)
        .await
        .map_err(|e| AuditError::CdpError(format!("Dark mode detection failed: {e}")))?;

    let json_str = js_result.value().and_then(|v| v.as_str()).unwrap_or("{}");
    let parsed: serde_json::Value = serde_json::from_str(json_str).unwrap_or_default();

    Ok(StaticDarkModeInfo {
        has_dark_media_query: parsed["hasDarkMediaQuery"].as_bool().unwrap_or(false),
        has_class_based_dark_mode: parsed["hasClassBasedDarkMode"].as_bool().unwrap_or(false),
        color_scheme_css: parsed["colorSchemeCss"].as_bool().unwrap_or(false),
        meta_color_scheme: parsed["metaColorScheme"]
            .as_str()
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string()),
        meta_theme_color_dark: parsed["metaThemeColorDark"].as_bool().unwrap_or(false),
        css_custom_properties: parsed["cssCustomProperties"].as_u64().unwrap_or(0) as u32,
    })
}

/// `Emulation.setEmulatedMedia` with `base` plus `extra` — the one place the
/// dark-mode analysis changes emulated media.
async fn emulate_media(
    page: &Page,
    media: &str,
    base: &[MediaFeature],
    extra: Option<MediaFeature>,
) -> std::result::Result<(), chromiumoxide::error::CdpError> {
    let features: Vec<MediaFeature> = base.iter().cloned().chain(extra).collect();
    page.execute(
        SetEmulatedMediaParams::builder()
            .media(media)
            .features(features)
            .build(),
    )
    .await
    .map(|_| ())
}

async fn analyze_print_stylesheet(
    page: &Page,
    base: &[MediaFeature],
) -> Result<PrintStylesheetAnalysis> {
    let stylesheet_detected = detect_print_stylesheet(page).await?;
    let mut analysis = PrintStylesheetAnalysis {
        stylesheet_detected,
        ..Default::default()
    };

    if let Err(e) = emulate_media(page, "print", base, None).await {
        warn!("Could not emulate print media: {e}");
        return Ok(analysis);
    }
    analysis.emulation_supported = true;

    if let Err(e) = settle(page).await {
        warn!("Could not wait for print media layout settle: {e}");
    }

    let metrics = evaluate_print_layout(page).await?;
    analysis.interactive_chrome_hidden = metrics.interactive_chrome_hidden;
    analysis.content_not_clipped = metrics.clipped_elements == 0;
    analysis.clipped_elements = metrics.clipped_elements;

    if let Err(e) = emulate_media(page, "screen", base, None).await {
        warn!("Could not restore screen media: {e}");
    }

    Ok(analysis)
}

async fn analyze_forced_colors(page: &Page, base: &[MediaFeature]) -> Result<ForcedColorsAnalysis> {
    let stylesheet_detected = detect_forced_colors_stylesheet(page).await?;
    let mut analysis = ForcedColorsAnalysis {
        stylesheet_detected,
        forced_color_adjust_count: count_forced_color_adjust(page).await?,
        ..Default::default()
    };

    let feature = MediaFeature {
        name: "forced-colors".to_string(),
        value: "active".to_string(),
    };
    if let Err(e) = emulate_media(page, "", base, Some(feature)).await {
        warn!("Could not emulate forced colors: {e}");
        return Ok(analysis);
    }
    analysis.emulation_supported = true;

    if let Err(e) = settle(page).await {
        warn!("Could not wait for forced-colors layout settle: {e}");
    }

    let metrics = evaluate_forced_colors_layout(page).await?;
    analysis.active_matches = metrics.active_matches;
    analysis.focus_indicators_visible = metrics.focus_indicators_visible;

    if let Err(e) = emulate_media(page, "", base, None).await {
        warn!("Could not restore media features after forced-colors check: {e}");
    }

    Ok(analysis)
}

async fn analyze_vision_deficiency(
    page: &Page,
    wcag_level: WcagLevel,
) -> Result<VisionDeficiencyAnalysis> {
    if !matches!(wcag_level, WcagLevel::AA | WcagLevel::AAA) {
        return Ok(VisionDeficiencyAnalysis::default());
    }

    let baseline_contrast = ContrastRule::check_with_page(
        page,
        &crate::accessibility::AXTree::default(),
        wcag_level,
        None,
    )
    .await;
    let baseline_use_of_color = check_use_of_color_with_page(page).await;

    let modes = [
        ("protanopia", SetEmulatedVisionDeficiencyType::Protanopia),
        (
            "deuteranopia",
            SetEmulatedVisionDeficiencyType::Deuteranopia,
        ),
        ("tritanopia", SetEmulatedVisionDeficiencyType::Tritanopia),
        (
            "achromatopsia",
            SetEmulatedVisionDeficiencyType::Achromatopsia,
        ),
    ];

    let mut results = Vec::new();
    let mut emulation_supported = false;
    for (label, deficiency) in modes {
        if let Err(e) = page
            .execute(SetEmulatedVisionDeficiencyParams::new(deficiency))
            .await
        {
            warn!("Could not emulate vision deficiency {label}: {e}");
            continue;
        }
        emulation_supported = true;

        if let Err(e) = settle(page).await {
            warn!("Could not wait for vision-deficiency layout settle: {e}");
        }

        let contrast = ContrastRule::check_with_page(
            page,
            &crate::accessibility::AXTree::default(),
            wcag_level,
            None,
        )
        .await;
        let use_of_color = check_use_of_color_with_page(page).await;
        let new_contrast = violations_only_in(&baseline_contrast, &contrast);

        results.push(VisionDeficiencyModeAnalysis {
            mode: label.to_string(),
            contrast_violations: contrast.len() as u32,
            new_contrast_violations: new_contrast.len() as u32,
            use_of_color_violations: use_of_color.len().max(baseline_use_of_color.len()) as u32,
            new_contrast_selectors: new_contrast.into_iter().take(10).collect(),
        });
    }

    if let Err(e) = page
        .execute(SetEmulatedVisionDeficiencyParams::new(
            SetEmulatedVisionDeficiencyType::None,
        ))
        .await
    {
        warn!("Could not restore normal vision emulation: {e}");
    }

    Ok(VisionDeficiencyAnalysis {
        emulation_supported,
        modes: results,
    })
}

fn violations_only_in(baseline: &[Violation], simulated: &[Violation]) -> Vec<String> {
    use std::collections::HashSet;

    fn key(v: &Violation) -> String {
        v.selector
            .as_deref()
            .filter(|selector| !selector.is_empty())
            .unwrap_or(&v.message)
            .to_string()
    }

    let baseline_keys: HashSet<String> = baseline.iter().map(key).collect();
    simulated
        .iter()
        .map(key)
        .filter(|key| !baseline_keys.contains(key))
        .collect()
}

async fn detect_print_stylesheet(page: &Page) -> Result<bool> {
    let js = r#"
    (() => {
        try {
            for (const el of document.querySelectorAll('link[rel~="stylesheet"], style')) {
                const media = (el.getAttribute('media') || '').toLowerCase();
                if (media.includes('print')) return true;
            }
            for (const sheet of document.styleSheets) {
                let rules;
                try { rules = sheet.cssRules || sheet.rules; } catch (_) { continue; }
                if (!rules) continue;
                for (const rule of rules) {
                    const text = (rule.conditionText || rule.media?.mediaText || rule.cssText || '').toLowerCase();
                    if (text.includes('@media print') || text.includes('print')) return true;
                }
            }
        } catch (_) {}
        return false;
    })()
    "#;
    eval_bool(page, js, "Print stylesheet detection failed").await
}

async fn detect_forced_colors_stylesheet(page: &Page) -> Result<bool> {
    let js = r#"
    (() => {
        try {
            for (const sheet of document.styleSheets) {
                let rules;
                try { rules = sheet.cssRules || sheet.rules; } catch (_) { continue; }
                if (!rules) continue;
                for (const rule of rules) {
                    const text = (rule.conditionText || rule.cssText || '').toLowerCase();
                    if (text.includes('forced-colors') || text.includes('forced-color-adjust')) return true;
                }
            }
            for (const el of document.querySelectorAll('[style*="forced-color-adjust" i]')) {
                if (el) return true;
            }
        } catch (_) {}
        return false;
    })()
    "#;
    eval_bool(page, js, "Forced-colors stylesheet detection failed").await
}

async fn count_forced_color_adjust(page: &Page) -> Result<u32> {
    let js = r#"
    (() => {
        let count = 0;
        try {
            for (const el of document.querySelectorAll('body *')) {
                const value = getComputedStyle(el).getPropertyValue('forced-color-adjust');
                if (value && value !== 'auto') count++;
            }
        } catch (_) {}
        return count;
    })()
    "#;
    eval_u32(page, js, "Forced-color-adjust counting failed").await
}

struct PrintLayoutMetrics {
    interactive_chrome_hidden: bool,
    clipped_elements: u32,
}

async fn evaluate_print_layout(page: &Page) -> Result<PrintLayoutMetrics> {
    let js = r#"
    (() => {
        const isVisible = (el) => {
            const style = getComputedStyle(el);
            const rect = el.getBoundingClientRect();
            return style.display !== 'none' && style.visibility !== 'hidden' &&
                style.opacity !== '0' && rect.width > 1 && rect.height > 1;
        };
        const chrome = Array.from(document.querySelectorAll(
            'nav, aside, [role="navigation"], [aria-modal="true"], .cookie, .cookies, .consent, [class*="cookie" i], [id*="cookie" i], button, input, select, textarea'
        ));
        const visibleChrome = chrome.filter(isVisible).length;
        const clipped = Array.from(document.querySelectorAll('main, article, section, [role="main"], p, h1, h2, h3'))
            .filter(isVisible)
            .filter((el) => {
                const style = getComputedStyle(el);
                if (!['hidden', 'clip', 'scroll', 'auto'].includes(style.overflow) &&
                    !['hidden', 'clip', 'scroll', 'auto'].includes(style.overflowY)) {
                    return false;
                }
                return el.scrollHeight > el.clientHeight + 2 || el.scrollWidth > el.clientWidth + 2;
            }).length;
        return JSON.stringify({
            interactiveChromeHidden: visibleChrome === 0,
            clippedElements: clipped
        });
    })()
    "#;
    let value = eval_json(page, js, "Print layout evaluation failed").await?;
    Ok(PrintLayoutMetrics {
        interactive_chrome_hidden: value["interactiveChromeHidden"].as_bool().unwrap_or(false),
        clipped_elements: value["clippedElements"].as_u64().unwrap_or(0) as u32,
    })
}

struct ForcedColorsMetrics {
    active_matches: bool,
    focus_indicators_visible: bool,
}

async fn evaluate_forced_colors_layout(page: &Page) -> Result<ForcedColorsMetrics> {
    let js = r#"
    (() => {
        const active = matchMedia('(forced-colors: active)').matches;
        const focusables = Array.from(document.querySelectorAll(
            'a[href], button, input, select, textarea, summary, [tabindex]:not([tabindex="-1"])'
        )).filter((el) => {
            const style = getComputedStyle(el);
            const rect = el.getBoundingClientRect();
            return !el.disabled && style.display !== 'none' && style.visibility !== 'hidden' &&
                rect.width > 1 && rect.height > 1;
        }).slice(0, 40);
        const visible = focusables.length === 0 || focusables.every((el) => {
            const style = getComputedStyle(el);
            const border = parseFloat(style.borderTopWidth || '0') +
                parseFloat(style.borderRightWidth || '0') +
                parseFloat(style.borderBottomWidth || '0') +
                parseFloat(style.borderLeftWidth || '0');
            const outline = parseFloat(style.outlineWidth || '0');
            const bg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
            return border > 0 || outline > 0 || bg;
        });
        return JSON.stringify({ activeMatches: active, focusIndicatorsVisible: visible });
    })()
    "#;
    let value = eval_json(page, js, "Forced-colors layout evaluation failed").await?;
    Ok(ForcedColorsMetrics {
        active_matches: value["activeMatches"].as_bool().unwrap_or(false),
        focus_indicators_visible: value["focusIndicatorsVisible"].as_bool().unwrap_or(false),
    })
}

async fn eval_bool(page: &Page, js: &str, context: &str) -> Result<bool> {
    let js_result = page
        .evaluate(js)
        .await
        .map_err(|e| AuditError::CdpError(format!("{context}: {e}")))?;
    Ok(js_result.value().and_then(|v| v.as_bool()).unwrap_or(false))
}

async fn eval_u32(page: &Page, js: &str, context: &str) -> Result<u32> {
    let js_result = page
        .evaluate(js)
        .await
        .map_err(|e| AuditError::CdpError(format!("{context}: {e}")))?;
    Ok(js_result.value().and_then(|v| v.as_u64()).unwrap_or(0) as u32)
}

async fn eval_json(page: &Page, js: &str, context: &str) -> Result<serde_json::Value> {
    let js_result = page
        .evaluate(js)
        .await
        .map_err(|e| AuditError::CdpError(format!("{context}: {e}")))?;
    let json_str = js_result.value().and_then(|v| v.as_str()).unwrap_or("{}");
    Ok(serde_json::from_str(json_str).unwrap_or_default())
}

// ─── Contrast comparison ─────────────────────────────────────────────────────

/// Runs contrast checks in light mode (current state) and dark mode (after CDP emulation).
/// Returns `(light_violations, dark_violations)` as full Violation objects.
async fn compare_contrast(
    page: &Page,
    level: WcagLevel,
    base: &[MediaFeature],
) -> (Vec<Violation>, Vec<Violation>) {
    let light_violations =
        ContrastRule::check_with_page(page, &crate::accessibility::AXTree::default(), level, None)
            .await;

    let dark_feature = MediaFeature {
        name: "prefers-color-scheme".to_string(),
        value: "dark".to_string(),
    };
    if let Err(e) = emulate_media(page, "", base, Some(dark_feature)).await {
        warn!("Could not emulate dark mode: {e}");
        return (light_violations, Vec::new());
    }

    if let Err(e) = settle(page).await {
        warn!("Could not wait for dark mode layout settle: {e}");
    }

    let dark_violations =
        ContrastRule::check_with_page(page, &crate::accessibility::AXTree::default(), level, None)
            .await;

    let light_feature = MediaFeature {
        name: "prefers-color-scheme".to_string(),
        value: "light".to_string(),
    };
    if let Err(e) = emulate_media(page, "", base, Some(light_feature)).await {
        warn!("Could not restore light mode: {e}");
    }

    (light_violations, dark_violations)
}

// ─── Scoring ─────────────────────────────────────────────────────────────────

fn compute_score(
    info: &StaticDarkModeInfo,
    dark_contrast_count: u32,
    dark_only: u32,
    print: &PrintStylesheetAnalysis,
    forced_colors: &ForcedColorsAnalysis,
    vision_deficiency: &VisionDeficiencyAnalysis,
) -> u32 {
    if !info.has_dark_media_query && !info.has_class_based_dark_mode {
        let mut score = 50;
        if print.stylesheet_detected {
            score += 5;
        }
        if forced_colors.stylesheet_detected {
            score += 5;
        }
        return score;
    }
    if !info.has_dark_media_query && info.has_class_based_dark_mode {
        let mut score = 65;
        if print.stylesheet_detected {
            score += 5;
        }
        if forced_colors.stylesheet_detected {
            score += 5;
        }
        return score.min(75);
    }

    let mut score: i32 = 70;

    if info.color_scheme_css {
        score += 10;
    }
    if info.meta_color_scheme.is_some() {
        score += 10;
    }
    if info.meta_theme_color_dark {
        score += 5;
    }
    if info.css_custom_properties >= 5 {
        score += 5;
    } else if info.css_custom_properties >= 3 {
        score += 3;
    }

    // Cap contrast penalties so structural implementation still gets credit.
    // Dark-mode regressions (dark_only) are penalised harder than pre-existing issues.
    let dark_only_penalty = ((dark_only as i32) * 5).min(20);
    let both_penalty = ((dark_contrast_count.saturating_sub(dark_only) as i32) * 2).min(10);
    score -= dark_only_penalty + both_penalty;

    if print.stylesheet_detected && print.content_not_clipped {
        score += 3;
    } else if !print.stylesheet_detected {
        score -= 3;
    }
    if forced_colors.stylesheet_detected && forced_colors.focus_indicators_visible {
        score += 3;
    } else if !forced_colors.stylesheet_detected {
        score -= 3;
    }
    let vision_penalty = vision_deficiency
        .modes
        .iter()
        .map(|mode| mode.new_contrast_violations)
        .sum::<u32>()
        .min(10) as i32;
    score -= vision_penalty;

    score.clamp(0, 100) as u32
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::wcag::Severity;

    fn make_info(
        has_dark: bool,
        color_scheme: bool,
        meta: bool,
        theme_color: bool,
        props: u32,
    ) -> StaticDarkModeInfo {
        StaticDarkModeInfo {
            has_dark_media_query: has_dark,
            has_class_based_dark_mode: false,
            color_scheme_css: color_scheme,
            meta_color_scheme: if meta {
                Some("dark light".into())
            } else {
                None
            },
            meta_theme_color_dark: theme_color,
            css_custom_properties: props,
        }
    }

    fn make_violation(selector: &str, message: &str) -> Violation {
        let mut v = Violation::new(
            "1.4.3",
            "Contrast (Minimum)",
            crate::cli::WcagLevel::AA,
            Severity::High,
            message,
            "node-1",
        );
        v.selector = Some(selector.to_string());
        v
    }

    fn print_default() -> PrintStylesheetAnalysis {
        PrintStylesheetAnalysis::default()
    }

    fn forced_default() -> ForcedColorsAnalysis {
        ForcedColorsAnalysis::default()
    }

    fn vision_default() -> VisionDeficiencyAnalysis {
        VisionDeficiencyAnalysis::default()
    }

    // ── Score tests ───────────────────────────────────────────────────────────

    #[test]
    fn score_no_dark_mode_is_50() {
        assert_eq!(
            compute_score(
                &make_info(false, false, false, false, 0),
                0,
                0,
                &print_default(),
                &forced_default(),
                &vision_default()
            ),
            50
        );
    }

    #[test]
    fn score_full_implementation_no_violations_is_100() {
        assert_eq!(
            compute_score(
                &make_info(true, true, true, true, 6),
                0,
                0,
                &PrintStylesheetAnalysis {
                    stylesheet_detected: true,
                    content_not_clipped: true,
                    ..Default::default()
                },
                &ForcedColorsAnalysis {
                    stylesheet_detected: true,
                    focus_indicators_visible: true,
                    ..Default::default()
                },
                &vision_default()
            ),
            100
        );
    }

    #[test]
    fn score_minimal_dark_mode_with_print_and_forced_colors_bonus_is_76() {
        assert_eq!(
            compute_score(
                &make_info(true, false, false, false, 0),
                0,
                0,
                &PrintStylesheetAnalysis {
                    stylesheet_detected: true,
                    content_not_clipped: true,
                    ..Default::default()
                },
                &ForcedColorsAnalysis {
                    stylesheet_detected: true,
                    focus_indicators_visible: true,
                    ..Default::default()
                },
                &vision_default()
            ),
            76
        );
    }

    #[test]
    fn score_dark_only_violations_reduce_score() {
        let score = compute_score(
            &make_info(true, true, true, true, 6),
            3,
            3,
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        assert!(score < 100, "score should be penalised, got {score}");
        assert!(score >= 70, "should retain base points, got {score}");
    }

    #[test]
    fn score_many_both_mode_violations_capped_at_minus_10() {
        // 101 violations in both modes: penalty capped at 10 → 95 - 10 = 85
        let score = compute_score(
            &make_info(true, true, true, false, 6),
            101,
            0,
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        assert_eq!(score, 79);
    }

    #[test]
    fn score_many_dark_only_violations_capped_at_minus_20() {
        // 101 dark-only violations: penalty capped at 20 → 95 - 20 = 75
        let score = compute_score(
            &make_info(true, true, true, false, 6),
            101,
            101,
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        assert_eq!(score, 69);
    }

    // ── Issue generation tests ────────────────────────────────────────────────

    #[test]
    fn issues_no_dark_mode_generates_exactly_one_support_issue() {
        let issues = build_issues(
            &make_info(false, false, false, false, 0),
            0,
            0,
            0,
            &[],
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        assert!(matches!(
            issues[0].kind,
            DarkModeIssueKind::NoDarkModeSupport
        ));
    }

    #[test]
    fn issues_dark_mode_with_zero_violations_no_contrast_issue() {
        let issues = build_issues(
            &make_info(true, true, true, false, 5),
            0,
            0,
            0,
            &[],
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        assert!(
            issues.iter().all(|i| !matches!(
                i.kind,
                DarkModeIssueKind::DarkOnlyContrastRegression { .. }
                    | DarkModeIssueKind::BothModesContrastFailure { .. }
                    | DarkModeIssueKind::LightOnlyContrastImproved { .. }
            )),
            "no contrast issue expected when violations=0"
        );
    }

    #[test]
    fn issues_both_mode_violations_generate_contrast_issue() {
        // 5 violations in both modes — the bug that was missing before
        let violations: Vec<DarkContrastViolation> = (0..5)
            .map(|i| DarkContrastViolation {
                selector: Some(format!("p.text-{i}")),
                message: "Low contrast".into(),
                mode: DarkContrastMode::LightAndDark,
            })
            .collect();

        let issues = build_issues(
            &make_info(true, true, true, false, 5),
            5,
            0,
            0,
            &violations,
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        let contrast_issues: Vec<_> = issues
            .iter()
            .filter(|i| matches!(i.kind, DarkModeIssueKind::BothModesContrastFailure { .. }))
            .collect();

        assert!(
            !contrast_issues.is_empty(),
            "expected contrast issue when both-mode violations > 0"
        );
        assert!(
            contrast_issues[0].description.contains('5')
                || contrast_issues[0].description.contains("5 "),
            "description should mention count, got: {}",
            contrast_issues[0].description
        );
    }

    #[test]
    fn issues_dark_only_violations_generate_regression_issue() {
        let violations: Vec<DarkContrastViolation> = (0..3)
            .map(|i| DarkContrastViolation {
                selector: Some(format!("button.dark-{i}")),
                message: "Low contrast in dark mode".into(),
                mode: DarkContrastMode::DarkOnly,
            })
            .collect();

        let issues = build_issues(
            &make_info(true, true, true, false, 5),
            3,
            3,
            0,
            &violations,
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        let regression = issues
            .iter()
            .find(|i| matches!(i.kind, DarkModeIssueKind::DarkOnlyContrastRegression { .. }));

        assert!(
            regression.is_some(),
            "expected regression issue for dark-only violations"
        );
        let desc = &regression.unwrap().description;
        assert!(
            desc.contains("dark mode"),
            "should mention dark mode regression"
        );
        assert_eq!(regression.unwrap().severity, "high");
    }

    #[test]
    fn issues_contrast_issue_lists_selectors_in_description() {
        let violations: Vec<DarkContrastViolation> = vec![
            DarkContrastViolation {
                selector: Some("h1.hero".into()),
                message: "Low contrast".into(),
                mode: DarkContrastMode::LightAndDark,
            },
            DarkContrastViolation {
                selector: Some("p.caption".into()),
                message: "Low contrast".into(),
                mode: DarkContrastMode::LightAndDark,
            },
        ];

        let issues = build_issues(
            &make_info(true, true, true, false, 5),
            2,
            0,
            0,
            &violations,
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        let contrast_issue = issues
            .iter()
            .find(|i| matches!(i.kind, DarkModeIssueKind::BothModesContrastFailure { .. }))
            .expect("contrast issue must exist");

        assert!(
            contrast_issue.description.contains("h1.hero"),
            "selector should appear in description: {}",
            contrast_issue.description
        );
    }

    #[test]
    fn classify_both_modes_correctly() {
        let light = vec![
            make_violation("#a", "low contrast"),
            make_violation("#b", "low contrast"),
        ];
        let dark = vec![
            make_violation("#a", "low contrast"),
            make_violation("#c", "low contrast"),
        ];

        let result = classify_contrast_violations(&light, &dark);

        let a = result
            .iter()
            .find(|v| v.selector.as_deref() == Some("#a"))
            .unwrap();
        assert_eq!(a.mode, DarkContrastMode::LightAndDark);

        let b = result
            .iter()
            .find(|v| v.selector.as_deref() == Some("#b"))
            .unwrap();
        assert_eq!(b.mode, DarkContrastMode::LightOnly);

        let c = result
            .iter()
            .find(|v| v.selector.as_deref() == Some("#c"))
            .unwrap();
        assert_eq!(c.mode, DarkContrastMode::DarkOnly);
    }

    #[test]
    fn classify_no_double_counting() {
        let shared = make_violation("#x", "low contrast");
        let light = vec![shared.clone(), shared.clone()]; // duplicate in light
        let dark = vec![shared.clone()];

        let result = classify_contrast_violations(&light, &dark);
        // HashMap dedup: only one entry per unique key
        let x_count = result
            .iter()
            .filter(|v| v.selector.as_deref() == Some("#x"))
            .count();
        assert_eq!(x_count, 1, "same selector must not be double-counted");
    }

    #[test]
    fn light_only_violations_generate_low_severity_issue() {
        let violations = vec![DarkContrastViolation {
            selector: Some("p.legacy".into()),
            message: "Low contrast".into(),
            mode: DarkContrastMode::LightOnly,
        }];

        let issues = build_issues(
            &make_info(true, true, true, false, 5),
            0,
            0,
            1,
            &violations,
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        let light_issue = issues
            .iter()
            .find(|i| matches!(i.kind, DarkModeIssueKind::LightOnlyContrastImproved { .. }));

        assert!(light_issue.is_some());
        assert_eq!(light_issue.unwrap().severity, "low");
    }

    #[test]
    fn score_class_based_dark_mode_is_65() {
        let info = StaticDarkModeInfo {
            has_dark_media_query: false,
            has_class_based_dark_mode: true,
            color_scheme_css: false,
            meta_color_scheme: None,
            meta_theme_color_dark: false,
            css_custom_properties: 0,
        };
        assert_eq!(
            compute_score(
                &info,
                0,
                0,
                &print_default(),
                &forced_default(),
                &vision_default()
            ),
            65
        );
    }

    #[test]
    fn issues_class_based_dark_mode_not_reported_as_no_support() {
        let info = StaticDarkModeInfo {
            has_dark_media_query: false,
            has_class_based_dark_mode: true,
            color_scheme_css: false,
            meta_color_scheme: None,
            meta_theme_color_dark: false,
            css_custom_properties: 0,
        };
        let issues = build_issues(
            &info,
            0,
            0,
            0,
            &[],
            &print_default(),
            &forced_default(),
            &vision_default(),
        );
        assert!(
            issues
                .iter()
                .all(|i| !matches!(i.kind, DarkModeIssueKind::NoDarkModeSupport)),
            "class-based dark mode should not be reported as NoDarkModeSupport"
        );
        assert!(
            issues
                .iter()
                .any(|i| matches!(i.kind, DarkModeIssueKind::ClassBasedDarkModeDetected)),
            "class-based dark mode should report ClassBasedDarkModeDetected"
        );
    }

    #[test]
    fn issues_missing_print_stylesheet_are_reported() {
        let issues = build_issues(
            &make_info(true, true, true, false, 5),
            0,
            0,
            0,
            &[],
            &PrintStylesheetAnalysis::default(),
            &ForcedColorsAnalysis {
                stylesheet_detected: true,
                focus_indicators_visible: true,
                ..Default::default()
            },
            &vision_default(),
        );

        assert!(issues
            .iter()
            .any(|i| matches!(i.kind, DarkModeIssueKind::NoPrintStylesheet)));
    }

    #[test]
    fn issues_forced_colors_focus_risk_are_reported() {
        let issues = build_issues(
            &make_info(true, true, true, false, 5),
            0,
            0,
            0,
            &[],
            &PrintStylesheetAnalysis {
                stylesheet_detected: true,
                content_not_clipped: true,
                interactive_chrome_hidden: true,
                ..Default::default()
            },
            &ForcedColorsAnalysis {
                stylesheet_detected: true,
                focus_indicators_visible: false,
                ..Default::default()
            },
            &vision_default(),
        );

        assert!(issues
            .iter()
            .any(|i| matches!(i.kind, DarkModeIssueKind::ForcedColorsFocusRisk)));
    }

    #[test]
    fn issues_vision_deficiency_new_contrast_are_reported() {
        let issues = build_issues(
            &make_info(true, true, true, false, 5),
            0,
            0,
            0,
            &[],
            &PrintStylesheetAnalysis {
                stylesheet_detected: true,
                content_not_clipped: true,
                interactive_chrome_hidden: true,
                ..Default::default()
            },
            &ForcedColorsAnalysis {
                stylesheet_detected: true,
                focus_indicators_visible: true,
                ..Default::default()
            },
            &VisionDeficiencyAnalysis {
                emulation_supported: true,
                modes: vec![VisionDeficiencyModeAnalysis {
                    mode: "protanopia".to_string(),
                    contrast_violations: 2,
                    new_contrast_violations: 2,
                    use_of_color_violations: 0,
                    new_contrast_selectors: vec![".danger".to_string()],
                }],
            },
        );

        assert!(issues.iter().any(|i| matches!(
            i.kind,
            DarkModeIssueKind::ColorVisionDeficiencyContrastFailure { .. }
        )));
    }

    #[test]
    fn english_issue_text_carries_no_german_umlauts() {
        // Guard against German leaking into EN reports (#406): exercise every
        // DarkModeIssueKind with en=true and assert no German umlauts/ß appear.
        let selectors = vec!["h1.hero".to_string(), "p.caption".to_string()];
        let kinds = vec![
            DarkModeIssueKind::NoDarkModeSupport,
            DarkModeIssueKind::NoColorSchemeDeclaration,
            DarkModeIssueKind::NoMetaColorScheme,
            DarkModeIssueKind::ClassBasedDarkModeDetected,
            DarkModeIssueKind::FewColorCustomProperties,
            DarkModeIssueKind::NoPrintStylesheet,
            DarkModeIssueKind::PrintLayoutRisk {
                chrome_hidden: false,
                clipped_elements: 3,
            },
            DarkModeIssueKind::NoForcedColorsSupport,
            DarkModeIssueKind::ForcedColorsFocusRisk,
            DarkModeIssueKind::ColorVisionDeficiencyContrastFailure {
                affected_modes: vec![("protanopia".to_string(), 2)],
            },
            DarkModeIssueKind::DarkOnlyContrastRegression { count: 1 },
            DarkModeIssueKind::DarkOnlyContrastRegression { count: 3 },
            DarkModeIssueKind::BothModesContrastFailure { count: 1 },
            DarkModeIssueKind::BothModesContrastFailure { count: 3 },
            DarkModeIssueKind::LightOnlyContrastImproved { count: 1 },
            DarkModeIssueKind::LightOnlyContrastImproved { count: 3 },
        ];

        for kind in &kinds {
            let text = dark_mode_issue_text(kind, &selectors, true);
            assert!(
                !text.chars().any(|c| "äöüÄÖÜß".contains(c)),
                "EN dark-mode issue text contains German umlaut ({kind:?}): {text}"
            );
        }
    }
}