htui 0.2.0

A terminal HTML/CSS renderer with an embedded JavaScript engine — build interactive TUIs from HTML, CSS and JS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
use std::sync::Arc;

use crossterm::style::Color;
use htui::html::css_parse::{
    Background, BorderStyle, BoxSizing, Combinator, CornerRadii, CssAttr, CssRule, CssRuleEntry,
    CssSelector, DynamicState, EdgeAuto, EdgeSizes, FontContext, FontStyleKind, FontWeight,
    GradientKind, INHERITED_PROPS, Length, LengthContext, LineHeight, MarginSizes, NthExpr,
    PX_PER_CELL, Parser, SUPPORTED_PROPERTIES, Selector, TextAlign, TextDecoration, TextTransform,
    UserSelect, Viewport, WhiteSpace, css_into_node, css_into_node_with_state,
    parse_background_str, parse_color_str, parse_declaration_text, reset_css_attr,
    resolve_line_height_cells, selector_chain_matches, selector_chain_matches_with_state,
};
use htui::html::html_parse;
use htui::tdom::node::{Node, NodeArena, NodeId, NodeType, effective_font_size_cells};
use indexmap::IndexMap;

/// Default font-size (in cells) used by [`Length::resolve`] tests so the
/// em / rem branches can be exercised without a DOM. Mirrors the
/// `FontContext::root(80, 24)` value passed to layout.
const DEFAULT_FONT_SIZE: usize = 1;
const DEFAULT_ROOT_FONT_SIZE: usize = 1;
/// Default viewport cols / rows for `vw` / `vh` resolution tests.
const DEFAULT_VIEWPORT_COLS: usize = 80;
const DEFAULT_VIEWPORT_ROWS: usize = 24;

fn font_ctx(font_size_cells: usize, root_font_size_cells: usize) -> FontContext {
    FontContext {
        font_size_cells,
        root_font_size_cells,
    }
}

fn viewport() -> Viewport {
    Viewport {
        cols: DEFAULT_VIEWPORT_COLS,
        rows: DEFAULT_VIEWPORT_ROWS,
    }
}

fn length_ctx(containing: usize, font: FontContext) -> LengthContext {
    LengthContext {
        containing,
        font,
        viewport: viewport(),
    }
}

fn default_font_ctx() -> FontContext {
    font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE)
}

fn init() {
    let _ = env_logger::builder().is_test(true).try_init();
}

fn build_test(arena: &mut NodeArena) -> (NodeId, NodeId) {
    let root = arena.insert(Node::from(NodeType::Document));
    let div_id = arena.insert(Node::from(NodeType::Div));
    arena[div_id].attributes = IndexMap::from([
        ("class".to_string(), "active".to_string()),
        ("id".to_string(), "main".to_string()),
    ]);
    let p_id = arena.insert(Node::from(NodeType::P));
    let text_id = arena.insert(Node::text("Hello"));
    Node::append_child(arena, p_id, text_id);
    Node::append_child(arena, div_id, p_id);
    Node::append_child(arena, root, div_id);
    (root, div_id)
}

/// Build `root -> div -> p(class="a b")`, returning `(root, p)`. Used by the
/// cascade tests that need same-specificity class selectors matching one node.
fn build_p_with_classes(arena: &mut NodeArena) -> (NodeId, NodeId) {
    let root = arena.insert(Node::from(NodeType::Document));
    let div_id = arena.insert(Node::from(NodeType::Div));
    let p_id = arena.insert(Node::from(NodeType::P));
    arena[p_id]
        .attributes
        .insert("class".to_string(), "a b".to_string());
    let text_id = arena.insert(Node::text("x"));
    Node::append_child(arena, p_id, text_id);
    Node::append_child(arena, div_id, p_id);
    Node::append_child(arena, root, div_id);
    (root, p_id)
}

#[test]
fn test_parse_simple() {
    init();
    let mut p = Parser::new("p { color: red; }");
    assert_eq!(p.parse().0.len(), 1);
}

#[test]
fn test_parse_desc() {
    init();
    let s: CssSelector = "div p".parse().unwrap();
    assert_eq!(s.combinators[0], Combinator::Descendant);
}

#[test]
fn test_parse_child() {
    init();
    let s: CssSelector = "div > p".parse().unwrap();
    assert_eq!(s.combinators[0], Combinator::Child);
}

#[test]
fn test_matches_descendant() {
    init();
    let mut arena = NodeArena::default();
    let (root, _) = build_test(&mut arena);
    let sel: CssSelector = "div p".parse().unwrap();
    let div_id = arena[root].children[0];
    let p_id = arena[div_id].children[0];
    assert!(selector_chain_matches(&arena, p_id, &sel));
}

#[test]
fn test_nth_child_even_matches_second_child() {
    // `:nth-child(even)` (== `2n`) must match the 2nd, 4th, … siblings and
    // skip the 1st, 3rd, …. Build a 4-row parent and verify each index.
    init();
    let mut arena = NodeArena::default();
    let parent = arena.insert(Node::from(NodeType::Div));
    let mut children = Vec::new();
    for _ in 0..4 {
        let id = arena.insert(Node::from(NodeType::P));
        Node::append_child(&mut arena, parent, id);
        children.push(id);
    }
    let sel: CssSelector = ":nth-child(even)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, children[0], &sel));
    assert!(selector_chain_matches(&arena, children[1], &sel));
    assert!(!selector_chain_matches(&arena, children[2], &sel));
    assert!(selector_chain_matches(&arena, children[3], &sel));
}

#[test]
fn test_nth_child_odd_matches_first_child() {
    // `:nth-child(odd)` (== `2n+1`) must match the 1st, 3rd, … siblings.
    init();
    let mut arena = NodeArena::default();
    let parent = arena.insert(Node::from(NodeType::Div));
    let mut children = Vec::new();
    for _ in 0..3 {
        let id = arena.insert(Node::from(NodeType::P));
        Node::append_child(&mut arena, parent, id);
        children.push(id);
    }
    let sel: CssSelector = ":nth-child(odd)".parse().unwrap();
    assert!(selector_chain_matches(&arena, children[0], &sel));
    assert!(!selector_chain_matches(&arena, children[1], &sel));
    assert!(selector_chain_matches(&arena, children[2], &sel));
}

#[test]
fn test_nth_child_bare_integer_matches_exact_position() {
    // `:nth-child(2)` must match only the 2nd child. `a=0` in the NthExpr
    // exercises the "single position" branch.
    init();
    let mut arena = NodeArena::default();
    let parent = arena.insert(Node::from(NodeType::Div));
    let mut children = Vec::new();
    for _ in 0..4 {
        let id = arena.insert(Node::from(NodeType::P));
        Node::append_child(&mut arena, parent, id);
        children.push(id);
    }
    let sel: CssSelector = ":nth-child(2)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, children[0], &sel));
    assert!(selector_chain_matches(&arena, children[1], &sel));
    assert!(!selector_chain_matches(&arena, children[2], &sel));
}

#[test]
fn test_nth_child_an_plus_b_form() {
    // `:nth-child(3n+2)` must match indices 2, 5, 8, …
    init();
    let mut arena = NodeArena::default();
    let parent = arena.insert(Node::from(NodeType::Div));
    let mut children = Vec::new();
    for _ in 0..9 {
        let id = arena.insert(Node::from(NodeType::P));
        Node::append_child(&mut arena, parent, id);
        children.push(id);
    }
    let sel: CssSelector = ":nth-child(3n+2)".parse().unwrap();
    for (i, id) in children.iter().enumerate() {
        let expected = (i + 1 == 2) || (i + 1 == 5) || (i + 1 == 8);
        assert_eq!(
            selector_chain_matches(&arena, *id, &sel),
            expected,
            "3n+2 should match index {} → {}",
            i + 1,
            expected
        );
    }
}

#[test]
fn test_nth_child_compound_with_tag() {
    // `tr:nth-child(even)` — the tabular form. The tag prefix must not
    // disturb the nth-child evaluation.
    init();
    let mut arena = NodeArena::default();
    let table = arena.insert(Node::from(NodeType::Table));
    let tr_ids: Vec<_> = (0..3)
        .map(|_| {
            let id = arena.insert(Node::from(NodeType::Tr));
            Node::append_child(&mut arena, table, id);
            id
        })
        .collect();
    let sel: CssSelector = "tr:nth-child(even)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, tr_ids[0], &sel));
    assert!(selector_chain_matches(&arena, tr_ids[1], &sel));
    assert!(!selector_chain_matches(&arena, tr_ids[2], &sel));

    // A non-`<tr>` element at the same index must not match — the tag
    // filter is applied first.
    let span = arena.insert(Node::from(NodeType::Span));
    Node::append_child(&mut arena, table, span);
    assert!(!selector_chain_matches(&arena, span, &sel));
}

#[test]
fn test_nth_child_descendant_combinator() {
    // `table tr:nth-child(even)` — a striping selector. The descendant
    // combinator must still walk ancestors correctly.
    init();
    let mut arena = NodeArena::default();
    let table = arena.insert(Node::from(NodeType::Table));
    let tr_ids: Vec<_> = (0..4)
        .map(|_| {
            let id = arena.insert(Node::from(NodeType::Tr));
            Node::append_child(&mut arena, table, id);
            id
        })
        .collect();
    let sel: CssSelector = "table tr:nth-child(even)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, tr_ids[0], &sel));
    assert!(selector_chain_matches(&arena, tr_ids[1], &sel));
    assert!(!selector_chain_matches(&arena, tr_ids[2], &sel));
    assert!(selector_chain_matches(&arena, tr_ids[3], &sel));
}

#[test]
fn test_nth_child_nth_expr_matches_predicate() {
    // Direct unit test on NthExpr — covers the even/odd constants and the
    // `a*n + b` math without needing an arena.
    init();
    assert!(!NthExpr::EVEN.matches(1));
    assert!(NthExpr::EVEN.matches(2));
    assert!(!NthExpr::EVEN.matches(3));
    assert!(NthExpr::EVEN.matches(4));
    assert!(NthExpr::ODD.matches(1));
    assert!(!NthExpr::ODD.matches(2));
    assert!(NthExpr::ODD.matches(3));
    let expr = NthExpr { a: 3, b: 2 };
    assert!(expr.matches(2));
    assert!(expr.matches(5));
    assert!(expr.matches(8));
    assert!(!expr.matches(1));
    assert!(!expr.matches(4));
    // Degenerate a=0 — only the exact position matches.
    let single = NthExpr { a: 0, b: 3 };
    assert!(single.matches(3));
    assert!(!single.matches(2));
    assert!(!single.matches(4));
}

#[test]
fn test_nth_child_unsupported_forms_fail_parse() {
    // Forms outside the supported subset (bare `n`, negative coefficients,
    // signed offsets) must fail to parse so we never silently mis-match.
    init();
    assert!(":nth-child(n)".parse::<CssSelector>().is_err());
    assert!(":nth-child(-n+3)".parse::<CssSelector>().is_err());
    assert!(":nth-child(2n-1)".parse::<CssSelector>().is_err());
    assert!(":nth-child(0)".parse::<CssSelector>().is_err());
    // The bare-nth-child token without parentheses must also be rejected.
    assert!(":nth-child".parse::<CssSelector>().is_err());
}

#[test]
fn test_css_into_node() {
    init();
    let mut arena = NodeArena::default();
    let (root, _) = build_test(&mut arena);
    let mut css = CssRule::new();
    let sel: CssSelector = "div p".parse().unwrap();
    let mut m = IndexMap::new();
    m.insert("color".into(), "red".into());
    css.add(sel, CssAttr::from(m));
    css_into_node(&mut arena, root, &css);
    let div_id = arena[root].children[0];
    let p_id = arena[div_id].children[0];
    assert!(arena[p_id].css_attr.get_color().is_some());
}

#[test]
fn test_css_selector_matches_title_and_meta() {
    // The `tag` branch of the selector parser must recognise the metadata
    // tags so that user CSS targeting `<title>` / `<meta>` parses and
    // matches the corresponding DOM nodes.
    init();
    let mut arena = NodeArena::default();
    let root = arena.insert(Node::from(NodeType::Html));
    let head_id = arena.insert(Node::from(NodeType::Head));
    Node::append_child(&mut arena, root, head_id);
    let title_id = arena.insert(Node::from(NodeType::Title));
    let meta_id = arena.insert(Node::from(NodeType::Meta));
    Node::append_child(&mut arena, head_id, title_id);
    Node::append_child(&mut arena, head_id, meta_id);

    let title_sel: CssSelector = "title".parse().unwrap();
    let meta_sel: CssSelector = "meta".parse().unwrap();
    assert!(selector_chain_matches(&arena, title_id, &title_sel));
    assert!(selector_chain_matches(&arena, meta_id, &meta_sel));
    // Cross-tag sanity: the wrong selector must not match.
    assert!(!selector_chain_matches(&arena, meta_id, &title_sel));
    assert!(!selector_chain_matches(&arena, title_id, &meta_sel));
}

#[test]
fn test_universal_selector_parses_and_matches_elements_only() {
    // `*` must parse to the `Universal` variant, match every element node,
    // and never match non-element nodes (text / comment / document).
    init();
    let mut arena = NodeArena::default();
    let (root, div_id) = build_test(&mut arena);
    let sel: CssSelector = "*".parse().unwrap();
    assert_eq!(sel.compounds.len(), 1);
    assert_eq!(sel.compounds[0], vec![Selector::Universal]);

    let p_id = arena[div_id].children[0];
    let text_id = arena[p_id].children[0];
    // Elements match the universal selector.
    assert!(selector_chain_matches(&arena, div_id, &sel));
    assert!(selector_chain_matches(&arena, p_id, &sel));
    // Non-element nodes never match.
    assert!(!selector_chain_matches(&arena, root, &sel));
    assert!(!selector_chain_matches(&arena, text_id, &sel));
}

#[test]
fn test_universal_selector_in_compound_and_descendant() {
    // `*.foo` and `div *` are the standard ways the universal selector
    // combines with classes and combinators.
    init();
    let mut arena = NodeArena::default();
    let (_, div_id) = build_test(&mut arena);
    let compound_sel: CssSelector = "*.active".parse().unwrap();
    assert!(selector_chain_matches(&arena, div_id, &compound_sel));

    let descendant_sel: CssSelector = "div *".parse().unwrap();
    let p_id = arena[div_id].children[0];
    assert!(selector_chain_matches(&arena, p_id, &descendant_sel));
    // The div itself is not a descendant of itself.
    assert!(!selector_chain_matches(&arena, div_id, &descendant_sel));
}

#[test]
fn test_universal_selector_specificity_is_zero() {
    // Per the CSS spec `*` contributes (0,0,0), so `* div` and `div` tie;
    // a rule combining the two must not outrank the plain type selector.
    init();
    let univ: CssSelector = "*".parse().unwrap();
    let tag: CssSelector = "div".parse().unwrap();
    let chain: CssSelector = "* div".parse().unwrap();
    assert_eq!(univ.specificity(), (0, 0, 0));
    assert_eq!(chain.specificity(), tag.specificity());
}

#[test]
fn test_universal_selector_cascades_to_elements_not_text() {
    // A `* { background-color: red }` rule must paint every element but leave
    // text nodes untouched — the cascade visits the whole subtree, so the
    // matcher's element-only guard is what keeps text unstyled. (An inheritable
    // property like `color` would reach text nodes through inheritance, so the
    // test uses `background-color`, which does not inherit.)
    init();
    let mut arena = NodeArena::default();
    let (root, _) = build_test(&mut arena);
    let mut css = CssRule::new();
    let sel: CssSelector = "*".parse().unwrap();
    let mut m = IndexMap::new();
    m.insert("background-color".into(), "red".into());
    css.add(sel, CssAttr::from(m));
    css_into_node(&mut arena, root, &css);

    let div_id = arena[root].children[0];
    let p_id = arena[div_id].children[0];
    let text_id = arena[p_id].children[0];
    assert!(arena[div_id].css_attr.get_bg_color().is_some());
    assert!(arena[p_id].css_attr.get_bg_color().is_some());
    assert!(arena[text_id].css_attr.get_bg_color().is_none());
}

#[test]
fn test_e_type_selector_covers_every_element_tag() {
    // Completeness: every element `NodeType` must be addressable by a CSS
    // type selector, and the three tag lookups (DOM `tag_name`, HTML parser
    // map, selector parser) must agree. `NodeType::ALL` is the single
    // enumeration — a new element variant that forgets `tag_name` /
    // `from_tag_name` fails here instead of silently matching nothing.
    init();
    let mut arena = NodeArena::default();
    for nt in NodeType::ALL {
        match nt.tag_name() {
            Some(tag) => {
                // Round-trip through the shared reverse lookup.
                assert_eq!(NodeType::from_tag_name(tag), Some(*nt));
                assert_eq!(html_parse::tag_name_to_node_type(tag), Some(*nt));
                // The selector parser must accept the tag as a type selector
                // and match a node of exactly that type.
                let sel: CssSelector = tag
                    .parse()
                    .unwrap_or_else(|e| panic!("tag {tag} failed as a selector: {e}"));
                let node_id = arena.insert(Node::from(*nt));
                assert!(
                    selector_chain_matches(&arena, node_id, &sel),
                    "selector `{tag}` must match its node type"
                );
            }
            None => {
                // Document-structure nodes have no tag name and must not be
                // creatable from a tag string.
                assert!(
                    matches!(
                        nt,
                        NodeType::Document
                            | NodeType::DocumentType
                            | NodeType::DocumentFragment
                            | NodeType::Text
                            | NodeType::Comment
                    ),
                    "{nt:?} is an element but has no tag name"
                );
            }
        }
    }
}

#[test]
fn test_e_type_selector_rejects_unknown_tag() {
    // Unknown tags must still fail to parse (the rule is dropped), never
    // silently matching nothing.
    init();
    assert!("madeup".parse::<CssSelector>().is_err());
    // `strong` is a supported element today; use a genuinely unknown tag.
    assert!("div blink".parse::<CssSelector>().is_err());
}

#[test]
fn test_is_set_distinguishes_unset_from_explicit_none() {
    // `is_set` is the public hook the `<a>` renderer uses to decide whether
    // to apply the user-agent default underline — it must report `false`
    // when the property was never declared, and `true` once a declaration
    // (even `none`) is recorded in the underlying map.
    init();
    let mut attr = CssAttr::new();
    assert!(!attr.is_set("text-decoration"));
    assert!(!attr.is_set("color"));

    let declared = parse_declaration_text("text-decoration: none;");
    attr.add(&CssAttr(declared));
    assert!(
        attr.is_set("text-decoration"),
        "explicit `none` declaration must still count as set"
    );
    // Parsed accessor folds `none` back to the variant, but `is_set` only
    // looks at the raw key.
    assert_eq!(attr.get_text_decoration(), TextDecoration::None);
}

#[test]
fn test_color_name_parsing() {
    assert_eq!(
        parse_color_str("darkblue"),
        Some(Color::Rgb {
            r: 0x00,
            g: 0x00,
            b: 0x8B
        })
    );
    assert_eq!(
        parse_color_str("DarkBlue"),
        Some(Color::Rgb {
            r: 0x00,
            g: 0x00,
            b: 0x8B
        })
    );
    assert_eq!(
        parse_color_str("red"),
        Some(Color::Rgb {
            r: 0xFF,
            g: 0x00,
            b: 0x00
        })
    );
    assert_eq!(
        parse_color_str("darkred"),
        Some(Color::Rgb {
            r: 0x8B,
            g: 0x00,
            b: 0x00
        })
    );
    assert_eq!(
        parse_color_str("blue"),
        Some(Color::Rgb {
            r: 0x00,
            g: 0x00,
            b: 0xFF
        })
    );
    assert_eq!(
        parse_color_str("grey"),
        Some(Color::Rgb {
            r: 0x80,
            g: 0x80,
            b: 0x80
        })
    );
    assert_eq!(
        parse_color_str("gray"),
        Some(Color::Rgb {
            r: 0x80,
            g: 0x80,
            b: 0x80
        })
    );
}

