rich-rs 1.2.0

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

use std::collections::BTreeMap;
use std::sync::Arc;

use crate::color::{ColorSystem, SimpleColor as Color};

/// A null style with all attributes set to `None`.
///
/// This is useful as a default or starting point for style combinations.
pub const NULL_STYLE: Style = Style {
    color: None,
    bgcolor: None,
    bold: None,
    dim: None,
    italic: None,
    underline: None,
    blink: None,
    blink2: None,
    reverse: None,
    conceal: None,
    strike: None,
    underline2: None,
    frame: None,
    encircle: None,
    overline: None,
};

/// Text style with color and attributes.
///
/// Uses `Option<bool>` for attributes to support three states:
/// - `None`: inherit from parent
/// - `Some(true)`: enable
/// - `Some(false)`: disable
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Style {
    /// Foreground color.
    pub color: Option<Color>,
    /// Background color.
    pub bgcolor: Option<Color>,
    /// Bold text.
    pub bold: Option<bool>,
    /// Dim/faint text.
    pub dim: Option<bool>,
    /// Italic text.
    pub italic: Option<bool>,
    /// Underlined text.
    pub underline: Option<bool>,
    /// Blinking text.
    pub blink: Option<bool>,
    /// Rapid blinking text (SGR 6).
    pub blink2: Option<bool>,
    /// Reverse video (swap fg/bg).
    pub reverse: Option<bool>,
    /// Concealed text (SGR 8).
    pub conceal: Option<bool>,
    /// Strikethrough text.
    pub strike: Option<bool>,
    /// Double underline (SGR 21).
    pub underline2: Option<bool>,
    /// Framed text (SGR 51).
    pub frame: Option<bool>,
    /// Encircled text (SGR 52).
    pub encircle: Option<bool>,
    /// Overlined text (SGR 53).
    pub overline: Option<bool>,
}

impl Style {
    /// Create a new empty style.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a style with a foreground color.
    pub fn color(color: Color) -> Self {
        Self {
            color: Some(color),
            ..Default::default()
        }
    }

    /// Create a style with a background color.
    pub fn bgcolor(color: Color) -> Self {
        Self {
            bgcolor: Some(color),
            ..Default::default()
        }
    }

    /// Builder: set foreground color.
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Builder: set background color.
    pub fn with_bgcolor(mut self, color: Color) -> Self {
        self.bgcolor = Some(color);
        self
    }

    /// Builder: set bold.
    pub fn with_bold(mut self, bold: bool) -> Self {
        self.bold = Some(bold);
        self
    }

    /// Builder: set dim.
    pub fn with_dim(mut self, dim: bool) -> Self {
        self.dim = Some(dim);
        self
    }

    /// Builder: set italic.
    pub fn with_italic(mut self, italic: bool) -> Self {
        self.italic = Some(italic);
        self
    }

    /// Builder: set underline.
    pub fn with_underline(mut self, underline: bool) -> Self {
        self.underline = Some(underline);
        self
    }

    /// Builder: set reverse video.
    pub fn with_reverse(mut self, reverse: bool) -> Self {
        self.reverse = Some(reverse);
        self
    }

    /// Builder: set strike.
    pub fn with_strike(mut self, strike: bool) -> Self {
        self.strike = Some(strike);
        self
    }

    /// Builder: set blink2 (rapid blink).
    pub fn with_blink2(mut self, blink2: bool) -> Self {
        self.blink2 = Some(blink2);
        self
    }

    /// Builder: set conceal.
    pub fn with_conceal(mut self, conceal: bool) -> Self {
        self.conceal = Some(conceal);
        self
    }

    /// Builder: set underline2 (double underline).
    pub fn with_underline2(mut self, underline2: bool) -> Self {
        self.underline2 = Some(underline2);
        self
    }

    /// Builder: set frame.
    pub fn with_frame(mut self, frame: bool) -> Self {
        self.frame = Some(frame);
        self
    }

    /// Builder: set encircle.
    pub fn with_encircle(mut self, encircle: bool) -> Self {
        self.encircle = Some(encircle);
        self
    }

    /// Builder: set overline.
    pub fn with_overline(mut self, overline: bool) -> Self {
        self.overline = Some(overline);
        self
    }

    /// Combine this style with another, with `other` taking precedence.
    ///
    /// Values from `other` override values from `self` only if they are `Some`.
    pub fn combine(&self, other: &Style) -> Self {
        Style {
            color: other.color.or(self.color),
            bgcolor: other.bgcolor.or(self.bgcolor),
            bold: other.bold.or(self.bold),
            dim: other.dim.or(self.dim),
            italic: other.italic.or(self.italic),
            underline: other.underline.or(self.underline),
            blink: other.blink.or(self.blink),
            blink2: other.blink2.or(self.blink2),
            reverse: other.reverse.or(self.reverse),
            conceal: other.conceal.or(self.conceal),
            strike: other.strike.or(self.strike),
            underline2: other.underline2.or(self.underline2),
            frame: other.frame.or(self.frame),
            encircle: other.encircle.or(self.encircle),
            overline: other.overline.or(self.overline),
        }
    }

    /// Parse a style from a string.
    ///
    /// Supports space-separated style definitions like:
    /// - "bold red on blue"
    /// - "italic #ff0000"
    /// - "bold underline"
    /// - "not bold" (negation)
    pub fn parse(s: &str) -> Option<Self> {
        let mut style = Style::new();
        let mut on_background = false;

        let mut words = s.split_whitespace().peekable();

        while let Some(word) = words.next() {
            let word_lower = word.to_lowercase();

            if word_lower == "on" {
                on_background = true;
                continue;
            }

            if on_background {
                if let Some(color) = Color::parse(&word_lower) {
                    style.bgcolor = Some(color);
                    on_background = false;
                    continue;
                }
                // If the token wasn't a valid color, drop the background flag and
                // continue processing it normally.
                on_background = false;
            }

            // Support Rich-style named styles from the default theme, e.g. "progress.percentage".
            // If a token matches a default style name, merge it into the current style.
            if let Some(named) = crate::theme::get_default_style(&word_lower) {
                style = style.combine(&named);
                continue;
            }

            // Handle negation: "not bold", "not italic", etc.
            // Also handles shorthand: "not b", "not i", "not u", "not s"
            if word_lower == "not" {
                if let Some(&next_word) = words.peek() {
                    let next_lower = next_word.to_lowercase();
                    match next_lower.as_str() {
                        "bold" | "b" => {
                            style.bold = Some(false);
                            words.next();
                            continue;
                        }
                        "dim" | "d" => {
                            style.dim = Some(false);
                            words.next();
                            continue;
                        }
                        "italic" | "i" => {
                            style.italic = Some(false);
                            words.next();
                            continue;
                        }
                        "underline" | "u" => {
                            style.underline = Some(false);
                            words.next();
                            continue;
                        }
                        "blink" => {
                            style.blink = Some(false);
                            words.next();
                            continue;
                        }
                        "blink2" => {
                            style.blink2 = Some(false);
                            words.next();
                            continue;
                        }
                        "reverse" | "r" => {
                            style.reverse = Some(false);
                            words.next();
                            continue;
                        }
                        "conceal" | "c" => {
                            style.conceal = Some(false);
                            words.next();
                            continue;
                        }
                        "strike" | "s" => {
                            style.strike = Some(false);
                            words.next();
                            continue;
                        }
                        "underline2" | "uu" => {
                            style.underline2 = Some(false);
                            words.next();
                            continue;
                        }
                        "frame" => {
                            style.frame = Some(false);
                            words.next();
                            continue;
                        }
                        "encircle" => {
                            style.encircle = Some(false);
                            words.next();
                            continue;
                        }
                        "overline" | "o" => {
                            style.overline = Some(false);
                            words.next();
                            continue;
                        }
                        _ => {}
                    }
                }
                // "not" without valid attribute - ignore
                continue;
            }

            // Check for attributes (including shorthand: b, d, i, u, s, r, c, o, uu)
            match word_lower.as_str() {
                "bold" | "b" => style.bold = Some(true),
                "dim" | "d" => style.dim = Some(true),
                "italic" | "i" => style.italic = Some(true),
                "underline" | "u" => style.underline = Some(true),
                "blink" => style.blink = Some(true),
                "blink2" => style.blink2 = Some(true),
                "reverse" | "r" => style.reverse = Some(true),
                "conceal" | "c" => style.conceal = Some(true),
                "strike" | "s" => style.strike = Some(true),
                "underline2" | "uu" => style.underline2 = Some(true),
                "frame" => style.frame = Some(true),
                "encircle" => style.encircle = Some(true),
                "overline" | "o" => style.overline = Some(true),
                _ => {
                    // Try to parse as color
                    if let Some(color) = Color::parse(&word_lower) {
                        style.color = Some(color);
                    }
                }
            }
        }

        Some(style)
    }

