html_generator/
accessibility.rs

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
//! Accessibility-related functionality for HTML processing.
//!
//! This module provides comprehensive tools for improving HTML accessibility through:
//! - Automated ARIA attribute management
//! - WCAG 2.1 compliance validation
//! - Accessibility issue detection and correction
//!
//! # WCAG Compliance
//!
//! This module implements checks for WCAG 2.1 compliance across three levels:
//! - Level A (minimum level of conformance)
//! - Level AA (addresses major accessibility barriers)
//! - Level AAA (highest level of accessibility conformance)
//!
//! For detailed information about WCAG guidelines, see:
//! <https://www.w3.org/WAI/WCAG21/quickref/>
//!
//! # Limitations
//!
//! While this module provides automated checks, some accessibility aspects require
//! manual review, including:
//! - Semantic correctness of ARIA labels
//! - Meaningful alternative text for images
//! - Logical heading structure
//! - Color contrast ratios
//!
//! # Examples
//!
//! ```rust
//! use html_generator::accessibility::{add_aria_attributes, validate_wcag, WcagLevel};
//!
//! use html_generator::accessibility::AccessibilityConfig;
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let html = r#"<button>Click me</button>"#;
//!
//!     // Add ARIA attributes automatically
//!     let enhanced_html = add_aria_attributes(html, None)?;
//!
//!     // Validate against WCAG AA level
//!     let config = AccessibilityConfig::default();
//!     validate_wcag(&enhanced_html, &config, None)?;
//!
//!     Ok(())
//! }
//! ```

use crate::accessibility::utils::get_missing_required_aria_properties;
use crate::accessibility::utils::is_valid_aria_role;
use crate::accessibility::utils::is_valid_language_code;
use once_cell::sync::Lazy;
use regex::Regex;
use scraper::{Html, Selector};
use std::collections::HashSet;
use std::sync::atomic::{AtomicUsize, Ordering};
use thiserror::Error;

/// Constants used throughout the accessibility module
pub mod constants {
    /// Maximum size of HTML input in bytes (1MB)
    pub const MAX_HTML_SIZE: usize = 1_000_000;

    /// Default ARIA role for navigation elements
    pub const DEFAULT_NAV_ROLE: &str = "navigation";

    /// Default ARIA role for buttons
    pub const DEFAULT_BUTTON_ROLE: &str = "button";

    /// Default ARIA role for forms
    pub const DEFAULT_FORM_ROLE: &str = "form";

    /// Default ARIA role for inputs
    pub const DEFAULT_INPUT_ROLE: &str = "textbox";
}

/// Global counter for unique ID generation
static COUNTER: AtomicUsize = AtomicUsize::new(0);

use constants::{
    DEFAULT_BUTTON_ROLE, DEFAULT_INPUT_ROLE, DEFAULT_NAV_ROLE,
    MAX_HTML_SIZE,
};

/// WCAG Conformance Levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WcagLevel {
    /// Level A: Minimum level of conformance
    /// Essential accessibility features that must be supported
    A,

    /// Level AA: Addresses major accessibility barriers
    /// Standard level of conformance for most websites
    AA,

    /// Level AAA: Highest level of accessibility conformance
    /// Includes additional enhancements and specialized features
    AAA,
}

/// Types of accessibility issues that can be detected
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueType {
    /// Missing alternative text for images
    MissingAltText,
    /// Improper heading structure
    HeadingStructure,
    /// Missing form labels
    MissingLabels,
    /// Invalid ARIA attributes
    InvalidAria,
    /// Color contrast issues
    ColorContrast,
    /// Keyboard navigation issues
    KeyboardNavigation,
    /// Missing or invalid language declarations
    LanguageDeclaration,
}

/// Enum to represent possible accessibility-related errors.
#[derive(Debug, Error)]
pub enum Error {
    /// Error indicating an invalid ARIA attribute.
    #[error("Invalid ARIA Attribute '{attribute}': {message}")]
    InvalidAriaAttribute {
        /// The name of the invalid attribute
        attribute: String,
        /// Description of the error
        message: String,
    },

    /// Error indicating failure to validate HTML against WCAG guidelines.
    #[error("WCAG {level} Validation Error: {message}")]
    WcagValidationError {
        /// WCAG conformance level where the error occurred
        level: WcagLevel,
        /// Description of the error
        message: String,
        /// Specific WCAG guideline reference
        guideline: Option<String>,
    },

    /// Error indicating the HTML input is too large to process.
    #[error(
        "HTML Input Too Large: size {size} exceeds maximum {max_size}"
    )]
    HtmlTooLarge {
        /// Actual size of the input
        size: usize,
        /// Maximum allowed size
        max_size: usize,
    },

    /// Error indicating a failure in processing HTML for accessibility.
    #[error("HTML Processing Error: {message}")]
    HtmlProcessingError {
        /// Description of the processing error
        message: String,
        /// Source of the error, if available
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Error indicating malformed HTML input.
    #[error("Malformed HTML: {message}")]
    MalformedHtml {
        /// Description of the HTML issue
        message: String,
        /// The problematic HTML fragment, if available
        fragment: Option<String>,
    },
}

/// Result type alias for accessibility operations.
pub type Result<T> = std::result::Result<T, Error>;

/// Structure representing an accessibility issue found in the HTML
#[derive(Debug, Clone)]
pub struct Issue {
    /// Type of accessibility issue
    pub issue_type: IssueType,
    /// Description of the issue
    pub message: String,
    /// WCAG guideline reference, if applicable
    pub guideline: Option<String>,
    /// HTML element where the issue was found
    pub element: Option<String>,
    /// Suggested fix for the issue
    pub suggestion: Option<String>,
}

/// Helper function to create a `Selector`, returning an `Option` on failure.
fn try_create_selector(selector: &str) -> Option<Selector> {
    match Selector::parse(selector) {
        Ok(s) => Some(s),
        Err(e) => {
            eprintln!(
                "Failed to create selector '{}': {}",
                selector, e
            );
            None
        }
    }
}

/// Helper function to create a `Regex`, returning an `Option` on failure.
fn try_create_regex(pattern: &str) -> Option<Regex> {
    match Regex::new(pattern) {
        Ok(r) => Some(r),
        Err(e) => {
            eprintln!("Failed to create regex '{}': {}", pattern, e);
            None
        }
    }
}

/// Static selectors for HTML elements and ARIA attributes
static BUTTON_SELECTOR: Lazy<Option<Selector>> =
    Lazy::new(|| try_create_selector("button:not([aria-label])"));

/// Selector for navigation elements without ARIA attributes
static NAV_SELECTOR: Lazy<Option<Selector>> =
    Lazy::new(|| try_create_selector("nav:not([aria-label])"));

/// Selector for form elements without ARIA attributes
static FORM_SELECTOR: Lazy<Option<Selector>> =
    Lazy::new(|| try_create_selector("form:not([aria-labelledby])"));

/// Regex for finding input elements
static INPUT_REGEX: Lazy<Option<Regex>> =
    Lazy::new(|| try_create_regex(r"<input[^>]*>"));

/// Comprehensive selector for all ARIA attributes
static ARIA_SELECTOR: Lazy<Option<Selector>> = Lazy::new(|| {
    try_create_selector(concat!(
        "[aria-label], [aria-labelledby], [aria-describedby], ",
        "[aria-hidden], [aria-expanded], [aria-haspopup], ",
        "[aria-controls], [aria-pressed], [aria-checked], ",
        "[aria-current], [aria-disabled], [aria-dropeffect], ",
        "[aria-grabbed], [aria-invalid], [aria-live], ",
        "[aria-owns], [aria-relevant], [aria-required], ",
        "[aria-role], [aria-selected], [aria-valuemax], ",
        "[aria-valuemin], [aria-valuenow], [aria-valuetext]"
    ))
});

/// Set of valid ARIA attributes
static VALID_ARIA_ATTRIBUTES: Lazy<HashSet<&'static str>> =
    Lazy::new(|| {
        [
            "aria-label",
            "aria-labelledby",
            "aria-describedby",
            "aria-hidden",
            "aria-expanded",
            "aria-haspopup",
            "aria-controls",
            "aria-pressed",
            "aria-checked",
            "aria-current",
            "aria-disabled",
            "aria-dropeffect",
            "aria-grabbed",
            "aria-invalid",
            "aria-live",
            "aria-owns",
            "aria-relevant",
            "aria-required",
            "aria-role",
            "aria-selected",
            "aria-valuemax",
            "aria-valuemin",
            "aria-valuenow",
            "aria-valuetext",
        ]
        .iter()
        .copied()
        .collect()
    });