#[test]
fn test_color_hex_parsing() {
    assert_eq!(
        parse_color_str("#1e293b"),
        Some(Color::Rgb {
            r: 0x1e,
            g: 0x29,
            b: 0x3b
        })
    );
    assert_eq!(
        parse_color_str("#fff"),
        Some(Color::Rgb {
            r: 255,
            g: 255,
            b: 255
        })
    );
}

#[test]
fn test_color_rgb_parsing() {
    assert_eq!(
        parse_color_str("rgb(30,41,59)"),
        Some(Color::Rgb {
            r: 30,
            g: 41,
            b: 59
        })
    );
}

#[test]
fn test_color_rgba_and_modern_syntax() {
    // Legacy comma syntax with a 4th alpha component.
    assert_eq!(
        parse_color_str("rgba(255, 0, 0, 0.5)"),
        Some(Color::Rgb { r: 255, g: 0, b: 0 }),
        "rgba alpha is dropped (opaque)"
    );
    // CSS Color 4 space syntax with a `/ alpha` separator.
    assert_eq!(
        parse_color_str("rgb(255 0 0 / 50%)"),
        Some(Color::Rgb { r: 255, g: 0, b: 0 })
    );
    // Percentage components + out-of-range clamping (CSS Color 4).
    assert_eq!(
        parse_color_str("rgb(100% 0% 0%)"),
        Some(Color::Rgb { r: 255, g: 0, b: 0 })
    );
    assert_eq!(
        parse_color_str("rgb(300, 0, 0)"),
        Some(Color::Rgb { r: 255, g: 0, b: 0 }),
        "out-of-range components clamp to 0…255"
    );
    assert_eq!(
        parse_color_str("rgb(20% 40% 60%)"),
        Some(Color::Rgb {
            r: 51,
            g: 102,
            b: 153
        })
    );
}

#[test]
fn test_color_hsl_parsing() {
    // hsl(0, 100%, 50%) == red; hsl(120, 100%, 50%) == green.
    assert_eq!(
        parse_color_str("hsl(0, 100%, 50%)"),
        Some(Color::Rgb { r: 255, g: 0, b: 0 })
    );
    assert_eq!(
        parse_color_str("hsl(120, 100%, 50%)"),
        Some(Color::Rgb { r: 0, g: 255, b: 0 })
    );
    // Space syntax + `/ alpha` (dropped).
    assert_eq!(
        parse_color_str("hsl(120 100% 50% / 0.25)"),
        Some(Color::Rgb { r: 0, g: 255, b: 0 })
    );
    assert_eq!(
        parse_color_str("hsl(480, 100%, 50%)"),
        Some(Color::Rgb { r: 0, g: 255, b: 0 })
    );
    // Zero saturation → gray.
    assert_eq!(
        parse_color_str("hsl(0, 0%, 50%)"),
        Some(Color::Rgb {
            r: 128,
            g: 128,
            b: 128
        })
    );
    // hsla legacy comma syntax with the 4th alpha component.
    assert_eq!(
        parse_color_str("hsla(0, 100%, 50%, 0.5)"),
        Some(Color::Rgb { r: 255, g: 0, b: 0 })
    );
}

#[test]
fn test_color_hex_alpha_parsing() {
    assert_eq!(
        parse_color_str("#ff000080"),
        Some(Color::Rgb { r: 255, g: 0, b: 0 }),
        "#RRGGBBAA drops the alpha channel"
    );
    assert_eq!(
        parse_color_str("#f008"),
        Some(Color::Rgb { r: 255, g: 0, b: 0 }),
        "#RGBA drops the alpha channel"
    );
}

#[test]
fn test_color_transparent_and_malformed() {
    // `transparent` is accepted for backgrounds / borders as "no paint"
    // (callers treat None that way), so a document background falls through
    // to the parent's, matching the browser.
    assert_eq!(parse_color_str("transparent"), None);
    // Malformed functional colors are dropped, not guessed.
    assert_eq!(parse_color_str("rgb(0, 0)"), None);
    assert_eq!(parse_color_str("rgb(0 0)"), None);
    assert_eq!(parse_color_str("hsl(0, 100%)"), None);
    assert_eq!(parse_color_str("rgba(0, 0, 0, 1.5)"), None);
    assert_eq!(parse_color_str("hsl(0, 0%, 0%, 2)"), None);
}

#[test]
fn test_linear_gradient_parsing_and_sampling() {
    let Some(Background::Gradient(gradient)) =
        parse_background_str("linear-gradient(to right, #ff0000 0%, rgb(0, 0, 255) 100%)")
    else {
        panic!("linear gradient should parse");
    };
    assert_eq!(gradient.kind, GradientKind::Linear { angle_deg: 90.0 });
    assert_eq!(gradient.stops.len(), 2);
    assert_eq!(gradient.stops[0].color, Color::Rgb { r: 255, g: 0, b: 0 });
    assert_eq!(gradient.stops[1].color, Color::Rgb { r: 0, g: 0, b: 255 });
    let left = gradient.color_at(0, 0, 10, 1).unwrap();
    let right = gradient.color_at(9, 0, 10, 1).unwrap();
    assert_ne!(left, right);
}

#[test]
fn test_radial_gradient_parsing_with_center() {
    let Some(Background::Gradient(gradient)) =
        parse_background_str("radial-gradient(circle at 25% 75%, red, blue)")
    else {
        panic!("radial gradient should parse");
    };
    assert_eq!(
        gradient.kind,
        GradientKind::Radial {
            center_x: 0.25,
            center_y: 0.75
        }
    );
    assert_eq!(gradient.stops.len(), 2);
    assert!(parse_background_str("linear-gradient(red)").is_none());
}

#[test]
fn test_background_clip_text_getter() {
    let mut attr = CssAttr::new();
    attr.add(&CssAttr(parse_declaration_text(
        "background-clip: text; color: transparent;",
    )));
    assert!(attr.background_clips_to_text());
    assert_eq!(attr.get_color(), None);
}

#[test]
fn test_css_attr_full_color() {
    let mut attr = CssAttr::new();
    let css = "color: darkblue; background-color: #1e293b;";
    let m = parse_declaration_text(css);
    attr.add(&CssAttr(m));
    assert_eq!(
        attr.get_color(),
        Some(Color::Rgb {
            r: 0x00,
            g: 0x00,
            b: 0x8B
        })
    );
    assert_eq!(
        attr.get_bg_color(),
        Some(Color::Rgb {
            r: 0x1e,
            g: 0x29,
            b: 0x3b
        })
    );
}

// ============================================================
// #1 refactor: property registry & parse robustness
// ============================================================

#[test]
fn user_select_is_recognised_and_resolved_against_ancestors() {
    assert!(SUPPORTED_PROPERTIES.contains(&"user-select"));
    let mut attr = CssAttr::new();
    attr.0.insert("user-select".into(), "none".into());
    assert_eq!(attr.get_user_select(), UserSelect::None);

    let mut arena = NodeArena::default();
    let root = arena.insert(Node::from(NodeType::Div));
    let child = arena.insert(Node::from(NodeType::Div));
    arena[root].children.push(child);
    arena[child].parent = Some(root);
    assert!(
        !htui::layout::user_select_is_none(&arena, child),
        "auto without an explicit ancestor defaults to selectable"
    );

    arena[root]
        .css_attr
        .0
        .insert("user-select".into(), "none".into());
    assert!(
        htui::layout::user_select_is_none(&arena, child),
        "auto resolves through the nearest explicit ancestor"
    );

    arena[child]
        .css_attr
        .0
        .insert("user-select".into(), "text".into());
    assert!(
        !htui::layout::user_select_is_none(&arena, child),
        "an explicit text descendant opts back into selection"
    );
}

#[test]
fn test_supported_properties_lists_known_names() {
    // The registry is the single source of truth for property names.
    assert!(SUPPORTED_PROPERTIES.contains(&"color"));
    assert!(SUPPORTED_PROPERTIES.contains(&"background-color"));
    assert!(SUPPORTED_PROPERTIES.contains(&"background"));
    assert!(SUPPORTED_PROPERTIES.contains(&"text-align"));
    assert!(SUPPORTED_PROPERTIES.contains(&"font-weight"));
    assert!(SUPPORTED_PROPERTIES.contains(&"font-style"));
    assert!(SUPPORTED_PROPERTIES.contains(&"text-decoration"));
    assert!(SUPPORTED_PROPERTIES.contains(&"width"));
    // Box-model longhands + shorthands.
    assert!(SUPPORTED_PROPERTIES.contains(&"padding"));
    assert!(SUPPORTED_PROPERTIES.contains(&"padding-top"));
    assert!(SUPPORTED_PROPERTIES.contains(&"margin"));
    assert!(SUPPORTED_PROPERTIES.contains(&"margin-left"));
    assert!(SUPPORTED_PROPERTIES.contains(&"border"));
    assert!(SUPPORTED_PROPERTIES.contains(&"border-top"));
    assert!(SUPPORTED_PROPERTIES.contains(&"border-width"));
    assert!(SUPPORTED_PROPERTIES.contains(&"border-style"));
    assert!(SUPPORTED_PROPERTIES.contains(&"border-color"));
    // Visibility / overflow (overflow keeps the renderer's default clip).
    assert!(SUPPORTED_PROPERTIES.contains(&"visibility"));
    assert!(SUPPORTED_PROPERTIES.contains(&"overflow"));
}

#[test]
fn visibility_is_supported_and_inheritable() {
    init();
    assert!(SUPPORTED_PROPERTIES.contains(&"visibility"));
    assert!(INHERITED_PROPS.contains(&"visibility"));
}

#[test]
fn overflow_hidden_is_parsed_and_kept_by_the_cascade() {
    init();
    // `overflow` is a supported property: the declaration survives the
    // cascade (the renderer's default already clips a box's static children
    // to its content area, so `overflow: hidden` matches that behaviour).
    let mut arena = NodeArena::default();
    let (root, div) = build_test(&mut arena);
    let css = Parser::new("div { overflow: hidden }").parse();
    css_into_node(&mut arena, root, &css);
    assert_eq!(
        arena[div].css_attr.0.get("overflow").map(|s| s.as_ref()),
        Some("hidden"),
        "overflow: hidden must survive the cascade"
    );
}

#[test]
fn test_inherited_props_is_a_subset_of_supported() {
    for p in INHERITED_PROPS {
        assert!(
            SUPPORTED_PROPERTIES.contains(p),
            "{p} is in INHERITED_PROPS but missing from SUPPORTED_PROPERTIES"
        );
    }
}

#[test]
fn test_inherited_props_contains_visual_inheritable_set() {
    // The set is curated by hand, so guard against accidental removal of
    // the five classic inheritable CSS properties.
    assert!(INHERITED_PROPS.contains(&"color"));
    assert!(INHERITED_PROPS.contains(&"text-align"));
    assert!(INHERITED_PROPS.contains(&"font-weight"));
    assert!(INHERITED_PROPS.contains(&"font-style"));
    assert!(INHERITED_PROPS.contains(&"text-decoration"));
    // Properties that should NOT inherit (negative set).
    assert!(!INHERITED_PROPS.contains(&"background-color"));
    assert!(!INHERITED_PROPS.contains(&"background"));
    assert!(!INHERITED_PROPS.contains(&"width"));
}

#[test]
fn test_important_marker_is_stripped_from_value() {
    let m = parse_declaration_text("color: red !important;");
    assert_eq!(m.get("color").map(|s| s.as_ref()), Some("red"));
}

#[test]
fn test_important_marker_with_space_is_not_recognised() {
    let m = parse_declaration_text("font-weight: bold ! important;");
    // CSS requires `!important` with no space; `! important` is invalid.
    // cssparser tokenises the `!` as an unknown token at declaration value
    // level, drops it, and parses the rest as the value. We end up storing
    // `bold` (without a false !important signal). What we assert here is
    // that we do NOT silently accept it as important.
    let val = m.get("font-weight").map(|s| s.as_ref());
    assert_eq!(val, Some("bold"));
    assert!(
        !val.unwrap().contains("!important"),
        "must not smuggle the bogus `! important` into the value"
    );
}

#[test]
fn test_important_marker_with_leading_space_is_kept_out_of_value() {
    let m = parse_declaration_text("font-style: italic  !important ;");
    assert_eq!(m.get("font-style").map(|s| s.as_ref()), Some("italic"));
}

#[test]
fn test_block_comment_is_stripped() {
    let m = parse_declaration_text("/* color: ignored */ color: red;");
    assert_eq!(m.get("color").map(|s| s.as_ref()), Some("red"));
    assert_eq!(m.len(), 1, "commented-out decl must not appear as a key");
}

#[test]
fn test_block_comment_inside_string_is_preserved() {
    // cssparser tracks string-literal state, so a `/* */` token inside
    // `"..."` is part of the value and survives parsing intact. (Before
    // the cssparser-based rewrite, the comment was textually stripped,
    // corrupting quoted strings.)
    let m = parse_declaration_text("content: \"a /* b */ c\";");
    assert_eq!(
        m.get("content").map(|s| s.as_ref()),
        Some("\"a /* b */ c\"")
    );
}

#[test]
fn test_unterminated_comment_truncates_input() {
    // Defensive: malformed CSS should not panic and should not leak the
    // comment text into a property key.
    let m = parse_declaration_text("color: red; /* oops");
    assert_eq!(m.get("color").map(|s| s.as_ref()), Some("red"));
}

#[test]
fn test_missing_trailing_semicolon_is_ok() {
    let m = parse_declaration_text("color: blue");
    assert_eq!(m.get("color").map(|s| s.as_ref()), Some("blue"));
}

// ============================================================
// Cascade rewrite: specificity ordering, `!important` and inline style
// ============================================================

#[test]
fn test_parse_splits_important_declarations() {
    init();
    // The stylesheet parser records `!important` per property: normal and
    // important declarations end up in separate bags on the rule entry.
    let css = Parser::new("p { color: red !important; width: 10px }").parse();
    assert_eq!(css.0.len(), 1);
    let entry = &css.0[0];
    assert_eq!(
        entry.normal.0.get("width").map(|s| s.as_ref()),
        Some("10px")
    );
    assert!(entry.normal.0.get("color").is_none());
    assert_eq!(
        entry.important.0.get("color").map(|s| s.as_ref()),
        Some("red")
    );
    assert!(entry.important.0.get("width").is_none());
}

#[test]
fn test_cascade_specificity_units() {
    init();
    let spec = |s: &str| s.parse::<CssSelector>().unwrap().specificity();
    assert_eq!(spec("p"), (0, 0, 1));
    assert_eq!(spec(".a"), (0, 1, 0));
    assert_eq!(spec("#i"), (1, 0, 0));
    assert_eq!(spec("div p span"), (0, 0, 3));
    assert_eq!(spec(".a .b"), (0, 2, 0));
    assert_eq!(spec("div.active"), (0, 1, 1));
    assert_eq!(spec("p:hover"), (0, 1, 1));
    assert_eq!(spec("li:nth-child(2)"), (0, 1, 1));
    assert_eq!(spec("div > p + span"), (0, 0, 3));
}

#[test]
fn test_cascade_specificity_wins_regardless_of_order() {
    init();
    // `div p` (0,0,2) must beat `p` (0,0,1) no matter the source order.
    for css_text in [
        "div p { color: red } p { color: blue }",
        "p { color: blue } div p { color: red }",
    ] {
        let mut arena = NodeArena::default();
        let (root, div_id) = build_test(&mut arena);
        let p_id = arena[div_id].children[0];
        let css = Parser::new(css_text).parse();
        css_into_node(&mut arena, root, &css);
        assert_eq!(
            arena[p_id].css_attr.get_color(),
            Some(Color::Rgb {
                r: 0xFF,
                g: 0x00,
                b: 0x00
            }),
            "css: {css_text}"
        );
    }
}

#[test]
fn test_cascade_important_beats_normal() {
    init();
    // `!important` beats normal regardless of source order.
    for css_text in [
        "p { color: blue } p { color: red !important }",
        "p { color: red !important } p { color: blue }",
    ] {
        let mut arena = NodeArena::default();
        let (root, div_id) = build_test(&mut arena);
        let p_id = arena[div_id].children[0];
        let css = Parser::new(css_text).parse();
        css_into_node(&mut arena, root, &css);
        assert_eq!(
            arena[p_id].css_attr.get_color(),
            Some(Color::Rgb {
                r: 0xFF,
                g: 0x00,
                b: 0x00
            }),
            "css: {css_text}"
        );
    }
}

#[test]
fn test_cascade_important_beats_higher_specificity_normal() {
    init();
    // `!important` outranks specificity: `p { … !important }` beats
    // `.b { … }` even though the class selector is more specific.
    let mut arena = NodeArena::default();
    let (root, p_id) = build_p_with_classes(&mut arena);
    let css = Parser::new("p { color: red !important } .b { color: blue }").parse();
    css_into_node(&mut arena, root, &css);
    assert_eq!(
        arena[p_id].css_attr.get_color(),
        Some(Color::Rgb {
            r: 0xFF,
            g: 0x00,
            b: 0x00
        })
    );
}

#[test]
fn test_cascade_inline_style_beats_stylesheet_normal() {
    init();
    let mut arena = NodeArena::default();
    let (root, div_id) = build_test(&mut arena);
    let p_id = arena[div_id].children[0];
    arena[p_id]
        .attributes
        .insert("style".to_string(), "color: blue".to_string());
    let css = Parser::new("p { color: red }").parse();
    css_into_node(&mut arena, root, &css);
    assert_eq!(
        arena[p_id].css_attr.get_color(),
        Some(Color::Rgb {
            r: 0x00,
            g: 0x00,
            b: 0xFF
        })
    );
}

#[test]
fn test_cascade_important_precedence_with_inline_style() {
    init();
    // Stylesheet `!important` beats inline normal declarations.
    let mut arena = NodeArena::default();
    let (root, div_id) = build_test(&mut arena);
    let p_id = arena[div_id].children[0];
    arena[p_id]
        .attributes
        .insert("style".to_string(), "color: blue".to_string());
    let css = Parser::new("p { color: red !important }").parse();
    css_into_node(&mut arena, root, &css);
    assert_eq!(
        arena[p_id].css_attr.get_color(),
        Some(Color::Rgb {
            r: 0xFF,
            g: 0x00,
            b: 0x00
        })
    );

    // Inline `!important` beats stylesheet `!important`.
    let mut arena2 = NodeArena::default();
    let (root2, div2) = build_test(&mut arena2);
    let p2 = arena2[div2].children[0];
    arena2[p2]
        .attributes
        .insert("style".to_string(), "color: blue !important".to_string());
    let css2 = Parser::new("p { color: red !important }").parse();
    css_into_node(&mut arena2, root2, &css2);
    assert_eq!(
        arena2[p2].css_attr.get_color(),
        Some(Color::Rgb {
            r: 0x00,
            g: 0x00,
            b: 0xFF
        })
    );
}