    /// Check if this is a null style (all attributes are None).
    pub fn is_null(&self) -> bool {
        *self == NULL_STYLE
    }

    /// Render text with this style using ANSI escape codes.
    ///
    /// # Arguments
    ///
    /// * `text` - The text to style.
    /// * `color_system` - The color system to render to.
    ///
    /// # Returns
    ///
    /// A string containing the text wrapped in ANSI escape codes.
    /// If text is empty, returns empty string.
    ///
    /// # Examples
    ///
    /// ```
    /// use rich_rs::{Style, ColorSystem, SimpleColor};
    ///
    /// let style = Style::new().with_bold(true).with_color(SimpleColor::Standard(1));
    /// let rendered = style.render("Hello", ColorSystem::TrueColor);
    /// assert!(rendered.contains("\x1b["));
    /// assert!(rendered.contains("Hello"));
    /// assert!(rendered.ends_with("\x1b[0m"));
    /// ```
    pub fn render(&self, text: &str, color_system: ColorSystem) -> String {
        if text.is_empty() {
            return String::new();
        }

        let attrs = self.make_ansi_codes(color_system);
        if attrs.is_empty() {
            text.to_string()
        } else {
            format!("\x1b[{}m{}\x1b[0m", attrs, text)
        }
    }

    /// Render styled text WITHOUT a trailing reset.
    ///
    /// This is used for streaming output where we want to minimize SGR resets
    /// to avoid visual artifacts (like black hairlines between colored lines).
    /// The caller is responsible for emitting a reset at the end.
    pub fn render_open(&self, text: &str, color_system: ColorSystem) -> String {
        if text.is_empty() {
            return String::new();
        }

        let attrs = self.make_ansi_codes(color_system);
        if attrs.is_empty() {
            text.to_string()
        } else {
            format!("\x1b[{}m{}", attrs, text)
        }
    }

    /// Generate the ANSI SGR codes for this style.
    ///
    /// Returns a semicolon-separated string of SGR parameters.
    fn make_ansi_codes(&self, color_system: ColorSystem) -> String {
        let mut sgr: Vec<String> = Vec::new();

        // SGR reset codes for explicitly disabled attributes (emit "off" before "on"):
        // 22 = bold/dim off (resets both)
        // 23 = italic off
        // 24 = underline/underline2 off (resets both)
        // 25 = blink/blink2 off (resets both)
        // 27 = reverse off
        // 28 = conceal off
        // 29 = strike off
        // 54 = frame/encircle off (resets both)
        // 55 = overline off
        //
        // Note: SGR 22 resets both bold AND dim, so we only emit it once if either is false.
        // Similarly SGR 24 resets underline AND underline2, SGR 25 resets blink AND blink2,
        // and SGR 54 resets frame AND encircle.
        if self.bold == Some(false) || self.dim == Some(false) {
            sgr.push("22".to_string());
        }
        if self.italic == Some(false) {
            sgr.push("23".to_string());
        }
        if self.underline == Some(false) || self.underline2 == Some(false) {
            sgr.push("24".to_string());
        }
        if self.blink == Some(false) || self.blink2 == Some(false) {
            sgr.push("25".to_string());
        }
        if self.reverse == Some(false) {
            sgr.push("27".to_string());
        }
        if self.conceal == Some(false) {
            sgr.push("28".to_string());
        }
        if self.strike == Some(false) {
            sgr.push("29".to_string());
        }
        if self.frame == Some(false) || self.encircle == Some(false) {
            sgr.push("54".to_string());
        }
        if self.overline == Some(false) {
            sgr.push("55".to_string());
        }

        // SGR codes for enabled attributes:
        // bold=1, dim=2, italic=3, underline=4, blink=5, blink2=6,
        // reverse=7, conceal=8, strike=9, underline2=21,
        // frame=51, encircle=52, overline=53
        if self.bold == Some(true) {
            sgr.push("1".to_string());
        }
        if self.dim == Some(true) {
            sgr.push("2".to_string());
        }
        if self.italic == Some(true) {
            sgr.push("3".to_string());
        }
        if self.underline == Some(true) {
            sgr.push("4".to_string());
        }
        if self.blink == Some(true) {
            sgr.push("5".to_string());
        }
        if self.blink2 == Some(true) {
            sgr.push("6".to_string());
        }
        if self.reverse == Some(true) {
            sgr.push("7".to_string());
        }
        if self.conceal == Some(true) {
            sgr.push("8".to_string());
        }
        if self.strike == Some(true) {
            sgr.push("9".to_string());
        }
        if self.underline2 == Some(true) {
            sgr.push("21".to_string());
        }
        if self.frame == Some(true) {
            sgr.push("51".to_string());
        }
        if self.encircle == Some(true) {
            sgr.push("52".to_string());
        }
        if self.overline == Some(true) {
            sgr.push("53".to_string());
        }

        // Foreground color
        if let Some(color) = self.color {
            let downgraded = color.downgrade(color_system);
            sgr.extend(downgraded.get_ansi_codes(true));
        }

        // Background color
        if let Some(bgcolor) = self.bgcolor {
            let downgraded = bgcolor.downgrade(color_system);
            sgr.extend(downgraded.get_ansi_codes(false));
        }

        sgr.join(";")
    }