/// Color contrast requirements for different WCAG levels
// static COLOR_CONTRAST_RATIOS: Lazy<HashMap<WcagLevel, f64>> = Lazy::new(|| {
//     let mut m = HashMap::new();
//     m.insert(WcagLevel::A, 3.0);       // Minimum contrast for Level A
//     m.insert(WcagLevel::AA, 4.5);      // Enhanced contrast for Level AA
//     m.insert(WcagLevel::AAA, 7.0);     // Highest contrast for Level AAA
//     m
// });
///
/// Set of elements that must have labels
// static LABELABLE_ELEMENTS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
//     [
//         "input", "select", "textarea", "button", "meter",
//         "output", "progress", "canvas"
//     ].iter().copied().collect()
// });
///
/// Selector for finding headings
// static HEADING_SELECTOR: Lazy<Selector> = Lazy::new(|| {
//     Selector::parse("h1, h2, h3, h4, h5, h6")
//         .expect("Failed to create heading selector")
// });
///
/// Selector for finding images
// static IMAGE_SELECTOR: Lazy<Selector> = Lazy::new(|| {
//     Selector::parse("img").expect("Failed to create image selector")
// });
/// Configuration for accessibility validation
#[derive(Debug, Copy, Clone)]
pub struct AccessibilityConfig {
    /// WCAG conformance level to validate against
    pub wcag_level: WcagLevel,
    /// Maximum allowed heading level jump (e.g., 1 means no skipping levels)
    pub max_heading_jump: u8,
    /// Minimum required color contrast ratio
    pub min_contrast_ratio: f64,
    /// Whether to automatically fix issues when possible
    pub auto_fix: bool,
}

impl Default for AccessibilityConfig {
    fn default() -> Self {
        Self {
            wcag_level: WcagLevel::AA,
            max_heading_jump: 1,
            min_contrast_ratio: 4.5, // WCAG AA standard
            auto_fix: true,
        }
    }
}

/// A comprehensive accessibility check result
#[derive(Debug)]
pub struct AccessibilityReport {
    /// List of accessibility issues found
    pub issues: Vec<Issue>,
    /// WCAG conformance level checked
    pub wcag_level: WcagLevel,
    /// Total number of elements checked
    pub elements_checked: usize,
    /// Number of issues found
    pub issue_count: usize,
    /// Time taken for the check (in milliseconds)
    pub check_duration_ms: u64,
}

/// Add ARIA attributes to HTML for improved accessibility.
///
/// This function performs a comprehensive analysis of the HTML content and adds
/// appropriate ARIA attributes to improve accessibility. It handles:
/// - Button labeling
/// - Navigation landmarks
/// - Form controls
/// - Input elements
/// - Dynamic content
///
/// # Arguments
///
/// * `html` - A string slice representing the HTML content
/// * `config` - Optional configuration for the enhancement process
///
/// # Returns
///
/// * `Result<String>` - The modified HTML with ARIA attributes included
///
/// # Errors
///
/// Returns an error if:
/// * The input HTML is larger than `MAX_HTML_SIZE`
/// * The HTML cannot be parsed
/// * There's an error adding ARIA attributes
///
/// # Examples
///
/// ```rust
/// use html_generator::accessibility::{add_aria_attributes, AccessibilityConfig};
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let html = r#"<button>Click me</button>"#;
///     let result = add_aria_attributes(html, None)?;
///     assert!(result.contains(r#"aria-label="Click me""#));
///
///     Ok(())
/// }
/// ```
pub fn add_aria_attributes(
    html: &str,
    config: Option<AccessibilityConfig>,
) -> Result<String> {
    let config = config.unwrap_or_default();

    if html.len() > MAX_HTML_SIZE {
        return Err(Error::HtmlTooLarge {
            size: html.len(),
            max_size: MAX_HTML_SIZE,
        });
    }

    let mut html_builder = HtmlBuilder::new(html);

    // Apply transformations
    html_builder = add_aria_to_buttons(html_builder)?;
    html_builder = add_aria_to_navs(html_builder)?;
    html_builder = add_aria_to_forms(html_builder)?;
    html_builder = add_aria_to_inputs(html_builder)?;

    // Additional transformations for stricter WCAG levels
    if matches!(config.wcag_level, WcagLevel::AA | WcagLevel::AAA) {
        html_builder = enhance_landmarks(html_builder)?;
        html_builder = add_live_regions(html_builder)?;
    }

    if matches!(config.wcag_level, WcagLevel::AAA) {
        html_builder = enhance_descriptions(html_builder)?;
    }

    // Validate and clean up
    let new_html =
        remove_invalid_aria_attributes(&html_builder.build());

    if !validate_aria(&new_html) {
        return Err(Error::InvalidAriaAttribute {
            attribute: "multiple".to_string(),
            message: "Failed to add valid ARIA attributes".to_string(),
        });
    }

    Ok(new_html)
}

/// A builder struct for constructing HTML content.
#[derive(Debug, Clone)]
struct HtmlBuilder {
    content: String,
}

impl HtmlBuilder {
    /// Creates a new `HtmlBuilder` with the given initial content.
    fn new(initial_content: &str) -> Self {
        HtmlBuilder {
            content: initial_content.to_string(),
        }
    }

    /// Builds the final HTML content.
    fn build(self) -> String {
        self.content
    }
}

/// Helper function to count total elements checked during validation
fn count_checked_elements(document: &Html) -> usize {
    document.select(&Selector::parse("*").unwrap()).count()
}

/// Add landmark regions to improve navigation
const fn enhance_landmarks(
    html_builder: HtmlBuilder,
) -> Result<HtmlBuilder> {
    // Implementation for adding landmarks
    Ok(html_builder)
}

/// Add live regions for dynamic content
const fn add_live_regions(
    html_builder: HtmlBuilder,
) -> Result<HtmlBuilder> {
    // Implementation for adding live regions
    Ok(html_builder)
}

/// Enhance element descriptions for better accessibility
const fn enhance_descriptions(
    html_builder: HtmlBuilder,
) -> Result<HtmlBuilder> {
    // Implementation for enhancing descriptions
    Ok(html_builder)
}

/// Check heading structure
fn check_heading_structure(document: &Html, issues: &mut Vec<Issue>) {
    let mut prev_level: Option<u8> = None;

    let selector = match Selector::parse("h1, h2, h3, h4, h5, h6") {
        Ok(selector) => selector,
        Err(e) => {
            eprintln!("Failed to parse selector: {}", e);
            return; // Skip checking if the selector is invalid
        }
    };

    for heading in document.select(&selector) {
        let current_level = heading
            .value()
            .name()
            .chars()
            .nth(1)
            .and_then(|c| c.to_digit(10))
            .and_then(|n| u8::try_from(n).ok());

        if let Some(current_level) = current_level {
            if let Some(prev_level) = prev_level {
                if current_level > prev_level + 1 {
                    issues.push(Issue {
                        issue_type: IssueType::HeadingStructure,
                        message: format!(
                            "Skipped heading level from h{} to h{}",
                            prev_level, current_level
                        ),
                        guideline: Some("WCAG 2.4.6".to_string()),
                        element: Some(heading.html()),
                        suggestion: Some(
                            "Use sequential heading levels".to_string(),
                        ),
                    });
                }
            }
            prev_level = Some(current_level);
        }
    }
}