#[test]
fn test_cascade_same_specificity_later_source_wins() {
    init();
    // `.a` appears before and after `.b` at equal specificity; the last
    // declaration in source order wins (green).
    let mut arena = NodeArena::default();
    let (root, p_id) = build_p_with_classes(&mut arena);
    let css = Parser::new(".a { color: red } .b { color: blue } .a { color: green }").parse();
    css_into_node(&mut arena, root, &css);
    assert_eq!(
        arena[p_id].css_attr.get_color(),
        Some(Color::Rgb {
            r: 0x00,
            g: 0x80,
            b: 0x00
        })
    );
}

#[test]
fn test_background_color_does_not_inherit() {
    // End-to-end: even though `background-color` is in SUPPORTED_PROPERTIES,
    // it must NOT propagate from parent to child. Set it on the parent and
    // verify the child does not pick it up.
    init();
    let mut arena = NodeArena::default();
    let (root, _) = build_test(&mut arena);
    let mut css = CssRule::new();
    let sel: CssSelector = "div".parse().unwrap();
    let mut m = IndexMap::new();
    m.insert("background-color".into(), "yellow".into());
    css.add(sel, CssAttr::from(m));
    css_into_node(&mut arena, root, &css);

    let div_id = arena[root].children[0];
    let p_id = arena[div_id].children[0];
    assert_eq!(
        arena[div_id].css_attr.get_bg_color(),
        Some(Color::Rgb {
            r: 0xFF,
            g: 0xFF,
            b: 0x00
        }),
        "div should have its own bg"
    );
    assert_eq!(
        arena[p_id].css_attr.get_bg_color(),
        None,
        "non-inheritable property must not leak to descendant"
    );
}

#[test]
fn test_color_does_inherit() {
    // Symmetric counterpart to the above — color IS inheritable and the
    // grandchild <p> must pick up the div's color.
    init();
    let mut arena = NodeArena::default();
    let (root, _) = build_test(&mut arena);
    let mut css = CssRule::new();
    let sel: CssSelector = "div".parse().unwrap();
    let mut m = IndexMap::new();
    m.insert("color".into(), "red".into());
    css.add(sel, CssAttr::from(m));
    css_into_node(&mut arena, root, &css);

    let div_id = arena[root].children[0];
    let p_id = arena[div_id].children[0];
    assert_eq!(
        arena[div_id].css_attr.get_color(),
        Some(Color::Rgb {
            r: 0xFF,
            g: 0x00,
            b: 0x00
        })
    );
    assert_eq!(
        arena[p_id].css_attr.get_color(),
        Some(Color::Rgb {
            r: 0xFF,
            g: 0x00,
            b: 0x00
        }),
        "inheritable property must propagate to descendant"
    );
}

#[test]
fn test_full_parse_pipeline_handles_important_and_comments() {
    // Pins !important stripping + comment removal at the call sites used
    // by the rest of the codebase (Parser::parse + apply_css_rule).
    init();
    let mut parser = Parser::new(
        "/* heading style */
\
         h1 { color: red !important; font-weight: bold; }
\
         h2 { /* nothing */ font-style: italic; }",
    );
    let _rules = parser.parse();

    let mut arena = NodeArena::default();
    let root = arena.insert(Node::from(NodeType::Document));
    let h1 = arena.insert(Node::from(NodeType::H1));
    Node::append_child(&mut arena, root, h1);

    let mut css = CssRule::new();
    let sel_h1: CssSelector = "h1".parse().unwrap();
    let mut decls = IndexMap::new();
    decls.insert("color".into(), "red".into());
    decls.insert("font-weight".into(), "bold".into());
    css.add(sel_h1, CssAttr::from(decls));
    css_into_node(&mut arena, root, &css);

    assert_eq!(
        arena[h1].css_attr.get_color(),
        Some(Color::Rgb {
            r: 0xFF,
            g: 0x00,
            b: 0x00
        })
    );
    assert_eq!(arena[h1].css_attr.get_font_weight(), FontWeight::Bold);
}

// =====================================================================
// Length value type tests
// =====================================================================

#[test]
fn length_parse_auto() {
    init();
    assert_eq!(Length::parse("auto"), Some(Length::Auto));
    assert_eq!(Length::parse("AUTO"), Some(Length::Auto));
    assert_eq!(Length::parse("Auto"), Some(Length::Auto));
    assert_eq!(Length::parse("  auto  "), Some(Length::Auto));
}

#[test]
fn length_parse_cells_px() {
    init();
    // `px` is now kept as a distinct `Px` variant and resolves through
    // `Length::resolve` instead of being collapsed at parse time. The browser
    // pipeline treats `px` as an absolute unit and only normalises to cells
    // at resolution; we mirror that.
    assert_eq!(Length::parse("40px"), Some(Length::Px(40.0)));
    assert_eq!(Length::parse("  40px  "), Some(Length::Px(40.0)));
    // Case-insensitive unit.
    assert_eq!(Length::parse("20Px"), Some(Length::Px(20.0)));
    assert_eq!(Length::parse("30PX"), Some(Length::Px(30.0)));
    // Trailing whitespace tolerated.
    assert_eq!(
        Length::parse(
            "20px
"
        ),
        Some(Length::Px(20.0))
    );
}

#[test]
fn px_per_cell_constant_anchors_px_to_browser_scale() {
    // Browser-scale px semantics: one terminal cell is 8 CSS px (a monospace
    // glyph is 0.5em wide at the 16px default font-size). px lengths divide
    // by this at resolution; this is the single edit-point for any future
    // DPI mode (e.g. 2x retina = 16.0).
    assert_eq!(PX_PER_CELL, 8.0);
}

#[test]
fn length_parse_cells_px_fractional_rounds_half_away_from_zero() {
    init();
    // `parse` stores the raw f32 multiplier; the rounding to integer cells
    // happens inside `Length::resolve` (which mirrors the browser's
    // "rendered pixel" step). We use round-half-away-from-zero (Rust's
    // f32::round), not banker's rounding, because terminals need a stable,
    // monotonic mapping. These edge cases pin the standardized behavior.
    assert_eq!(Length::parse("0.4px"), Some(Length::Px(0.4)));
    assert_eq!(Length::parse("0.5px"), Some(Length::Px(0.5)));
    assert_eq!(Length::parse("0.6px"), Some(Length::Px(0.6)));
    assert_eq!(Length::parse("1.5px"), Some(Length::Px(1.5)));
    assert_eq!(Length::parse("2.5px"), Some(Length::Px(2.5)));
    assert_eq!(Length::parse("100.4px"), Some(Length::Px(100.4)));
}

#[test]
fn length_parse_cells_px_zero_and_integer_exact() {
    init();
    // 0px must parse to Px(0), not None -- otherwise zero-sized boxes would
    // silently fall through to the containing block width.
    assert_eq!(Length::parse("0px"), Some(Length::Px(0.0)));
    assert_eq!(Length::parse("1px"), Some(Length::Px(1.0)));
    assert_eq!(Length::parse("1000px"), Some(Length::Px(1000.0)));
}

#[test]
fn length_parse_cells_px_divide_matches_browser_scale() {
    // `Length::Px(n).resolve(...)` divides by PX_PER_CELL (8px per cell) and
    // rounds, mirroring a browser rendered on a character grid: `parse`
    // keeps the raw px multiplier; resolve applies the ratio. This test pins
    // the division so any future change to the constant forces a deliberate
    // update here.
    init();
    assert_eq!(
        (40.0_f32 / PX_PER_CELL).round() as usize,
        Length::parse("40px")
            .unwrap()
            .resolve(length_ctx(80, default_font_ctx()))
    );
}

#[test]
fn length_parse_cells_bare_number() {
    init();
    // Bare integers and floats parse as `Px`; CSS treats a unitless number
    // as px, so `Length::resolve` divides by PX_PER_CELL. `parse` preserves
    // the raw f32 value; rounding happens inside `Length::resolve`.
    assert_eq!(Length::parse("40"), Some(Length::Px(40.0)));
    assert_eq!(Length::parse("0"), Some(Length::Px(0.0)));
    assert_eq!(Length::parse("1.5"), Some(Length::Px(1.5)));
    assert_eq!(Length::parse("0.5"), Some(Length::Px(0.5)));
}

#[test]
fn length_parse_pct() {
    init();
    // Integer percentages round-trip through f32 exactly; non-integer
    // percentages (e.g. 33.33%) inherit f32 rounding error from the
    // tokenizer. The resolve tests below cover fractional percentages.
    assert_eq!(Length::parse("50%"), Some(Length::Pct(50.0)));
    assert_eq!(Length::parse("33%"), Some(Length::Pct(33.0)));
    assert_eq!(Length::parse("0%"), Some(Length::Pct(0.0)));
    assert_eq!(Length::parse("100%"), Some(Length::Pct(100.0)));
}

#[test]
fn length_parse_em_rem() {
    init();
    assert_eq!(Length::parse("2em"), Some(Length::Em(2.0)));
    assert_eq!(Length::parse("1.5em"), Some(Length::Em(1.5)));
    assert_eq!(Length::parse("2REM"), Some(Length::Rem(2.0)));
    assert_eq!(Length::parse("0.5rem"), Some(Length::Rem(0.5)));
}

#[test]
fn length_parse_vw_vh() {
    init();
    // 1vw = viewport_cols / 100, 1vh = viewport_rows / 100.
    // The parser only stores the raw multiplier; the viewport is supplied
    // at `Length::resolve` time.
    assert_eq!(Length::parse("50vw"), Some(Length::Vw(50.0)));
    assert_eq!(Length::parse("50vh"), Some(Length::Vh(50.0)));
    assert_eq!(Length::parse("100VW"), Some(Length::Vw(100.0)));
    assert_eq!(Length::parse("12.5vh"), Some(Length::Vh(12.5)));
}

#[test]
fn length_parse_ch() {
    init();
    // `ch` is the CSS character-width unit: 1ch == the advance width of the
    // `0` glyph, which is exactly one cell on a terminal's monospace grid.
    // Unlike `em`, `ch` measures characters, so widths stay aligned with
    // character counts regardless of font-size.
    assert_eq!(Length::parse("12ch"), Some(Length::Ch(12.0)));
    assert_eq!(Length::parse("1.5ch"), Some(Length::Ch(1.5)));
    assert_eq!(Length::parse("8CH"), Some(Length::Ch(8.0)));
    assert_eq!(Length::parse(" 4ch  "), Some(Length::Ch(4.0)));
}

#[test]
fn length_parse_rejects_unsupported_units() {
    init();
    // vmin / vmax not yet wired through (see doc/layout.md 10.6).
    assert_eq!(Length::parse("50vmin"), None);
    assert_eq!(Length::parse("50vmax"), None);
    // Physical units — no DPI.
    assert_eq!(Length::parse("12pt"), None);
    assert_eq!(Length::parse("5cm"), None);
    assert_eq!(Length::parse("5mm"), None);
    assert_eq!(Length::parse("1in"), None);
    assert_eq!(Length::parse("1pc"), None);
}

#[test]
fn length_parse_rejects_signed_and_junk() {
    init();
    assert_eq!(Length::parse("-10px"), None);
    assert_eq!(Length::parse("+10px"), None);
    assert_eq!(Length::parse(""), None);
    assert_eq!(Length::parse("   "), None);
    // CSS forbids whitespace between number and unit (Number then Ident).
    assert_eq!(Length::parse("40 px"), None);
    assert_eq!(Length::parse("40 PX"), None);
    // Trailing junk after a valid value.
    assert_eq!(Length::parse("40px garbage"), None);
    // Bare garbage.
    assert_eq!(Length::parse("hello"), None);
    assert_eq!(Length::parse("!important"), None);
}

#[test]
fn length_resolve_auto_and_cells() {
    init();
    assert_eq!(Length::Auto.resolve(length_ctx(80, default_font_ctx())), 80);
    // A bare number is px per CSS, so it divides by PX_PER_CELL like `px`:
    // 40 -> 5 cells at 8px/cell.
    assert_eq!(
        Length::Px(40.0).resolve(length_ctx(80, default_font_ctx())),
        5
    );
    assert_eq!(
        Length::Px(0.0).resolve(length_ctx(80, default_font_ctx())),
        0
    ); // caller clamps via resolve_block_width
    assert_eq!(
        Length::Px(1000.0).resolve(length_ctx(80, default_font_ctx())),
        125
    ); // ditto
}

#[test]
fn length_resolve_pct_rounds_and_min_1() {
    init();
    assert_eq!(
        Length::Pct(50.0).resolve(length_ctx(80, default_font_ctx())),
        40
    );
    assert_eq!(
        Length::Pct(100.0).resolve(length_ctx(80, default_font_ctx())),
        80
    );
    // round(), not truncate: 80 * 33 / 100 = 26.4 → 26.
    assert_eq!(
        Length::Pct(33.0).resolve(length_ctx(80, default_font_ctx())),
        26
    );
    // Half-percent boundary: 80 * 50.5 / 100 = 40.4 → 40 (round).
    assert_eq!(
        Length::Pct(50.5).resolve(length_ctx(80, default_font_ctx())),
        40
    );
    // 80 * 50.6 / 100 = 40.48 → 40 (round).
    assert_eq!(
        Length::Pct(50.6).resolve(length_ctx(80, default_font_ctx())),
        40
    );
    // Minimum 1 column: a non-zero percentage of zero yields 1, not 0.
    assert_eq!(
        Length::Pct(50.0).resolve(length_ctx(0, default_font_ctx())),
        1
    );
    assert_eq!(
        Length::Pct(0.0).resolve(length_ctx(80, default_font_ctx())),
        1
    ); // min-1 even at 0%
}

#[test]
fn length_resolve_em_rem_rounds_away_from_zero() {
    init();
    // With the default font-size / root-font-size of 1, em and rem collapse
    // to `n.round()`, so the existing round-away-from-zero behaviour holds.
    assert_eq!(
        Length::Em(2.0).resolve(length_ctx(80, default_font_ctx())),
        2
    );
    assert_eq!(
        Length::Em(1.5).resolve(length_ctx(80, default_font_ctx())),
        2
    ); // 1.5 rounds away → 2
    assert_eq!(
        Length::Em(0.5).resolve(length_ctx(80, default_font_ctx())),
        1
    ); // 0.5 rounds away → 1
    assert_eq!(
        Length::Em(2.5).resolve(length_ctx(80, default_font_ctx())),
        3
    ); // 2.5 rounds away → 3
    assert_eq!(
        Length::Rem(1.5).resolve(length_ctx(80, default_font_ctx())),
        2
    );
    assert_eq!(
        Length::Rem(0.0).resolve(length_ctx(80, default_font_ctx())),
        0
    );
}

#[test]
fn length_resolve_em_scales_with_font_size() {
    init();
    // em resolves against the element's font-size: 2em at font-size=2
    // yields 4 cells, 1.5em at font-size=3 yields 5 cells (round away).
    assert_eq!(Length::Em(2.0).resolve(length_ctx(80, font_ctx(2, 1))), 4);
    assert_eq!(Length::Em(1.5).resolve(length_ctx(80, font_ctx(3, 1))), 5);
    assert_eq!(Length::Em(0.5).resolve(length_ctx(80, font_ctx(2, 1))), 1);
}

#[test]
fn length_resolve_rem_scales_with_root_font_size() {
    init();
    // rem ignores the element's font-size and uses the root font-size: 2rem
    // at root font-size=3 yields 6 cells, regardless of the element's size.
    assert_eq!(Length::Rem(2.0).resolve(length_ctx(80, font_ctx(1, 3))), 6);
    assert_eq!(Length::Rem(1.5).resolve(length_ctx(80, font_ctx(2, 4))), 6);
    assert_eq!(Length::Rem(0.0).resolve(length_ctx(80, font_ctx(5, 5))), 0);
}

#[test]
fn length_resolve_ch_is_font_size_independent() {
    init();
    // 1ch == 1 cell no matter the effective font-size — unlike `em`, `ch`
    // counts characters, and a terminal cell *is* a character. Rounding
    // follows the same away-from-zero rule as the other multipliers.
    assert_eq!(
        Length::Ch(12.0).resolve(length_ctx(80, default_font_ctx())),
        12
    );
    assert_eq!(Length::Ch(1.5).resolve(length_ctx(80, font_ctx(2, 1))), 2); // 1.5 rounds away
    assert_eq!(Length::Ch(0.4).resolve(length_ctx(80, font_ctx(3, 2))), 0);
}

#[test]
fn length_resolve_vw_vh_anchor_to_viewport() {
    init();
    // 1vw = viewport_cols / 100, 1vh = viewport_rows / 100.
    // `containing` is intentionally a different number to prove `vw` does
    // NOT anchor to the containing block — it always uses the viewport.
    assert_eq!(Length::Vw(50.0).resolve(length_ctx(80, font_ctx(1, 1))), 40); // 50 * 80 / 100
    assert_eq!(
        Length::Vw(100.0).resolve(length_ctx(80, font_ctx(1, 1))),
        80
    );
    assert_eq!(
        Length::Vw(50.0).resolve(length_ctx(999, font_ctx(1, 1))),
        40
    ); // containing irrelevant
    assert_eq!(Length::Vh(50.0).resolve(length_ctx(80, font_ctx(1, 1))), 12); // 50 * 24 / 100
    assert_eq!(
        Length::Vh(100.0).resolve(length_ctx(80, font_ctx(1, 1))),
        24
    );
    // Rounding: 33.3 * 80 / 100 = 26.64 → 27.
    assert_eq!(Length::Vw(33.3).resolve(length_ctx(80, font_ctx(1, 1))), 27);
    // Min-1 clamp: 0.5vw at viewport_cols=80 → 0.4 → 1.
    assert_eq!(Length::Vw(0.5).resolve(length_ctx(80, font_ctx(1, 1))), 1);
}