    /// Get a CSS style string for this style.
    ///
    /// # Returns
    ///
    /// A semicolon-separated CSS string suitable for use in a `style` attribute.
    ///
    /// # Examples
    ///
    /// ```
    /// use rich_rs::{Style, SimpleColor};
    ///
    /// let style = Style::new()
    ///     .with_bold(true)
    ///     .with_color(SimpleColor::Rgb { r: 255, g: 0, b: 0 });
    /// let css = style.get_html_style();
    /// assert!(css.contains("font-weight: bold"));
    /// assert!(css.contains("color:"));
    /// ```
    pub fn get_html_style(&self) -> String {
        let mut css: Vec<String> = Vec::new();

        // Handle reverse by swapping colors conceptually
        let (color, bgcolor) = if self.reverse == Some(true) {
            (self.bgcolor, self.color)
        } else {
            (self.color, self.bgcolor)
        };

        // Foreground color
        if let Some(c) = color {
            let hex = c.get_hex();
            css.push(format!("color: {}", hex));
            css.push(format!("text-decoration-color: {}", hex));
        }

        // Background color
        if let Some(c) = bgcolor {
            let hex = c.get_hex();
            css.push(format!("background-color: {}", hex));
        }

        // Text attributes
        if self.bold == Some(true) {
            css.push("font-weight: bold".to_string());
        }
        if self.italic == Some(true) {
            css.push("font-style: italic".to_string());
        }

        // Collect text-decoration values to avoid clobbering
        let mut decorations = Vec::new();
        if self.underline == Some(true) {
            decorations.push("underline");
        }
        if self.strike == Some(true) {
            decorations.push("line-through");
        }
        if self.overline == Some(true) {
            decorations.push("overline");
        }
        if !decorations.is_empty() {
            css.push(format!("text-decoration: {}", decorations.join(" ")));
        }

        css.join("; ")
    }

    /// Chain multiple styles together. Like `combine` but applied left-to-right.
    ///
    /// This is equivalent to Python Rich's `Style.chain(*styles)`.
    pub fn chain(styles: &[Style]) -> Self {
        let mut result = Style::new();
        for style in styles {
            result = result.combine(style);
        }
        result
    }

    /// Create a style with only foreground/background colors.
    ///
    /// This is equivalent to Python Rich's `Style.from_color`.
    pub fn from_color(color: Option<Color>, bgcolor: Option<Color>) -> Self {
        Self {
            color,
            bgcolor,
            ..Default::default()
        }
    }

    /// Create blank style metadata with optional event handlers.
    ///
    /// In Python Rich, `Style.on(...)` returns a Style with metadata attached.
    /// In this crate, metadata is represented separately as `StyleMeta`.
    pub fn on<I, K>(meta: Option<BTreeMap<String, MetaValue>>, handlers: I) -> StyleMeta
    where
        I: IntoIterator<Item = (K, MetaValue)>,
        K: Into<String>,
    {
        let mut merged = meta.unwrap_or_default();
        for (key, value) in handlers {
            merged.insert(format!("@{}", key.into()), value);
        }

        StyleMeta {
            meta: if merged.is_empty() {
                None
            } else {
                Some(Arc::new(merged))
            },
            ..Default::default()
        }
    }

    /// Normalize a style definition to a canonical representation.
    ///
    /// This is equivalent to Python Rich's `Style.normalize`.
    /// Returns lowercased/trimmed input for syntactically invalid definitions.
    pub fn normalize(style: &str) -> String {
        let normalized = style.trim().to_lowercase();
        if normalized.is_empty() {
            return "none".to_string();
        }

        fn is_attr(word: &str) -> bool {
            matches!(
                word,
                "bold"
                    | "b"
                    | "dim"
                    | "d"
                    | "italic"
                    | "i"
                    | "underline"
                    | "u"
                    | "blink"
                    | "blink2"
                    | "reverse"
                    | "r"
                    | "conceal"
                    | "c"
                    | "strike"
                    | "s"
                    | "underline2"
                    | "uu"
                    | "frame"
                    | "encircle"
                    | "overline"
                    | "o"
            )
        }

        let mut words = normalized.split_whitespace().peekable();
        while let Some(word) = words.next() {
            match word {
                "on" => match words.next() {
                    Some(color) if Color::parse(color).is_some() => {}
                    _ => return normalized,
                },
                "not" => match words.next() {
                    Some(attr) if is_attr(attr) => {}
                    _ => return normalized,
                },
                _ => {
                    if is_attr(word)
                        || Color::parse(word).is_some()
                        || crate::theme::get_default_style(word).is_some()
                    {
                        continue;
                    }
                    return normalized;
                }
            }
        }

        let parsed = Self::parse(&normalized).unwrap_or_default();
        let canonical = parsed.to_markup_string();
        if canonical.is_empty() {
            "none".to_string()
        } else {
            canonical
        }
    }

    /// Return the first non-`None` style from a sequence.
    ///
    /// Panics if all styles are `None`, matching Python Rich's ValueError behavior.
    pub fn pick_first(values: &[Option<Style>]) -> Style {
        values
            .iter()
            .flatten()
            .copied()
            .next()
            .expect("expected at least one non-None style")
    }

    /// Apply the style to text and return the ANSI string.
    ///
    /// This is equivalent to Python Rich's `Style.test()`.
    pub fn test(&self, text: &str, color_system: ColorSystem) -> String {
        self.render(text, color_system)
    }

    /// Return a new Style with only the background color.
    ///
    /// This is equivalent to Python Rich's `Style.background_style`.
    pub fn background_style(&self) -> Self {
        Style {
            bgcolor: self.bgcolor,
            ..Default::default()
        }
    }

    /// Return a new Style with colors stripped but attributes preserved.
    ///
    /// This is equivalent to Python Rich's `Style.without_color`.
    pub fn without_color(&self) -> Self {
        Style {
            color: None,
            bgcolor: None,
            bold: self.bold,
            dim: self.dim,
            italic: self.italic,
            underline: self.underline,
            blink: self.blink,
            blink2: self.blink2,
            reverse: self.reverse,
            conceal: self.conceal,
            strike: self.strike,
            underline2: self.underline2,
            frame: self.frame,
            encircle: self.encircle,
            overline: self.overline,
        }
    }

    /// Check if the style has a transparent (unset or default) background.
    ///
    /// This is equivalent to Python Rich's `Style.transparent_background`.
    pub fn has_transparent_background(&self) -> bool {
        matches!(self.bgcolor, None | Some(Color::Default))
    }

    /// Convert this style to its markup-compatible string representation.
    ///
    /// Returns a string like `"bold red on blue"` that can be used in Rich markup tags.
    /// This is the canonical way to serialize a Style for markup — all consumers
    /// (Text::to_markup, Theme serialization, etc.) should use this method.
    pub fn to_markup_string(&self) -> String {
        use crate::color::ANSI_COLOR_NAMES;

        let mut parts: Vec<&str> = Vec::new();
        // Macro to reduce repetition for bool attributes
        macro_rules! attr {
            ($field:ident, $name:expr, $neg:expr) => {
                match self.$field {
                    Some(true) => parts.push($name),
                    Some(false) => parts.push($neg),
                    None => {}
                }
            };
            ($field:ident, $name:expr) => {
                if self.$field == Some(true) {
                    parts.push($name);
                }
            };
        }
        attr!(bold, "bold", "not bold");
        attr!(dim, "dim", "not dim");
        attr!(italic, "italic", "not italic");
        attr!(underline, "underline", "not underline");
        attr!(blink, "blink", "not blink");
        attr!(blink2, "blink2", "not blink2");
        attr!(reverse, "reverse", "not reverse");
        attr!(conceal, "conceal", "not conceal");
        attr!(strike, "strike", "not strike");
        attr!(underline2, "underline2", "not underline2");
        attr!(frame, "frame", "not frame");
        attr!(encircle, "encircle", "not encircle");
        attr!(overline, "overline", "not overline");

        let mut owned_parts: Vec<String> = parts.iter().map(|s| s.to_string()).collect();

        // Foreground color
        if let Some(ref color) = self.color {
            owned_parts.push(simple_color_name(color, &ANSI_COLOR_NAMES));
        }

        // Background color
        if let Some(ref bgcolor) = self.bgcolor {
            owned_parts.push(format!(
                "on {}",
                simple_color_name(bgcolor, &ANSI_COLOR_NAMES)
            ));
        }

        owned_parts.join(" ")
    }
}