/// Validate HTML against WCAG guidelines with detailed reporting.
///
/// Performs a comprehensive accessibility check based on WCAG guidelines and
/// provides detailed feedback about any issues found.
///
/// # Arguments
///
/// * `html` - The HTML content to validate
/// * `config` - Configuration options for the validation
///
/// # Returns
///
/// * `Result<AccessibilityReport>` - A detailed report of the accessibility check
///
/// # Examples
///
/// ```rust
/// use html_generator::accessibility::{validate_wcag, AccessibilityConfig, WcagLevel};
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let html = r#"<img src="test.jpg" alt="A descriptive alt text">"#;
///     let config = AccessibilityConfig::default();
///
///     let report = validate_wcag(html, &config, None)?;
///     println!("Found {} issues", report.issue_count);
///
///     Ok(())
/// }
/// ```
pub fn validate_wcag(
    html: &str,
    config: &AccessibilityConfig,
    disable_checks: Option<&[IssueType]>,
) -> Result<AccessibilityReport> {
    let start_time = std::time::Instant::now();
    let mut issues = Vec::new();
    let mut elements_checked = 0;

    if html.trim().is_empty() {
        return Ok(AccessibilityReport {
            issues: Vec::new(),
            wcag_level: config.wcag_level,
            elements_checked: 0,
            issue_count: 0,
            check_duration_ms: 0,
        });
    }

    let document = Html::parse_document(html);

    if disable_checks
        .map_or(true, |d| !d.contains(&IssueType::LanguageDeclaration))
    {
        check_language_attributes(&document, &mut issues)?; // Returns Result<()>, so `?` works.
    }

    // This function returns `()`, so no `?`.
    check_heading_structure(&document, &mut issues);

    elements_checked += count_checked_elements(&document);

    // Explicit error conversion for u64::try_from
    let check_duration_ms = u64::try_from(
        start_time.elapsed().as_millis(),
    )
    .map_err(|err| Error::HtmlProcessingError {
        message: "Failed to convert duration to milliseconds"
            .to_string(),
        source: Some(Box::new(err)),
    })?;

    Ok(AccessibilityReport {
        issues: issues.clone(),
        wcag_level: config.wcag_level,
        elements_checked,
        issue_count: issues.len(),
        check_duration_ms,
    })
}

/// From implementation for TryFromIntError
impl From<std::num::TryFromIntError> for Error {
    fn from(err: std::num::TryFromIntError) -> Self {
        Error::HtmlProcessingError {
            message: "Integer conversion error".to_string(),
            source: Some(Box::new(err)),
        }
    }
}

/// Display implementation for WCAG levels
impl std::fmt::Display for WcagLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WcagLevel::A => write!(f, "A"),
            WcagLevel::AA => write!(f, "AA"),
            WcagLevel::AAA => write!(f, "AAA"),
        }
    }
}

/// Internal helper functions for accessibility checks
impl AccessibilityReport {
    /// Creates a new accessibility issue
    fn add_issue(
        issues: &mut Vec<Issue>,
        issue_type: IssueType,
        message: impl Into<String>,
        guideline: Option<String>,
        element: Option<String>,
        suggestion: Option<String>,
    ) {
        issues.push(Issue {
            issue_type,
            message: message.into(),
            guideline,
            element,
            suggestion,
        });
    }
}

/// Add ARIA attributes to button elements.
fn add_aria_to_buttons(
    mut html_builder: HtmlBuilder,
) -> Result<HtmlBuilder> {
    let document = Html::parse_document(&html_builder.content);

    // Safely unwrap the BUTTON_SELECTOR
    if let Some(selector) = BUTTON_SELECTOR.as_ref() {
        for button in document.select(selector) {
            // Check if the button has no aria-label
            if button.value().attr("aria-label").is_none() {
                let button_html = button.html();
                let inner_content = button.inner_html();

                // Generate a new button with appropriate aria-label
                let new_button_html = if inner_content.trim().is_empty()
                {
                    format!(
                        r#"<button aria-label="{}" role="button">{}</button>"#,
                        DEFAULT_BUTTON_ROLE, inner_content
                    )
                } else {
                    format!(
                        r#"<button aria-label="{}" role="button">{}</button>"#,
                        inner_content.trim(),
                        inner_content
                    )
                };

                // Replace the old button HTML with the new one
                html_builder.content = html_builder
                    .content
                    .replace(&button_html, &new_button_html);
            }
        }
    }

    Ok(html_builder)
}

/// Add ARIA attributes to navigation elements.
fn add_aria_to_navs(
    mut html_builder: HtmlBuilder,
) -> Result<HtmlBuilder> {
    let document = Html::parse_document(&html_builder.content);

    if let Some(selector) = NAV_SELECTOR.as_ref() {
        for nav in document.select(selector) {
            let nav_html = nav.html();
            let new_nav_html = nav_html.replace(
                "<nav",
                &format!(
                    r#"<nav aria-label="{}" role="navigation""#,
                    DEFAULT_NAV_ROLE
                ),
            );
            html_builder.content =
                html_builder.content.replace(&nav_html, &new_nav_html);
        }
    }

    Ok(html_builder)
}

/// Add ARIA attributes to form elements.
fn add_aria_to_forms(
    mut html_builder: HtmlBuilder,
) -> Result<HtmlBuilder> {
    let document = Html::parse_document(&html_builder.content);

    if let Some(selector) = FORM_SELECTOR.as_ref() {
        for form in document.select(selector) {
            let form_html = form.html();
            let form_id = format!("form-{}", generate_unique_id());
            let new_form_html = form_html.replace(
                "<form",
                &format!(
                    r#"<form id="{}" aria-labelledby="{}" role="form""#,
                    form_id, form_id
                ),
            );
            html_builder.content = html_builder
                .content
                .replace(&form_html, &new_form_html);
        }
    }

    Ok(html_builder)
}

/// Add ARIA attributes to input elements.
fn add_aria_to_inputs(
    mut html_builder: HtmlBuilder,
) -> Result<HtmlBuilder> {
    if let Some(regex) = INPUT_REGEX.as_ref() {
        let mut replacements: Vec<(String, String)> = Vec::new();

        for cap in regex.captures_iter(&html_builder.content) {
            let input_tag = &cap[0];
            if !input_tag.contains("aria-label") {
                let input_type = extract_input_type(input_tag)
                    .unwrap_or_else(|| "text".to_string());
                let new_input_tag = format!(
                    r#"<input aria-label="{}" role="{}" type="{}""#,
                    input_type, DEFAULT_INPUT_ROLE, input_type
                );
                replacements
                    .push((input_tag.to_string(), new_input_tag));
            }
        }

        for (old, new) in replacements {
            html_builder.content =
                html_builder.content.replace(&old, &new);
        }
    }

    Ok(html_builder)
}

/// Extract input type from an input tag.
fn extract_input_type(input_tag: &str) -> Option<String> {
    static TYPE_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r#"type=["']([^"']+)["']"#)
            .expect("Failed to create type regex")
    });

    TYPE_REGEX
        .captures(input_tag)
        .and_then(|cap| cap.get(1))
        .map(|m| m.as_str().to_string())
}

/// Generate a unique ID for form elements.
fn generate_unique_id() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .subsec_nanos();
    let count = COUNTER.fetch_add(1, Ordering::SeqCst);
    format!("aria-{}-{}", nanos, count)
}

/// Validate ARIA attributes within the HTML.
fn validate_aria(html: &str) -> bool {
    let document = Html::parse_document(html);

    if let Some(selector) = ARIA_SELECTOR.as_ref() {
        document
            .select(selector)
            .flat_map(|el| el.value().attrs())
            .filter(|(name, _)| name.starts_with("aria-"))
            .all(|(name, value)| is_valid_aria_attribute(name, value))
    } else {
        eprintln!("ARIA_SELECTOR failed to initialize.");
        false
    }
}