#[test]
fn css_attr_get_width_end_to_end() {
    init();
    // Mirrors the existing `width: ...` semantics: `auto` / missing /
    // unsupported returns None (caller fills the container); everything
    // else resolves into a concrete column count.
    let mut attr = CssAttr::new();
    let mut decls = IndexMap::new();
    decls.insert("width".into(), "auto".into());
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_width(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        None
    );

    let mut attr = CssAttr::new();
    let mut decls = IndexMap::new();
    decls.insert("width".into(), "40ch".into());
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_width(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        Some(40)
    );

    let mut attr = CssAttr::new();
    let mut decls = IndexMap::new();
    decls.insert("width".into(), "50%".into());
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_width(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        Some(40)
    );

    let mut attr = CssAttr::new();
    let mut decls = IndexMap::new();
    decls.insert("width".into(), "2em".into());
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_width(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        Some(2)
    );

    let mut attr = CssAttr::new();
    let mut decls = IndexMap::new();
    decls.insert("width".into(), "1.5em".into());
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_width(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        Some(2)
    ); // 1.5 rounds away

    let mut attr = CssAttr::new();
    let mut decls = IndexMap::new();
    decls.insert("width".into(), "2rem".into());
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_width(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        Some(2)
    );

    // 50vw anchors to viewport_cols (80 cols here) → 50 * 80 / 100 = 40.
    let mut attr = CssAttr::new();
    let mut decls = IndexMap::new();
    decls.insert("width".into(), "50vw".into());
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_width(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        Some(40)
    );

    // 50vh anchors to viewport_rows (24 rows here) → 50 * 24 / 100 = 12.
    let mut attr = CssAttr::new();
    let mut decls = IndexMap::new();
    decls.insert("width".into(), "50vh".into());
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_width(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        Some(12)
    );

    // Missing property → None.
    assert_eq!(
        CssAttr::new().get_width(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        None
    );
}

// ============================================================
// Box-model: padding / margin / border parsing
// ============================================================

fn attr_from_decl(name: &str, value: &str) -> CssAttr {
    let mut decls = IndexMap::new();
    decls.insert(name.into(), value.into());
    let mut attr = CssAttr::new();
    attr.add(&CssAttr::from(decls));
    attr
}

#[test]
fn padding_shorthand_one_value_fills_all_sides() {
    let attr = attr_from_decl("padding", "5ch");
    let edges = attr.get_padding(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(edges, EdgeSizes::new(5, 5, 5, 5));
}

#[test]
fn padding_shorthand_two_values_vertical_horizontal() {
    // `padding: 10ch 20ch;` → top/bottom = 10, left/right = 20
    let attr = attr_from_decl("padding", "10ch 20ch");
    assert_eq!(
        attr.get_padding(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        EdgeSizes::new(10, 20, 10, 20)
    );
}

#[test]
fn padding_shorthand_three_values_top_horizontal_bottom() {
    // `padding: 1ch 2ch 3ch;` → top=1, left/right=2, bottom=3
    let attr = attr_from_decl("padding", "1ch 2ch 3ch");
    assert_eq!(
        attr.get_padding(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        EdgeSizes::new(1, 2, 3, 2)
    );
}

#[test]
fn padding_shorthand_four_values_clockwise() {
    // `padding: 1ch 2ch 3ch 4ch;` → top=1, right=2, bottom=3, left=4
    let attr = attr_from_decl("padding", "1ch 2ch 3ch 4ch");
    assert_eq!(
        attr.get_padding(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        EdgeSizes::new(1, 2, 3, 4)
    );
}

#[test]
fn padding_longhands_override_shorthand() {
    // `padding: 0; padding-top: 7ch;` → top=7, others=0
    let mut decls = IndexMap::new();
    decls.insert("padding".into(), "0".into());
    decls.insert("padding-top".into(), "7ch".into());
    let mut attr = CssAttr::new();
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_padding(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        EdgeSizes::new(7, 0, 0, 0)
    );
}

#[test]
fn padding_supports_percent_and_em() {
    let attr = attr_from_decl("padding", "50%");
    assert_eq!(
        attr.get_padding(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        )
        .left,
        40
    );
    let attr = attr_from_decl("padding-top", "3em");
    assert_eq!(
        attr.get_padding(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        )
        .top,
        3
    );
}

#[test]
fn margin_shorthand_mirrors_padding() {
    let attr = attr_from_decl("margin", "2ch 4ch");
    assert_eq!(
        attr.get_margin(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        MarginSizes::new(2, 4, 2, 4)
    );
    let attr = attr_from_decl("margin-left", "6ch");
    assert_eq!(
        attr.get_margin(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        MarginSizes::new(0, 0, 0, 6)
    );
}

#[test]
fn margin_auto_collapses_to_zero() {
    // Terminals don't honour `margin: auto`; we surface it as 0 so callers
    // don't need a special case.
    let attr = attr_from_decl("margin", "auto");
    assert_eq!(
        attr.get_margin(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport()
        ),
        MarginSizes::default()
    );
}

#[test]
fn border_shorthand_solid_parses_width_and_style() {
    let attr = attr_from_decl("border", "1ch solid red");
    let sides = attr.get_border(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(sides.top.width, 1);
    assert_eq!(sides.top.style, BorderStyle::Solid);
    assert_eq!(
        sides.top.color,
        Some(Color::Rgb {
            r: 0xFF,
            g: 0x00,
            b: 0x00
        })
    );
    assert_eq!(sides.right.width, 1);
    assert_eq!(sides.bottom.width, 1);
    assert_eq!(sides.left.width, 1);
}

#[test]
fn border_shorthand_parses_functional_colors() {
    // `border: 1ch solid rgb(255, 0, 0)` — the parenthesised color must stay
    // one token through the shorthand's whitespace split.
    let attr = attr_from_decl("border", "1ch solid rgb(255, 0, 0)");
    let sides = attr.get_border(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(
        sides.top.color,
        Some(Color::Rgb { r: 255, g: 0, b: 0 }),
        "comma-syntax rgb() must survive the border shorthand"
    );
    assert_eq!(sides.top.style, BorderStyle::Solid);

    // Space-syntax hsl() with internal spaces also works.
    let attr = attr_from_decl("border", "2ch solid hsl(120 100% 50%)");
    let sides = attr.get_border(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(
        sides.top.color,
        Some(Color::Rgb { r: 0, g: 255, b: 0 }),
        "space-syntax hsl() must survive the border shorthand"
    );
    assert_eq!(sides.top.width, 2);
}

#[test]
fn border_shorthand_style_alone_applies_to_all_sides() {
    let attr = attr_from_decl("border", "solid");
    let sides = attr.get_border(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(sides.top.style, BorderStyle::Solid);
    assert_eq!(sides.bottom.style, BorderStyle::Solid);
    assert_eq!(sides.left.style, BorderStyle::Solid);
    assert_eq!(sides.right.style, BorderStyle::Solid);
}

#[test]
fn border_longhand_overrides_universal_shorthand() {
    // `border: 1ch solid red; border-top: 3ch solid blue;` — top wins, others
    // come from the shorthand.
    let mut decls = IndexMap::new();
    decls.insert("border".into(), "1ch solid red".into());
    decls.insert("border-top".into(), "3ch solid blue".into());
    let mut attr = CssAttr::new();
    attr.add(&CssAttr::from(decls));
    let sides = attr.get_border(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(sides.top.width, 3);
    assert_eq!(
        sides.top.color,
        Some(Color::Rgb {
            r: 0x00,
            g: 0x00,
            b: 0xFF
        })
    );
    assert_eq!(sides.right.width, 1);
    assert_eq!(
        sides.right.color,
        Some(Color::Rgb {
            r: 0xFF,
            g: 0x00,
            b: 0x00
        })
    );
}

#[test]
fn border_universal_width_style_color_layers_correctly() {
    // `border-width: 2ch; border-style: solid; border-color: green;`
    // should produce a green 2ch border on every side.
    let mut decls = IndexMap::new();
    decls.insert("border-width".into(), "2ch".into());
    decls.insert("border-style".into(), "solid".into());
    decls.insert("border-color".into(), "green".into());
    let mut attr = CssAttr::new();
    attr.add(&CssAttr::from(decls));
    let sides = attr.get_border(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(sides.top.width, 2);
    assert_eq!(sides.top.style, BorderStyle::Solid);
    assert_eq!(
        sides.top.color,
        Some(Color::Rgb {
            r: 0x00,
            g: 0x80,
            b: 0x00
        })
    );
}

#[test]
fn border_style_none_hides_the_border() {
    let attr = attr_from_decl("border-style", "none");
    let sides = attr.get_border(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert!(!sides.any_visible());
}

#[test]
fn border_unknown_style_falls_back_to_solid() {
    // `dashed`, `dotted`, `double` etc. all render as solid in the terminal.
    for keyword in ["dashed", "dotted", "double", "groove"] {
        let attr = attr_from_decl("border", &format!("1ch {keyword} red"));
        let sides = attr.get_border(
            80,
            font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
            viewport(),
        );
        assert_eq!(
            sides.top.style,
            BorderStyle::Solid,
            "keyword {keyword} should fall back to solid"
        );
    }
}

#[test]
fn get_box_edges_returns_combined_padding_border_margin() {
    let mut decls = IndexMap::new();
    decls.insert("padding".into(), "2ch".into());
    decls.insert("margin".into(), "4ch".into());
    decls.insert("border".into(), "1ch solid red".into());
    let mut attr = CssAttr::new();
    attr.add(&CssAttr::from(decls));
    let edges = attr.get_box_edges(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(edges.padding.top, 2);
    assert_eq!(edges.margin.left, 4);
    assert_eq!(edges.border.top.width, 1);
    assert_eq!(edges.border.top.style, BorderStyle::Solid);
    assert_eq!(edges.inner_horizontal(), 6); // 2 + 2 + 1 + 1
}

// ============================================================
// font-size — em / rem resolve against the active font-size context.
// ============================================================

#[test]
fn font_size_parses_to_length() {
    init();
    // `font-size: 2em` → Length::Em(2.0); missing property → None.
    let attr = attr_from_decl("font-size", "2em");
    assert_eq!(attr.get_font_size(), Some(Length::Em(2.0)));
    let attr = attr_from_decl("font-size", "1.5rem");
    assert_eq!(attr.get_font_size(), Some(Length::Rem(1.5)));
    let attr = attr_from_decl("font-size", "16px");
    assert_eq!(attr.get_font_size(), Some(Length::Px(16.0)));
    let attr = attr_from_decl("font-size", "120%");
    assert_eq!(attr.get_font_size(), Some(Length::Pct(120.0)));
    assert_eq!(CssAttr::new().get_font_size(), None);
}

#[test]
fn font_size_property_is_supported_and_inheritable() {
    init();
    assert!(
        SUPPORTED_PROPERTIES.contains(&"font-size"),
        "font-size should be a supported CSS property"
    );
    assert!(
        INHERITED_PROPS.contains(&"font-size"),
        "font-size should inherit from the parent so nested spans keep the same em base"
    );
}

#[test]
fn padding_em_scales_with_element_font_size() {
    init();
    // `padding: 1em` on an element whose effective font-size is 2 should
    // resolve to 2 cells, not 1.
    let attr = attr_from_decl("padding", "1em");
    assert_eq!(attr.get_padding(80, font_ctx(2, 1), viewport()).top, 2);
    // Same property on an element with font-size 3 yields 3 cells.
    assert_eq!(attr.get_padding(80, font_ctx(3, 1), viewport()).top, 3);
    // On the default font-size of 1 it stays at 1.
    assert_eq!(attr.get_padding(80, font_ctx(1, 1), viewport()).top, 1);
}

#[test]
fn margin_rem_uses_root_font_size_not_element() {
    init();
    // rem ignores the element's font-size; it always resolves against the
    // root's font-size. So `margin: 2rem` is 6 cells regardless of the
    // element's own size.
    let attr = attr_from_decl("margin", "2rem");
    assert_eq!(attr.get_margin(80, font_ctx(1, 3), viewport()).top, 6);
    assert_eq!(attr.get_margin(80, font_ctx(5, 3), viewport()).top, 6);
    assert_eq!(attr.get_margin(80, font_ctx(1, 1), viewport()).top, 2);
}

// ============================================================
// text-transform
// ============================================================

#[test]
fn text_transform_parses_and_defaults_to_none() {
    init();
    let attr = attr_from_decl("text-transform", "uppercase");
    assert_eq!(attr.get_text_transform(), TextTransform::Uppercase);
    let attr = attr_from_decl("text-transform", "LOWERCASE");
    assert_eq!(attr.get_text_transform(), TextTransform::Lowercase);
    let attr = attr_from_decl("text-transform", "capitalize");
    assert_eq!(attr.get_text_transform(), TextTransform::Capitalize);
    // Unset / garbage -> none.
    assert_eq!(CssAttr::new().get_text_transform(), TextTransform::None);
    let attr = attr_from_decl("text-transform", "full-width");
    assert_eq!(attr.get_text_transform(), TextTransform::None);
}

#[test]
fn text_transform_is_supported_and_inheritable() {
    init();
    assert!(SUPPORTED_PROPERTIES.contains(&"text-transform"));
    assert!(INHERITED_PROPS.contains(&"text-transform"));
}

// ============================================================
// line-height
// ============================================================

#[test]
fn line_height_parses_normal_number_and_length() {
    init();
    let attr = attr_from_decl("line-height", "normal");
    assert_eq!(attr.get_line_height(), LineHeight::Normal);
    let attr = attr_from_decl("line-height", "1.5");
    assert_eq!(attr.get_line_height(), LineHeight::Number(1.5));
    let attr = attr_from_decl("line-height", "2em");
    assert_eq!(attr.get_line_height(), LineHeight::Length(Length::Em(2.0)));
    let attr = attr_from_decl("line-height", "150%");
    assert_eq!(
        attr.get_line_height(),
        LineHeight::Length(Length::Pct(150.0))
    );
    assert_eq!(CssAttr::new().get_line_height(), LineHeight::Normal);
}

#[test]
fn line_height_resolves_to_whole_rows() {
    init();
    // normal -> font size (1 row per cell).
    assert_eq!(
        resolve_line_height_cells(LineHeight::Normal, 1, default_font_ctx(), viewport()),
        1
    );
    // A unitless multiplier scales the font-size, rounding to whole rows.
    assert_eq!(
        resolve_line_height_cells(LineHeight::Number(1.5), 1, default_font_ctx(), viewport()),
        2
    );
    assert_eq!(
        resolve_line_height_cells(LineHeight::Number(2.0), 2, default_font_ctx(), viewport()),
        4
    );
    // em resolves against the element font-size.
    assert_eq!(
        resolve_line_height_cells(
            LineHeight::Length(Length::Em(1.0)),
            3,
            font_ctx(3, 1),
            viewport()
        ),
        3
    );
    // Percentage resolves against the font-size (not the containing block).
    assert_eq!(
        resolve_line_height_cells(
            LineHeight::Length(Length::Pct(150.0)),
            2,
            font_ctx(2, 1),
            viewport()
        ),
        3
    );
}

#[test]
fn line_height_is_supported_and_inheritable() {
    init();
    assert!(SUPPORTED_PROPERTIES.contains(&"line-height"));
    assert!(INHERITED_PROPS.contains(&"line-height"));
}

// ============================================================
// box-sizing
// ============================================================

#[test]
fn box_sizing_defaults_to_border_box_and_parses() {
    init();
    // Unset -> the engine's historical border-box model.
    assert_eq!(CssAttr::new().get_box_sizing(), BoxSizing::BorderBox);
    let attr = attr_from_decl("box-sizing", "content-box");
    assert_eq!(attr.get_box_sizing(), BoxSizing::ContentBox);
    let attr = attr_from_decl("box-sizing", "BORDER-BOX");
    assert_eq!(attr.get_box_sizing(), BoxSizing::BorderBox);
    // Garbage falls back to the default.
    let attr = attr_from_decl("box-sizing", "padding-box");
    assert_eq!(attr.get_box_sizing(), BoxSizing::BorderBox);
}

#[test]
fn box_sizing_is_supported() {
    init();
    assert!(SUPPORTED_PROPERTIES.contains(&"box-sizing"));
}

// ============================================================
// border-radius
// ============================================================

#[test]
fn border_radius_parses_one_to_four_values() {
    init();
    // One value -> every corner.
    let attr = attr_from_decl("border-radius", "2ch");
    let r = attr.get_border_radius(80, default_font_ctx(), viewport());
    assert_eq!(
        r,
        CornerRadii {
            top_left: 2,
            top_right: 2,
            bottom_right: 2,
            bottom_left: 2
        }
    );
    // Two values -> diagonal pairs.
    let attr = attr_from_decl("border-radius", "4ch 1ch");
    let r = attr.get_border_radius(80, default_font_ctx(), viewport());
    assert_eq!(
        r,
        CornerRadii {
            top_left: 4,
            top_right: 1,
            bottom_right: 4,
            bottom_left: 1
        }
    );
    // Four values -> clockwise order.
    let attr = attr_from_decl("border-radius", "1ch 2ch 3ch 4ch");
    let r = attr.get_border_radius(80, default_font_ctx(), viewport());
    assert_eq!(
        r,
        CornerRadii {
            top_left: 1,
            top_right: 2,
            bottom_right: 3,
            bottom_left: 4
        }
    );
    // Unset -> square corners.
    assert_eq!(
        CssAttr::new().get_border_radius(80, default_font_ctx(), viewport()),
        CornerRadii::default()
    );
}

#[test]
fn border_radius_is_supported() {
    init();
    assert!(SUPPORTED_PROPERTIES.contains(&"border-radius"));
}

#[test]
fn border_radius_corner_longhands_override_shorthand() {
    init();
    // `border-radius: 2ch` then `border-top-left-radius: 5ch` — the longhand
    // wins on that corner, the others keep the shorthand value.
    let mut decls = IndexMap::new();
    decls.insert("border-radius".into(), "2ch".into());
    decls.insert("border-top-left-radius".into(), "5ch".into());
    let mut attr = CssAttr::new();
    attr.add(&CssAttr::from(decls));
    assert_eq!(
        attr.get_border_radius(80, default_font_ctx(), viewport()),
        CornerRadii {
            top_left: 5,
            top_right: 2,
            bottom_right: 2,
            bottom_left: 2,
        }
    );
}

#[test]
fn border_radius_corner_longhand_alone() {
    init();
    // Only the longhand declared — the other corners stay square.
    let attr = attr_from_decl("border-top-right-radius", "3ch");
    assert_eq!(
        attr.get_border_radius(80, default_font_ctx(), viewport()),
        CornerRadii {
            top_left: 0,
            top_right: 3,
            bottom_right: 0,
            bottom_left: 0,
        }
    );
}

#[test]
fn border_radius_corner_longhands_are_supported() {
    init();
    for p in [
        "border-top-left-radius",
        "border-top-right-radius",
        "border-bottom-right-radius",
        "border-bottom-left-radius",
    ] {
        assert!(
            SUPPORTED_PROPERTIES.contains(&p),
            "{p} must be in SUPPORTED_PROPERTIES"
        );
    }
}

#[test]
fn border_side_component_longhand_overrides_side_shorthand() {
    init();
    // `border: 1px solid red; border-top: 3px solid blue; border-top-width:
    // 5px;` — the component longhand overrides just the width of the side
    // shorthand; style / color stay from `border-top`.
    let mut decls = IndexMap::new();
    decls.insert("border".into(), "1ch solid red".into());
    decls.insert("border-top".into(), "3ch solid blue".into());
    decls.insert("border-top-width".into(), "5ch".into());
    let mut attr = CssAttr::new();
    attr.add(&CssAttr::from(decls));
    let sides = attr.get_border(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(sides.top.width, 5, "component longhand wins the width");
    assert_eq!(sides.top.style, BorderStyle::Solid);
    assert_eq!(
        sides.top.color,
        Some(Color::Rgb { r: 0, g: 0, b: 255 }),
        "style/color come from the side shorthand"
    );
    // The other sides are untouched by the top longhand.
    assert_eq!(sides.right.width, 1);
}

#[test]
fn border_side_component_longhand_alone() {
    init();
    // Only `border-left-color` declared — width 0 / style none, color set.
    let attr = attr_from_decl("border-left-color", "green");
    let sides = attr.get_border(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(sides.left.width, 0);
    assert_eq!(sides.left.style, BorderStyle::None);
    assert_eq!(sides.left.color, Some(Color::Rgb { r: 0, g: 128, b: 0 }));
    assert_eq!(sides.top.color, None, "other sides unaffected");
}

#[test]
fn border_side_component_longhands_are_supported() {
    init();
    for side in ["top", "right", "bottom", "left"] {
        for prop in ["width", "style", "color"] {
            let name = format!("border-{side}-{prop}");
            assert!(
                SUPPORTED_PROPERTIES.contains(&name.as_str()),
                "{name} must be in SUPPORTED_PROPERTIES"
            );
        }
    }
}

#[test]
fn margin_auto_flags_parse_from_shorthand_and_longhand() {
    init();
    // `margin: 0 auto` -> left+right auto.
    let attr = attr_from_decl("margin", "0 auto");
    let auto = attr.get_margin_auto();
    assert!(!auto.top && !auto.bottom, "vertical auto stays false");
    assert!(auto.left && auto.right, "horizontal edges are auto");

    // Four-value shorthand: `margin: 1px auto 2px 3px` -> right auto.
    let attr = attr_from_decl("margin", "1px auto 2px 3px");
    let auto = attr.get_margin_auto();
    assert!(!auto.top && auto.right && !auto.bottom && !auto.left);

    // Single-value shorthand applies to all four edges.
    let attr = attr_from_decl("margin", "auto");
    let auto = attr.get_margin_auto();
    assert!(auto.top && auto.right && auto.bottom && auto.left);

    // Per-side longhand wins over the shorthand position.
    let mut decls = IndexMap::new();
    decls.insert("margin".into(), "auto".into());
    decls.insert("margin-right".into(), "5px".into());
    let mut attr = CssAttr::new();
    attr.add(&CssAttr::from(decls));
    let auto = attr.get_margin_auto();
    assert!(auto.left, "shorthand left stays auto");
    assert!(!auto.right, "longhand clears the right auto");

    // No margin declarations -> all false.
    assert_eq!(CssAttr::new().get_margin_auto(), EdgeAuto::default());
}

// ============================================================
// min-width / max-width / min-height / max-height
// ============================================================

#[test]
fn percentage_height_resolves_against_definite_containing_height_only() {
    init();
    // CSS 10.5: percentage heights resolve against the containing block's
    // *height*; with an indefinite containing height they compute to `auto`
    // — never against the width.
    let attr = attr_from_decl("height", "50%");
    assert_eq!(
        attr.get_height(Some(100), font_ctx(1, 1), viewport()),
        Some(50),
        "definite containing height: 50% of 100"
    );
    assert_eq!(
        attr.get_height(None, font_ctx(1, 1), viewport()),
        None,
        "indefinite containing height: percentage height is auto"
    );

    let mh = attr_from_decl("min-height", "25%");
    assert_eq!(
        mh.get_min_height(Some(200), font_ctx(1, 1), viewport()),
        Some(50)
    );
    assert_eq!(mh.get_min_height(None, font_ctx(1, 1), viewport()), None);
}

#[test]
fn min_max_size_getters_resolve_and_default_to_none() {
    init();
    let mut decls = IndexMap::new();
    decls.insert("min-width".into(), "10ch".into());
    decls.insert("max-width".into(), "40ch".into());
    decls.insert("min-height".into(), "3ch".into());
    decls.insert("max-height".into(), "none".into());
    let mut attr = CssAttr::new();
    attr.add(&CssAttr::from(decls));
    let f = default_font_ctx();
    assert_eq!(attr.get_min_width(80, f, viewport()), Some(10));
    assert_eq!(attr.get_max_width(80, f, viewport()), Some(40));
    assert_eq!(attr.get_min_height(Some(80), f, viewport()), Some(3));
    // `none` (and `auto`) mean "no constraint".
    assert_eq!(attr.get_max_height(Some(80), f, viewport()), None);
    let attr = attr_from_decl("min-width", "auto");
    assert_eq!(attr.get_min_width(80, f, viewport()), None);
    // Unset properties -> None.
    assert_eq!(CssAttr::new().get_min_width(80, f, viewport()), None);
    assert_eq!(CssAttr::new().get_max_width(80, f, viewport()), None);
    assert_eq!(CssAttr::new().get_min_height(Some(80), f, viewport()), None);
    assert_eq!(CssAttr::new().get_max_height(Some(80), f, viewport()), None);
}

#[test]
fn min_max_size_properties_are_supported_not_inherited() {
    init();
    assert!(SUPPORTED_PROPERTIES.contains(&"min-width"));
    assert!(SUPPORTED_PROPERTIES.contains(&"max-width"));
    assert!(SUPPORTED_PROPERTIES.contains(&"min-height"));
    assert!(SUPPORTED_PROPERTIES.contains(&"max-height"));
    // Sizes do not inherit in CSS.
    assert!(!INHERITED_PROPS.contains(&"min-width"));
    assert!(!INHERITED_PROPS.contains(&"max-height"));
}

/// Test-only oracle: the pre-optimization cascade (per-rule full-tree walks,
/// per-call specificity sort, per-node inherited-map clones). `style`
/// attributes are not modelled (the inline declaration parser is
/// crate-private); documents compared against it must not use inline styles
/// (`cascade_inline_style_precedence_unchanged` covers those separately).
fn ref_apply_rule(
    arena: &mut NodeArena,
    node_id: NodeId,
    selector: &CssSelector,
    decls: &CssAttr,
    state: &DynamicState,
) {
    if selector_chain_matches_with_state(arena, node_id, selector, state) {
        arena[node_id].css_attr.add(decls);
    }
    let children: Vec<NodeId> = arena[node_id].children.clone();
    for child in children {
        ref_apply_rule(arena, child, selector, decls, state);
    }
}

fn ref_inherit(arena: &mut NodeArena, node_id: NodeId, parent: &IndexMap<Arc<str>, Arc<str>>) {
    {
        let node = &mut arena[node_id];
        for key in INHERITED_PROPS {
            if let Some(value) = parent.get(*key) {
                node.css_attr
                    .0
                    .entry(Arc::from(*key))
                    .or_insert_with(|| value.clone());
            }
        }
    }
    let node = &arena[node_id];
    let mut merged = parent.clone();
    for key in INHERITED_PROPS {
        if let Some(value) = node.css_attr.0.get(*key) {
            merged.insert(Arc::from(*key), value.clone());
        }
    }
    let children: Vec<NodeId> = node.children.clone();
    for child in children {
        ref_inherit(arena, child, &merged);
    }
}

fn reference_cascade(arena: &mut NodeArena, root: NodeId, css: &CssRule, state: &DynamicState) {
    reset_css_attr(arena, root);
    let mut rules: Vec<&CssRuleEntry> = css.0.iter().collect();
    rules.sort_by_key(|entry| entry.selector.specificity());
    for entry in &rules {
        if !entry.normal.0.is_empty() {
            ref_apply_rule(arena, root, &entry.selector, &entry.normal, state);
        }
    }
    for entry in &rules {
        if !entry.important.0.is_empty() {
            ref_apply_rule(arena, root, &entry.selector, &entry.important, state);
        }
    }
    ref_inherit(arena, root, &IndexMap::new());
}

/// Assert every node's `css_attr` equals what the reference cascade computes
/// for the same document + stylesheet + interaction state.
fn assert_matches_reference(arena: &NodeArena, root: NodeId, css: &str, state: &DynamicState) {
    let mut reference = arena.clone();
    let mut parser = Parser::new(css);
    let rules = parser.parse();
    reference_cascade(&mut reference, root, &rules, state);
    let mut stack = vec![root];
    while let Some(id) = stack.pop() {
        assert_eq!(
            arena[id].css_attr.0,
            reference[id].css_attr.0,
            "css_attr mismatch at node {:?} (class {:?})",
            arena[id].node_type,
            arena[id].attributes.get("class")
        );
        stack.extend(arena[id].children.iter().copied());
    }
}

/// `Document > div.menu#main > (p#lead, ul > li×3, a.nav, em)` — a tree that
/// exercises every bucket key (tag / class / id / wildcard) and every
/// combinator.
fn build_cascade_tree(arena: &mut NodeArena) -> (NodeId, NodeId, NodeId, NodeId, NodeId) {
    let root = arena.insert(Node::from(NodeType::Document));
    let div = arena.insert(Node::from(NodeType::Div));
    arena[div].attributes = IndexMap::from([
        ("class".to_string(), "menu".to_string()),
        ("id".to_string(), "main".to_string()),
    ]);
    let p = arena.insert(Node::from(NodeType::P));
    arena[p]
        .attributes
        .insert("id".to_string(), "lead".to_string());
    let ul = arena.insert(Node::from(NodeType::Ul));
    let li1 = arena.insert(Node::from(NodeType::Li));
    let li2 = arena.insert(Node::from(NodeType::Li));
    let li3 = arena.insert(Node::from(NodeType::Li));
    let a = arena.insert(Node::from(NodeType::A));
    arena[a]
        .attributes
        .insert("class".to_string(), "nav".to_string());
    let em = arena.insert(Node::from(NodeType::Em));
    // `ul` children are exactly three `li` so `:nth-child` indices are
    // unambiguous (no whitespace text nodes).
    for (parent, children) in [
        (root, vec![div]),
        (div, vec![p, ul, a, em]),
        (ul, vec![li1, li2, li3]),
    ] {
        for child in children {
            Node::append_child(&mut *arena, parent, child);
        }
    }
    (root, div, ul, li2, em)
}

/// One stylesheet touching tag / class / id / universal / pseudo-class keys
/// and every combinator, with specificity ties resolved by source order and
/// an `!important` override.
const CASCADE_SHEET: &str = "
div { padding-top: 1px; }
div { color: purple; }
.menu { color: red; }
#lead { font-weight: bold; }
* { line-height: 2px; }
ul li { text-align: center; }
div > a { text-decoration: underline; }
li + li { color: green; }
p ~ em { font-style: italic; }
p:nth-child(odd) { font-style: italic; }
li:hover { background-color: blue; }
li:nth-child(even) { text-transform: uppercase; }
a { color: yellow; }
a { color: orange; }
em { color: black !important; }
";

#[test]
fn bucketed_cascade_matches_reference_cascade() {
    init();
    let mut arena = NodeArena::default();
    let (root, div, _ul, li2, em) = build_cascade_tree(&mut arena);

    // Static pass.
    css_into_node_with_state(
        &mut arena,
        root,
        &parse_sheet(CASCADE_SHEET),
        &DynamicState::default(),
    );
    assert_matches_reference(&arena, root, CASCADE_SHEET, &DynamicState::default());
    // Spot-check the cascade semantics the buckets must preserve.
    assert_eq!(
        arena[div].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("red")
    );
    assert_eq!(
        arena[li2].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("green")
    );
    assert_eq!(
        arena[em].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("black")
    );
    assert_eq!(
        arena[em].css_attr.0.get("font-style").map(|s| s.as_ref()),
        Some("italic")
    );
    assert_eq!(
        arena[div].css_attr.0.get("padding-top").map(|s| s.as_ref()),
        Some("1px")
    );

    // Hovered pass: `:hover` must restyle only the matching chain, and the
    // rest of the tree must stay byte-identical to the reference.
    let hovered = DynamicState {
        hovered: Some(li2),
        ..Default::default()
    };
    let mut arena = NodeArena::default();
    let (root, _div, _ul, _li2, _em) = build_cascade_tree(&mut arena);
    css_into_node_with_state(&mut arena, root, &parse_sheet(CASCADE_SHEET), &hovered);
    assert_matches_reference(&arena, root, CASCADE_SHEET, &hovered);
}

fn parse_sheet(css: &str) -> CssRule {
    let mut parser = Parser::new(css);
    parser.parse()
}

#[test]
fn cascade_index_is_rebuilt_after_push() {
    init();
    let mut arena = NodeArena::default();
    let (root, div) = build_test(&mut arena);
    let rules = parse_sheet("div { color: red; }");
    let mut cascaded = arena.clone();
    css_into_node_with_state(&mut cascaded, root, &rules, &DynamicState::default());
    assert_eq!(
        cascaded[div].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("red")
    );

    // A rule appended after the first cascade must take part in the next
    // one (same specificity → later source order wins).
    let mut rules = rules;
    let selector: CssSelector = "div".parse().unwrap();
    let mut decls = IndexMap::new();
    decls.insert("color".to_string(), "blue".to_string());
    rules.push(selector, CssAttr::from(decls), CssAttr::new());
    let mut recascaded = arena.clone();
    css_into_node_with_state(&mut recascaded, root, &rules, &DynamicState::default());
    assert_eq!(
        recascaded[div].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("blue")
    );
}

#[test]
fn cascade_inline_style_precedence_unchanged() {
    init();
    let mut arena = NodeArena::default();
    let root = arena.insert(Node::from(NodeType::Document));
    let div = arena.insert(Node::from(NodeType::Div));
    arena[div].attributes = IndexMap::from([(
        "style".to_string(),
        "color: green; background-color: white !important".to_string(),
    )]);
    Node::append_child(&mut arena, root, div);
    let rules = parse_sheet("div { color: red !important; }");
    css_into_node_with_state(&mut arena, root, &rules, &DynamicState::default());
    // Stylesheet `!important` beats inline normal (green loses)…
    assert_eq!(
        arena[div].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("red")
    );
    // …while inline `!important` still lands (no competing declaration).
    assert_eq!(
        arena[div]
            .css_attr
            .0
            .get("background-color")
            .map(|s| s.as_ref()),
        Some("white")
    );

    // Inline normal beats stylesheet normal.
    let mut arena = NodeArena::default();
    let root = arena.insert(Node::from(NodeType::Document));
    let div = arena.insert(Node::from(NodeType::Div));
    arena[div]
        .attributes
        .insert("style".to_string(), "color: green".to_string());
    Node::append_child(&mut arena, root, div);
    let rules = parse_sheet("div { color: red; }");
    css_into_node_with_state(&mut arena, root, &rules, &DynamicState::default());
    assert_eq!(
        arena[div].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("green")
    );
}

#[test]
fn cascade_inheritance_values_survive_copy_on_write() {
    init();
    // div(red) > p(red, equal to inherited — shared-map path) >
    // span(blue, diverging — cloned-map path) > em (inherits blue).
    let mut arena = NodeArena::default();
    let root = arena.insert(Node::from(NodeType::Document));
    let div = arena.insert(Node::from(NodeType::Div));
    let p = arena.insert(Node::from(NodeType::P));
    let span = arena.insert(Node::from(NodeType::Span));
    let em = arena.insert(Node::from(NodeType::Em));
    for (parent, child) in [(root, div), (div, p), (p, span), (span, em)] {
        Node::append_child(&mut arena, parent, child);
    }
    let rules = parse_sheet("div { color: red; } p { color: red; } span { color: blue; }");
    css_into_node_with_state(&mut arena, root, &rules, &DynamicState::default());
    assert_eq!(
        arena[div].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("red")
    );
    assert_eq!(
        arena[p].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("red")
    );
    assert_eq!(
        arena[span].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("blue")
    );
    assert_eq!(
        arena[em].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("blue")
    );
}

// ============================================================
// B: CSS property-name and keyword case-insensitivity + logical keywords
// ============================================================

#[test]
fn declaration_property_names_are_case_insensitive() {
    init();
    // `parse_declaration_text` backs the inline `style` attribute and `el.style`.
    // Declaration names normalise to lowercase so the canonical keys the
    // `CssAttr` accessors read are produced (`WIDTH` → `width`, …).
    let m =
        parse_declaration_text("WIDTH: 10px; BACKGROUND-COLOR: red; Text-Transform: uppercase;");
    assert_eq!(m.get("width").map(|s| s.as_ref()), Some("10px"));
    assert_eq!(m.get("background-color").map(|s| s.as_ref()), Some("red"));
    assert_eq!(
        m.get("text-transform").map(|s| s.as_ref()),
        Some("uppercase")
    );
}

#[test]
fn text_align_keywords_are_case_insensitive_and_support_start_end() {
    init();
    assert_eq!(
        attr_from_decl("text-align", "CENTER").get_text_align(),
        TextAlign::Center
    );
    assert_eq!(
        attr_from_decl("text-align", "Right").get_text_align(),
        TextAlign::Right
    );
    assert_eq!(
        attr_from_decl("text-align", "end").get_text_align(),
        TextAlign::Right
    );
    assert_eq!(
        attr_from_decl("text-align", "start").get_text_align(),
        TextAlign::Left
    );
    // `justify` collapses to left (no inter-word justification).
    assert_eq!(
        attr_from_decl("text-align", "justify").get_text_align(),
        TextAlign::Left
    );
}

#[test]
fn font_weight_is_case_insensitive_and_600_is_bold() {
    init();
    assert_eq!(
        attr_from_decl("font-weight", "BOLD").get_font_weight(),
        FontWeight::Bold
    );
    assert_eq!(
        attr_from_decl("font-weight", "bolder").get_font_weight(),
        FontWeight::Bold
    );
    assert_eq!(
        attr_from_decl("font-weight", "600").get_font_weight(),
        FontWeight::Bold
    );
    assert_eq!(
        attr_from_decl("font-weight", "500").get_font_weight(),
        FontWeight::Normal
    );
}

#[test]
fn font_style_is_case_insensitive() {
    init();
    assert_eq!(
        attr_from_decl("font-style", "Italic").get_font_style_kind(),
        FontStyleKind::Italic
    );
    assert_eq!(
        attr_from_decl("font-style", "OBLIQUE").get_font_style_kind(),
        FontStyleKind::Oblique
    );
    assert_eq!(
        attr_from_decl("font-style", "normal").get_font_style_kind(),
        FontStyleKind::Normal
    );
}

// ============================================================
// C: signed negative lengths — margins and positioning insets
// ============================================================

#[test]
fn negative_margin_resolves_signed_horizontally() {
    init();
    // `margin: -4ch` applies to every side: vertical clamps to 0 (no
    // overlapping rows), horizontal keeps the sign (gutter pull-out).
    let attr = attr_from_decl("margin", "-4ch");
    let m = attr.get_margin(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(m, MarginSizes::new(0, -4, 0, -4));
    // A per-side longhand overrides the shorthand.
    let attr = attr_from_decl("margin-left", "-6ch");
    let m = attr.get_margin(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(m, MarginSizes::new(0, 0, 0, -6));
}

#[test]
fn negative_inset_resolves_signed() {
    init();
    // `top: -2ch`, `left: -10ch` — negative absolute / relative offsets.
    let mut attr = attr_from_decl("top", "-2ch");
    attr.add(&attr_from_decl("left", "-10ch"));
    let pos = attr.get_positioning(
        80,
        font_ctx(DEFAULT_FONT_SIZE, DEFAULT_ROOT_FONT_SIZE),
        viewport(),
    );
    assert_eq!(pos.inset.top, Some(-2));
    assert_eq!(pos.inset.left, Some(-10));
}

// ============================================================
// C: font-size percentage resolves against the parent font-size
// ============================================================

#[test]
fn font_size_percentage_resolves_against_parent() {
    init();
    let mut arena = NodeArena::default();
    let root = arena.insert(Node::from(NodeType::Document));
    let div_id = arena.insert(Node::from(NodeType::Div));
    Node::append_child(&mut arena, root, div_id);
    let rules = parse_sheet("div { font-size: 200%; }");
    css_into_node(&mut arena, root, &rules);
    // Parent font-size = 2 cells; `200%` → 4 cells (not the containing width).
    let ctx = FontContext {
        font_size_cells: 2,
        root_font_size_cells: 1,
    };
    assert_eq!(
        effective_font_size_cells(&arena, div_id, ctx, viewport()),
        4
    );
}

// ============================================================
// D: white-space inherits to inline children
// ============================================================

#[test]
fn white_space_inherits_to_inline_children() {
    init();
    let mut arena = NodeArena::default();
    let root = arena.insert(Node::from(NodeType::Document));
    let div_id = arena.insert(Node::from(NodeType::Div));
    let span_id = arena.insert(Node::from(NodeType::Span));
    Node::append_child(&mut arena, root, div_id);
    Node::append_child(&mut arena, div_id, span_id);
    let rules = parse_sheet("div { white-space: pre-wrap; }");
    css_into_node(&mut arena, root, &rules);
    // The (unstyled) span picks up the div's `pre-wrap` by inheritance.
    assert_eq!(
        arena[span_id]
            .css_attr
            .get_white_space(&arena[span_id].node_type),
        WhiteSpace::PreWrap
    );
}

#[test]
fn stale_node_id_fails_to_match_instead_of_panicking() {
    // A `NodeId` absent from the current arena — for example after JS removes
    // the node between the hit-map snapshot and a hover repaint — must fail
    // to match rather than panic. Public entry points use `arena.get` lookups.
    let mut p = html_parse::Parser::new(r#"<div class="btn"><span class="btn">x</span></div>"#);
    let (root_id, mut arena, _) = p.parse();
    let mut cp = Parser::new(".btn:hover { color: red }");
    css_into_node(&mut arena, root_id, &cp.parse());
    let mut cp2 = Parser::new(".btn:hover { color: red }");
    let rules = cp2.parse();
    let sel = &rules.0[0].selector;

    // Manufacture a *genuinely* stale key: remove the span from the arena.
    // Its key version is now behind the slot's — indexing it reproduces the
    // exact "invalid SlotMap key used" panic the field report showed.
    // (`NodeId::default()` would NOT do: slotmap's default key happens to be
    // the first allocated slot, i.e. a live key.)
    let span = arena
        .iter()
        .find(|(_, n)| n.node_type == NodeType::Span)
        .map(|(id, _)| id)
        .expect("span present");
    let stale = span;
    arena.remove(stale).expect("span removed");

    // A stale node id simply fails to match.
    assert!(
        arena.get(stale).is_none(),
        "the removed key must be stale for this arena"
    );
    assert!(!selector_chain_matches_with_state(
        &arena,
        stale,
        sel,
        &DynamicState::default(),
    ));
    // A stale `:hover` target against a real node also fails to match (and
    // never panics inside the ancestor-chain walk).
    let real = arena
        .iter()
        .find(|(_, n)| n.node_type == NodeType::Div)
        .map(|(id, _)| id)
        .expect("div present");
    assert!(!selector_chain_matches_with_state(
        &arena,
        real,
        sel,
        &DynamicState {
            hovered: Some(stale),
            ..Default::default()
        },
    ));
}

// ============================================================
// 结构伪类(:first-child / :last-child / :only-child /
// :nth-last-child / :root / :empty / :not / 表单状态)
// ============================================================

/// Build a parent with `n` `<p>` children, returning their ids in order.
fn children_of(n: usize) -> (NodeArena, NodeId, Vec<NodeId>) {
    let mut arena = NodeArena::default();
    let parent = arena.insert(Node::from(NodeType::Div));
    let children: Vec<_> = (0..n)
        .map(|_| {
            let id = arena.insert(Node::from(NodeType::P));
            Node::append_child(&mut arena, parent, id);
            id
        })
        .collect();
    (arena, parent, children)
}

#[test]
fn test_first_last_only_child_pseudo_classes() {
    init();
    let (arena, _parent, kids) = children_of(3);

    let first: CssSelector = "p:first-child".parse().unwrap();
    assert!(selector_chain_matches(&arena, kids[0], &first));
    assert!(!selector_chain_matches(&arena, kids[1], &first));
    assert!(!selector_chain_matches(&arena, kids[2], &first));

    let last: CssSelector = "p:last-child".parse().unwrap();
    assert!(!selector_chain_matches(&arena, kids[0], &last));
    assert!(!selector_chain_matches(&arena, kids[1], &last));
    assert!(selector_chain_matches(&arena, kids[2], &last));

    // `:only-child` = first AND last: matches only on a single-child parent.
    let only: CssSelector = "p:only-child".parse().unwrap();
    assert!(!selector_chain_matches(&arena, kids[0], &only));
    let (arena1, _p1, kids1) = children_of(1);
    assert!(selector_chain_matches(&arena1, kids1[0], &only));

    // Case-insensitive pseudo-class names, like the existing tag handling.
    let upper: CssSelector = "p:FIRST-CHILD".parse().unwrap();
    assert!(selector_chain_matches(&arena, kids[0], &upper));
}

#[test]
fn test_nth_last_child_matches_from_end() {
    init();
    let (arena, _parent, kids) = children_of(4);

    // `:nth-last-child(2)` — the second-to-last child only.
    let sel: CssSelector = "p:nth-last-child(2)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, kids[0], &sel));
    assert!(!selector_chain_matches(&arena, kids[1], &sel));
    assert!(selector_chain_matches(&arena, kids[2], &sel));
    assert!(!selector_chain_matches(&arena, kids[3], &sel));

    // `:nth-last-child(odd)` counts 1-based from the end: with four
    // children, kids[1] is from-end 3 and kids[3] is from-end 1 — the two
    // odd positions.
    let odd: CssSelector = "p:nth-last-child(odd)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, kids[0], &odd));
    assert!(selector_chain_matches(&arena, kids[1], &odd));
    assert!(!selector_chain_matches(&arena, kids[2], &odd));
    assert!(selector_chain_matches(&arena, kids[3], &odd));
}

#[test]
fn test_root_and_empty_pseudo_classes() {
    init();
    // A document-shaped tree: Document → html → body → div.
    let mut arena = NodeArena::default();
    let doc = arena.insert(Node::from(NodeType::Document));
    let html = arena.insert(Node::from(NodeType::Html));
    Node::append_child(&mut arena, doc, html);
    let body = arena.insert(Node::from(NodeType::Body));
    Node::append_child(&mut arena, html, body);
    let empty_div = arena.insert(Node::from(NodeType::Div));
    Node::append_child(&mut arena, body, empty_div);

    let root: CssSelector = ":root".parse().unwrap();
    assert!(selector_chain_matches(&arena, html, &root));
    // Only the Document's child is the root — nothing deeper, and the
    // Document node itself is not an element.
    assert!(!selector_chain_matches(&arena, doc, &root));
    assert!(!selector_chain_matches(&arena, body, &root));

    let empty: CssSelector = "div:empty".parse().unwrap();
    assert!(selector_chain_matches(&arena, empty_div, &empty));

    // Any element child kills emptiness.
    let child = arena.insert(Node::from(NodeType::Span));
    Node::append_child(&mut arena, empty_div, child);
    assert!(!selector_chain_matches(&arena, empty_div, &empty));

    // Comments never affect emptiness (CSS Selectors semantics).
    let mut arena2 = NodeArena::default();
    let div = arena2.insert(Node::from(NodeType::Div));
    let mut comment = Node::from(NodeType::Comment);
    comment.data = Some("note".to_string());
    let comment_id = arena2.insert(comment);
    Node::append_child(&mut arena2, div, comment_id);
    let empty_sel: CssSelector = ":empty".parse().unwrap();
    assert!(selector_chain_matches(&arena2, div, &empty_sel));

    // Non-empty text (including a lone space) does affect emptiness.
    let empty_sel: CssSelector = ":empty".parse().unwrap();
    for data in ["hi", " "] {
        let mut arena3 = NodeArena::default();
        let div = arena3.insert(Node::from(NodeType::Div));
        let text = arena3.insert(Node::text(data));
        Node::append_child(&mut arena3, div, text);
        assert!(
            !selector_chain_matches(&arena3, div, &empty_sel),
            "text child {data:?} must make :empty fail"
        );
    }
}

#[test]
fn test_not_pseudo_class_matches() {
    init();
    let mut arena = NodeArena::default();
    let parent = arena.insert(Node::from(NodeType::Div));
    let attach = |nt: NodeType, class: &str, arena: &mut NodeArena| {
        let mut node = Node::from(nt);
        if !class.is_empty() {
            node.attributes
                .insert("class".to_string(), class.to_string());
        }
        let id = arena.insert(node);
        Node::append_child(arena, parent, id);
        id
    };
    let p = attach(NodeType::P, "lead", &mut arena);
    let span = attach(NodeType::Span, "", &mut arena);
    let div = attach(NodeType::Div, "lead", &mut arena);

    // `:not(.lead)` — excludes both `.lead` children.
    let sel: CssSelector = ":not(.lead)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, p, &sel));
    assert!(selector_chain_matches(&arena, span, &sel));
    assert!(!selector_chain_matches(&arena, div, &sel));

    // Comma-separated argument list: none of the compounds may match.
    let list: CssSelector = ":not(p, div)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, p, &list));
    assert!(!selector_chain_matches(&arena, div, &list));
    assert!(selector_chain_matches(&arena, span, &list));

    // `:not()` composes with other compound parts and combinators.
    let chained: CssSelector = "div > :not(span)".parse().unwrap();
    assert!(selector_chain_matches(&arena, p, &chained));
    assert!(!selector_chain_matches(&arena, span, &chained));

    // Spaces inside the argument list survive parsing.
    let spaced: CssSelector = ":not( p , div )".parse().unwrap();
    assert!(selector_chain_matches(&arena, span, &spaced));

    // `:not` chains compose (element must dodge both arguments).
    let double: CssSelector = ":not(p):not(div)".parse().unwrap();
    assert!(selector_chain_matches(&arena, span, &double));
    assert!(!selector_chain_matches(&arena, p, &double));
}

#[test]
fn test_not_pseudo_class_parse_errors() {
    init();
    // Missing parens / missing close paren / empty argument.
    assert!(":not".parse::<CssSelector>().is_err());
    assert!(":not(".parse::<CssSelector>().is_err());
    assert!(":not()".parse::<CssSelector>().is_err());
    // Combinators inside `:not` are out of the supported subset — the tag
    // parse of "p div" fails rather than silently matching wrong.
    assert!(":not(p div)".parse::<CssSelector>().is_err());
    // Pathologically deep nesting is rejected instead of recursing.
    let deep = format!("{}{}", ":not(".repeat(32), ")".repeat(32));
    assert!(deep.parse::<CssSelector>().is_err());
}

#[test]
fn test_form_state_pseudo_classes() {
    init();
    let mut arena = NodeArena::default();
    let mut checkbox = Node::from(NodeType::Input);
    checkbox
        .attributes
        .insert("type".to_string(), "checkbox".to_string());
    checkbox
        .attributes
        .insert("checked".to_string(), String::new());
    let checked = arena.insert(checkbox);

    let mut unchecked = Node::from(NodeType::Input);
    unchecked
        .attributes
        .insert("type".to_string(), "checkbox".to_string());
    let unchecked = arena.insert(unchecked);

    // A text input with a stray `checked` attribute is not `:checked` —
    // only checkbox / radio inputs participate.
    let mut text_input = Node::from(NodeType::Input);
    text_input
        .attributes
        .insert("checked".to_string(), String::new());
    let text_input = arena.insert(text_input);

    let mut selected = Node::from(NodeType::HtmlOption);
    selected
        .attributes
        .insert("selected".to_string(), String::new());
    let selected = arena.insert(selected);

    let checked_sel: CssSelector = ":checked".parse().unwrap();
    assert!(selector_chain_matches(&arena, checked, &checked_sel));
    assert!(!selector_chain_matches(&arena, unchecked, &checked_sel));
    assert!(!selector_chain_matches(&arena, text_input, &checked_sel));
    assert!(selector_chain_matches(&arena, selected, &checked_sel));

    // `:disabled` via the own attribute…
    let mut disabled_btn = Node::from(NodeType::Button);
    disabled_btn
        .attributes
        .insert("disabled".to_string(), String::new());
    let disabled_btn = arena.insert(disabled_btn);
    let enabled_btn = arena.insert(Node::from(NodeType::Button));
    let disabled_sel: CssSelector = ":disabled".parse().unwrap();
    let enabled_sel: CssSelector = ":enabled".parse().unwrap();
    assert!(selector_chain_matches(&arena, disabled_btn, &disabled_sel));
    assert!(!selector_chain_matches(&arena, disabled_btn, &enabled_sel));
    assert!(selector_chain_matches(&arena, enabled_btn, &enabled_sel));

    // …and via a `<fieldset disabled>` ancestor (legend exemption not
    // modelled — the whole subtree is disabled).
    let mut fieldset = Node::from(NodeType::Fieldset);
    fieldset
        .attributes
        .insert("disabled".to_string(), String::new());
    let fieldset = arena.insert(fieldset);
    let inner = arena.insert(Node::from(NodeType::Input));
    Node::append_child(&mut arena, fieldset, inner);
    assert!(selector_chain_matches(&arena, inner, &disabled_sel));
    assert!(!selector_chain_matches(&arena, inner, &enabled_sel));

    // Non-form-control elements match neither state.
    let plain = arena.insert(Node::from(NodeType::Div));
    assert!(!selector_chain_matches(&arena, plain, &enabled_sel));
    assert!(!selector_chain_matches(&arena, plain, &disabled_sel));
}

#[test]
fn test_selector_paren_args_allow_spaces() {
    // Whitespace is allowed inside a pseudo-class function argument.
    init();
    let sel: CssSelector = ":nth-child(2n + 1)".parse().unwrap();
    let (arena, _parent, kids) = children_of(3);
    assert!(selector_chain_matches(&arena, kids[0], &sel));
    assert!(!selector_chain_matches(&arena, kids[1], &sel));
    assert!(selector_chain_matches(&arena, kids[2], &sel));
}

#[test]
fn test_not_specificity_takes_most_specific_argument() {
    // CSS spec: `:not(...)` contributes the specificity of its most
    // specific argument — `:not(#a)` outranks a plain class selector.
    init();
    let class_sel: CssSelector = "p.leading".parse().unwrap();
    let not_sel: CssSelector = "p:not(#a)".parse().unwrap();
    assert_eq!(class_sel.specificity(), (0, 1, 1));
    assert_eq!(not_sel.specificity(), (1, 0, 1));
}

/// Mixed-sibling fixture: `text, p, span, p, comment, p, span` — the `*-of-type`
/// selectors must count per-type while `*-child` counts every node.
fn mixed_children() -> (NodeArena, NodeId, Vec<NodeId>, Vec<NodeId>) {
    let mut arena = NodeArena::default();
    let parent = arena.insert(Node::from(NodeType::Div));
    let text = arena.insert(Node::text("t"));
    Node::append_child(&mut arena, parent, text);
    let mut ps = Vec::new();
    let mut spans = Vec::new();
    for (i, nt) in [
        NodeType::P,
        NodeType::Span,
        NodeType::P,
        NodeType::P,
        NodeType::Span,
    ]
    .into_iter()
    .enumerate()
    {
        // A comment before the 3rd `<p>` — of-type indices must ignore it.
        if i == 3 {
            let mut comment = Node::from(NodeType::Comment);
            comment.data = Some("c".to_string());
            let comment_id = arena.insert(comment);
            Node::append_child(&mut arena, parent, comment_id);
        }
        let id = arena.insert(Node::from(nt));
        Node::append_child(&mut arena, parent, id);
        if nt == NodeType::P {
            ps.push(id);
        } else {
            spans.push(id);
        }
    }
    (arena, parent, ps, spans)
}

#[test]
fn test_nth_of_type_counts_same_type_only() {
    init();
    let (arena, _parent, ps, spans) = mixed_children();

    // `p:nth-of-type(2)` — the second `<p>`, ignoring the text / span /
    // comment children around it.
    let sel: CssSelector = "p:nth-of-type(2)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, ps[0], &sel));
    assert!(selector_chain_matches(&arena, ps[1], &sel));
    assert!(!selector_chain_matches(&arena, ps[2], &sel));

    // `:nth-of-type(even)` over the span sequence (indices 1, 2).
    let even: CssSelector = "span:nth-of-type(even)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, spans[0], &even));
    assert!(selector_chain_matches(&arena, spans[1], &even));

    // `:nth-last-of-type(1)` == `:last-of-type` for the p sequence.
    let last: CssSelector = "p:nth-last-of-type(1)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, ps[0], &last));
    assert!(!selector_chain_matches(&arena, ps[1], &last));
    assert!(selector_chain_matches(&arena, ps[2], &last));

    // `:nth-last-of-type(2)` — the second `<p>` counting from the end.
    let second_last: CssSelector = "p:nth-last-of-type(2)".parse().unwrap();
    assert!(selector_chain_matches(&arena, ps[1], &second_last));
}

#[test]
fn test_first_last_only_of_type() {
    init();
    let (arena, _parent, ps, spans) = mixed_children();

    let first_p: CssSelector = "p:first-of-type".parse().unwrap();
    assert!(selector_chain_matches(&arena, ps[0], &first_p));
    assert!(!selector_chain_matches(&arena, ps[1], &first_p));

    let last_span: CssSelector = "span:last-of-type".parse().unwrap();
    assert!(!selector_chain_matches(&arena, spans[0], &last_span));
    assert!(selector_chain_matches(&arena, spans[1], &last_span));

    // `:only-of-type` needs exactly one same-type sibling: neither the p
    // nor span sequences qualify here.
    let only: CssSelector = ":only-of-type".parse().unwrap();
    for id in ps.iter().chain(spans.iter()) {
        assert!(!selector_chain_matches(&arena, *id, &only));
    }
    // A lone `<b>` child qualifies.
    let mut arena2 = NodeArena::default();
    let parent = arena2.insert(Node::from(NodeType::Div));
    let b = arena2.insert(Node::from(NodeType::B));
    Node::append_child(&mut arena2, parent, b);
    let text = arena2.insert(Node::text("x"));
    Node::append_child(&mut arena2, parent, text);
    assert!(selector_chain_matches(&arena2, b, &only));

    // Case-insensitive names, like the other pseudo-classes.
    let upper: CssSelector = "p:FIRST-OF-TYPE".parse().unwrap();
    assert!(selector_chain_matches(&arena, ps[0], &upper));
}

#[test]
fn test_nth_of_type_parse_errors() {
    init();
    assert!("p:nth-of-type".parse::<CssSelector>().is_err());
    assert!("p:nth-of-type(".parse::<CssSelector>().is_err());
    assert!("p:nth-of-type(0)".parse::<CssSelector>().is_err());
    assert!("p:nth-last-of-type(n)".parse::<CssSelector>().is_err());
    // Spaces inside the argument survive (paren-aware split).
    assert!("p:nth-of-type(2n + 1)".parse::<CssSelector>().is_ok());
}

// ============================================================
// list-style / font / table 新属性与简写
// ============================================================

/// Parse `html` and cascade an empty stylesheet, returning the first
/// `tag` element's post-cascade `CssAttr`.
fn cascaded_node(html: &str, tag: &str) -> CssAttr {
    let mut parser = html_parse::Parser::new(html);
    let (root_id, mut arena, _) = parser.parse();
    let rules = Parser::new("p {}").parse();
    css_into_node(&mut arena, root_id, &rules);
    let id = arena
        .iter()
        .find(|(_, n)| n.node_type.tag_name().is_some_and(|t| t == tag))
        .map(|(id, _)| id)
        .expect("tag present");
    arena[id].css_attr.clone()
}

#[test]
fn test_list_style_type_and_shorthand() {
    init();
    use htui::html::css_parse::ListStyleType as L;
    // Longhand on the list reaches `<li>` through inheritance.
    let attr = cascaded_node(
        "<ul style=\"list-style-type: square\"><li>x</li></ul>",
        "li",
    );
    assert_eq!(attr.get_list_style_type(L::Disc), L::Square);
    // Shorthand expands to the type longhand at parse time.
    let attr = cascaded_node(
        "<ul style=\"list-style: lower-alpha\"><li>x</li></ul>",
        "li",
    );
    assert_eq!(attr.get_list_style_type(L::Disc), L::LowerAlpha);
    // No declaration: the getter echoes the caller's element default (the
    // `disc`-vs-`decimal` choice is made by the `<li>` layout, not the CSS
    // cascade).
    let attr = cascaded_node("<ol><li>x</li></ol>", "li");
    assert_eq!(attr.get_list_style_type(L::Disc), L::Disc);
    assert_eq!(attr.get_list_style_type(L::Decimal), L::Decimal);
    // Marker strings for each family.
    assert_eq!(L::Circle.marker(1), "○ ");
    assert_eq!(L::LowerRoman.marker(4), "iv ");
    assert_eq!(L::UpperRoman.marker(9), "IX ");
    assert_eq!(L::UpperAlpha.marker(27), "AA. ");
    assert_eq!(L::None.marker(3), "");
}

#[test]
fn test_font_shorthand_expands() {
    init();
    let attr = cascaded_node(
        "<p style=\"font: italic bold 2em/1.5 monospace\">x</p>",
        "p",
    );
    assert_eq!(attr.get_font_weight(), FontWeight::Bold);
    assert_eq!(attr.get_font_style_kind(), FontStyleKind::Italic);
    // line-height rides along as its own longhand.
    assert!(
        attr.0
            .get("line-height")
            .is_some_and(|v| v.as_ref() == "1.5"),
        "line-height component expanded, got {:?}",
        attr.0.get("line-height")
    );
    // Size-only form without flags still lands.
    let attr = cascaded_node("<p style=\"font: 12px serif\">x</p>", "p");
    assert!(
        attr.0
            .get("font-size")
            .is_some_and(|v| v.as_ref() == "12px")
    );
    // Missing family fails the whole declaration (no longhands).
    let attr = cascaded_node("<p style=\"font: 12px\">x</p>", "p");
    assert!(attr.0.get("font-size").is_none());
}

#[test]
fn test_table_property_getters() {
    init();
    let attr = cascaded_node(
        "<table style=\"table-layout: fixed; caption-side: bottom; empty-cells: hide\"><tr><td>a</td></tr></table>",
        "table",
    );
    assert_eq!(
        attr.get_table_layout(),
        htui::html::css_parse::TableLayout::Fixed
    );
    assert_eq!(
        attr.get_caption_side(),
        htui::html::css_parse::CaptionSide::Bottom
    );
    assert_eq!(
        attr.get_empty_cells(),
        htui::html::css_parse::EmptyCells::Hide
    );
    // Defaults.
    let attr = cascaded_node("<table><tr><td>a</td></tr></table>", "table");
    assert_eq!(
        attr.get_table_layout(),
        htui::html::css_parse::TableLayout::Auto
    );
    assert_eq!(
        attr.get_caption_side(),
        htui::html::css_parse::CaptionSide::Top
    );
    assert_eq!(
        attr.get_empty_cells(),
        htui::html::css_parse::EmptyCells::Show
    );
}

#[test]
fn test_lang_pseudo_class() {
    init();
    // The nearest `lang` attribute wins — an ancestor's declaration reaches
    // descendants that do not override it, and primary-subtag matching
    // treats `zh-CN` as `zh`.
    let mut arena = NodeArena::default();
    let doc = arena.insert(Node::from(NodeType::Document));
    let html = {
        let mut n = Node::from(NodeType::Html);
        n.attributes.insert("lang".to_string(), "zh-CN".to_string());
        arena.insert(n)
    };
    Node::append_child(&mut arena, doc, html);
    let p = arena.insert(Node::from(NodeType::P));
    Node::append_child(&mut arena, html, p);
    let en_child = {
        let mut n = Node::from(NodeType::Span);
        n.attributes.insert("lang".to_string(), "EN".to_string());
        arena.insert(n)
    };
    Node::append_child(&mut arena, html, en_child);

    let zh: CssSelector = ":lang(zh)".parse().unwrap();
    assert!(selector_chain_matches(&arena, html, &zh));
    assert!(
        selector_chain_matches(&arena, p, &zh),
        "descendant inherits the ancestor lang"
    );
    let en: CssSelector = ":lang(en)".parse().unwrap();
    assert!(
        selector_chain_matches(&arena, en_child, &en),
        "nearest lang wins (case-insensitive)"
    );
    assert!(!selector_chain_matches(&arena, p, &en));
    // Exact subtag only: `:lang(zh-cn)` does not match `zh`.
    let zh_cn: CssSelector = ":lang(zh-cn)".parse().unwrap();
    assert!(!selector_chain_matches(&arena, p, &zh_cn));
    // Parse errors: missing parens / empty / spaced argument.
    assert!(":lang".parse::<CssSelector>().is_err());
    assert!(":lang()".parse::<CssSelector>().is_err());
    assert!(":lang(zh en)".parse::<CssSelector>().is_err());
}

#[test]
fn test_inherit_and_initial_keywords() {
    init();
    // `inherit` on an inherited property takes the parent's computed value.
    let attr = cascaded_node(
        r#"<div style="color: red"><p style="color: inherit">x</p></div>"#,
        "p",
    );
    assert_eq!(attr.0.get("color").map(|s| s.as_ref()), Some("red"));
    // `inherit` on a NON-inherited property reads the parent's computed
    // value too (width here).
    let attr = cascaded_node(
        r#"<div style="width: 20ch"><p style="width: inherit">x</p></div>"#,
        "p",
    );
    assert_eq!(attr.0.get("width").map(|s| s.as_ref()), Some("20ch"));
    // `initial` swaps the declaration for an unparseable sentinel: the
    // getter falls back to its default AND the inherited red cannot refill
    // the slot (the keyword's whole point on inherited properties).
    let attr = cascaded_node(
        r#"<div style="color: red"><p style="color: initial">x</p></div>"#,
        "p",
    );
    assert_eq!(
        attr.get_color(),
        None,
        "initial beats the inherited value (getter falls back to default)"
    );
    // `inherit` without a parent value degrades to the initial sentinel.
    let attr = cascaded_node(r#"<p style="color: inherit">x</p>"#, "p");
    assert_eq!(attr.get_color(), None);
    // Case-insensitive keyword.
    let attr = cascaded_node(
        r#"<div style="color: red"><p style="color: INHERIT">x</p></div>"#,
        "p",
    );
    assert_eq!(attr.0.get("color").map(|s| s.as_ref()), Some("red"));
}

#[test]
fn test_math_functions_parse_and_resolve() {
    init();
    let ctx = length_ctx(80, font_ctx(1, 1));

    // calc(100% - 4ch): 80 - 4 = 76 cells.
    let len = Length::parse("calc(100% - 4ch)").expect("calc parses");
    assert_eq!(len.resolve(ctx), 76);
    // calc(2 * 10px): 20px / 8 = 2.5 → round 3, min 1.
    let len = Length::parse("calc(2 * 10px)").expect("calc with * parses");
    assert_eq!(len.resolve(ctx), 3);
    // calc(10ch / 2) = 5.
    let len = Length::parse("calc(10ch / 2)").expect("calc with / parses");
    assert_eq!(len.resolve(ctx), 5);
    // A lone term inside calc.
    let len = Length::parse("calc(6ch)").expect("lone term parses");
    assert_eq!(len.resolve(ctx), 6);

    // min / max pick per resolve-context.
    let len = Length::parse("min(50%, 30ch)").expect("min parses");
    assert_eq!(len.resolve(ctx), 30, "30ch < 50% of 80");
    let len = Length::parse("max(50%, 30ch)").expect("max parses");
    assert_eq!(len.resolve(ctx), 40, "50% of 80 > 30ch");

    // clamp(min, val, max).
    let len = Length::parse("clamp(10ch, 50%, 30ch)").expect("clamp parses");
    assert_eq!(len.resolve(ctx), 30, "50% of 80 clamps down to 30ch");
    let len = Length::parse("clamp(10ch, 2ch, 30ch)").expect("clamp parses");
    assert_eq!(len.resolve(ctx), 10, "2ch clamps up to 10ch");

    // resolve_signed keeps the sign through calc.
    let len = Length::parse_signed("calc(2ch - 10ch)").expect("signed calc parses");
    assert_eq!(len.resolve_signed(ctx), -8);

    // Unsupported forms fail cleanly.
    assert!(Length::parse("calc(4ch").is_none(), "missing )");
    assert!(Length::parse("calc()").is_none(), "empty body");
    assert!(Length::parse("min(1ch)").is_none(), "min needs 2 terms");
    assert!(Length::parse("clamp(1ch, 2ch)").is_none(), "clamp needs 3");
    assert!(
        Length::parse("calc(10pt + 2ch)").is_none(),
        "unsupported unit"
    );
}

#[test]
fn test_math_functions_flow_through_properties() {
    init();
    // Through a real cascade: `width: calc(100% - 4ch)` on a fixed-width
    // parent resolves through the layout getters.
    let attr = cascaded_node(
        r#"<div style="width: 80ch"><p style="width: calc(100% - 4ch)">x</p></div>"#,
        "p",
    );
    let len = attr
        .0
        .get("width")
        .and_then(|raw| Length::parse(raw))
        .expect("calc width survives the cascade");
    assert_eq!(len.resolve(length_ctx(80, font_ctx(1, 1))), 76);
}

#[test]
fn test_pseudo_element_selector_parses() {
    init();
    // The pseudo-element is lifted off the chain; the chain matches the
    // origin element.
    let sel: CssSelector = "p.note::before".parse().expect("::before parses");
    assert_eq!(
        sel.pseudo_element,
        Some(htui::html::css_parse::PseudoElement::Before)
    );
    assert_eq!(sel.compounds.len(), 1);
    let sel: CssSelector = "div > a:after".parse().expect("legacy :after parses");
    assert_eq!(
        sel.pseudo_element,
        Some(htui::html::css_parse::PseudoElement::After)
    );
    assert_eq!(sel.compounds.len(), 2, "combinator chain survives");
    // Other pseudo-elements stay unsupported.
    assert!("p::first-line".parse::<CssSelector>().is_err());
    assert!(
        "::before".parse::<CssSelector>().is_err(),
        "bare pseudo-element has no origin"
    );
}

#[test]
fn test_generated_content_renders_before_and_after() {
    init();
    // End-to-end through the render pipeline: the generated runs surround
    // the element's real text and carry their own styles.
    let (root_id, mut arena, _) = {
        let mut parser = html_parse::Parser::new("<p>mid</p>");
        parser.parse()
    };
    let rules = Parser::new(
        "p::before { content: \"[\"; color: red; } p::after { content: \"]\"; font-weight: bold; }",
    )
    .parse();
    css_into_node(&mut arena, root_id, &rules);
    let term_map = htui::layout::layout::TermMap {
        columns: 80,
        rows: 24,
    };
    let mut tl = htui::tui::graph_api::TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(
        canvas.contains("[mid]"),
        "generated ::before/::after runs surround the text, got {canvas:?}"
    );
    assert!(
        tl.layout.iter().any(|b| {
            b.word == "["
                && b.fcolor
                    == Some(Color::Rgb {
                        r: 0xFF,
                        g: 0,
                        b: 0,
                    })
        }),
        "::before colour applies to the generated run"
    );

    // content: none generates nothing.
    let (root2, mut arena2, _) = {
        let mut parser = html_parse::Parser::new("<p>mid</p>");
        parser.parse()
    };
    let rules = Parser::new("p::before { content: none; }").parse();
    css_into_node(&mut arena2, root2, &rules);
    let mut tl2 = htui::tui::graph_api::TermLayout::new(&term_map, 1.0);
    tl2.draw(&arena2, root2, &term_map);
    let canvas2: String = tl2.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(
        canvas2.contains("mid") && !canvas2.contains('['),
        "content: none generates nothing"
    );
}

// ============================================================
// @media conditions
// ============================================================

use htui::html::css_parse::{MediaQuery, MediaQueryList};

fn media_queries(css: &str) -> Vec<Option<MediaQueryList>> {
    Parser::new(css)
        .parse()
        .0
        .iter()
        .map(|e| e.media.clone())
        .collect()
}

#[test]
fn test_media_query_matches_features_and_or() {
    init();
    let list = MediaQueryList(vec![MediaQuery {
        max_width: Some(70.0),
        ..Default::default()
    }]);
    assert!(
        list.matches(&Viewport { cols: 70, rows: 24 }),
        "boundary is inclusive"
    );
    assert!(list.matches(&Viewport { cols: 40, rows: 24 }));
    assert!(!list.matches(&Viewport { cols: 71, rows: 24 }));

    // Two features in one query AND together.
    let both = MediaQueryList(vec![MediaQuery {
        max_width: Some(70.0),
        min_width: Some(40.0),
        ..Default::default()
    }]);
    assert!(both.matches(&Viewport { cols: 60, rows: 24 }));
    assert!(!both.matches(&Viewport { cols: 39, rows: 24 }));
    assert!(!both.matches(&Viewport { cols: 80, rows: 24 }));

    // Comma-separated queries OR together.
    let or = MediaQueryList(vec![
        MediaQuery {
            max_width: Some(40.0),
            ..Default::default()
        },
        MediaQuery {
            max_height: Some(10.0),
            ..Default::default()
        },
    ]);
    assert!(or.matches(&Viewport { cols: 39, rows: 24 }), "first query");
    assert!(or.matches(&Viewport { cols: 80, rows: 9 }), "second query");
    assert!(
        !or.matches(&Viewport { cols: 80, rows: 24 }),
        "neither query"
    );

    // An empty list never matches.
    assert!(!MediaQueryList(vec![]).matches(&Viewport { cols: 80, rows: 24 }));

    // The 0x0 "no viewport known" default never matches a size condition.
    assert!(!list.matches(&Viewport { cols: 0, rows: 0 }));
}

#[test]
fn test_media_at_rule_parses_conditional_entries() {
    init();
    // Bare numbers and `ch` are both cell counts.
    let media = media_queries("@media (max-width: 70ch) { .side { display: none; } }");
    assert_eq!(media.len(), 1);
    let list = media[0].as_ref().expect("condition attached");
    assert!(list.matches(&Viewport { cols: 60, rows: 24 }));
    assert!(!list.matches(&Viewport { cols: 80, rows: 24 }));

    // Unconditional rules carry no condition.
    let mixed = media_queries("p { color: red; } @media (max-height: 14) { .x { color: blue; } }");
    assert_eq!(mixed.len(), 2);
    assert!(mixed[0].is_none());
    let list = mixed[1].as_ref().expect("media condition");
    assert!(list.matches(&Viewport { cols: 80, rows: 10 }));
    assert!(!list.matches(&Viewport { cols: 80, rows: 24 }));

    // `and` between features, comma OR between queries.
    let list = media_queries(
        "@media (max-width: 40) and (min-height: 20), (min-width: 100) { .x { color: red; } }",
    );
    let list = list[0].as_ref().expect("condition attached");
    assert!(
        list.matches(&Viewport { cols: 30, rows: 24 }),
        "first query"
    );
    assert!(
        !list.matches(&Viewport { cols: 30, rows: 10 }),
        "height too small"
    );
    assert!(
        list.matches(&Viewport {
            cols: 120,
            rows: 24
        }),
        "second query"
    );
}

#[test]
fn test_media_cascade_by_viewport() {
    init();
    // The unconditional `.side` twin verifies the non-media rule always
    // applies to the same node (color and display are independent keys).
    let css = "@media (max-width: 40) { .side { display: none; } } .side { color: red; }";
    let rules = Parser::new(css).parse();
    let mut arena = NodeArena::default();
    let (root, div_id) = build_test(&mut arena);
    arena[div_id]
        .attributes
        .insert("class".to_string(), "side".to_string());

    // Wide viewport: the conditional rule never applies.
    css_into_node_with_state(
        &mut arena,
        root,
        &rules,
        &DynamicState {
            viewport: Viewport { cols: 80, rows: 24 },
            ..Default::default()
        },
    );
    assert_eq!(
        arena[div_id].css_attr.0.get("display").map(|s| s.as_ref()),
        None
    );

    // Narrow viewport: the rule applies.
    let mut arena = NodeArena::default();
    let (root, div_id) = build_test(&mut arena);
    arena[div_id]
        .attributes
        .insert("class".to_string(), "side".to_string());
    css_into_node_with_state(
        &mut arena,
        root,
        &rules,
        &DynamicState {
            viewport: Viewport { cols: 40, rows: 24 },
            ..Default::default()
        },
    );
    assert_eq!(
        arena[div_id].css_attr.0.get("display").map(|s| s.as_ref()),
        Some("none")
    );

    // Re-cascading the same tree at the wide viewport (the resize path) drops
    // the rule again — nothing about the old pass leaks through `reset_css_attr`.
    reset_css_attr(&mut arena, root);
    css_into_node_with_state(
        &mut arena,
        root,
        &rules,
        &DynamicState {
            viewport: Viewport { cols: 80, rows: 24 },
            ..Default::default()
        },
    );
    assert_eq!(
        arena[div_id].css_attr.0.get("display").map(|s| s.as_ref()),
        None
    );
    assert_eq!(
        arena[div_id].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("red")
    );

    // Unknown viewport (the DynamicState default): size conditions never match.
    let mut arena = NodeArena::default();
    let (root, div_id) = build_test(&mut arena);
    arena[div_id]
        .attributes
        .insert("class".to_string(), "side".to_string());
    css_into_node_with_state(&mut arena, root, &rules, &DynamicState::default());
    assert_eq!(
        arena[div_id].css_attr.0.get("display").map(|s| s.as_ref()),
        None
    );
    assert_eq!(
        arena[div_id].css_attr.0.get("color").map(|s| s.as_ref()),
        Some("red")
    );
}

#[test]
fn test_media_unsupported_query_drops_the_block() {
    init();
    // An unsupported unit makes the query false — the rule is parsed but can
    // never match any viewport.
    let media = media_queries("@media (max-width: 5em) { .side { display: none; } }");
    assert_eq!(media.len(), 1);
    let list = media[0].as_ref().expect("condition attached");
    assert!(!list.matches(&Viewport { cols: 1, rows: 1 }));

    // An unknown feature also drops its query; the other comma alternative
    // still works.
    let media =
        media_queries("@media (hover: hover), (max-width: 40) { .side { display: none; } }");
    assert_eq!(media.len(), 1);
    let list = media[0].as_ref().expect("condition attached");
    assert!(list.matches(&Viewport { cols: 30, rows: 24 }));
    assert!(!list.matches(&Viewport { cols: 80, rows: 24 }));

    // `orientation` is supported: landscape (cols >= rows) and portrait.
    let media = media_queries("@media (orientation: landscape) { .side { display: none; } }");
    let list = media[0].as_ref().expect("condition attached");
    assert!(list.matches(&Viewport { cols: 80, rows: 24 }));
    assert!(!list.matches(&Viewport { cols: 30, rows: 40 }), "portrait");
    let media = media_queries("@media (orientation: portrait) { .side { display: none; } }");
    let list = media[0].as_ref().expect("condition attached");
    assert!(list.matches(&Viewport { cols: 30, rows: 40 }));

    // Media types: `screen` / `all` match, `print` never does.
    let media = media_queries("@media screen and (max-width: 40) { .side { display: none; } }");
    let list = media[0].as_ref().expect("condition attached");
    assert!(list.matches(&Viewport { cols: 30, rows: 24 }));
    assert!(!list.matches(&Viewport { cols: 80, rows: 24 }));
    let media = media_queries("@media print { .side { display: none; } }");
    let list = media[0].as_ref().expect("condition attached");
    assert!(!list.matches(&Viewport { cols: 30, rows: 24 }));

    // `not` inverts the whole query; `only` is an ignored legacy prefix.
    let media = media_queries("@media not (max-width: 40) { .side { display: none; } }");
    let list = media[0].as_ref().expect("condition attached");
    assert!(!list.matches(&Viewport { cols: 30, rows: 24 }));
    assert!(list.matches(&Viewport { cols: 80, rows: 24 }));
    let media =
        media_queries("@media only screen and (max-width: 40) { .side { display: none; } }");
    let list = media[0].as_ref().expect("condition attached");
    assert!(list.matches(&Viewport { cols: 30, rows: 24 }));

    // An empty prelude drops the whole block (no rules at all). A query that
    // cannot parse (missing value) leaves the rule in place but its empty
    // query list matches no viewport — CSS treats an unknown media query as
    // false.
    assert!(media_queries("@media { .side { display: none; } }").is_empty());
    let media = media_queries("@media (max-width:) { .side { display: none; } }");
    assert_eq!(media.len(), 1);
    assert!(
        !media[0]
            .as_ref()
            .expect("condition attached")
            .matches(&Viewport { cols: 1, rows: 1 })
    );
}

#[test]
fn test_media_at_rule_does_not_disturb_following_rules() {
    init();
    let css = "@media (max-width: 40) { .side { display: none; } } .after { color: red; }";
    let rules = Parser::new(css).parse();
    assert_eq!(rules.0.len(), 2, "media child + following rule");
    assert!(rules.0[0].media.is_some());
    assert!(rules.0[1].media.is_none());
    assert_eq!(
        rules.0[1].normal.0.get("color").map(|s| s.as_ref()),
        Some("red")
    );
}

#[test]
fn attribute_selector_exists() {
    let sel: CssSelector = "[disabled]".parse().expect("bare attr parses");
    assert_eq!(sel.compounds.len(), 1);
    assert_eq!(sel.compounds[0].len(), 1);
    let htui::html::css_parse::AttributeSelector {
        name, op, value, ..
    } = match &sel.compounds[0][0] {
        htui::html::css_parse::Selector::Attribute(a) => a.clone(),
        _ => panic!("expected Attribute"),
    };
    assert_eq!(name, "disabled");
    assert_eq!(op, htui::html::css_parse::AttributeOp::Exists);
    assert_eq!(value, "");
}

#[test]
fn attribute_selector_equals_quoted_and_unquoted() {
    for css in ["[type=\"range\"]", "[type=range]"] {
        let sel: CssSelector = css.parse().expect("equals attr parses");
        match &sel.compounds[0][0] {
            htui::html::css_parse::Selector::Attribute(a) => {
                assert_eq!(a.name, "type");
                assert_eq!(a.op, htui::html::css_parse::AttributeOp::Equals);
                assert_eq!(a.value, "range");
            }
            _ => panic!("expected Attribute"),
        }
    }
}

#[test]
fn attribute_selector_compound_with_tag() {
    let sel: CssSelector = "input[type=\"range\"]"
        .parse()
        .expect("compound attr parses");
    assert_eq!(sel.compounds[0].len(), 2, "tag + attribute");
    match &sel.compounds[0][0] {
        htui::html::css_parse::Selector::Tag(nt) => {
            assert_eq!(*nt, htui::tdom::node::NodeType::Input);
        }
        _ => panic!("expected Tag"),
    }
}

#[test]
fn attribute_selector_prefix_suffix_substring() {
    let sel: CssSelector = "[href^=\"https\"]".parse().unwrap();
    match &sel.compounds[0][0] {
        htui::html::css_parse::Selector::Attribute(a) => {
            assert_eq!(a.op, htui::html::css_parse::AttributeOp::PrefixMatch);
            assert_eq!(a.value, "https");
        }
        _ => panic!(),
    }
    let sel: CssSelector = "[href$=\".pdf\"]".parse().unwrap();
    match &sel.compounds[0][0] {
        htui::html::css_parse::Selector::Attribute(a) => {
            assert_eq!(a.op, htui::html::css_parse::AttributeOp::SuffixMatch);
        }
        _ => panic!(),
    }
    let sel: CssSelector = "[href*=\"example\"]".parse().unwrap();
    match &sel.compounds[0][0] {
        htui::html::css_parse::Selector::Attribute(a) => {
            assert_eq!(a.op, htui::html::css_parse::AttributeOp::SubstringMatch);
        }
        _ => panic!(),
    }
}

#[test]
fn attribute_selector_dash_and_includes() {
    let sel: CssSelector = "[lang|=\"en\"]".parse().unwrap();
    match &sel.compounds[0][0] {
        htui::html::css_parse::Selector::Attribute(a) => {
            assert_eq!(a.op, htui::html::css_parse::AttributeOp::DashMatch);
        }
        _ => panic!(),
    }
    let sel: CssSelector = "[class~=\"btn\"]".parse().unwrap();
    match &sel.compounds[0][0] {
        htui::html::css_parse::Selector::Attribute(a) => {
            assert_eq!(a.op, htui::html::css_parse::AttributeOp::Includes);
        }
        _ => panic!(),
    }
}

#[test]
fn attribute_selector_case_insensitive_flag() {
    let sel: CssSelector = "[type=\"RANGE\" i]".parse().unwrap();
    match &sel.compounds[0][0] {
        htui::html::css_parse::Selector::Attribute(a) => {
            assert!(a.case_insensitive);
            assert_eq!(a.value, "RANGE");
        }
        _ => panic!(),
    }
}

#[test]
fn attribute_selector_specificity_is_class_level() {
    let bare: CssSelector = "input".parse().unwrap();
    let attr: CssSelector = "input[type]".parse().unwrap();
    let (_, b_bare, _) = bare.specificity();
    let (_, b_attr, _) = attr.specificity();
    assert_eq!(b_attr, b_bare + 1, "attribute adds one b-level specificity");
}

#[test]
fn attribute_selector_unclosed_bracket_is_error() {
    assert!("[type".parse::<CssSelector>().is_err());
    assert!("[]".parse::<CssSelector>().is_err());
}

fn parse_and_cascade(html: &str) -> (NodeId, NodeArena) {
    let mut html_parser = html_parse::Parser::new(html);
    let (root_id, mut arena, embedded) = html_parser.parse();
    let mut css_parser = Parser::new(&embedded);
    let rules = css_parser.parse();
    css_into_node(&mut arena, root_id, &rules);
    (root_id, arena)
}

fn find_first_by_tag(arena: &NodeArena, root: NodeId, tag: NodeType) -> NodeId {
    fn walk(arena: &NodeArena, id: NodeId, tag: NodeType) -> Option<NodeId> {
        if arena[id].node_type == tag {
            return Some(id);
        }
        for &c in &arena[id].children {
            if let Some(found) = walk(arena, c, tag) {
                return Some(found);
            }
        }
        None
    }
    walk(arena, root, tag).expect("node with tag not found")
}

#[test]
fn css_var_basic_substitution() {
    let (root, arena) = parse_and_cascade(
        r#"<style>
            :root { --primary: #ff0000; }
            p { color: var(--primary); }
        </style><p>hi</p>"#,
    );
    let p = find_first_by_tag(&arena, root, NodeType::P);
    let color = arena[p].css_attr.get_color();
    assert_eq!(
        color,
        Some(Color::Rgb { r: 255, g: 0, b: 0 }),
        "var(--primary) resolves to red"
    );
}

#[test]
fn css_var_fallback_value() {
    let (root, arena) = parse_and_cascade(
        r#"<style>
            p { color: var(--undefined, blue); }
        </style><p>hi</p>"#,
    );
    let p = find_first_by_tag(&arena, root, NodeType::P);
    assert_eq!(
        arena[p].css_attr.get_color(),
        Some(Color::Rgb { r: 0, g: 0, b: 255 }),
        "fallback is used when the variable is undefined"
    );
}

#[test]
fn css_var_inheritance_children() {
    let (root, arena) = parse_and_cascade(
        r#"<style>
            div { --c: green; }
            span { color: var(--c); }
        </style><div><span>s</span></div>"#,
    );
    let div = find_first_by_tag(&arena, root, NodeType::Div);
    let span = arena[div].children[0];
    assert_eq!(
        arena[span].css_attr.get_color(),
        Some(Color::Rgb { r: 0, g: 128, b: 0 }),
        "--c inherits from div to span"
    );
}

#[test]
fn css_var_override_in_child() {
    let (root, arena) = parse_and_cascade(
        r#"<style>
            div { --c: red; }
            span { --c: blue; color: var(--c); }
        </style><div><span>s</span></div>"#,
    );
    let div = find_first_by_tag(&arena, root, NodeType::Div);
    let span = arena[div].children[0];
    assert_eq!(
        arena[span].css_attr.get_color(),
        Some(Color::Rgb { r: 0, g: 0, b: 255 }),
        "child's --c override wins over parent"
    );
}

#[test]
fn css_var_in_calc() {
    let (root, arena) = parse_and_cascade(
        r#"<style>
            :root { --w: 20ch; }
            div { width: calc(var(--w) + 5ch); }
        </style><div>d</div>"#,
    );
    let div = find_first_by_tag(&arena, root, NodeType::Div);
    let w = arena[div]
        .css_attr
        .get_width(80, font_ctx(1, 1), viewport());
    assert_eq!(w, Some(25), "calc(var(--w) + 5ch) = 20 + 5 = 25");
}

#[test]
fn css_var_chain_reference() {
    let (root, arena) = parse_and_cascade(
        r#"<style>
            :root { --a: red; --b: var(--a); }
            p { color: var(--b); }
        </style><p>x</p>"#,
    );
    let p = find_first_by_tag(&arena, root, NodeType::P);
    assert_eq!(
        arena[p].css_attr.get_color(),
        Some(Color::Rgb { r: 255, g: 0, b: 0 }),
        "--b references --a which is red"
    );
}

#[test]
fn css_var_undefined_no_fallback_substitutes_empty() {
    let (root, arena) = parse_and_cascade(
        r#"<style>
            p { color: var(--nothing); }
        </style><p>x</p>"#,
    );
    let p = find_first_by_tag(&arena, root, NodeType::P);
    // Value becomes empty string → parser returns None.
    assert_eq!(arena[p].css_attr.get_color(), None);
}

#[test]
fn css_var_multiple_in_one_value() {
    let (root, arena) = parse_and_cascade(
        r#"<style>
            :root { --bw: 2ch; --bc: red; }
            div { border: var(--bw) solid var(--bc); }
        </style><div>d</div>"#,
    );
    let div = find_first_by_tag(&arena, root, NodeType::Div);
    // After substitution no `var(` should remain in any stored value.
    let has_unresolved = arena[div].css_attr.0.values().any(|v| v.contains("var("));
    assert!(!has_unresolved, "all var() references are substituted");
    let border = arena[div].css_attr.0.get("border");
    assert_eq!(
        border.map(|s| s.as_ref()),
        Some("2ch solid red"),
        "border shorthand has both vars substituted"
    );
}

// ============================================================
// CSS Grid value parsing
// ============================================================

#[test]
fn grid_line_parses_numbers_spans_and_area_names() {
    use htui::html::css_parse::{GridLine, parse_grid_axis_shorthand};
    assert_eq!(GridLine::parse("3"), Some(GridLine::Line(3)));
    assert_eq!(GridLine::parse("-2"), Some(GridLine::Line(-2)));
    assert_eq!(GridLine::parse("0"), None);
    assert_eq!(GridLine::parse("span 2"), Some(GridLine::Span(2)));
    assert_eq!(GridLine::parse("span"), None);
    assert_eq!(GridLine::parse("auto"), Some(GridLine::Auto));
    assert_eq!(
        GridLine::parse("head"),
        Some(GridLine::Name(Arc::from("head")))
    );
    assert_eq!(GridLine::parse("2ch"), None, "lengths are not grid lines");
    // A bare custom-ident start copies into the omitted end line.
    assert_eq!(
        parse_grid_axis_shorthand("sidebar"),
        Some((
            GridLine::Name(Arc::from("sidebar")),
            GridLine::Name(Arc::from("sidebar"))
        ))
    );
    assert_eq!(
        parse_grid_axis_shorthand("2"),
        Some((GridLine::Line(2), GridLine::Auto))
    );
}

#[test]
fn grid_area_shorthand_copies_ident_starts_into_end_lines() {
    use htui::html::css_parse::{GridLine, parse_grid_area};
    let name = |s: &str| Some(GridLine::Name(Arc::from(s)));
    let whole = parse_grid_area("head").expect("single name addresses the whole area");
    assert_eq!(whole.row_start, name("head"));
    assert_eq!(whole.column_start, name("head"));
    assert_eq!(whole.row_end, name("head"));
    assert_eq!(whole.column_end, name("head"));
    let numeric = parse_grid_area("2 / 3").expect("numeric lines");
    assert_eq!(numeric.row_start, Some(GridLine::Line(2)));
    assert_eq!(numeric.column_start, Some(GridLine::Line(3)));
    assert_eq!(numeric.row_end, Some(GridLine::Auto));
    assert_eq!(numeric.column_end, Some(GridLine::Auto));
}

#[test]
fn grid_template_areas_parses_a_rectangular_matrix() {
    use htui::html::css_parse::{GridAreas, parse_grid_template_areas};
    let areas = parse_grid_template_areas(r#""a . b" "a . b""#).expect("valid matrix");
    assert_eq!(areas.row_count(), 2);
    assert_eq!(areas.column_count(), 3);
    assert_eq!(areas.cells[1][0].as_deref(), Some("a"));
    assert_eq!(areas.cells[1][1], None, "a dot cell is null");
    assert_eq!(areas.cells[1][2].as_deref(), Some("b"));
    assert_eq!(
        parse_grid_template_areas("none"),
        Some(GridAreas { cells: Vec::new() })
    );
}

#[test]
fn grid_template_areas_rejects_ragged_or_non_rectangular_values() {
    use htui::html::css_parse::parse_grid_template_areas;
    assert!(
        parse_grid_template_areas(r#""a a" "a""#).is_none(),
        "rows must share one width"
    );
    assert!(
        parse_grid_template_areas(r#""a b" "b a""#).is_none(),
        "an L-shaped area is invalid"
    );
    assert!(parse_grid_template_areas("a b").is_none(), "unquoted cells");
    assert!(parse_grid_template_areas("").is_none());
}

#[test]
fn grid_track_parses_minmax_and_fit_content() {
    use htui::html::css_parse::{GridTrack, Length, parse_grid_track_list};
    let length_track = |s: &str| GridTrack::Length(Length::parse(s).expect("test lengths parse"));
    assert_eq!(
        GridTrack::parse("minmax(1ch, 3ch)"),
        Some(GridTrack::MinMax {
            min: Box::new(length_track("1ch")),
            max: Box::new(length_track("3ch")),
        })
    );
    assert_eq!(
        GridTrack::parse("minmax(1fr, 2ch)"),
        None,
        "the min side of minmax is never flexible"
    );
    assert_eq!(
        GridTrack::parse("minmax(minmax(1ch, 2ch), 3ch)"),
        None,
        "a breadth is never a nested function"
    );
    assert_eq!(
        GridTrack::parse("FIT-CONTENT(2ch)"),
        Some(GridTrack::MinMax {
            min: Box::new(GridTrack::Auto),
            max: Box::new(length_track("2ch")),
        }),
        "fit-content desugars to minmax(auto, length); function names are case-insensitive"
    );
    let fr_max = GridTrack::parse("minmax(auto, 1fr)").expect("a flexible max is valid");
    assert!(fr_max.is_fr(), "a flexible max joins fr distribution");
    let repeated = parse_grid_track_list("repeat(2, minmax(1ch, 3ch))").expect("repeat expands");
    assert_eq!(repeated.len(), 2);
    assert!(
        repeated
            .iter()
            .all(|t| matches!(t, GridTrack::MinMax { .. }))
    );
}

#[test]
fn grid_track_parses_auto_fill_and_auto_fit_repeats() {
    use htui::html::css_parse::{GridTrack, parse_grid_track_list};
    let list = parse_grid_track_list("repeat(auto-fill, minmax(10ch, 1fr))").expect("auto-fill");
    assert_eq!(list.len(), 1, "an auto-repeat stays one unresolved track");
    assert!(
        matches!(&list[0], GridTrack::AutoRepeat { fit: false, tracks } if tracks.len() == 1),
        "auto-fill is recorded with its inner track list"
    );
    let fit =
        parse_grid_track_list("repeat(AUTO-FIT, 3ch 1ch)").expect("auto-fit, case-insensitive");
    assert!(matches!(&fit[0], GridTrack::AutoRepeat { fit: true, tracks } if tracks.len() == 2));
    assert!(
        parse_grid_track_list("repeat(auto-fill, repeat(auto-fill, 3ch))").is_none(),
        "auto-repeats cannot nest"
    );
    assert!(
        parse_grid_track_list("repeat(2, repeat(auto-fill, 3ch))").is_none(),
        "auto-repeats cannot nest inside an integer repeat"
    );
    assert!(
        parse_grid_track_list("repeat(auto-fill,)").is_none(),
        "an empty track list is invalid"
    );
}

#[test]
fn grid_line_parses_named_spans() {
    use htui::html::css_parse::GridLine;
    assert_eq!(
        GridLine::parse("span 2 head"),
        Some(GridLine::SpanName {
            span: 2,
            name: Arc::from("head")
        })
    );
    assert_eq!(
        GridLine::parse("span head"),
        Some(GridLine::SpanName {
            span: 1,
            name: Arc::from("head")
        })
    );
    assert_eq!(GridLine::parse("span 2"), Some(GridLine::Span(2)));
    assert_eq!(GridLine::parse("span 0"), None);
    assert_eq!(GridLine::parse("span 2 3"), None, "two integers");
    assert_eq!(GridLine::parse("span head tail"), None, "two idents");
}

#[test]
fn grid_template_shorthand_expands_area_strings() {
    let (root, arena) = parse_and_cascade(
        r#"<style>
            .g { grid-template: "head head" 1fr "side main" 2ch / 2ch 1fr; }
        </style><div class="g"></div>"#,
    );
    let div = find_first_by_tag(&arena, root, NodeType::Div);
    assert_eq!(
        arena[div]
            .css_attr
            .0
            .get("grid-template-areas")
            .map(|s| s.as_ref()),
        Some(r#""head head" "side main""#)
    );
    assert_eq!(
        arena[div]
            .css_attr
            .0
            .get("grid-template-rows")
            .map(|s| s.as_ref()),
        Some("1fr 2ch"),
        "each area row gets its size, defaulting to auto"
    );
    assert_eq!(
        arena[div]
            .css_attr
            .0
            .get("grid-template-columns")
            .map(|s| s.as_ref()),
        Some("2ch 1fr")
    );
    let (root, arena) = parse_and_cascade(
        r#"<style>
            .p { grid-template: 2ch 1fr; }
        </style><div class="p"></div>"#,
    );
    let div = find_first_by_tag(&arena, root, NodeType::Div);
    assert!(
        arena[div].css_attr.0.contains_key("grid-template"),
        "the plain track-list form keeps the raw shorthand"
    );
    assert!(!arena[div].css_attr.0.contains_key("grid-template-areas"));
}

#[test]
fn stylesheet_prelude_blocks_do_not_truncate_selectors() {
    // Regression: the rule-prelude reader used to stop at the first `[…]`
    // block (block content never advanced the position), silently dropping
    // every rule whose selector carried an attribute selector — the page's
    // `input[type="range"]` accent-color styling never applied. Argumented
    // pseudo-classes (`:not(…)`) hit the same truncation.
    let (root, arena) = parse_and_cascade(
        r#"<style>
            :root { --accent: #43e5a0; }
            input[type="range"] { accent-color: var(--accent); }
            p:not(.x) { color: #ff7a90; }
        </style>
        <input type="range"><p>one</p>"#,
    );
    let input = find_first_by_tag(&arena, root, NodeType::Input);
    assert_eq!(
        arena[input].css_attr.get_accent_color(),
        parse_color_str("#43e5a0"),
        "an attribute-selector rule applies, with var() substituted"
    );
    let p = find_first_by_tag(&arena, root, NodeType::P);
    assert_eq!(
        arena[p].css_attr.get_color(),
        parse_color_str("#ff7a90"),
        "an argumented pseudo-class rule applies"
    );
}