/// Convert a SimpleColor to its markup name.
fn simple_color_name(color: &Color, color_names: &std::collections::HashMap<&str, u8>) -> String {
    match color {
        Color::Default => String::new(),
        Color::Standard(n) => {
            for (name, &idx) in color_names.iter() {
                if idx == *n {
                    return name.to_string();
                }
            }
            format!("color({})", n)
        }
        Color::EightBit(n) => format!("color({})", n),
        Color::Rgb { r, g, b } => format!("#{:02x}{:02x}{:02x}", r, g, b),
    }
}

/// A stack of styles where the current style is the combination of all pushed styles.
///
/// This mirrors Python Rich's `StyleStack`.
#[derive(Debug, Clone)]
pub struct StyleStack {
    _stack: Vec<Style>,
}

impl StyleStack {
    /// Create a new StyleStack with the given default style.
    pub fn new(default_style: Style) -> Self {
        StyleStack {
            _stack: vec![default_style],
        }
    }

    /// Get the current (top) style.
    pub fn current(&self) -> Style {
        *self._stack.last().unwrap()
    }

    /// Push a new style, combined with the current style.
    pub fn push(&mut self, style: Style) {
        let combined = self.current().combine(&style);
        self._stack.push(combined);
    }

    /// Pop the top style and return the new current.
    pub fn pop(&mut self) -> Style {
        self._stack.pop();
        self.current()
    }
}

impl std::ops::Add for Style {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        self.combine(&other)
    }
}

/// Metadata for styles, used for hyperlinks and custom data.
///
/// This is kept separate from `Style` to preserve `Style: Copy` for the
/// common case. Only segments with links or metadata need a `StyleMeta`.
///
/// Uses `BTreeMap` instead of `HashMap` for deterministic ordering,
/// which is important for segment simplification and serialization.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct StyleMeta {
    /// Hyperlink URL (terminal OSC 8 escape sequence).
    pub link: Option<Arc<str>>,
    /// Link ID for grouping multiple segments with the same link.
    pub link_id: Option<Arc<str>>,
    /// Custom metadata (used by Textual for event handlers).
    pub meta: Option<Arc<BTreeMap<String, MetaValue>>>,
}

impl StyleMeta {
    /// Create a new empty StyleMeta.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a StyleMeta with a hyperlink.
    pub fn with_link(link: impl Into<Arc<str>>) -> Self {
        StyleMeta {
            link: Some(link.into()),
            ..Default::default()
        }
    }

    /// Check if this meta has any content.
    pub fn is_empty(&self) -> bool {
        self.link.is_none() && self.link_id.is_none() && self.meta.is_none()
    }

    /// Combine with another StyleMeta, with `other` taking precedence.
    pub fn combine(&self, other: &StyleMeta) -> Self {
        StyleMeta {
            link: other.link.clone().or_else(|| self.link.clone()),
            link_id: other.link_id.clone().or_else(|| self.link_id.clone()),
            meta: match (&self.meta, &other.meta) {
                (Some(a), Some(b)) => {
                    let mut merged = (**a).clone();
                    merged.extend((**b).clone());
                    Some(Arc::new(merged))
                }
                (None, Some(b)) => Some(b.clone()),
                (Some(a), None) => Some(a.clone()),
                (None, None) => None,
            },
        }
    }
}

/// Structured metadata values (used by Textual handlers and richer annotations).
///
/// This is intentionally deterministic and `Eq` so it can be compared / merged
/// and used in segment simplification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetaValue {
    None,
    Bool(bool),
    Int(i64),
    Str(Arc<str>),
    List(Vec<MetaValue>),
    Tuple(Vec<MetaValue>),
    Map(BTreeMap<String, MetaValue>),
}

impl Default for MetaValue {
    fn default() -> Self {
        MetaValue::None
    }
}

impl MetaValue {
    pub fn str(value: impl Into<Arc<str>>) -> Self {
        MetaValue::Str(value.into())
    }

    /// Parse a small, deterministic subset of Python literals (like `ast.literal_eval`).
    ///
    /// Supported:
    /// - `None`, `True`, `False`
    /// - integers (base-10)
    /// - quoted strings `'...'` / `"..."` with basic escapes
    /// - lists `[a, b]`
    /// - tuples `(a, b)` (single element tuples require a trailing comma, like Python)
    /// - dicts `{'k': 1}` (string keys only)
    pub fn parse_python_literal(input: &str) -> Option<Self> {
        struct Parser<'a> {
            s: &'a str,
            i: usize,
        }

        impl<'a> Parser<'a> {
            fn new(s: &'a str) -> Self {
                Self { s, i: 0 }
            }

            fn is_eof(&self) -> bool {
                self.i >= self.s.len()
            }

            fn rest(&self) -> &'a str {
                &self.s[self.i..]
            }

            fn skip_ws(&mut self) {
                while let Some(ch) = self.peek() {
                    if ch.is_whitespace() {
                        self.bump(ch);
                    } else {
                        break;
                    }
                }
            }

            fn peek(&self) -> Option<char> {
                self.rest().chars().next()
            }

            fn bump(&mut self, ch: char) {
                self.i += ch.len_utf8();
            }

            fn eat(&mut self, expected: char) -> bool {
                self.skip_ws();
                if self.peek() == Some(expected) {
                    self.bump(expected);
                    true
                } else {
                    false
                }
            }

            fn parse_value(&mut self) -> Option<MetaValue> {
                self.skip_ws();
                let ch = self.peek()?;

                match ch {
                    '\'' | '"' => self.parse_string().map(|s| MetaValue::Str(Arc::from(s))),
                    '[' => self.parse_list(),
                    '{' => self.parse_map(),
                    '(' => self.parse_parens(),
                    '-' | '0'..='9' => self.parse_int().map(MetaValue::Int),
                    _ => self.parse_ident_or_keyword(),
                }
            }

            fn parse_ident_or_keyword(&mut self) -> Option<MetaValue> {
                self.skip_ws();
                let start = self.i;
                while let Some(ch) = self.peek() {
                    if ch.is_ascii_alphanumeric() || ch == '_' {
                        self.bump(ch);
                    } else {
                        break;
                    }
                }
                if self.i == start {
                    return None;
                }
                let ident = &self.s[start..self.i];
                match ident {
                    "None" => Some(MetaValue::None),
                    "True" => Some(MetaValue::Bool(true)),
                    "False" => Some(MetaValue::Bool(false)),
                    _ => None,
                }
            }

            fn parse_int(&mut self) -> Option<i64> {
                self.skip_ws();
                let start = self.i;
                if self.peek() == Some('-') {
                    self.bump('-');
                }
                let mut saw_digit = false;
                while let Some(ch) = self.peek() {
                    if ch.is_ascii_digit() {
                        saw_digit = true;
                        self.bump(ch);
                    } else {
                        break;
                    }
                }
                if !saw_digit {
                    self.i = start;
                    return None;
                }
                self.s[start..self.i].parse::<i64>().ok()
            }