fn remove_invalid_aria_attributes(html: &str) -> String {
    let document = Html::parse_document(html);
    let mut new_html = html.to_string();

    if let Some(selector) = ARIA_SELECTOR.as_ref() {
        for element in document.select(selector) {
            let element_html = element.html();
            let mut updated_html = element_html.clone();

            for (attr_name, attr_value) in element.value().attrs() {
                if attr_name.starts_with("aria-")
                    && !is_valid_aria_attribute(attr_name, attr_value)
                {
                    updated_html = updated_html.replace(
                        &format!(r#" {}="{}""#, attr_name, attr_value),
                        "",
                    );
                }
            }

            new_html = new_html.replace(&element_html, &updated_html);
        }
    }

    new_html
}

/// Check if an ARIA attribute is valid.
fn is_valid_aria_attribute(name: &str, value: &str) -> bool {
    if !VALID_ARIA_ATTRIBUTES.contains(name) {
        return false; // Invalid ARIA attribute name
    }

    match name {
        "aria-hidden" | "aria-expanded" | "aria-pressed"
        | "aria-invalid" => {
            matches!(value, "true" | "false") // Only "true" or "false" are valid
        }
        "aria-level" => value.parse::<u32>().is_ok(), // Must be a valid integer
        _ => !value.trim().is_empty(), // General check for non-empty values
    }
}

fn check_language_attributes(
    document: &Html,
    issues: &mut Vec<Issue>,
) -> Result<()> {
    if let Some(html_element) =
        document.select(&Selector::parse("html").unwrap()).next()
    {
        if html_element.value().attr("lang").is_none() {
            AccessibilityReport::add_issue(
                issues,
                IssueType::LanguageDeclaration,
                "Missing language declaration on HTML element",
                Some("WCAG 3.1.1".to_string()),
                Some("<html>".to_string()),
                Some("Add lang attribute to HTML element".to_string()),
            );
        }
    }

    for element in document.select(&Selector::parse("[lang]").unwrap())
    {
        if let Some(lang) = element.value().attr("lang") {
            if !is_valid_language_code(lang) {
                AccessibilityReport::add_issue(
                    issues,
                    IssueType::LanguageDeclaration,
                    format!("Invalid language code: {}", lang),
                    Some("WCAG 3.1.2".to_string()),
                    Some(element.html()),
                    Some("Use valid BCP 47 language code".to_string()),
                );
            }
        }
    }
    Ok(())
}

/// Helper functions for WCAG validation
impl AccessibilityReport {
    /// Check keyboard navigation
    pub fn check_keyboard_navigation(
        document: &Html,
        issues: &mut Vec<Issue>,
    ) -> Result<()> {
        let binding = Selector::parse(
            "a, button, input, select, textarea, [tabindex]",
        )
        .unwrap();
        let interactive_elements = document.select(&binding);

        for element in interactive_elements {
            // Check tabindex
            if let Some(tabindex) = element.value().attr("tabindex") {
                if let Ok(index) = tabindex.parse::<i32>() {
                    if index < 0 {
                        issues.push(Issue {
                        issue_type: IssueType::KeyboardNavigation,
                        message: "Negative tabindex prevents keyboard focus".to_string(),
                        guideline: Some("WCAG 2.1.1".to_string()),
                        element: Some(element.html()),
                        suggestion: Some("Remove negative tabindex value".to_string()),
                    });
                    }
                }
            }

            // Check for click handlers without keyboard equivalents
            if element.value().attr("onclick").is_some()
                && element.value().attr("onkeypress").is_none()
                && element.value().attr("onkeydown").is_none()
            {
                issues.push(Issue {
                    issue_type: IssueType::KeyboardNavigation,
                    message:
                        "Click handler without keyboard equivalent"
                            .to_string(),
                    guideline: Some("WCAG 2.1.1".to_string()),
                    element: Some(element.html()),
                    suggestion: Some(
                        "Add keyboard event handlers".to_string(),
                    ),
                });
            }
        }
        Ok(())
    }

    /// Check language attributes
    pub fn check_language_attributes(
        document: &Html,
        issues: &mut Vec<Issue>,
    ) -> Result<()> {
        // Check html lang attribute
        let html_element =
            document.select(&Selector::parse("html").unwrap()).next();
        if let Some(element) = html_element {
            if element.value().attr("lang").is_none() {
                Self::add_issue(
                    issues,
                    IssueType::LanguageDeclaration,
                    "Missing language declaration",
                    Some("WCAG 3.1.1".to_string()),
                    Some(element.html()),
                    Some(
                        "Add lang attribute to html element"
                            .to_string(),
                    ),
                );
            }
        }

        // Check for changes in language
        let binding = Selector::parse("[lang]").unwrap();
        let text_elements = document.select(&binding);
        for element in text_elements {
            if let Some(lang) = element.value().attr("lang") {
                if !is_valid_language_code(lang) {
                    Self::add_issue(
                        issues,
                        IssueType::LanguageDeclaration,
                        format!("Invalid language code: {}", lang),
                        Some("WCAG 3.1.2".to_string()),
                        Some(element.html()),
                        Some(
                            "Use valid BCP 47 language code"
                                .to_string(),
                        ),
                    );
                }
            }
        }
        Ok(())
    }

    /// Check advanced ARIA usage
    pub fn check_advanced_aria(
        document: &Html,
        issues: &mut Vec<Issue>,
    ) -> Result<()> {
        // Check for proper ARIA roles
        let binding = Selector::parse("[role]").unwrap();
        let elements_with_roles = document.select(&binding);
        for element in elements_with_roles {
            if let Some(role) = element.value().attr("role") {
                if !is_valid_aria_role(role, &element) {
                    Self::add_issue(
                        issues,
                        IssueType::InvalidAria,
                        format!(
                            "Invalid ARIA role '{}' for element",
                            role
                        ),
                        Some("WCAG 4.1.2".to_string()),
                        Some(element.html()),
                        Some("Use appropriate ARIA role".to_string()),
                    );
                }
            }
        }

        // Check for required ARIA properties
        let elements_with_aria =
            document.select(ARIA_SELECTOR.as_ref().unwrap());
        for element in elements_with_aria {
            if let Some(missing_props) =
                get_missing_required_aria_properties(&element)
            {
                Self::add_issue(
                    issues,
                    IssueType::InvalidAria,
                    format!(
                        "Missing required ARIA properties: {}",
                        missing_props.join(", ")
                    ),
                    Some("WCAG 4.1.2".to_string()),
                    Some(element.html()),
                    Some("Add required ARIA properties".to_string()),
                );
            }
        }
        Ok(())
    }
}

/// Utility functions for accessibility checks
pub mod utils {
    use scraper::ElementRef;
    use std::collections::HashMap;

    /// Validate language code against BCP 47
    use once_cell::sync::Lazy;
    use regex::Regex;

    /// Validate language code against simplified BCP 47 rules.
    pub(crate) fn is_valid_language_code(lang: &str) -> bool {
        static LANGUAGE_CODE_REGEX: Lazy<Regex> = Lazy::new(|| {
            // Match primary language and optional subtags
            Regex::new(r"(?i)^[a-z]{2,3}(-[a-z0-9]{2,8})*$").unwrap()
        });

        // Ensure the regex matches and the code does not end with a hyphen
        LANGUAGE_CODE_REGEX.is_match(lang) && !lang.ends_with('-')
    }

    /// Check if ARIA role is valid for element
    pub(crate) fn is_valid_aria_role(
        role: &str,
        element: &ElementRef,
    ) -> bool {
        static VALID_ROLES: Lazy<HashMap<&str, Vec<&str>>> =
            Lazy::new(|| {
                let mut map = HashMap::new();
                _ = map.insert(
                    "button",
                    vec!["button", "link", "menuitem"],
                );
                _ = map.insert(
                    "input",
                    vec!["textbox", "radio", "checkbox", "button"],
                );
                _ = map.insert(
                    "div",
                    vec!["alert", "tooltip", "dialog", "slider"],
                );
                _ = map.insert("a", vec!["link", "button", "menuitem"]);
                map
            });

        // Elements like <div>, <span>, and <a> are more permissive
        let tag_name = element.value().name();
        if ["div", "span", "a"].contains(&tag_name) {
            return true;
        }

        // Validate roles strictly for specific elements
        if let Some(valid_roles) = VALID_ROLES.get(tag_name) {
            valid_roles.contains(&role)
        } else {
            false
        }
    }

    /// Get missing required ARIA properties
    pub(crate) fn get_missing_required_aria_properties(
        element: &ElementRef,
    ) -> Option<Vec<String>> {
        let mut missing = Vec::new();

        static REQUIRED_ARIA_PROPS: Lazy<HashMap<&str, Vec<&str>>> =
            Lazy::new(|| {
                HashMap::from([
                    (
                        "slider",
                        vec![
                            "aria-valuenow",
                            "aria-valuemin",
                            "aria-valuemax",
                        ],
                    ),
                    ("combobox", vec!["aria-expanded"]),
                ])
            });

        if let Some(role) = element.value().attr("role") {
            if let Some(required_props) = REQUIRED_ARIA_PROPS.get(role)
            {
                for prop in required_props {
                    if element.value().attr(prop).is_none() {
                        missing.push(prop.to_string());
                    }
                }
            }
        }

        if missing.is_empty() {
            None
        } else {
            Some(missing)
        }
    }
}

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

    // Test WCAG Level functionality
    mod wcag_level_tests {
        use super::*;

        #[test]
        fn test_wcag_level_ordering() {
            assert!(matches!(WcagLevel::A, WcagLevel::A));
            assert!(matches!(WcagLevel::AA, WcagLevel::AA));
            assert!(matches!(WcagLevel::AAA, WcagLevel::AAA));
        }

        #[test]
        fn test_wcag_level_debug() {
            assert_eq!(format!("{:?}", WcagLevel::A), "A");
            assert_eq!(format!("{:?}", WcagLevel::AA), "AA");
            assert_eq!(format!("{:?}", WcagLevel::AAA), "AAA");
        }
    }

    // Test AccessibilityConfig functionality
    mod config_tests {
        use super::*;

        #[test]
        fn test_default_config() {
            let config = AccessibilityConfig::default();
            assert_eq!(config.wcag_level, WcagLevel::AA);
            assert_eq!(config.max_heading_jump, 1);
            assert_eq!(config.min_contrast_ratio, 4.5);
            assert!(config.auto_fix);
        }

        #[test]
        fn test_custom_config() {
            let config = AccessibilityConfig {
                wcag_level: WcagLevel::AAA,
                max_heading_jump: 2,
                min_contrast_ratio: 7.0,
                auto_fix: false,
            };
            assert_eq!(config.wcag_level, WcagLevel::AAA);
            assert_eq!(config.max_heading_jump, 2);
            assert_eq!(config.min_contrast_ratio, 7.0);
            assert!(!config.auto_fix);
        }
    }

    // Test ARIA attribute management
    mod aria_attribute_tests {
        use super::*;

        #[test]
        fn test_valid_aria_attributes() {
            assert!(is_valid_aria_attribute("aria-label", "Test"));
            assert!(is_valid_aria_attribute("aria-hidden", "true"));
            assert!(is_valid_aria_attribute("aria-hidden", "false"));
            assert!(!is_valid_aria_attribute("aria-hidden", "yes"));
            assert!(!is_valid_aria_attribute("invalid-aria", "value"));
        }

        #[test]
        fn test_empty_aria_value() {
            assert!(!is_valid_aria_attribute("aria-label", ""));
            assert!(!is_valid_aria_attribute("aria-label", "  "));
        }
    }

    // Test HTML modification functions
    mod html_modification_tests {
        use super::*;

        #[test]
        fn test_add_aria_to_button() {
            let html = "<button>Click me</button>";
            let result = add_aria_attributes(html, None);
            assert!(result.is_ok());
            let enhanced = result.unwrap();
            assert!(enhanced.contains(r#"aria-label="Click me""#));
            assert!(enhanced.contains(r#"role="button""#));
        }

        #[test]
        fn test_add_aria_to_empty_button() {
            let html = "<button></button>";
            let result = add_aria_attributes(html, None);
            assert!(result.is_ok());
            let enhanced = result.unwrap();
            assert!(enhanced.contains(r#"aria-label="button""#));
        }

        #[test]
        fn test_large_input() {
            let large_html = "a".repeat(MAX_HTML_SIZE + 1);
            let result = add_aria_attributes(&large_html, None);
            assert!(matches!(result, Err(Error::HtmlTooLarge { .. })));
        }
    }

    // Test accessibility validation
    mod validation_tests {
        use super::*;

        #[test]
        fn test_heading_structure() {
            let valid_html = "<h1>Main Title</h1><h2>Subtitle</h2>";
            let invalid_html =
                "<h1>Main Title</h1><h3>Skipped Heading</h3>";

            let config = AccessibilityConfig::default();

            // Validate correct heading structure
            let valid_result = validate_wcag(
                valid_html,
                &config,
                Some(&[IssueType::LanguageDeclaration]),
            )
            .unwrap();
            assert_eq!(
                valid_result.issue_count, 0,
                "Expected no issues for valid HTML, but found: {:#?}",
                valid_result.issues
            );

            // Validate incorrect heading structure
            let invalid_result = validate_wcag(
                invalid_html,
                &config,
                Some(&[IssueType::LanguageDeclaration]),
            )
            .unwrap();
            assert_eq!(
        invalid_result.issue_count,
        1,
        "Expected one issue for skipped heading levels, but found: {:#?}",
        invalid_result.issues
    );

            let issue = &invalid_result.issues[0];
            assert_eq!(issue.issue_type, IssueType::HeadingStructure);
            assert_eq!(
                issue.message,
                "Skipped heading level from h1 to h3"
            );
            assert_eq!(issue.guideline, Some("WCAG 2.4.6".to_string()));
            assert_eq!(
                issue.suggestion,
                Some("Use sequential heading levels".to_string())
            );
        }
    }

    // Test report generation
    mod report_tests {
        use super::*;

        #[test]
        fn test_report_generation() {
            let html = r#"<img src="test.jpg">"#;
            let config = AccessibilityConfig::default();
            let report = validate_wcag(html, &config, None).unwrap();

            assert!(report.issue_count > 0);

            assert_eq!(report.wcag_level, WcagLevel::AA);
        }

        #[test]
        fn test_empty_html_report() {
            let html = "";
            let config = AccessibilityConfig::default();
            let report = validate_wcag(html, &config, None).unwrap();

            assert_eq!(report.elements_checked, 0);
            assert_eq!(report.issue_count, 0);
        }

        #[test]
        fn test_missing_selector_handling() {
            // Simulate a scenario where NAV_SELECTOR fails to initialize.
            static TEST_NAV_SELECTOR: Lazy<Option<Selector>> =
                Lazy::new(|| None);

            let html = "<nav>Main Navigation</nav>";
            let document = Html::parse_document(html);

            if let Some(selector) = TEST_NAV_SELECTOR.as_ref() {
                let navs: Vec<_> = document.select(selector).collect();
                assert_eq!(navs.len(), 0);
            }
        }

        #[test]
        fn test_html_processing_error_with_source() {
            let source_error = std::io::Error::new(
                std::io::ErrorKind::Other,
                "test source error",
            );
            let error = Error::HtmlProcessingError {
                message: "Processing failed".to_string(),
                source: Some(Box::new(source_error)),
            };

            assert_eq!(
                format!("{}", error),
                "HTML Processing Error: Processing failed"
            );
        }
    }
    #[cfg(test)]
    mod utils_tests {
        use super::*;

        mod language_code_validation {
            use super::*;

            #[test]
            fn test_valid_language_codes() {
                let valid_codes = [
                    "en", "en-US", "zh-CN", "fr-FR", "de-DE", "es-419",
                    "ar-001", "pt-BR", "ja-JP", "ko-KR",
                ];
                for code in valid_codes {
                    assert!(
                        is_valid_language_code(code),
                        "Language code '{}' should be valid",
                        code
                    );
                }
            }

            #[test]
            fn test_invalid_language_codes() {
                let invalid_codes = [
                    "",               // Empty string
                    "a",              // Single character
                    "123",            // Numeric code
                    "en_US",          // Underscore instead of hyphen
                    "en-",            // Trailing hyphen
                    "-en",            // Leading hyphen
                    "en--US",         // Consecutive hyphens
                    "toolong",        // Primary subtag too long
                    "en-US-INVALID-", // Trailing hyphen with subtags
                ];
                for code in invalid_codes {
                    assert!(
                        !is_valid_language_code(code),
                        "Language code '{}' should be invalid",
                        code
                    );
                }
            }

            #[test]
            fn test_language_code_case_sensitivity() {
                assert!(is_valid_language_code("en-GB"));
                assert!(is_valid_language_code("fr-FR"));
                assert!(is_valid_language_code("zh-Hans"));
                assert!(is_valid_language_code("EN-GB"));
            }
        }

        mod aria_role_validation {
            use super::*;

            #[test]
            fn test_valid_button_roles() {
                let html = "<button>Test</button>";
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("button").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();
                let valid_roles = ["button", "link", "menuitem"];
                for role in valid_roles {
                    assert!(
                        is_valid_aria_role(role, &element),
                        "Role '{}' should be valid for button",
                        role
                    );
                }
            }

            #[test]
            fn test_valid_input_roles() {
                let html = "<input type='text'>";
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("input").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();
                let valid_roles =
                    ["textbox", "radio", "checkbox", "button"];
                for role in valid_roles {
                    assert!(
                        is_valid_aria_role(role, &element),
                        "Role '{}' should be valid for input",
                        role
                    );
                }
            }

            #[test]
            fn test_valid_anchor_roles() {
                let html = "<a href=\"\\#\">Test</a>";
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("a").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();

                let valid_roles = ["button", "link", "menuitem"];
                for role in valid_roles {
                    assert!(
                        is_valid_aria_role(role, &element),
                        "Role '{}' should be valid for anchor",
                        role
                    );
                }
            }

            #[test]
            fn test_invalid_element_roles() {
                let html = "<button>Test</button>";
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("button").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();
                let invalid_roles =
                    ["textbox", "radio", "checkbox", "invalid"];
                for role in invalid_roles {
                    assert!(
                        !is_valid_aria_role(role, &element),
                        "Role '{}' should be invalid for button",
                        role
                    );
                }
            }

            #[test]
            fn test_unrestricted_elements() {
                // Testing with <div>
                let html_div = "<div>Test</div>";
                let fragment_div = Html::parse_fragment(html_div);
                let selector_div = Selector::parse("div").unwrap();
                let element_div =
                    fragment_div.select(&selector_div).next().unwrap();

                // Testing with <span>
                let html_span = "<span>Test</span>";
                let fragment_span = Html::parse_fragment(html_span);
                let selector_span = Selector::parse("span").unwrap();
                let element_span = fragment_span
                    .select(&selector_span)
                    .next()
                    .unwrap();

                let roles =
                    ["button", "textbox", "navigation", "banner"];

                for role in roles {
                    assert!(
                        is_valid_aria_role(role, &element_div),
                        "Role '{}' should be allowed for div",
                        role
                    );
                    assert!(
                        is_valid_aria_role(role, &element_span),
                        "Role '{}' should be allowed for span",
                        role
                    );
                }
            }

            #[test]
            fn test_validate_wcag_with_level_aaa() {
                let html =
                    "<h1>Main Title</h1><h3>Skipped Heading</h3>";
                let config = AccessibilityConfig {
                    wcag_level: WcagLevel::AAA,
                    ..Default::default()
                };
                let report =
                    validate_wcag(html, &config, None).unwrap();
                assert!(report.issue_count > 0);
                assert_eq!(report.wcag_level, WcagLevel::AAA);
            }

            #[test]
            fn test_html_builder_empty() {
                let builder = HtmlBuilder::new("");
                assert_eq!(builder.build(), "");
            }

            #[test]
            fn test_generate_unique_id_uniqueness() {
                let id1 = generate_unique_id();
                let id2 = generate_unique_id();
                assert_ne!(id1, id2);
            }
        }

        mod required_aria_properties {
            use super::*;
            use scraper::{Html, Selector};

            #[test]
            fn test_combobox_required_properties() {
                let html = r#"<div role="combobox">Test</div>"#;
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("div").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();

                let missing =
                    get_missing_required_aria_properties(&element)
                        .unwrap();
                assert!(missing.contains(&"aria-expanded".to_string()));
            }

            #[test]
            fn test_complete_combobox() {
                let html = r#"<div role="combobox" aria-expanded="true">Test</div>"#;
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("div").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();

                let missing =
                    get_missing_required_aria_properties(&element);
                assert!(missing.is_none());
            }

            #[test]
            fn test_add_aria_attributes_empty_html() {
                let html = "";
                let result = add_aria_attributes(html, None);
                assert!(result.is_ok());
                assert_eq!(result.unwrap(), "");
            }

            #[test]
            fn test_add_aria_attributes_whitespace_html() {
                let html = "   ";
                let result = add_aria_attributes(html, None);
                assert!(result.is_ok());
                assert_eq!(result.unwrap(), "   ");
            }

            #[test]
            fn test_validate_wcag_with_minimal_config() {
                let html = r#"<html lang="en"><div>Accessible Content</div></html>"#;
                let config = AccessibilityConfig {
                    wcag_level: WcagLevel::A,
                    max_heading_jump: 0, // No heading enforcement
                    min_contrast_ratio: 0.0, // No contrast enforcement
                    auto_fix: false,
                };
                let report =
                    validate_wcag(html, &config, None).unwrap();
                assert_eq!(report.issue_count, 0);
            }

            #[test]
            fn test_add_partial_aria_attributes_to_button() {
                let html =
                    r#"<button aria-label="Existing">Click</button>"#;
                let result = add_aria_attributes(html, None);
                assert!(result.is_ok());
                let enhanced = result.unwrap();
                assert!(enhanced.contains(r#"aria-label="Existing""#));
            }

            #[test]
            fn test_add_aria_to_elements_with_existing_roles() {
                let html = r#"<nav aria-label=\"navigation\" role=\"navigation\" role=\"navigation\">Content</nav>"#;
                let result = add_aria_attributes(html, None);
                assert!(result.is_ok());
                assert_eq!(result.unwrap(), html);
            }

            #[test]
            fn test_slider_required_properties() {
                let html = r#"<div role="slider">Test</div>"#;
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("div").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();

                let missing =
                    get_missing_required_aria_properties(&element)
                        .unwrap();

                assert!(missing.contains(&"aria-valuenow".to_string()));
                assert!(missing.contains(&"aria-valuemin".to_string()));
                assert!(missing.contains(&"aria-valuemax".to_string()));
            }

            #[test]
            fn test_complete_slider() {
                let html = r#"<div role="slider"
                   aria-valuenow="50"
                   aria-valuemin="0"
                   aria-valuemax="100">Test</div>"#;
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("div").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();

                let missing =
                    get_missing_required_aria_properties(&element);
                assert!(missing.is_none());
            }

            #[test]
            fn test_partial_slider_properties() {
                let html = r#"<div role="slider" aria-valuenow="50">Test</div>"#;
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("div").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();

                let missing =
                    get_missing_required_aria_properties(&element)
                        .unwrap();

                assert!(!missing.contains(&"aria-valuenow".to_string()));
                assert!(missing.contains(&"aria-valuemin".to_string()));
                assert!(missing.contains(&"aria-valuemax".to_string()));
            }

            #[test]
            fn test_unknown_role() {
                let html = r#"<div role="unknown">Test</div>"#;
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("div").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();

                let missing =
                    get_missing_required_aria_properties(&element);
                assert!(missing.is_none());
            }

            #[test]
            fn test_no_role() {
                let html = "<div>Test</div>";
                let fragment = Html::parse_fragment(html);
                let selector = Selector::parse("div").unwrap();
                let element =
                    fragment.select(&selector).next().unwrap();

                let missing =
                    get_missing_required_aria_properties(&element);
                assert!(missing.is_none());
            }
        }
    }

    #[cfg(test)]
    mod accessibility_tests {
        use crate::accessibility::{
            get_missing_required_aria_properties, is_valid_aria_role,
            is_valid_language_code,
        };
        use scraper::Selector;

        #[test]
        fn test_is_valid_language_code() {
            assert!(
                is_valid_language_code("en"),
                "Valid language code 'en' was incorrectly rejected"
            );
            assert!(
                is_valid_language_code("en-US"),
                "Valid language code 'en-US' was incorrectly rejected"
            );
            assert!(
                !is_valid_language_code("123"),
                "Invalid language code '123' was incorrectly accepted"
            );
            assert!(!is_valid_language_code("日本語"), "Non-ASCII language code '日本語' was incorrectly accepted");
        }

        #[test]
        fn test_is_valid_aria_role() {
            use scraper::Html;

            let html = r#"<button></button>"#;
            let document = Html::parse_fragment(html);
            let element = document
                .select(&Selector::parse("button").unwrap())
                .next()
                .unwrap();

            assert!(
                is_valid_aria_role("button", &element),
                "Valid ARIA role 'button' was incorrectly rejected"
            );

            assert!(
        !is_valid_aria_role("invalid-role", &element),
        "Invalid ARIA role 'invalid-role' was incorrectly accepted"
    );
        }

        #[test]
        fn test_get_missing_required_aria_properties() {
            use scraper::{Html, Selector};

            // Case 1: Missing all properties for slider
            let html = r#"<div role="slider"></div>"#;
            let document = Html::parse_fragment(html);
            let element = document
                .select(&Selector::parse("div").unwrap())
                .next()
                .unwrap();

            let missing_props =
                get_missing_required_aria_properties(&element).unwrap();
            assert!(
        missing_props.contains(&"aria-valuenow".to_string()),
        "Did not detect missing 'aria-valuenow' for role 'slider'"
    );
            assert!(
        missing_props.contains(&"aria-valuemin".to_string()),
        "Did not detect missing 'aria-valuemin' for role 'slider'"
    );
            assert!(
        missing_props.contains(&"aria-valuemax".to_string()),
        "Did not detect missing 'aria-valuemax' for role 'slider'"
    );

            // Case 2: All properties present
            let html = r#"<div role="slider" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>"#;
            let document = Html::parse_fragment(html);
            let element = document
                .select(&Selector::parse("div").unwrap())
                .next()
                .unwrap();

            let missing_props =
                get_missing_required_aria_properties(&element);
            assert!(missing_props.is_none(), "Unexpectedly found missing properties for a complete slider");

            // Case 3: Partially missing properties
            let html =
                r#"<div role="slider" aria-valuenow="50"></div>"#;
            let document = Html::parse_fragment(html);
            let element = document
                .select(&Selector::parse("div").unwrap())
                .next()
                .unwrap();

            let missing_props =
                get_missing_required_aria_properties(&element).unwrap();
            assert!(
                !missing_props.contains(&"aria-valuenow".to_string()),
                "Incorrectly flagged 'aria-valuenow' as missing"
            );
            assert!(
        missing_props.contains(&"aria-valuemin".to_string()),
        "Did not detect missing 'aria-valuemin' for role 'slider'"
    );
            assert!(
        missing_props.contains(&"aria-valuemax".to_string()),
        "Did not detect missing 'aria-valuemax' for role 'slider'"
    );
        }
    }

    #[cfg(test)]
    mod additional_tests {
        use super::*;
        use scraper::Html;

        #[test]
        fn test_validate_empty_html() {
            let html = "";
            let config = AccessibilityConfig::default();
            let report = validate_wcag(html, &config, None).unwrap();
            assert_eq!(
                report.issue_count, 0,
                "Empty HTML should not produce issues"
            );
        }

        #[test]
        fn test_validate_only_whitespace_html() {
            let html = "   ";
            let config = AccessibilityConfig::default();
            let report = validate_wcag(html, &config, None).unwrap();
            assert_eq!(
                report.issue_count, 0,
                "Whitespace-only HTML should not produce issues"
            );
        }

        #[test]
        fn test_validate_language_with_edge_cases() {
            let html = "<html lang=\"en-US\"></html>";
            let _config = AccessibilityConfig::default();
            let mut issues = Vec::new();
            let document = Html::parse_document(html);

            check_language_attributes(&document, &mut issues).unwrap();
            assert_eq!(
                issues.len(),
                0,
                "Valid language declaration should not create issues"
            );
        }

        #[test]
        fn test_validate_invalid_language_code() {
            let html = "<html lang=\"invalid-lang\"></html>";
            let _config = AccessibilityConfig::default();
            let mut issues = Vec::new();
            let document = Html::parse_document(html);

            check_language_attributes(&document, &mut issues).unwrap();
            assert!(
                issues
                    .iter()
                    .any(|i| i.issue_type
                        == IssueType::LanguageDeclaration),
                "Failed to detect invalid language declaration"
            );
        }

        #[test]
        fn test_edge_case_for_generate_unique_id() {
            let ids: Vec<String> =
                (0..100).map(|_| generate_unique_id()).collect();
            let unique_ids: HashSet<String> = ids.into_iter().collect();
            assert_eq!(
                unique_ids.len(),
                100,
                "Generated IDs are not unique in edge case testing"
            );
        }

        #[test]
        fn test_enhance_landmarks_noop() {
            let html = "<div>Simple Content</div>";
            let builder = HtmlBuilder::new(html);
            let result = enhance_landmarks(builder);
            assert!(
                result.is_ok(),
                "Failed to handle simple HTML content"
            );
            assert_eq!(result.unwrap().build(), html, "Landmark enhancement altered simple content unexpectedly");
        }

        #[test]
        fn test_html_with_non_standard_elements() {
            let html =
                "<custom-element aria-label=\"test\"></custom-element>";
            let cleaned_html = remove_invalid_aria_attributes(html);
            assert_eq!(cleaned_html, html, "Unexpectedly modified valid custom element with ARIA attributes");
        }

        #[test]
        fn test_add_aria_to_buttons() {
            let html = r#"<button>Click me</button>"#;
            let builder = HtmlBuilder::new(html);
            let result = add_aria_to_buttons(builder).unwrap().build();
            assert!(result.contains("aria-label"));
        }

        #[test]
        fn test_add_aria_to_empty_buttons() {
            let html = r#"<button></button>"#;
            let builder = HtmlBuilder::new(html);
            let result = add_aria_to_buttons(builder).unwrap();
            assert!(result.build().contains("aria-label"));
        }

        #[test]
        fn test_validate_wcag_empty_html() {
            let html = "";
            let config = AccessibilityConfig::default();
            let disable_checks = None;

            let result = validate_wcag(html, &config, disable_checks);

            match result {
                Ok(report) => assert!(
                    report.issues.is_empty(),
                    "Empty HTML should have no issues"
                ),
                Err(e) => {
                    panic!("Validation failed with error: {:?}", e)
                }
            }
        }

        #[test]
        fn test_validate_wcag_with_complex_html() {
            let html = "
            <html>
                <head></head>
                <body>
                    <button>Click me</button>
                    <a href=\"\\#\"></a>
                </body>
            </html>
        ";
            let config = AccessibilityConfig::default();
            let disable_checks = None;
            let result = validate_wcag(html, &config, disable_checks);

            match result {
                Ok(report) => assert!(
                    !report.issues.is_empty(),
                    "Report should have issues"
                ),
                Err(e) => {
                    panic!("Validation failed with error: {:?}", e)
                }
            }
        }

        #[test]
        fn test_generate_unique_id_uniqueness() {
            let id1 = generate_unique_id();
            let id2 = generate_unique_id();
            assert_ne!(id1, id2);
        }

        #[test]
        fn test_try_create_selector_valid() {
            let selector = "div.class";
            let result = try_create_selector(selector);
            assert!(result.is_some());
        }

        #[test]
        fn test_try_create_selector_invalid() {
            let selector = "div..class";
            let result = try_create_selector(selector);
            assert!(result.is_none());
        }

        #[test]
        fn test_try_create_regex_valid() {
            let pattern = r"\d+";
            let result = try_create_regex(pattern);
            assert!(result.is_some());
        }

        #[test]
        fn test_try_create_regex_invalid() {
            let pattern = r"\d+(";
            let result = try_create_regex(pattern);
            assert!(result.is_none());
        }

        /// Test the `enhance_descriptions` function
        #[test]
        fn test_enhance_descriptions() {
            let builder =
                HtmlBuilder::new("<html><body></body></html>");
            let result = enhance_descriptions(builder);
            assert!(result.is_ok(), "Enhance descriptions failed");
        }

        /// Test `From<TryFromIntError>` for `Error`
        #[test]
        fn test_error_from_try_from_int_error() {
            // Trigger a TryFromIntError by attempting to convert a large integer
            let result: std::result::Result<u8, _> = i32::try_into(300); // This will fail
            let err = result.unwrap_err(); // Extract the TryFromIntError
            let error: Error = Error::from(err);

            if let Error::HtmlProcessingError { message, source } =
                error
            {
                assert_eq!(message, "Integer conversion error");
                assert!(source.is_some());
            } else {
                panic!("Expected HtmlProcessingError");
            }
        }

        /// Test `Display` implementation for `WcagLevel`
        #[test]
        fn test_wcag_level_display() {
            assert_eq!(WcagLevel::A.to_string(), "A");
            assert_eq!(WcagLevel::AA.to_string(), "AA");
            assert_eq!(WcagLevel::AAA.to_string(), "AAA");
        }

        /// Test `check_keyboard_navigation`
        #[test]
        fn test_check_keyboard_navigation() {
            let document =
                Html::parse_document("<a tabindex='-1'></a>");
            let mut issues = vec![];
            let result = AccessibilityReport::check_keyboard_navigation(
                &document,
                &mut issues,
            );
            assert!(result.is_ok());
            assert_eq!(issues.len(), 1);
            assert_eq!(
                issues[0].message,
                "Negative tabindex prevents keyboard focus"
            );
        }

        /// Test `check_language_attributes`
        #[test]
        fn test_check_language_attributes() {
            let document = Html::parse_document("<html></html>");
            let mut issues = vec![];
            let result = AccessibilityReport::check_language_attributes(
                &document,
                &mut issues,
            );
            assert!(result.is_ok());
            assert_eq!(issues.len(), 1);
            assert_eq!(
                issues[0].message,
                "Missing language declaration"
            );
        }
    }

    mod missing_tests {
        use super::*;
        use std::collections::HashSet;

        /// Test for color contrast ratio calculation
        #[test]
        fn test_color_contrast_ratio() {
            let low_contrast = 2.5;
            let high_contrast = 7.1;

            let config = AccessibilityConfig {
                min_contrast_ratio: 4.5,
                ..Default::default()
            };

            assert!(
                low_contrast < config.min_contrast_ratio,
                "Low contrast should not pass"
            );

            assert!(
                high_contrast >= config.min_contrast_ratio,
                "High contrast should pass"
            );
        }

        /// Test dynamic content ARIA attributes
        #[test]
        fn test_dynamic_content_aria_attributes() {
            let html = r#"<div aria-live="polite"></div>"#;
            let cleaned_html = remove_invalid_aria_attributes(html);
            assert_eq!(
                cleaned_html, html,
                "Dynamic content ARIA attributes should be preserved"
            );
        }

        /// Test strict WCAG AAA behavior
        #[test]
        fn test_strict_wcag_aaa_behavior() {
            let html = r#"<h1>Main Title</h1><h4>Skipped Level</h4>"#;
            let config = AccessibilityConfig {
                wcag_level: WcagLevel::AAA,
                ..Default::default()
            };

            let report = validate_wcag(html, &config, None).unwrap();
            assert!(
                report.issue_count > 0,
                "WCAG AAA strictness should detect issues"
            );

            let issue = &report.issues[0];
            assert_eq!(
                issue.issue_type,
                IssueType::LanguageDeclaration,
                "Expected heading structure issue"
            );
        }

        /// Test performance with large HTML input
        #[test]
        fn test_large_html_performance() {
            let large_html =
                "<div>".repeat(1_000) + &"</div>".repeat(1_000);
            let result = validate_wcag(
                &large_html,
                &AccessibilityConfig::default(),
                None,
            );
            assert!(
                result.is_ok(),
                "Large HTML should not cause performance issues"
            );
        }

        /// Test nested elements with ARIA attributes
        #[test]
        fn test_nested_elements_with_aria_attributes() {
            let html = r#"
        <div>
            <button aria-label="Test">Click</button>
            <nav aria-label="Main Navigation">
                <ul><li>Item 1</li></ul>
            </nav>
        </div>
        "#;
            let enhanced_html =
                add_aria_attributes(html, None).unwrap();
            assert!(
                enhanced_html.contains("aria-label"),
                "Nested elements should have ARIA attributes"
            );
        }

        /// Test heading structure validation with deeply nested headings
        #[test]
        fn test_deeply_nested_headings() {
            let html = r#"
        <div>
            <h1>Main Title</h1>
            <div>
                <h3>Skipped Level</h3>
            </div>
        </div>
        "#;
            let mut issues = Vec::new();
            let document = Html::parse_document(html);
            check_heading_structure(&document, &mut issues);

            assert!(
            issues.iter().any(|issue| issue.issue_type == IssueType::HeadingStructure),
            "Deeply nested headings with skipped levels should produce issues"
        );
        }

        /// Test unique ID generation over a long runtime
        #[test]
        fn test_unique_id_long_runtime() {
            let ids: HashSet<_> =
                (0..10_000).map(|_| generate_unique_id()).collect();
            assert_eq!(
                ids.len(),
                10_000,
                "Generated IDs should be unique over long runtime"
            );
        }

        /// Test custom selector failure handling
        #[test]
        fn test_custom_selector_failure() {
            let invalid_selector = "div..class";
            let result = try_create_selector(invalid_selector);
            assert!(
                result.is_none(),
                "Invalid selector should return None"
            );
        }

        /// Test invalid regex pattern
        #[test]
        fn test_invalid_regex_pattern() {
            let invalid_pattern = r"\d+(";
            let result = try_create_regex(invalid_pattern);
            assert!(
                result.is_none(),
                "Invalid regex pattern should return None"
            );
        }

        /// Test ARIA attribute removal with invalid values
        #[test]
        fn test_invalid_aria_attribute_removal() {
            let html = r#"<div aria-hidden="invalid"></div>"#;
            let cleaned_html = remove_invalid_aria_attributes(html);
            assert!(
                !cleaned_html.contains("aria-hidden"),
                "Invalid ARIA attributes should be removed"
            );
        }

        // Test invalid selector handling
        #[test]
        fn test_invalid_selector() {
            let invalid_selector = "div..class";
            let result = try_create_selector(invalid_selector);
            assert!(result.is_none());
        }

        // Test `issue_type` handling in `Issue` struct
        #[test]
        fn test_issue_type_in_issue_struct() {
            let issue = Issue {
                issue_type: IssueType::MissingAltText,
                message: "Alt text is missing".to_string(),
                guideline: Some("WCAG 1.1.1".to_string()),
                element: Some("<img>".to_string()),
                suggestion: Some(
                    "Add descriptive alt text".to_string(),
                ),
            };
            assert_eq!(issue.issue_type, IssueType::MissingAltText);
        }

        // Test `add_aria_to_navs`
        #[test]
        fn test_add_aria_to_navs() {
            let html = "<nav>Main Navigation</nav>";
            let builder = HtmlBuilder::new(html);
            let result = add_aria_to_navs(builder).unwrap().build();
            assert!(result.contains(r#"aria-label="navigation""#));
            assert!(result.contains(r#"role="navigation""#));
        }

        // Test `add_aria_to_forms`
        #[test]
        fn test_add_aria_to_forms() {
            let html = "<form>Form Content</form>";
            let builder = HtmlBuilder::new(html);
            let result = add_aria_to_forms(builder).unwrap().build();
            assert!(result.contains(r#"aria-labelledby="form-"#));
            assert!(result.contains(r#"role="form""#));
        }

        // Test `add_aria_to_inputs`
        #[test]
        fn test_add_aria_to_inputs() {
            let html = r#"<input type="text">"#;
            let builder = HtmlBuilder::new(html);
            let result = add_aria_to_inputs(builder).unwrap().build();
            assert!(result.contains(r#"aria-label="text""#));
            assert!(result.contains(r#"role="textbox""#));
        }

        // Test `check_keyboard_navigation` click handlers without keyboard equivalents
        #[test]
        fn test_check_keyboard_navigation_click_handlers() {
            let html = r#"<button onclick="handleClick()"></button>"#;
            let document = Html::parse_document(html);
            let mut issues = vec![];

            AccessibilityReport::check_keyboard_navigation(
                &document,
                &mut issues,
            )
            .unwrap();

            assert!(
        issues.iter().any(|i| i.message == "Click handler without keyboard equivalent"),
        "Expected an issue for missing keyboard equivalents, but found: {:?}",
        issues
    );
        }

        // Test invalid language codes in `check_language_attributes`
        #[test]
        fn test_invalid_language_code() {
            let html = r#"<html lang="invalid-lang"></html>"#;
            let document = Html::parse_document(html);
            let mut issues = vec![];
            AccessibilityReport::check_language_attributes(
                &document,
                &mut issues,
            )
            .unwrap();
            assert!(issues
                .iter()
                .any(|i| i.message.contains("Invalid language code")));
        }

        // Test `get_missing_required_aria_properties`
        #[test]
        fn test_missing_required_aria_properties() {
            let html = r#"<div role="slider"></div>"#;
            let fragment = Html::parse_fragment(html);
            let element = fragment
                .select(&Selector::parse("div").unwrap())
                .next()
                .unwrap();
            let missing =
                get_missing_required_aria_properties(&element).unwrap();
            assert!(missing.contains(&"aria-valuenow".to_string()));
        }
    }
}