            fn parse_string(&mut self) -> Option<String> {
                self.skip_ws();
                let quote = self.peek()?;
                if quote != '\'' && quote != '"' {
                    return None;
                }
                self.bump(quote);
                let mut out = String::new();
                while let Some(ch) = self.peek() {
                    self.bump(ch);
                    if ch == quote {
                        return Some(out);
                    }
                    if ch == '\\' {
                        let esc = self.peek()?;
                        self.bump(esc);
                        match esc {
                            'n' => out.push('\n'),
                            'r' => out.push('\r'),
                            't' => out.push('\t'),
                            '\\' => out.push('\\'),
                            '\'' => out.push('\''),
                            '"' => out.push('"'),
                            other => out.push(other),
                        }
                    } else {
                        out.push(ch);
                    }
                }
                None
            }

            fn parse_list(&mut self) -> Option<MetaValue> {
                if !self.eat('[') {
                    return None;
                }
                let mut items = Vec::new();
                loop {
                    self.skip_ws();
                    if self.eat(']') {
                        break;
                    }
                    let value = self.parse_value()?;
                    items.push(value);
                    self.skip_ws();
                    if self.eat(']') {
                        break;
                    }
                    if !self.eat(',') {
                        return None;
                    }
                }
                Some(MetaValue::List(items))
            }

            fn parse_map(&mut self) -> Option<MetaValue> {
                if !self.eat('{') {
                    return None;
                }
                let mut map: BTreeMap<String, MetaValue> = BTreeMap::new();
                loop {
                    self.skip_ws();
                    if self.eat('}') {
                        break;
                    }
                    let key = match self.parse_value()? {
                        MetaValue::Str(s) => s.to_string(),
                        _ => return None,
                    };
                    if !self.eat(':') {
                        return None;
                    }
                    let value = self.parse_value()?;
                    map.insert(key, value);
                    self.skip_ws();
                    if self.eat('}') {
                        break;
                    }
                    if !self.eat(',') {
                        return None;
                    }
                }
                Some(MetaValue::Map(map))
            }

            fn parse_parens(&mut self) -> Option<MetaValue> {
                if !self.eat('(') {
                    return None;
                }
                self.skip_ws();
                if self.eat(')') {
                    return Some(MetaValue::Tuple(Vec::new()));
                }

                let first = self.parse_value()?;
                self.skip_ws();

                // If there's no comma, treat as grouping: `(x)` -> `x`
                if self.eat(')') {
                    return Some(first);
                }
                if !self.eat(',') {
                    return None;
                }

                let mut items = vec![first];
                loop {
                    self.skip_ws();
                    if self.eat(')') {
                        break;
                    }
                    let value = self.parse_value()?;
                    items.push(value);
                    self.skip_ws();
                    if self.eat(')') {
                        break;
                    }
                    if !self.eat(',') {
                        return None;
                    }
                }

                Some(MetaValue::Tuple(items))
            }
        }

        let mut p = Parser::new(input);
        let value = p.parse_value()?;
        p.skip_ws();
        if !p.is_eof() {
            return None;
        }
        Some(value)
    }
}

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

    #[test]
    fn test_style_builder() {
        let style = Style::new().with_bold(true).with_color(Color::Standard(1));
        assert_eq!(style.bold, Some(true));
        assert_eq!(style.color, Some(Color::Standard(1)));
    }

    #[test]
    fn test_style_combine() {
        let base = Style::new().with_bold(true);
        let overlay = Style::new().with_italic(true);
        let combined = base.combine(&overlay);
        assert_eq!(combined.bold, Some(true));
        assert_eq!(combined.italic, Some(true));
    }

    #[test]
    fn test_style_parse() {
        let style = Style::parse("bold red").unwrap();
        assert_eq!(style.bold, Some(true));
        assert_eq!(style.color, Some(Color::Standard(1)));
    }

    #[test]
    fn test_style_parse_background() {
        let style = Style::parse("on blue").unwrap();
        assert_eq!(style.color, None);
        assert_eq!(style.bgcolor, Some(Color::Standard(4)));

        let style = Style::parse("bold red on blue").unwrap();
        assert_eq!(style.bold, Some(true));
        assert_eq!(style.color, Some(Color::Standard(1)));
        assert_eq!(style.bgcolor, Some(Color::Standard(4)));
    }

    // --- NULL_STYLE tests ---

    #[test]
    fn test_null_style_is_default() {
        assert_eq!(NULL_STYLE, Style::default());
        assert!(NULL_STYLE.is_null());
    }

    #[test]
    fn test_null_style_all_none() {
        assert_eq!(NULL_STYLE.color, None);
        assert_eq!(NULL_STYLE.bgcolor, None);
        assert_eq!(NULL_STYLE.bold, None);
        assert_eq!(NULL_STYLE.dim, None);
        assert_eq!(NULL_STYLE.italic, None);
        assert_eq!(NULL_STYLE.underline, None);
        assert_eq!(NULL_STYLE.blink, None);
        assert_eq!(NULL_STYLE.blink2, None);
        assert_eq!(NULL_STYLE.reverse, None);
        assert_eq!(NULL_STYLE.conceal, None);
        assert_eq!(NULL_STYLE.strike, None);
        assert_eq!(NULL_STYLE.underline2, None);
        assert_eq!(NULL_STYLE.frame, None);
        assert_eq!(NULL_STYLE.encircle, None);
        assert_eq!(NULL_STYLE.overline, None);
    }

    #[test]
    fn test_is_null() {
        assert!(Style::new().is_null());
        assert!(!Style::new().with_bold(true).is_null());
        assert!(!Style::new().with_color(Color::Standard(1)).is_null());
    }

    // --- render() tests ---

    #[test]
    fn test_render_empty_text() {
        let style = Style::new().with_bold(true);
        assert_eq!(style.render("", ColorSystem::TrueColor), "");
    }

    #[test]
    fn test_render_null_style() {
        let style = Style::new();
        // Null style should return text without ANSI codes
        assert_eq!(style.render("Hello", ColorSystem::TrueColor), "Hello");
    }

    #[test]
    fn test_render_bold() {
        let style = Style::new().with_bold(true);
        let rendered = style.render("Hello", ColorSystem::TrueColor);
        assert_eq!(rendered, "\x1b[1mHello\x1b[0m");
    }

    #[test]
    fn test_render_multiple_attributes() {
        let style = Style::new().with_bold(true).with_italic(true);
        let rendered = style.render("Hello", ColorSystem::TrueColor);
        assert_eq!(rendered, "\x1b[1;3mHello\x1b[0m");
    }

    #[test]
    fn test_render_all_attributes() {
        let style = Style {
            bold: Some(true),
            dim: Some(true),
            italic: Some(true),
            underline: Some(true),
            blink: Some(true),
            reverse: Some(true),
            strike: Some(true),
            ..Default::default()
        };
        let rendered = style.render("X", ColorSystem::TrueColor);
        // SGR codes: bold=1, dim=2, italic=3, underline=4, blink=5, reverse=7, strike=9
        assert_eq!(rendered, "\x1b[1;2;3;4;5;7;9mX\x1b[0m");
    }

    #[test]
    fn test_render_with_standard_color() {
        let style = Style::new().with_color(Color::Standard(1)); // red
        let rendered = style.render("Hi", ColorSystem::TrueColor);
        // Standard color 1 = red, foreground code = 31
        assert_eq!(rendered, "\x1b[31mHi\x1b[0m");
    }

    #[test]
    fn test_render_with_bright_color() {
        let style = Style::new().with_color(Color::Standard(9)); // bright red
        let rendered = style.render("Hi", ColorSystem::TrueColor);
        // Bright red, foreground code = 91
        assert_eq!(rendered, "\x1b[91mHi\x1b[0m");
    }

    #[test]
    fn test_render_with_256_color() {
        let style = Style::new().with_color(Color::EightBit(196));
        let rendered = style.render("Hi", ColorSystem::TrueColor);
        assert_eq!(rendered, "\x1b[38;5;196mHi\x1b[0m");
    }

    #[test]
    fn test_render_with_rgb_color() {
        let style = Style::new().with_color(Color::Rgb {
            r: 255,
            g: 128,
            b: 0,
        });
        let rendered = style.render("Hi", ColorSystem::TrueColor);
        assert_eq!(rendered, "\x1b[38;2;255;128;0mHi\x1b[0m");
    }

    #[test]
    fn test_render_with_bgcolor() {
        let style = Style::new().with_bgcolor(Color::Standard(4)); // blue bg
        let rendered = style.render("Hi", ColorSystem::TrueColor);
        // Blue background code = 44
        assert_eq!(rendered, "\x1b[44mHi\x1b[0m");
    }

    #[test]
    fn test_render_with_fg_and_bg() {
        let style = Style::new()
            .with_color(Color::Standard(1)) // red fg
            .with_bgcolor(Color::Standard(7)); // white bg
        let rendered = style.render("Hi", ColorSystem::TrueColor);
        assert_eq!(rendered, "\x1b[31;47mHi\x1b[0m");
    }

    #[test]
    fn test_render_bold_and_color() {
        let style = Style::new().with_bold(true).with_color(Color::Standard(2)); // green
        let rendered = style.render("OK", ColorSystem::TrueColor);
        assert_eq!(rendered, "\x1b[1;32mOK\x1b[0m");
    }

    #[test]
    fn test_render_color_downgrade_to_256() {
        // RGB color should be downgraded when using 256 color system
        let style = Style::new().with_color(Color::Rgb { r: 255, g: 0, b: 0 });
        let rendered = style.render("X", ColorSystem::EightBit);
        // Should contain 38;5;N format, not 38;2;R;G;B
        assert!(rendered.contains("38;5;"));
        assert!(!rendered.contains("38;2;"));
    }

    #[test]
    fn test_render_color_downgrade_to_standard() {
        // RGB color should be downgraded when using standard color system
        let style = Style::new().with_color(Color::Rgb { r: 255, g: 0, b: 0 });
        let rendered = style.render("X", ColorSystem::Standard);
        // Should contain simple code like 31 or 91, not extended format
        assert!(!rendered.contains("38;5;"));
        assert!(!rendered.contains("38;2;"));
    }

    // --- get_html_style() tests ---

    #[test]
    fn test_html_style_empty() {
        let style = Style::new();
        assert_eq!(style.get_html_style(), "");
    }

    #[test]
    fn test_html_style_bold() {
        let style = Style::new().with_bold(true);
        assert_eq!(style.get_html_style(), "font-weight: bold");
    }

    #[test]
    fn test_html_style_italic() {
        let style = Style::new().with_italic(true);
        assert_eq!(style.get_html_style(), "font-style: italic");
    }

    #[test]
    fn test_html_style_underline() {
        let style = Style::new().with_underline(true);
        assert_eq!(style.get_html_style(), "text-decoration: underline");
    }

    #[test]
    fn test_html_style_strike() {
        let style = Style::new().with_strike(true);
        assert_eq!(style.get_html_style(), "text-decoration: line-through");
    }

    #[test]
    fn test_with_reverse_builder_sets_flag() {
        let style = Style::new().with_reverse(true);
        assert_eq!(style.reverse, Some(true));
    }

    #[test]
    fn test_html_style_color_rgb() {
        let style = Style::new().with_color(Color::Rgb { r: 255, g: 0, b: 0 });
        let css = style.get_html_style();
        assert!(css.contains("color: #ff0000"));
        assert!(css.contains("text-decoration-color: #ff0000"));
    }

    #[test]
    fn test_html_style_bgcolor() {
        let style = Style::new().with_bgcolor(Color::Rgb { r: 0, g: 0, b: 255 });
        let css = style.get_html_style();
        assert!(css.contains("background-color: #0000ff"));
    }

    #[test]
    fn test_html_style_reverse_swaps_colors() {
        let style = Style {
            color: Some(Color::Rgb { r: 255, g: 0, b: 0 }),
            bgcolor: Some(Color::Rgb { r: 0, g: 0, b: 255 }),
            reverse: Some(true),
            ..Default::default()
        };
        let css = style.get_html_style();
        // After reverse, fg should be blue and bg should be red
        assert!(css.contains("color: #0000ff"));
        assert!(css.contains("background-color: #ff0000"));
    }

    #[test]
    fn test_html_style_combined() {
        let style = Style::new()
            .with_bold(true)
            .with_italic(true)
            .with_color(Color::Rgb {
                r: 255,
                g: 128,
                b: 0,
            });
        let css = style.get_html_style();
        assert!(css.contains("font-weight: bold"));
        assert!(css.contains("font-style: italic"));
        assert!(css.contains("color: #ff8000"));
    }

    #[test]
    fn test_html_style_standard_color() {
        // Standard color 1 = red
        let style = Style::new().with_color(Color::Standard(1));
        let css = style.get_html_style();
        // Should look up in palette and return hex
        assert!(css.contains("color: #"));
    }

    #[test]
    fn test_html_style_underline_and_strike_combined() {
        // Bug fix: underline + strike should combine into single text-decoration
        let style = Style::new().with_underline(true).with_strike(true);
        let css = style.get_html_style();
        // Should emit "text-decoration: underline line-through" (single property)
        assert!(css.contains("text-decoration: underline line-through"));
        // Should NOT have two separate text-decoration properties
        assert_eq!(css.matches("text-decoration").count(), 1);
    }

    // --- make_ansi_codes() tests ---

    #[test]
    fn test_make_ansi_codes_empty() {
        let style = Style::new();
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "");
    }

    #[test]
    fn test_make_ansi_codes_attributes_only() {
        let style = Style::new().with_bold(true).with_dim(true);
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "1;2");
    }

    #[test]
    fn test_make_ansi_codes_false_attributes_emit_reset() {
        // Explicitly false attributes should emit SGR reset codes before "on" codes
        let style = Style {
            bold: Some(false),
            italic: Some(true),
            ..Default::default()
        };
        // 22 = bold/dim off, 3 = italic on
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "22;3");
    }

    // --- Bug fix tests ---

    #[test]
    fn test_parse_not_bold() {
        // Bug 1: "not bold" should set bold = Some(false)
        let style = Style::parse("not bold").unwrap();
        assert_eq!(style.bold, Some(false));
    }

    #[test]
    fn test_parse_not_italic() {
        let style = Style::parse("not italic").unwrap();
        assert_eq!(style.italic, Some(false));
    }

    #[test]
    fn test_parse_not_underline() {
        let style = Style::parse("not underline").unwrap();
        assert_eq!(style.underline, Some(false));
    }

    #[test]
    fn test_parse_not_dim() {
        let style = Style::parse("not dim").unwrap();
        assert_eq!(style.dim, Some(false));
    }

    #[test]
    fn test_parse_not_blink() {
        let style = Style::parse("not blink").unwrap();
        assert_eq!(style.blink, Some(false));
    }

    #[test]
    fn test_parse_not_reverse() {
        let style = Style::parse("not reverse").unwrap();
        assert_eq!(style.reverse, Some(false));
    }

    #[test]
    fn test_parse_not_strike() {
        let style = Style::parse("not strike").unwrap();
        assert_eq!(style.strike, Some(false));
    }

    #[test]
    fn test_parse_mixed_attributes_with_negation() {
        // "bold not italic red" should set bold=true, italic=false, color=red
        let style = Style::parse("bold not italic red").unwrap();
        assert_eq!(style.bold, Some(true));
        assert_eq!(style.italic, Some(false));
        assert_eq!(style.color, Some(Color::Standard(1)));
    }

    #[test]
    fn test_make_ansi_codes_bold_false_emits_22() {
        // Bug 2: bold = Some(false) should emit SGR code 22
        let style = Style {
            bold: Some(false),
            ..Default::default()
        };
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "22");
    }

    #[test]
    fn test_make_ansi_codes_italic_false_emits_23() {
        let style = Style {
            italic: Some(false),
            ..Default::default()
        };
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "23");
    }

    #[test]
    fn test_make_ansi_codes_underline_false_emits_24() {
        let style = Style {
            underline: Some(false),
            ..Default::default()
        };
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "24");
    }

    #[test]
    fn test_make_ansi_codes_blink_false_emits_25() {
        let style = Style {
            blink: Some(false),
            ..Default::default()
        };
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "25");
    }

    #[test]
    fn test_make_ansi_codes_reverse_false_emits_27() {
        let style = Style {
            reverse: Some(false),
            ..Default::default()
        };
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "27");
    }

    #[test]
    fn test_make_ansi_codes_strike_false_emits_29() {
        let style = Style {
            strike: Some(false),
            ..Default::default()
        };
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "29");
    }

    #[test]
    fn test_make_ansi_codes_dim_false_emits_22() {
        // dim=false also uses 22 (same as bold off)
        let style = Style {
            dim: Some(false),
            ..Default::default()
        };
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "22");
    }

    #[test]
    fn test_make_ansi_codes_bold_false_dim_true() {
        // Edge case: bold=false, dim=true should emit 22 (off), then 2 (dim on)
        let style = Style {
            bold: Some(false),
            dim: Some(true),
            ..Default::default()
        };
        assert_eq!(style.make_ansi_codes(ColorSystem::TrueColor), "22;2");
    }

    #[test]
    fn test_render_with_false_attribute() {
        let style = Style {
            bold: Some(false),
            ..Default::default()
        };
        let rendered = style.render("Hi", ColorSystem::TrueColor);
        assert_eq!(rendered, "\x1b[22mHi\x1b[0m");
    }

    // --- Shorthand aliases tests ---

    #[test]
    fn test_parse_shorthand_b_for_bold() {
        let style = Style::parse("b").unwrap();
        assert_eq!(style.bold, Some(true));
    }

    #[test]
    fn test_parse_shorthand_i_for_italic() {
        let style = Style::parse("i").unwrap();
        assert_eq!(style.italic, Some(true));
    }

    #[test]
    fn test_parse_shorthand_u_for_underline() {
        let style = Style::parse("u").unwrap();
        assert_eq!(style.underline, Some(true));
    }

    #[test]
    fn test_parse_shorthand_s_for_strike() {
        let style = Style::parse("s").unwrap();
        assert_eq!(style.strike, Some(true));
    }

    #[test]
    fn test_parse_shorthand_combined() {
        let style = Style::parse("b i red").unwrap();
        assert_eq!(style.bold, Some(true));
        assert_eq!(style.italic, Some(true));
        assert_eq!(style.color, Some(Color::Standard(1)));
    }

    #[test]
    fn test_parse_shorthand_negation() {
        let style = Style::parse("not b").unwrap();
        assert_eq!(style.bold, Some(false));

        let style = Style::parse("not i").unwrap();
        assert_eq!(style.italic, Some(false));
    }

    // --- New attribute tests ---

    #[test]
    fn test_parse_new_attributes() {
        let style = Style::parse("overline").unwrap();
        assert_eq!(style.overline, Some(true));

        let style = Style::parse("blink2").unwrap();
        assert_eq!(style.blink2, Some(true));

        let style = Style::parse("conceal").unwrap();
        assert_eq!(style.conceal, Some(true));

        let style = Style::parse("underline2").unwrap();
        assert_eq!(style.underline2, Some(true));

        let style = Style::parse("frame").unwrap();
        assert_eq!(style.frame, Some(true));

        let style = Style::parse("encircle").unwrap();
        assert_eq!(style.encircle, Some(true));
    }

    #[test]
    fn test_parse_new_attribute_shorthand() {
        let style = Style::parse("o").unwrap();
        assert_eq!(style.overline, Some(true));

        let style = Style::parse("uu").unwrap();
        assert_eq!(style.underline2, Some(true));

        let style = Style::parse("c").unwrap();
        assert_eq!(style.conceal, Some(true));
    }

    #[test]
    fn test_parse_not_new_attributes() {
        let style = Style::parse("not overline").unwrap();
        assert_eq!(style.overline, Some(false));

        let style = Style::parse("not blink2").unwrap();
        assert_eq!(style.blink2, Some(false));

        let style = Style::parse("not conceal").unwrap();
        assert_eq!(style.conceal, Some(false));

        let style = Style::parse("not underline2").unwrap();
        assert_eq!(style.underline2, Some(false));

        let style = Style::parse("not frame").unwrap();
        assert_eq!(style.frame, Some(false));

        let style = Style::parse("not encircle").unwrap();
        assert_eq!(style.encircle, Some(false));
    }

    #[test]
    fn test_builder_new_attributes() {
        let style = Style::new().with_overline(true);
        assert_eq!(style.overline, Some(true));

        let style = Style::new().with_blink2(true);
        assert_eq!(style.blink2, Some(true));

        let style = Style::new().with_conceal(true);
        assert_eq!(style.conceal, Some(true));

        let style = Style::new().with_underline2(true);
        assert_eq!(style.underline2, Some(true));

        let style = Style::new().with_frame(true);
        assert_eq!(style.frame, Some(true));

        let style = Style::new().with_encircle(true);
        assert_eq!(style.encircle, Some(true));
    }

    #[test]
    fn test_render_new_attributes() {
        // overline = SGR 53
        let style = Style::new().with_overline(true);
        assert_eq!(
            style.render("X", ColorSystem::TrueColor),
            "\x1b[53mX\x1b[0m"
        );

        // blink2 = SGR 6
        let style = Style::new().with_blink2(true);
        assert_eq!(style.render("X", ColorSystem::TrueColor), "\x1b[6mX\x1b[0m");

        // conceal = SGR 8
        let style = Style::new().with_conceal(true);
        assert_eq!(style.render("X", ColorSystem::TrueColor), "\x1b[8mX\x1b[0m");

        // underline2 = SGR 21
        let style = Style::new().with_underline2(true);
        assert_eq!(
            style.render("X", ColorSystem::TrueColor),
            "\x1b[21mX\x1b[0m"
        );

        // frame = SGR 51
        let style = Style::new().with_frame(true);
        assert_eq!(
            style.render("X", ColorSystem::TrueColor),
            "\x1b[51mX\x1b[0m"
        );

        // encircle = SGR 52
        let style = Style::new().with_encircle(true);
        assert_eq!(
            style.render("X", ColorSystem::TrueColor),
            "\x1b[52mX\x1b[0m"
        );
    }

    #[test]
    fn test_render_new_attributes_off() {
        // overline off = SGR 55
        let style = Style::new().with_overline(false);
        assert_eq!(
            style.render("X", ColorSystem::TrueColor),
            "\x1b[55mX\x1b[0m"
        );

        // conceal off = SGR 28
        let style = Style::new().with_conceal(false);
        assert_eq!(
            style.render("X", ColorSystem::TrueColor),
            "\x1b[28mX\x1b[0m"
        );

        // frame off = SGR 54
        let style = Style::new().with_frame(false);
        assert_eq!(
            style.render("X", ColorSystem::TrueColor),
            "\x1b[54mX\x1b[0m"
        );
    }

    #[test]
    fn test_combine_new_attributes() {
        let a = Style::new().with_overline(true);
        let b = Style::new().with_blink2(true);
        let combined = a.combine(&b);
        assert_eq!(combined.overline, Some(true));
        assert_eq!(combined.blink2, Some(true));
    }

    #[test]
    fn test_render_all_new_attributes() {
        let style = Style {
            blink2: Some(true),
            conceal: Some(true),
            underline2: Some(true),
            frame: Some(true),
            encircle: Some(true),
            overline: Some(true),
            ..Default::default()
        };
        let rendered = style.render("X", ColorSystem::TrueColor);
        // blink2=6, conceal=8, underline2=21, frame=51, encircle=52, overline=53
        assert_eq!(rendered, "\x1b[6;8;21;51;52;53mX\x1b[0m");
    }

    // --- chain / test / background_style / without_color / transparent_background ---

    #[test]
    fn test_chain() {
        let a = Style::new().with_bold(true);
        let b = Style::new()
            .with_italic(true)
            .with_color(Color::Standard(1));
        let c = Style::new().with_underline(true);
        let result = Style::chain(&[a, b, c]);
        assert_eq!(result.bold, Some(true));
        assert_eq!(result.italic, Some(true));
        assert_eq!(result.underline, Some(true));
        assert_eq!(result.color, Some(Color::Standard(1)));
    }

    #[test]
    fn test_from_color() {
        let style = Style::from_color(Some(Color::Standard(1)), Some(Color::Standard(4)));
        assert_eq!(style.color, Some(Color::Standard(1)));
        assert_eq!(style.bgcolor, Some(Color::Standard(4)));
        assert_eq!(style.bold, None);
        assert_eq!(style.italic, None);
    }

    #[test]
    fn test_on_builds_meta_with_handlers() {
        let meta = Style::on(
            None,
            [
                ("click", MetaValue::str("handler")),
                ("focus", MetaValue::Bool(true)),
            ],
        );

        assert!(meta.link.is_none());
        assert!(meta.link_id.is_none());
        let map = meta.meta.as_ref().expect("meta should be present");
        assert_eq!(map.get("@click"), Some(&MetaValue::str("handler")));
        assert_eq!(map.get("@focus"), Some(&MetaValue::Bool(true)));
    }

    #[test]
    fn test_on_merges_existing_meta() {
        let mut base = BTreeMap::new();
        base.insert("existing".to_string(), MetaValue::Int(1));

        let meta = Style::on(Some(base), [("blur", MetaValue::Bool(false))]);
        let map = meta.meta.as_ref().expect("meta should be present");
        assert_eq!(map.get("existing"), Some(&MetaValue::Int(1)));
        assert_eq!(map.get("@blur"), Some(&MetaValue::Bool(false)));
    }

    #[test]
    fn test_normalize_valid_style() {
        assert_eq!(Style::normalize("  BOLD red ON blue "), "bold red on blue");
        assert_eq!(Style::normalize(""), "none");
        assert_eq!(Style::normalize(" none "), "none");
    }

    #[test]
    fn test_normalize_invalid_style_returns_trimmed_lower() {
        assert_eq!(Style::normalize("  no_such_token  "), "no_such_token");
        assert_eq!(Style::normalize("foo bold"), "foo bold");
        assert_eq!(
            Style::normalize("bold on not_a_color"),
            "bold on not_a_color"
        );
    }

    #[test]
    fn test_pick_first_returns_first_non_none() {
        let first = Style::new().with_bold(true);
        let second = Style::new().with_italic(true);
        let picked = Style::pick_first(&[None, Some(first), Some(second)]);
        assert_eq!(picked, first);
    }

    #[test]
    #[should_panic(expected = "expected at least one non-None style")]
    fn test_pick_first_panics_when_all_none() {
        let _ = Style::pick_first(&[None, None]);
    }

    #[test]
    fn test_background_style() {
        let style = Style::new()
            .with_bold(true)
            .with_color(Color::Standard(1))
            .with_bgcolor(Color::Standard(4));
        let bg = style.background_style();
        assert_eq!(bg.bgcolor, Some(Color::Standard(4)));
        assert_eq!(bg.color, None);
        assert_eq!(bg.bold, None);
    }

    #[test]
    fn test_without_color() {
        let style = Style::new()
            .with_bold(true)
            .with_color(Color::Standard(1))
            .with_bgcolor(Color::Standard(4));
        let nc = style.without_color();
        assert_eq!(nc.color, None);
        assert_eq!(nc.bgcolor, None);
        assert_eq!(nc.bold, Some(true));
    }

    #[test]
    fn test_has_transparent_background() {
        assert!(Style::new().has_transparent_background());
        assert!(
            Style::new()
                .with_bgcolor(Color::Default)
                .has_transparent_background()
        );
        assert!(
            !Style::new()
                .with_bgcolor(Color::Standard(1))
                .has_transparent_background()
        );
    }

    // --- StyleStack tests ---

    #[test]
    fn test_style_stack_new() {
        let stack = StyleStack::new(Style::new().with_bold(true));
        assert_eq!(stack.current().bold, Some(true));
    }

    #[test]
    fn test_style_stack_push_pop() {
        let mut stack = StyleStack::new(Style::new().with_bold(true));
        stack.push(Style::new().with_italic(true));
        let current = stack.current();
        assert_eq!(current.bold, Some(true));
        assert_eq!(current.italic, Some(true));

        stack.pop();
        let current = stack.current();
        assert_eq!(current.bold, Some(true));
        assert_eq!(current.italic, None);
    }

    #[test]
    fn test_style_stack_multiple_push() {
        let mut stack = StyleStack::new(Style::new());
        stack.push(Style::new().with_bold(true));
        stack.push(Style::new().with_italic(true));
        stack.push(Style::new().with_underline(true));

        let current = stack.current();
        assert_eq!(current.bold, Some(true));
        assert_eq!(current.italic, Some(true));
        assert_eq!(current.underline, Some(true));

        stack.pop();
        let current = stack.current();
        assert_eq!(current.bold, Some(true));
        assert_eq!(current.italic, Some(true));
        assert_eq!(current.underline, None);
    }

    // --- HTML style with overline ---

    #[test]
    fn test_html_style_overline() {
        let style = Style::new().with_overline(true);
        let css = style.get_html_style();
        assert!(css.contains("text-decoration: overline"));
    }

    #[test]
    fn test_html_style_underline_strike_overline_combined() {
        let style = Style::new()
            .with_underline(true)
            .with_strike(true)
            .with_overline(true);
        let css = style.get_html_style();
        assert!(css.contains("text-decoration: underline line-through overline"));
        assert_eq!(css.matches("text-decoration").count(), 1);
    }
}