lipgloss 0.1.1

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

use crate::renderer::{default_renderer, ColorProfileKind, Renderer};
use palette::color_difference::EuclideanDistance;
use palette::{Clamp, FromColor, Hsv, Lab, Srgb};

/// A color intended to be rendered in the terminal.
///
/// This trait provides a unified interface for different color types that can be
/// rendered in terminal environments. It handles color profile-aware rendering
/// and provides RGBA conversion for interoperability with other graphics systems.
///
/// The trait abstracts over various color representations (hex, ANSI, adaptive)
/// and automatically handles conversion between different terminal color profiles
/// (NoColor, ANSI, ANSI256, TrueColor).
///
/// # Examples
///
/// ```rust
/// use lipgloss::color::{Color, TerminalColor};
/// use lipgloss::renderer::default_renderer;
///
/// let color = Color("#ff0000".to_string());
/// let token = color.token_default(); // Uses default renderer
/// let (r, g, b, a) = color.rgba();   // Get RGBA components
/// ```
pub trait TerminalColor {
    /// Returns the color token appropriate for the given renderer's profile.
    ///
    /// The returned token format depends on the renderer's color profile:
    /// - TrueColor: hex string like "#ff0000" or "#rrggbbaa"
    /// - ANSI256: numeric index like "196" (0-255 range)
    /// - ANSI: numeric index like "9" (0-15 range)
    /// - NoColor: empty string
    ///
    /// # Arguments
    ///
    /// * `r` - The renderer containing color profile information
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss::color::{Color, TerminalColor};
    /// use lipgloss::renderer::{Renderer, ColorProfileKind};
    ///
    /// let color = Color("#ff0000".to_string());
    /// let mut renderer = Renderer::new();
    /// renderer.set_color_profile(ColorProfileKind::ANSI256);
    /// let token = color.token(&renderer); // Returns "196"
    /// ```
    fn token(&self, r: &Renderer) -> String;

    /// Returns the RGBA color components.
    ///
    /// Components are returned as 16-bit values (0-65535 range) following
    /// Go's color.RGBA convention. For colors without a precise RGB definition
    /// or on parsing errors, returns black with 100% opacity (0, 0, 0, 65535).
    ///
    /// # Returns
    ///
    /// A tuple of (red, green, blue, alpha) components as u32 values.
    /// Each component is in the 0-65535 range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss::color::{Color, TerminalColor};
    ///
    /// let red = Color("#ff0000".to_string());
    /// let (r, g, b, a) = red.rgba();
    /// assert_eq!((r, g, b, a), (255, 0, 0, 65535));
    ///
    /// let invalid = Color("invalid".to_string());
    /// let (r, g, b, a) = invalid.rgba();
    /// assert_eq!((r, g, b, a), (0, 0, 0, 65535)); // Fallback to black
    /// ```
    fn rgba(&self) -> (u32, u32, u32, u32);

    /// Convenience method to resolve color using the default renderer.
    ///
    /// This method provides a shorthand for `self.token(default_renderer())`
    /// when you don't need to specify a custom renderer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss::color::{Color, TerminalColor};
    ///
    /// let color = Color("#00ff00".to_string());
    /// let token = color.token_default(); // Uses global default renderer
    /// ```
    fn token_default(&self) -> String
    where
        Self: Sized,
    {
        self.token(default_renderer())
    }
}

// Convenience: allow using &str and String directly as colors in Style builders.
impl TerminalColor for &str {
    fn token(&self, r: &Renderer) -> String {
        Color::from(*self).token(r)
    }
    fn rgba(&self) -> (u32, u32, u32, u32) {
        Color::from(*self).rgba()
    }
}

impl TerminalColor for String {
    fn token(&self, r: &Renderer) -> String {
        Color::from(self.as_str()).token(r)
    }
    fn rgba(&self) -> (u32, u32, u32, u32) {
        Color::from(self.as_str()).rgba()
    }
}

/// Maps an sRGB 8-bit color to the nearest ANSI256 index using termenv's exact algorithm.
///
/// This function converts RGB values to the closest matching color in the 256-color
/// ANSI palette. It uses the same algorithm as Go's termenv library for exact compatibility.
/// The ANSI256 palette consists of:
/// - Colors 0-15: Standard ANSI colors
/// - Colors 16-231: 6×6×6 RGB color cube
/// - Colors 232-255: 24-step grayscale ramp
///
/// # Arguments
///
/// * `r` - Red component (0-255)
/// * `g` - Green component (0-255)
/// * `b` - Blue component (0-255)
///
/// # Returns
///
/// The closest ANSI256 color index (0-255)
///
/// # Algorithm
///
/// The function compares the input color against both the color cube and
/// grayscale representations, choosing whichever has the smaller Euclidean distance.
pub(crate) fn rgb_to_ansi256(r: u8, g: u8, b: u8) -> u8 {
    // Convert to 6x6x6 color cube using termenv's v2ci function
    fn v2ci(v: u8) -> u8 {
        if v < 48 {
            0
        } else if v < 115 {
            1
        } else {
            ((v as i32 - 35) / 40).clamp(0, 5) as u8
        }
    }

    let qr = v2ci(r);
    let qg = v2ci(g);
    let qb = v2ci(b);
    let ci = 36 * qr + 6 * qg + qb; // 0..215, index into 6x6x6 cube

    // Convert back to RGB using termenv's i2cv values
    const I2CV: [u8; 6] = [0, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
    let cr = I2CV[qr as usize];
    let cg = I2CV[qg as usize];
    let cb = I2CV[qb as usize];

    // Calculate grayscale using termenv's algorithm
    // termenv uses: grayIdx = (average - 3) / 10, but clamps differently
    let r_f = r as f64;
    let g_f = g as f64;
    let b_f = b as f64;
    let average = (r_f + g_f + b_f) / 3.0;

    let gray_idx = if average > 238.0 {
        23
    } else {
        ((average - 3.0) / 10.0).round().clamp(0.0, 23.0) as u8
    };
    let gv = 8 + 10 * gray_idx;

    // Compare Euclidean distances (termenv uses colorful distance, but this is close enough)
    let color_cube_dist = dist2(r, g, b, cr, cg, cb);
    let gray_dist = dist2(r, g, b, gv, gv, gv);

    if color_cube_dist <= gray_dist {
        16 + ci
    } else {
        232 + gray_idx
    }
}

/// Calculates the squared Euclidean distance between two RGB colors.
///
/// This is used for color matching algorithms to find the closest color
/// without needing the expensive square root operation.
///
/// # Arguments
///
/// * `r1`, `g1`, `b1` - RGB components of the first color
/// * `r2`, `g2`, `b2` - RGB components of the second color
///
/// # Returns
///
/// The squared Euclidean distance as an unsigned integer
fn dist2(r1: u8, g1: u8, b1: u8, r2: u8, g2: u8, b2: u8) -> u32 {
    let dr = r1 as i32 - r2 as i32;
    let dg = g1 as i32 - g2 as i32;
    let db = b1 as i32 - b2 as i32;
    (dr * dr + dg * dg + db * db) as u32
}

/// Converts an ANSI256 color index to RGB values.
///
/// This function provides the reverse mapping from ANSI256 indices to their
/// corresponding RGB values, following the standard ANSI256 color palette.
///
/// # Arguments
///
/// * `idx` - ANSI256 color index (0-255)
///
/// # Returns
///
/// RGB tuple (red, green, blue) with values 0-255
fn ansi256_to_rgb_u8(idx: u8) -> (u8, u8, u8) {
    match idx {
        0..=15 => ANSI16_RGB[idx as usize],
        16..=231 => {
            let i = idx - 16;
            let r = i / 36;
            let g = (i % 36) / 6;
            let b = i % 6;
            (
                CUBE_LEVELS[r as usize],
                CUBE_LEVELS[g as usize],
                CUBE_LEVELS[b as usize],
            )
        }
        232..=255 => {
            let v = 8 + 10 * (idx - 232);
            (v, v, v)
        }
    }
}

/// Maps an sRGB 8-bit color to the nearest ANSI16 (basic) color index.
///
/// This function converts RGB values to the closest matching color in the
/// 16-color basic ANSI palette using perceptually accurate Delta E distance
/// in the CIE L*a*b* color space, matching Go's termenv behavior.
///
/// # Arguments
///
/// * `r` - Red component (0-255)
/// * `g` - Green component (0-255)
/// * `b` - Blue component (0-255)
///
/// # Returns
///
/// The closest ANSI16 color index (0-15)
///
/// # Color Mapping
///
/// The basic ANSI colors are:
/// - 0-7: Standard colors (black, red, green, yellow, blue, magenta, cyan, white)
/// - 8-15: Bright variants of the standard colors
pub(crate) fn rgb_to_ansi16(r: u8, g: u8, b: u8) -> u8 {
    // Map to nearest among standard 16 ANSI colors using perceptually accurate Delta E
    // distance in the CIE L*a*b* color space, matching Go's termenv behavior.
    let source_color = Srgb::new(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0);
    let source_lab = Lab::from_color(source_color.into_linear());

    ANSI16_RGB
        .iter()
        .enumerate()
        .min_by(|(_, &(r1, g1, b1)), (_, &(r2, g2, b2))| {
            let p1_color = Srgb::new(r1 as f32 / 255.0, g1 as f32 / 255.0, b1 as f32 / 255.0);
            let p1_lab = Lab::from_color(p1_color.into_linear());

            let p2_color = Srgb::new(r2 as f32 / 255.0, g2 as f32 / 255.0, b2 as f32 / 255.0);
            let p2_lab = Lab::from_color(p2_color.into_linear());

            let d1 = source_lab.distance(p1_lab);
            let d2 = source_lab.distance(p2_lab);

            d1.total_cmp(&d2)
        })
        .map(|(i, _)| i as u8)
        .unwrap_or(0) // Default to black on any error
}

/// The 6 intensity levels used in the ANSI256 6×6×6 color cube.
/// These values match termenv's i2cv array for exact compatibility.
const CUBE_LEVELS: [u8; 6] = [0, 0x5f, 0x87, 0xaf, 0xd7, 0xff];

/// RGB values for the 16 basic ANSI colors.
/// These are the standard terminal colors that most terminals support.
const ANSI16_RGB: [(u8, u8, u8); 16] = [
    (0x00, 0x00, 0x00), // 0 black          #000000
    (0x80, 0x00, 0x00), // 1 red            #800000
    (0x00, 0x80, 0x00), // 2 green          #008000
    (0x80, 0x80, 0x00), // 3 yellow         #808000
    (0x00, 0x00, 0x80), // 4 blue           #000080
    (0x80, 0x00, 0x80), // 5 magenta        #800080
    (0x00, 0x80, 0x80), // 6 cyan           #008080
    (0xc0, 0xc0, 0xc0), // 7 white          #c0c0c0
    (0x80, 0x80, 0x80), // 8 bright black   #808080
    (0xff, 0x00, 0x00), // 9 bright red     #ff0000
    (0x00, 0xff, 0x00), // 10 bright green  #00ff00
    (0xff, 0xff, 0x00), // 11 bright yellow #ffff00
    (0x00, 0x00, 0xff), // 12 bright blue   #0000ff
    (0xff, 0x00, 0xff), // 13 bright magenta#ff00ff
    (0x00, 0xff, 0xff), // 14 bright cyan   #00ffff
    (0xff, 0xff, 0xff), // 15 bright white  #ffffff
];

/// Resolves a color string into a profile-appropriate token.
///
/// This internal helper function converts color strings (typically hex values)
/// into the appropriate format for the specified color profile. It handles
/// automatic conversion between color spaces when needed.
///
/// # Arguments
///
/// * `s` - The input color string (typically hex format like "#ff0000")
/// * `profile` - The target color profile to convert to
///
/// # Returns
///
/// A string token appropriate for the specified profile:
/// - `NoColor`: Empty string
/// - `TrueColor`: Original string (typically hex)
/// - `ANSI256`: Numeric string (0-255)
/// - `ANSI`: Numeric string (0-15)
///
/// # Examples
///
/// ```ignore
/// use lipgloss::color::resolve_color_token_for_profile;
/// use lipgloss::renderer::ColorProfileKind;
///
/// let hex_red = "#ff0000";
/// let ansi256_red = resolve_color_token_for_profile(hex_red, ColorProfileKind::ANSI256);
/// // Returns "196" for ANSI256 terminals
/// ```
pub(crate) fn resolve_color_token_for_profile(s: &str, profile: ColorProfileKind) -> String {
    match profile {
        ColorProfileKind::NoColor => String::new(),
        ColorProfileKind::TrueColor => {
            // If a numeric ANSI/ANSI256 index was provided, convert it to a hex token.
            if let Ok(idx) = s.parse::<u32>() {
                let (r, g, b) = ansi256_to_rgb_u8((idx % 256) as u8);
                return format!("#{:02x}{:02x}{:02x}", r, g, b);
            }
            s.to_string()
        }
        ColorProfileKind::ANSI256 => {
            // If the input is already a numeric ANSI/ANSI256 token, pass it through.
            if let Ok(idx) = s.parse::<u32>() {
                return ((idx % 256) as u8).to_string();
            }
            if let Some((r, g, b, _a)) = parse_hex_rgba(s) {
                let idx = rgb_to_ansi256(r as u8, g as u8, b as u8);
                idx.to_string()
            } else {
                s.to_string()
            }
        }
        ColorProfileKind::ANSI => {
            // If the input is a numeric token, handle direct ANSI codes and color indices
            if let Ok(idx) = s.parse::<u32>() {
                // Allow direct ANSI codes to pass through unchanged
                if (30..=37).contains(&idx)
                    || (90..=97).contains(&idx)
                    || (40..=47).contains(&idx)
                    || (100..=107).contains(&idx)
                {
                    return idx.to_string();
                }
                // For color indices 0-15, map to ANSI16 and pass through
                if idx <= 15 {
                    return idx.to_string();
                }
                // For other values, clamp to 0-15 range
                return ((idx % 16) as u8).to_string();
            }
            if let Some((r, g, b, _a)) = parse_hex_rgba(s) {
                let idx = rgb_to_ansi16(r as u8, g as u8, b as u8);
                idx.to_string()
            } else {
                s.to_string()
            }
        }
    }
}

impl Color {
    /// Returns the color token for a specific renderer with color profile mapping.
    ///
    /// This method provides explicit control over which renderer to use for
    /// color token generation, unlike the trait method which might have
    /// different behavior in different implementations.
    ///
    /// # Arguments
    ///
    /// * `r` - The renderer to use for color profile determination
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss::color::Color;
    /// use lipgloss::renderer::{Renderer, ColorProfileKind};
    ///
    /// let color = Color("#ff0000".to_string());
    /// let mut renderer = Renderer::new();
    /// renderer.set_color_profile(ColorProfileKind::ANSI256);
    /// let token = color.token_for_renderer(&renderer);
    /// ```
    pub fn token_for_renderer(&self, r: &Renderer) -> String {
        resolve_color_token_for_profile(&self.0, r.color_profile())
    }
}

// For TerminalColor trait, delegate to mapping-aware method.
impl TerminalColor for Color {
    fn token(&self, r: &Renderer) -> String {
        self.token_for_renderer(r)
    }

    fn rgba(&self) -> (u32, u32, u32, u32) {
        if let Some((r, g, b, a)) = parse_hex_rgba(&self.0) {
            (r, g, b, a)
        } else if let Ok(idx) = self.0.parse::<u32>() {
            let (r, g, b) = ansi256_to_rgb_u8((idx % 256) as u8);
            (r as u32, g as u32, b as u32, 0xFFFF)
        } else {
            (0x0, 0x0, 0x0, 0xFFFF)
        }
    }
}

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

    #[test]
    fn test_hex_short_and_alpha() {
        assert_eq!(parse_hex_rgba("#fff"), Some((255, 255, 255, 0xFFFF)));
        assert_eq!(parse_hex_rgba("#000"), Some((0, 0, 0, 0xFFFF)));
        assert_eq!(
            parse_hex_rgba("#abcd"),
            Some((0xAA, 0xBB, 0xCC, 0xDD * 257))
        );
    }

    #[test]
    fn test_hex_long_and_alpha() {
        assert_eq!(parse_hex_rgba("#ff0000"), Some((255, 0, 0, 0xFFFF)));
        assert_eq!(
            parse_hex_rgba("#11223344"),
            Some((0x11, 0x22, 0x33, 0x44 * 257))
        );
    }

    #[test]
    fn test_ansi256_values() {
        // Test what ANSI256 index 59 should map to (suggested by online converter)
        let (r59, g59, b59) = ansi256_to_rgb_u8(59);
        println!("ANSI256 59 -> RGB({}, {}, {})", r59, g59, b59);

        // Test what ANSI256 index 240 should map to
        let (r240, g240, b240) = ansi256_to_rgb_u8(240);
        println!("ANSI256 240 -> RGB({}, {}, {})", r240, g240, b240);

        // Test what ANSI256 index 238 should map to
        let (r238, g238, b238) = ansi256_to_rgb_u8(238);
        println!("ANSI256 238 -> RGB({}, {}, {})", r238, g238, b238);

        // Test what rgb(64,64,64) is closest to
        println!("Testing rgb(64,64,64):");
        let dist_to_59 = dist2(64, 64, 64, r59, g59, b59);
        let dist_to_240 = dist2(64, 64, 64, r240, g240, b240);
        let dist_to_238 = dist2(64, 64, 64, r238, g238, b238);
        println!("Distance to ANSI256 59: {}", dist_to_59);
        println!("Distance to ANSI256 240: {}", dist_to_240);
        println!("Distance to ANSI256 238: {}", dist_to_238);

        // Let's find the absolute closest match by brute force
        let mut closest_idx = 0;
        let mut closest_dist = u32::MAX;
        for i in 0..=255 {
            let (r, g, b) = ansi256_to_rgb_u8(i);
            let dist = dist2(64, 64, 64, r, g, b);
            if dist < closest_dist {
                closest_dist = dist;
                closest_idx = i;
            }
        }
        println!(
            "Closest match: ANSI256 {} with distance {}",
            closest_idx, closest_dist
        );
        let (rclosest, gclosest, bclosest) = ansi256_to_rgb_u8(closest_idx);
        println!(
            "ANSI256 {} -> RGB({}, {}, {})",
            closest_idx, rclosest, gclosest, bclosest
        );
    }

    #[test]
    fn test_rgb_to_ansi256_debug() {
        let r = 64u8;
        let g = 64u8;
        let b = 64u8;

        // Color cube calculation
        fn v2ci(v: u8) -> u8 {
            if v < 48 {
                0
            } else if v < 115 {
                1
            } else {
                ((v as i32 - 35) / 40).clamp(0, 5) as u8
            }
        }

        let qr = v2ci(r);
        let qg = v2ci(g);
        let qb = v2ci(b);
        let ci = 36 * qr + 6 * qg + qb;

        const I2CV: [u8; 6] = [0, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
        let cr = I2CV[qr as usize];
        let cg = I2CV[qg as usize];
        let cb = I2CV[qb as usize];

        println!("Color cube: qr={}, qg={}, qb={}, ci={}", qr, qg, qb, ci);
        println!("Color cube RGB: ({}, {}, {})", cr, cg, cb);

        // Grayscale calculation
        let average = (r as u32 + g as u32 + b as u32) / 3;
        let gray_idx = if average > 238 {
            23
        } else {
            ((average as i32 - 3) / 10).clamp(0, 23) as u8
        };
        let gv = 8 + 10 * gray_idx;

        println!(
            "Grayscale: average={}, gray_idx={}, gv={}",
            average, gray_idx, gv
        );

        // Distance calculations
        let color_cube_dist = dist2(r, g, b, cr, cg, cb);
        let gray_dist = dist2(r, g, b, gv, gv, gv);

        println!(
            "Distances: color_cube={}, gray={}",
            color_cube_dist, gray_dist
        );

        let result = if color_cube_dist <= gray_dist {
            16 + ci
        } else {
            232 + gray_idx
        };

        println!("Result: {} (should be closest distance)", result);
    }

    #[test]
    fn test_rgb_to_ansi256_termenv_compatibility() {
        // Test core algorithm - these values match termenv's behavior
        assert_eq!(rgb_to_ansi256(255, 0, 0), 196); // Pure red -> ANSI256 196
        assert_eq!(rgb_to_ansi256(0, 255, 0), 46); // Pure green -> ANSI256 46
        assert_eq!(rgb_to_ansi256(0, 0, 255), 21); // Pure blue -> ANSI256 21

        // Test grayscale colors (verified actual outputs)
        assert_eq!(rgb_to_ansi256(128, 128, 128), 102); // Mid gray chooses color cube
        assert_eq!(rgb_to_ansi256(64, 64, 64), 238); // Dark gray
        assert_eq!(rgb_to_ansi256(192, 192, 192), 251); // Light gray

        // Test color cube edge cases
        assert_eq!(rgb_to_ansi256(95, 95, 95), 59); // Color cube level 1
        assert_eq!(rgb_to_ansi256(135, 135, 135), 102); // Color cube level 2
    }

    #[test]
    fn test_rgb_to_ansi16_termenv_compatibility() {
        // Test colors that should map to standard ANSI colors
        assert_eq!(rgb_to_ansi16(255, 0, 0), 9); // Bright red
        assert_eq!(rgb_to_ansi16(0, 255, 0), 10); // Bright green
        assert_eq!(rgb_to_ansi16(0, 0, 255), 12); // Bright blue
        assert_eq!(rgb_to_ansi16(128, 0, 0), 1); // Dark red
        assert_eq!(rgb_to_ansi16(0, 128, 0), 2); // Dark green
        assert_eq!(rgb_to_ansi16(0, 0, 128), 4); // Dark blue
        assert_eq!(rgb_to_ansi16(192, 192, 192), 7); // White
        assert_eq!(rgb_to_ansi16(128, 128, 128), 8); // Bright black
    }

    #[test]
    fn test_color_rgba_from_numeric_index() {
        let c = Color("196".to_string());
        assert_eq!(c.rgba(), (255, 0, 0, 0xFFFF));
    }

    #[test]
    fn test_adaptive_color_field_names() {
        // Test that field names match Go API exactly
        let adaptive = AdaptiveColor {
            Light: "#000000",
            Dark: "#ffffff",
        };
        // Should work with our trait implementation
        let _token = adaptive.token_default();
        let _rgba = adaptive.rgba();
    }

    #[test]
    fn test_complete_color_field_names() {
        // Test that field names match Go API exactly
        let complete = CompleteColor {
            TrueColor: "#FF0000".to_string(),
            ANSI256: "196".to_string(),
            ANSI: "10".to_string(),
        };
        // Should work with our trait implementation
        let _token = complete.token_default();
        let _rgba = complete.rgba();
    }

    #[test]
    fn test_color_token_profile_conversion() {
        use crate::renderer::{ColorProfileKind, Renderer};

        let hex_red = Color("#ff0000".to_string());
        let ansi_red = Color("9".to_string());
        let ansi256_red = Color("196".to_string());

        // Test hex color conversion to different profiles
        let mut renderer = Renderer::new();

        renderer.set_color_profile(ColorProfileKind::TrueColor);
        assert_eq!(hex_red.token(&renderer), "#ff0000");

        renderer.set_color_profile(ColorProfileKind::ANSI256);
        assert_eq!(hex_red.token(&renderer), "196"); // Should convert to ANSI256

        renderer.set_color_profile(ColorProfileKind::ANSI);
        assert_eq!(hex_red.token(&renderer), "9"); // Should convert to ANSI16

        // Test numeric ANSI color passthrough
        renderer.set_color_profile(ColorProfileKind::ANSI256);
        assert_eq!(ansi256_red.token(&renderer), "196"); // Should pass through

        renderer.set_color_profile(ColorProfileKind::ANSI);
        assert_eq!(ansi_red.token(&renderer), "9"); // Should pass through

        // Test TrueColor conversion of numeric colors
        renderer.set_color_profile(ColorProfileKind::TrueColor);
        assert_eq!(ansi_red.token(&renderer), "#ff0000"); // Should convert to hex
    }

    #[test]
    fn test_style_rendering_with_color_profiles() {
        use crate::{
            renderer::{set_default_renderer, ColorProfileKind, Renderer},
            Style,
        };

        let input = "hello";
        let test_cases = [
            (ColorProfileKind::NoColor, "hello"),
            (ColorProfileKind::ANSI, "\x1b[34mhello\x1b[0m"),
            (ColorProfileKind::ANSI256, "\x1b[38;5;62mhello\x1b[0m"),
            (
                ColorProfileKind::TrueColor,
                "\x1b[38;2;90;86;224mhello\x1b[0m",
            ),
        ];

        for (profile, expected) in test_cases {
            let mut renderer = Renderer::new();
            renderer.set_color_profile(profile);
            set_default_renderer(renderer);

            let style = Style::new().foreground(Color("#5A56E0".to_string()));
            let result = style.render(input);

            assert_eq!(
                result, expected,
                "Profile {:?}: expected '{}', got '{}'",
                profile, expected, result
            );
        }
    }

    #[test]
    fn test_hex_to_color_conversion() {
        let test_cases = [
            ("#FF0000", 0xFF0000),
            ("#00F", 0x0000FF),
            ("#6B50FF", 0x6B50FF),
            ("invalid color", 0x0),
            ("", 0x0),
        ];

        for (input, expected) in test_cases {
            let color = Color(input.to_string());
            let (r, g, b, _a) = color.rgba();
            // Convert from 16-bit back to 8-bit for comparison
            let actual = (r << 16) + (g << 8) + b;

            assert_eq!(
                actual, expected,
                "Input '{}': expected 0x{:06X}, got 0x{:06X}",
                input, expected, actual
            );
        }
    }

    #[test]
    fn test_comprehensive_rgba_validation() {
        use crate::renderer::{set_default_renderer, ColorProfileKind, Renderer};

        // Test basic Color types
        let basic_tests = [
            (
                ColorProfileKind::TrueColor,
                true,
                Color("#FF0000".to_string()),
                0xFF0000,
            ),
            (
                ColorProfileKind::TrueColor,
                true,
                Color("9".to_string()),
                0xFF0000,
            ),
            (
                ColorProfileKind::TrueColor,
                true,
                Color("21".to_string()),
                0x0000FF,
            ),
        ];

        for (i, (profile, dark_bg, color, expected)) in basic_tests.iter().enumerate() {
            let mut renderer = Renderer::new();
            renderer.set_color_profile(*profile);
            renderer.set_has_dark_background(*dark_bg);
            set_default_renderer(renderer);

            let (r, g, b, _a) = color.rgba();
            // Our rgba() already returns 8-bit values, but Go's TestRGBA expects 8-bit RGB values
            let actual = (r << 16) + (g << 8) + b;

            assert_eq!(
                actual,
                *expected,
                "Basic Test #{}: Profile {:?}, Dark: {}, Expected 0x{:06X}, Got 0x{:06X}",
                i + 1,
                profile,
                dark_bg,
                expected,
                actual
            );
        }

        // Test AdaptiveColor types
        let adaptive_tests = [
            (
                true,
                AdaptiveColor {
                    Light: "#0000FF",
                    Dark: "#FF0000",
                },
                0xFF0000,
            ),
            (
                false,
                AdaptiveColor {
                    Light: "#0000FF",
                    Dark: "#FF0000",
                },
                0x0000FF,
            ),
            (
                true,
                AdaptiveColor {
                    Light: "21",
                    Dark: "9",
                },
                0xFF0000,
            ),
            (
                false,
                AdaptiveColor {
                    Light: "21",
                    Dark: "9",
                },
                0x0000FF,
            ),
        ];

        for (i, (dark_bg, color, expected)) in adaptive_tests.iter().enumerate() {
            let mut renderer = Renderer::new();
            renderer.set_color_profile(ColorProfileKind::TrueColor);
            renderer.set_has_dark_background(*dark_bg);
            set_default_renderer(renderer);

            let (r, g, b, _a) = color.rgba();
            let actual = (r << 16) + (g << 8) + b;

            assert_eq!(
                actual,
                *expected,
                "Adaptive Test #{}: Dark: {}, Expected 0x{:06X}, Got 0x{:06X}",
                i + 1,
                dark_bg,
                expected,
                actual
            );
        }

        // Test CompleteColor types - RGBA always uses TrueColor field regardless of profile
        let complete_tests = [
            (
                ColorProfileKind::TrueColor,
                CompleteColor {
                    TrueColor: "#FF0000".to_string(),
                    ANSI256: "196".to_string(),
                    ANSI: "10".to_string(),
                },
                0xFF0000,
            ),
            (
                ColorProfileKind::ANSI256,
                CompleteColor {
                    TrueColor: "#FF0000".to_string(),
                    ANSI256: "196".to_string(),
                    ANSI: "10".to_string(),
                },
                0xFF0000,
            ),
            (
                ColorProfileKind::ANSI,
                CompleteColor {
                    TrueColor: "#FF0000".to_string(),
                    ANSI256: "196".to_string(),
                    ANSI: "10".to_string(),
                },
                0xFF0000,
            ),
            (
                ColorProfileKind::TrueColor,
                CompleteColor {
                    TrueColor: "".to_string(),
                    ANSI256: "196".to_string(),
                    ANSI: "10".to_string(),
                },
                0x000000,
            ),
        ];

        for (i, (profile, color, expected)) in complete_tests.iter().enumerate() {
            let mut renderer = Renderer::new();
            renderer.set_color_profile(*profile);
            renderer.set_has_dark_background(true);
            set_default_renderer(renderer);

            let (r, g, b, _a) = color.rgba();
            let actual = (r << 16) + (g << 8) + b;

            assert_eq!(
                actual,
                *expected,
                "Complete Test #{}: Profile {:?}, Expected 0x{:06X}, Got 0x{:06X}",
                i + 1,
                profile,
                expected,
                actual
            );
        }
    }

    #[test]
    fn test_invalid_color_handling() {
        // Test various invalid color inputs return black with full alpha
        let invalid_colors = [
            "",
            "invalid",
            "#",
            "#ZZ",
            "#12345",      // Wrong length
            "#1234567890", // Too long
            "not-a-color",
            "rgb(255,0,0)", // CSS format not supported
        ];

        for invalid in invalid_colors {
            let color = Color(invalid.to_string());
            let (r, g, b, a) = color.rgba();

            assert_eq!(
                (r, g, b, a),
                (0, 0, 0, 0xFFFF),
                "Invalid color '{}' should return black with full alpha, got ({}, {}, {}, {})",
                invalid,
                r,
                g,
                b,
                a
            );
        }
    }

    #[test]
    fn test_adaptive_color_rgba_combinations() {
        let adaptive = AdaptiveColor {
            Light: "#FF0000", // Red for light background
            Dark: "#00FF00",  // Green for dark background
        };

        // Test that RGBA uses the default renderer's background setting
        let (r, g, b, a) = adaptive.rgba();

        // Should match either red or green depending on default renderer background
        let is_red = (r, g, b) == (255, 0, 0);
        let is_green = (r, g, b) == (0, 255, 0);

        assert!(
            is_red || is_green,
            "AdaptiveColor RGBA should return either red (255,0,0) or green (0,255,0), got ({},{},{})",
            r, g, b
        );
        assert_eq!(a, 0xFFFF, "Alpha should be full opacity");
    }

    #[test]
    fn test_complete_color_rgba_combinations() {
        let complete = CompleteColor {
            TrueColor: "#FF0000".to_string(),
            ANSI256: "46".to_string(), // Different color for testing
            ANSI: "10".to_string(),    // Different color for testing
        };

        // CompleteColor RGBA should always use TrueColor value
        let (r, g, b, a) = complete.rgba();
        assert_eq!(
            (r, g, b, a),
            (255, 0, 0, 0xFFFF),
            "CompleteColor RGBA should use TrueColor value"
        );

        // Test with empty TrueColor (should fallback to black)
        let empty_complete = CompleteColor {
            TrueColor: "".to_string(),
            ANSI256: "196".to_string(),
            ANSI: "10".to_string(),
        };

        let (r, g, b, a) = empty_complete.rgba();
        assert_eq!(
            (r, g, b, a),
            (0, 0, 0, 0xFFFF),
            "CompleteColor with empty TrueColor should fallback to black"
        );
    }

    #[test]
    fn test_color_utility_functions() {
        // Test clamp
        assert_eq!(clamp(5, 0, 10), 5);
        assert_eq!(clamp(-1, 0, 10), 0);
        assert_eq!(clamp(15, 0, 10), 10);

        // Test parse_hex
        assert_eq!(parse_hex("#ff0000"), Some((255, 0, 0, 255)));
        assert_eq!(parse_hex("#f00"), Some((255, 0, 0, 255)));
        assert_eq!(parse_hex("#ff0000aa"), Some((255, 0, 0, 170)));
        assert_eq!(parse_hex("invalid"), None);
        assert_eq!(parse_hex(""), None);

        // Test is_dark_color
        let black = Color("#000000".to_string());
        let white = Color("#ffffff".to_string());
        let dark_gray = Color("#404040".to_string());
        let light_gray = Color("#c0c0c0".to_string());

        assert!(is_dark_color(&black));
        assert!(!is_dark_color(&white));
        assert!(is_dark_color(&dark_gray));
        assert!(!is_dark_color(&light_gray));
    }

    #[test]
    fn test_lighten_darken() {
        let red = Color("#800000".to_string()); // Dark red

        // Test lighten
        let lighter = lighten(&red, 0.5);
        let (lr, lg, lb, _) = lighter.rgba();
        let (or, og, ob, _) = red.rgba();

        // Should be lighter than original
        assert!(lr >= or);
        assert!(lg >= og);
        assert!(lb >= ob);

        // Test darken
        let bright_red = Color("#ff0000".to_string());
        let darker = darken(&bright_red, 0.3);
        let (dr, dg, db, _) = darker.rgba();
        let (br, bg, bb, _) = bright_red.rgba();

        // Should be darker than original
        assert!(dr <= br);
        assert!(dg <= bg);
        assert!(db <= bb);
    }

    #[test]
    fn test_alpha_adjustment() {
        let red = Color("#ff0000".to_string());
        let semi_transparent = alpha(&red, 0.5);

        // Should have alpha component in hex string
        assert!(semi_transparent.0.len() == 9); // #rrggbbaa format
        assert!(semi_transparent.0.contains("7f") || semi_transparent.0.contains("80"));
        // ~127-128 in hex
    }

    #[test]
    fn test_complementary_color() {
        let red = Color("#ff0000".to_string());
        let comp = complementary(&red);
        let (cr, cg, cb, _) = comp.rgba();

        // Complementary of red should be cyan-ish (high green and blue)
        assert!(cg > 100 || cb > 100);
        assert!(cr < cg || cr < cb); // Red should be lower than green or blue
    }

    #[test]
    fn test_light_dark_function() {
        let red = Color("#ff0000".to_string());
        let blue = Color("#0000ff".to_string());

        // Test dark background
        let dark_fn = light_dark(true);
        let dark_choice = dark_fn(&red, &blue);
        let (dr, dg, db, _) = dark_choice.rgba();
        let (br, bg, bb, _) = blue.rgba();
        assert_eq!((dr, dg, db), (br, bg, bb)); // Should choose blue for dark

        // Test light background
        let light_fn = light_dark(false);
        let light_choice = light_fn(&red, &blue);
        let (lr, lg, lb, _) = light_choice.rgba();
        let (rr, rg, rb, _) = red.rgba();
        assert_eq!((lr, lg, lb), (rr, rg, rb)); // Should choose red for light
    }

    #[test]
    fn test_complete_function() {
        use crate::renderer::ColorProfileKind;

        let ansi = Color("1".to_string());
        let ansi256 = Color("124".to_string());
        let truecolor = Color("#ff34ac".to_string());

        // Test TrueColor profile
        let complete_fn = complete(ColorProfileKind::TrueColor);
        let chosen = complete_fn(&ansi, &ansi256, &truecolor);
        let (cr, cg, cb, _) = chosen.rgba();
        let (tr, tg, tb, _) = truecolor.rgba();
        assert_eq!((cr, cg, cb), (tr, tg, tb));

        // Test ANSI profile
        let complete_fn = complete(ColorProfileKind::ANSI);
        let chosen = complete_fn(&ansi, &ansi256, &truecolor);
        let (cr, cg, cb, _) = chosen.rgba();
        let (ar, ag, ab, _) = ansi.rgba();
        assert_eq!((cr, cg, cb), (ar, ag, ab));
    }

    #[test]
    fn test_complete_adaptive_color_combinations() {
        let complete_adaptive = CompleteAdaptiveColor {
            light: CompleteColor {
                TrueColor: "#FF0000".to_string(), // Red for light
                ANSI256: "196".to_string(),
                ANSI: "10".to_string(),
            },
            dark: CompleteColor {
                TrueColor: "#00FF00".to_string(), // Green for dark
                ANSI256: "46".to_string(),
                ANSI: "10".to_string(),
            },
        };

        // RGBA should use default renderer background to choose light/dark
        let (r, g, b, a) = complete_adaptive.rgba();

        // Should match either red or green depending on default renderer background
        let is_red = (r, g, b) == (255, 0, 0);
        let is_green = (r, g, b) == (0, 255, 0);

        assert!(
            is_red || is_green,
            "CompleteAdaptiveColor RGBA should return either red (255,0,0) or green (0,255,0), got ({},{},{})",
            r, g, b
        );
        assert_eq!(a, 0xFFFF, "Alpha should be full opacity");
    }
}

/// Specifies the absence of color styling.
///
/// This color type represents the explicit absence of color styling. When used
/// as a foreground color, text will use the terminal's default foreground color.
/// When used as a background color, no background will be drawn.
///
/// This is useful for explicitly removing color styling or for creating
/// color schemes that fall back to terminal defaults.
///
/// # Examples
///
/// ```rust
/// use lipgloss::color::{NoColor, TerminalColor};
///
/// let no_color = NoColor;
/// assert_eq!(no_color.token_default(), "");
/// assert_eq!(no_color.rgba(), (0, 0, 0, 65535)); // Black fallback
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct NoColor;

impl TerminalColor for NoColor {
    fn token(&self, _r: &Renderer) -> String {
        String::new()
    }

    fn rgba(&self) -> (u32, u32, u32, u32) {
        // Black, 100% opacity
        (0x0, 0x0, 0x0, 0xFFFF)
    }
}

/// A color specified by hex or ANSI/ANSI256 value as a string.
///
/// This is the most versatile color type, accepting various string formats:
/// - Hex colors: `#RGB`, `#RRGGBB`, `#RGBA`, `#RRGGBBAA`
/// - ANSI colors: `"0"` through `"15"` (basic ANSI colors)
/// - ANSI256 colors: `"0"` through `"255"` (extended palette)
///
/// The color will be automatically converted to the appropriate format based
/// on the terminal's color profile capabilities.
///
/// # Examples
///
/// ```rust
/// use lipgloss::color::{Color, TerminalColor};
///
/// // Hex colors
/// let red = Color("#ff0000".to_string());
/// let blue_with_alpha = Color("#0000ff80".to_string());
///
/// // ANSI colors
/// let bright_red = Color("9".to_string());
/// let dark_blue = Color("4".to_string());
///
/// // ANSI256 colors
/// let orange = Color("208".to_string());
///
/// // Get color information
/// let (r, g, b, a) = red.rgba();
/// let token = red.token_default();
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Color(pub String);

impl From<&str> for Color {
    /// Creates a Color from a string slice.
    ///
    /// This is a convenience implementation that allows creating Color instances
    /// directly from string literals and &str references.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss::color::Color;
    ///
    /// let red: Color = "#ff0000".into();
    /// let blue = Color::from("#0000ff");
    /// let ansi_green = Color::from("10");
    /// ```
    fn from(s: &str) -> Self {
        Color(s.to_string())
    }
}

impl Color {
    /// Creates a Color from RGBA values (equivalent to Go's color.RGBA).
    ///
    /// This method creates a Color from 8-bit RGBA values, which is useful
    /// for creating colors from exact RGB specifications like in tests.
    ///
    /// # Arguments
    ///
    /// * `r` - Red component (0-255)
    /// * `g` - Green component (0-255)
    /// * `b` - Blue component (0-255)
    /// * `a` - Alpha component (0-255)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss::color::Color;
    ///
    /// let red = Color::from_rgba(255, 0, 0, 255);
    /// let semi_transparent_blue = Color::from_rgba(0, 0, 255, 127);
    /// ```
    pub fn from_rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
        if a == 255 {
            // Fully opaque, no need for alpha channel
            Color(format!("#{:02x}{:02x}{:02x}", r, g, b))
        } else {
            // Include alpha channel
            Color(format!("#{:02x}{:02x}{:02x}{:02x}", r, g, b, a))
        }
    }

    /// Creates a Color from RGB values with full opacity.
    ///
    /// This is a convenience method for creating fully opaque colors.
    ///
    /// # Arguments
    ///
    /// * `r` - Red component (0-255)
    /// * `g` - Green component (0-255)
    /// * `b` - Blue component (0-255)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss::color::Color;
    ///
    /// let red = Color::from_rgb(255, 0, 0);
    /// let green = Color::from_rgb(0, 255, 0);
    /// ```
    pub fn from_rgb(r: u8, g: u8, b: u8) -> Self {
        Self::from_rgba(r, g, b, 255)
    }

    /// Returns 16-bit RGBA values (0-65535) for blending operations.
    /// This matches Go's color.RGBA interface for exact parity.
    pub fn rgba16(&self) -> (u32, u32, u32, u32) {
        if let Some((r, g, b, a)) = parse_hex_rgba_8bit(&self.0) {
            // Convert 8-bit values to true 16-bit for Go compatibility
            srgb_to_true_rgba16(Srgb::new(r as u8, g as u8, b as u8), a as u8)
        } else if let Ok(idx) = self.0.parse::<u32>() {
            let (r, g, b) = ansi256_to_rgb_u8((idx % 256) as u8);
            srgb_to_true_rgba16(Srgb::new(r, g, b), 255)
        } else {
            srgb_to_true_rgba16(Srgb::new(0, 0, 0), 255)
        }
    }
}

/// A color specified by an ANSI color value.
///
/// This is a type-safe wrapper around numeric ANSI color codes, providing
/// syntactic sugar for the more general `Color` type. It accepts values
/// from 0-255, where:
/// - 0-15: Standard ANSI colors (black, red, green, etc.)
/// - 16-231: 216-color cube (6×6×6 RGB values)
/// - 232-255: 24-step grayscale ramp
///
/// Values are automatically clamped to the 0-255 range using modulo arithmetic.
///
/// # Examples
///
/// ```rust
/// use lipgloss::color::{ANSIColor, TerminalColor};
///
/// // Basic ANSI colors (0-15)
/// let red = ANSIColor(1);          // Dark red
/// let bright_red = ANSIColor(9);   // Bright red
///
/// // 256-color palette
/// let orange = ANSIColor(208);
/// let dark_gray = ANSIColor(235);
///
/// // Get color information
/// let (r, g, b, a) = orange.rgba();
/// let token = orange.token_default();
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ANSIColor(pub u32);

impl TerminalColor for ANSIColor {
    fn token(&self, _r: &Renderer) -> String {
        self.0.to_string()
    }

    fn rgba(&self) -> (u32, u32, u32, u32) {
        let (r, g, b) = ansi256_to_rgb_u8((self.0 % 256) as u8);
        (r as u32, g as u32, b as u32, 0xFFFF)
    }
}

/// Provides color options for light and dark backgrounds.
///
/// This color type automatically adapts based on the terminal's background
/// color detection. It contains two color specifications - one for light
/// backgrounds and one for dark backgrounds - and the appropriate color
/// is selected at render time.
///
/// This is particularly useful for creating themes that work well in both
/// light and dark terminal environments without requiring manual color
/// profile switching.
///
/// # Examples
///
/// ```rust
/// use lipgloss::color::{AdaptiveColor, TerminalColor};
///
/// let adaptive_text = AdaptiveColor {
///     Light: "#000000", // Black text on light background
///     Dark: "#ffffff",  // White text on dark background
/// };
///
/// let adaptive_accent = AdaptiveColor {
///     Light: "#0066cc", // Dark blue on light background
///     Dark: "#66b3ff",  // Light blue on dark background
/// };
///
/// // Color automatically adapts based on terminal background
/// let token = adaptive_text.token_default();
/// let (r, g, b, a) = adaptive_text.rgba();
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(non_snake_case)]
pub struct AdaptiveColor {
    /// Color specification for light backgrounds
    pub Light: &'static str,
    /// Color specification for dark backgrounds
    pub Dark: &'static str,
}

impl TerminalColor for AdaptiveColor {
    fn token(&self, r: &Renderer) -> String {
        if r.has_dark_background() {
            Color::from(self.Dark).token(r)
        } else {
            Color::from(self.Light).token(r)
        }
    }

    fn rgba(&self) -> (u32, u32, u32, u32) {
        // Use default renderer's background to pick, then use Color's logic for parsing
        let color_str = if default_renderer().has_dark_background() {
            self.Dark
        } else {
            self.Light
        };
        Color::from(color_str).rgba()
    }
}

/// Specifies exact color values for all terminal color profiles.
///
/// This color type provides explicit control over how a color appears in
/// different terminal environments by specifying exact values for each
/// color profile type. This is useful when you need precise color matching
/// across different terminal capabilities.
///
/// Unlike other color types that perform automatic conversion, CompleteColor
/// uses the exact values you specify for each profile, giving you full
/// control over the color appearance.
///
/// # Examples
///
/// ```rust
/// use lipgloss::color::{CompleteColor, TerminalColor};
/// use lipgloss::renderer::{Renderer, ColorProfileKind};
///
/// let red = CompleteColor {
///     TrueColor: "#FF0000".to_string(),    // Hex for true color terminals
///     ANSI256: "196".to_string(),           // Index for 256-color terminals
///     ANSI: "9".to_string(),                // Index for basic ANSI terminals
/// };
///
/// // Different renderers will use different values
/// let mut true_color_renderer = Renderer::new();
/// true_color_renderer.set_color_profile(ColorProfileKind::TrueColor);
/// assert_eq!(red.token(&true_color_renderer), "#FF0000");
///
/// let mut ansi_renderer = Renderer::new();
/// ansi_renderer.set_color_profile(ColorProfileKind::ANSI);
/// assert_eq!(red.token(&ansi_renderer), "9");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(non_snake_case)]
pub struct CompleteColor {
    /// Color value for true color (24-bit) terminals
    pub TrueColor: String,
    /// Color value for 256-color terminals
    pub ANSI256: String,
    /// Color value for basic ANSI (16-color) terminals
    pub ANSI: String,
}

impl TerminalColor for CompleteColor {
    fn token(&self, r: &Renderer) -> String {
        match r.color_profile() {
            ColorProfileKind::TrueColor => self.TrueColor.clone(),
            ColorProfileKind::ANSI256 => self.ANSI256.clone(),
            ColorProfileKind::ANSI => self.ANSI.clone(),
            ColorProfileKind::NoColor => String::new(),
        }
    }

    fn rgba(&self) -> (u32, u32, u32, u32) {
        // CompleteColor RGBA should always use TrueColor value for consistent RGBA conversion
        if !self.TrueColor.is_empty() {
            Color(self.TrueColor.clone()).rgba()
        } else {
            (0x0, 0x0, 0x0, 0xFFFF)
        }
    }
}

/// Provides exact color values for light/dark backgrounds across all profiles.
///
/// This color type combines the features of `CompleteColor` and `AdaptiveColor`,
/// providing explicit control over color values for each terminal profile while
/// also adapting to light and dark backgrounds.
///
/// This is the most comprehensive color type, offering maximum control over
/// color appearance across different terminal environments and background types.
///
/// # Examples
///
/// ```rust
/// use lipgloss::color::{CompleteAdaptiveColor, CompleteColor, TerminalColor};
///
/// let adaptive_red = CompleteAdaptiveColor {
///     light: CompleteColor {
///         TrueColor: "#FF0000".to_string(),  // Darker red for light backgrounds
///         ANSI256: "196".to_string(),
///         ANSI: "10".to_string(),
///     },
///     dark: CompleteColor {
///         TrueColor: "#FF0000".to_string(),  // Lighter red for dark backgrounds
///         ANSI256: "196".to_string(),
///         ANSI: "10".to_string(),
///     },
/// };
///
/// // Color adapts based on both terminal capabilities AND background
/// let token = adaptive_red.token_default();
/// let (r, g, b, a) = adaptive_red.rgba();
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompleteAdaptiveColor {
    /// Color specification for light backgrounds
    pub light: CompleteColor,
    /// Color specification for dark backgrounds
    pub dark: CompleteColor,
}

// ================================================================================================
// Theme-Aware Color Constants
// ================================================================================================
//
// These AdaptiveColor constants provide semantic color definitions that automatically
// adapt to light and dark terminal backgrounds. They follow modern UI design patterns
// and ensure consistent, accessible theming across different terminal environments.

// Text Colors - Hierarchical text content
/// Primary text color with maximum contrast for main content readability.
///
/// Use for body text, primary content, and any text that needs to be highly readable.
/// Automatically selects dark colors on light backgrounds and light colors on dark backgrounds.
pub const TEXT_PRIMARY: AdaptiveColor = AdaptiveColor {
    Light: "#262626", // Very dark gray on light backgrounds
    Dark: "#FAFAFA",  // Very light gray on dark backgrounds
};

/// Muted text color for secondary information and less prominent content.
///
/// Use for captions, metadata, secondary descriptions, and supporting text that should
/// be readable but not compete with primary content for attention.
pub const TEXT_MUTED: AdaptiveColor = AdaptiveColor {
    Light: "#737373", // Medium gray on light backgrounds
    Dark: "#A3A3A3",  // Light gray on dark backgrounds
};

/// Subtle text color for least important details and placeholder content.
///
/// Use for disabled states, placeholder text, and the least important information
/// that should remain visible but unobtrusive.
pub const TEXT_SUBTLE: AdaptiveColor = AdaptiveColor {
    Light: "#A3A3A3", // Light gray on light backgrounds
    Dark: "#737373",  // Medium gray on dark backgrounds
};

/// Header text color with maximum contrast for titles and headings.
///
/// Use for section titles, headings, and any text that needs maximum emphasis
/// and contrast. Slightly more prominent than primary text.
pub const TEXT_HEADER: AdaptiveColor = AdaptiveColor {
    Light: "#171717", // Near-black on light backgrounds
    Dark: "#F5F5F5",  // Near-white on dark backgrounds
};

// Accent Colors - Brand and interactive elements
/// Primary brand/accent color for main interactive elements and highlights.
///
/// Use for primary buttons, active states, brand elements, and the most important
/// interactive components. This purple provides good contrast on both themes.
pub const ACCENT_PRIMARY: AdaptiveColor = AdaptiveColor {
    Light: "#7C3AED", // Purple-600 on light backgrounds
    Dark: "#A855F7",  // Purple-500 on dark backgrounds
};

/// Secondary accent color for alternative highlights and complementary elements.
///
/// Use for secondary buttons, alternative highlights, and accent elements that
/// should stand out but not compete with the primary accent.
pub const ACCENT_SECONDARY: AdaptiveColor = AdaptiveColor {
    Light: "#0891B2", // Cyan-600 on light backgrounds
    Dark: "#06B6D4",  // Cyan-500 on dark backgrounds
};

/// Interactive element color for links, clickable items, and active states.
///
/// Use for hyperlinks, clickable text, active menu items, and other interactive
/// elements that need to be clearly identifiable as clickable.
pub const INTERACTIVE: AdaptiveColor = AdaptiveColor {
    Light: "#DC2626", // Red-600 on light backgrounds
    Dark: "#EF4444",  // Red-500 on dark backgrounds
};

// Status Colors - Semantic feedback and states
/// Success state color for positive feedback and completed actions.
///
/// Use for success messages, completed tasks, positive status indicators,
/// and any UI element representing successful or positive states.
pub const STATUS_SUCCESS: AdaptiveColor = AdaptiveColor {
    Light: "#059669", // Emerald-600 on light backgrounds
    Dark: "#10B981",  // Emerald-500 on dark backgrounds
};

/// Warning state color for caution and attention-needed states.
///
/// Use for warning messages, cautionary states, pending actions,
/// and UI elements that need user attention but aren't critical.
pub const STATUS_WARNING: AdaptiveColor = AdaptiveColor {
    Light: "#D97706", // Amber-600 on light backgrounds
    Dark: "#F59E0B",  // Amber-500 on dark backgrounds
};

/// Error state color for failures and critical issues.
///
/// Use for error messages, failed states, destructive actions,
/// and any UI element representing errors or critical issues.
pub const STATUS_ERROR: AdaptiveColor = AdaptiveColor {
    Light: "#DC2626", // Red-600 on light backgrounds
    Dark: "#EF4444",  // Red-500 on dark backgrounds
};

/// Information state color for neutral information and tips.
///
/// Use for informational messages, helpful tips, neutral status indicators,
/// and UI elements that provide information without emotional weight.
pub const STATUS_INFO: AdaptiveColor = AdaptiveColor {
    Light: "#2563EB", // Blue-600 on light backgrounds
    Dark: "#3B82F6",  // Blue-500 on dark backgrounds
};

// Surface Colors - Backgrounds and containers
/// Subtle surface color for cards and elevated content areas.
///
/// Use for card backgrounds, subtle containers, and content areas that need
/// to be slightly differentiated from the main background.
pub const SURFACE_SUBTLE: AdaptiveColor = AdaptiveColor {
    Light: "#F5F5F5", // Light gray background on light themes
    Dark: "#262626",  // Dark gray background on dark themes
};

/// Elevated surface color for prominent containers and overlays.
///
/// Use for modal backgrounds, elevated cards, prominent content areas,
/// and containers that should appear "above" other content.
pub const SURFACE_ELEVATED: AdaptiveColor = AdaptiveColor {
    Light: "#FFFFFF", // Pure white on light themes
    Dark: "#171717",  // Very dark gray on dark themes
};

// Border Colors - Separators and frames
/// Subtle border color for gentle separation and quiet frames.
///
/// Use for subtle dividers, gentle card borders, and separators that
/// should define boundaries without being visually prominent.
pub const BORDER_SUBTLE: AdaptiveColor = AdaptiveColor {
    Light: "#E5E5E5", // Light gray border on light themes
    Dark: "#404040",  // Medium gray border on dark themes
};

/// Prominent border color for emphasized frames and active states.
///
/// Use for focused elements, active containers, emphasized frames,
/// and borders that need to be clearly visible and prominent.
pub const BORDER_PROMINENT: AdaptiveColor = AdaptiveColor {
    Light: "#D4D4D8", // Slightly darker gray on light themes
    Dark: "#525252",  // Lighter gray on dark themes
};

// Component-Specific Colors
// List Components
/// Primary color for list item text content.
///
/// Use for main list item text to ensure good readability across themes.
pub const LIST_ITEM_PRIMARY: AdaptiveColor = TEXT_PRIMARY;

/// Secondary color for list item supporting text.
///
/// Use for list item subtitles, descriptions, and secondary information.
pub const LIST_ITEM_SECONDARY: AdaptiveColor = TEXT_MUTED;

/// Color for list enumerators and bullets.
///
/// Use for list numbers, bullets, and enumeration symbols to make
/// them visually distinct from content while maintaining readability.
pub const LIST_ENUMERATOR: AdaptiveColor = ACCENT_PRIMARY;

// Table Components
/// Color for table header text.
///
/// Use for table column headers and other header content that needs
/// to stand out against header backgrounds.
pub const TABLE_HEADER_TEXT: AdaptiveColor = AdaptiveColor {
    Light: "#FAFAFA", // Light text on light themes (assumes dark header background)
    Dark: "#171717",  // Dark text on dark themes (assumes light header background)
};

/// Background color for table headers.
///
/// Use for table header backgrounds to create clear distinction
/// between headers and data rows.
pub const TABLE_HEADER_BG: AdaptiveColor = ACCENT_PRIMARY;

/// Color for table row text content.
///
/// Use for main table cell content to ensure good readability.
pub const TABLE_ROW_TEXT: AdaptiveColor = TEXT_PRIMARY;

/// Background color for alternating table rows.
///
/// Use for even/odd row backgrounds to improve table readability
/// through subtle row separation.
pub const TABLE_ROW_EVEN_BG: AdaptiveColor = AdaptiveColor {
    Light: "#F9FAFB", // Very light gray on light themes
    Dark: "#1F1F1F",  // Very dark gray on dark themes
};

/// Color for table borders and separators.
///
/// Use for table borders, cell separators, and grid lines to create
/// clear table structure without overwhelming the content.
pub const TABLE_BORDER: AdaptiveColor = BORDER_PROMINENT;

impl TerminalColor for CompleteAdaptiveColor {
    fn token(&self, r: &Renderer) -> String {
        if r.has_dark_background() {
            self.dark.token(r)
        } else {
            self.light.token(r)
        }
    }

    fn rgba(&self) -> (u32, u32, u32, u32) {
        if default_renderer().has_dark_background() {
            self.dark.rgba()
        } else {
            self.light.rgba()
        }
    }
}

// --- Helper Functions ---

/// Parse hex color with 8-bit RGBA values for backward compatibility
pub(crate) fn parse_hex_rgba_8bit(s: &str) -> Option<(u32, u32, u32, u32)> {
    // Support #RGB, #RRGGBB, #RGBA, #RRGGBBAA forms.
    let s = s.trim();
    let hex = s.strip_prefix('#')?;

    let (r, g, b, a_u8) = match hex.len() {
        3 => {
            // #RGB -> expand each nibble
            let r = u8::from_str_radix(&hex[0..1], 16).ok()?;
            let g = u8::from_str_radix(&hex[1..2], 16).ok()?;
            let b = u8::from_str_radix(&hex[2..3], 16).ok()?;
            let r = (r << 4) | r;
            let g = (g << 4) | g;
            let b = (b << 4) | b;
            (r, g, b, 0xFF)
        }
        4 => {
            // #RGBA -> expand
            let r = u8::from_str_radix(&hex[0..1], 16).ok()?;
            let g = u8::from_str_radix(&hex[1..2], 16).ok()?;
            let b = u8::from_str_radix(&hex[2..3], 16).ok()?;
            let a = u8::from_str_radix(&hex[3..4], 16).ok()?;
            let r = (r << 4) | r;
            let g = (g << 4) | g;
            let b = (b << 4) | b;
            let a = (a << 4) | a;
            (r, g, b, a)
        }
        6 => {
            // #RRGGBB
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            (r, g, b, 0xFF)
        }
        8 => {
            // #RRGGBBAA
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            let a = u8::from_str_radix(&hex[6..8], 16).ok()?;
            (r, g, b, a)
        }
        _ => return None,
    };

    // Return 8-bit values (no expansion to 16-bit)
    Some((r as u32, g as u32, b as u32, a_u8 as u32))
}

/// Parse hex color with 16-bit RGBA values for blending operations (Go compatibility)
pub(crate) fn parse_hex_rgba(s: &str) -> Option<(u32, u32, u32, u32)> {
    // Support #RGB, #RRGGBB, #RGBA, #RRGGBBAA forms.
    let s = s.trim();
    let hex = s.strip_prefix('#')?;

    let (r, g, b, a_u8) = match hex.len() {
        3 => {
            // #RGB -> expand each nibble
            let r = u8::from_str_radix(&hex[0..1], 16).ok()?;
            let g = u8::from_str_radix(&hex[1..2], 16).ok()?;
            let b = u8::from_str_radix(&hex[2..3], 16).ok()?;
            let r = (r << 4) | r;
            let g = (g << 4) | g;
            let b = (b << 4) | b;
            (r, g, b, 0xFF)
        }
        4 => {
            // #RGBA -> expand
            let r = u8::from_str_radix(&hex[0..1], 16).ok()?;
            let g = u8::from_str_radix(&hex[1..2], 16).ok()?;
            let b = u8::from_str_radix(&hex[2..3], 16).ok()?;
            let a = u8::from_str_radix(&hex[3..4], 16).ok()?;
            let r = (r << 4) | r;
            let g = (g << 4) | g;
            let b = (b << 4) | b;
            let a = (a << 4) | a;
            (r, g, b, a)
        }
        6 => {
            // #RRGGBB
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            (r, g, b, 0xFF)
        }
        8 => {
            // #RRGGBBAA
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            let a = u8::from_str_radix(&hex[6..8], 16).ok()?;
            (r, g, b, a)
        }
        _ => return None,
    };

    // Use palette for consistent sRGB semantics and expand to 16-bit for blending.
    let rgb = Srgb::new(r, g, b);
    Some(srgb_to_rgba16(rgb, a_u8))
}

/// Converts sRGB and alpha to 16-bit RGBA values with 8-bit RGB preservation.
///
/// This function preserves the original behavior where RGB components remain
/// as 8-bit values while alpha is expanded to 16-bit for blending operations.
///
/// # Arguments
///
/// * `rgb` - sRGB color with 8-bit components
/// * `a_u8` - Alpha value (0-255)
///
/// # Returns
///
/// RGBA tuple (r, g, b, a) where RGB are 8-bit values and alpha is 16-bit
fn srgb_to_rgba16(rgb: Srgb<u8>, a_u8: u8) -> (u32, u32, u32, u32) {
    // Original behavior: keep RGB as 8-bit, expand alpha to 16-bit
    let (r, g, b) = (rgb.red as u32, rgb.green as u32, rgb.blue as u32);
    let a = a_u8 as u32;
    (r, g, b, a * 257)
}

/// Converts 8-bit RGBA to true 16-bit RGBA for Go blending compatibility.
///
/// This function expands all components from 8-bit to 16-bit values using the
/// same algorithm as Go's color.RGBA interface, where each 8-bit value is
/// multiplied by 257 to fill the full 16-bit range.
///
/// # Arguments
///
/// * `rgb` - sRGB color with 8-bit components
/// * `a_u8` - Alpha value (0-255)
///
/// # Returns
///
/// RGBA tuple with all components expanded to 16-bit (0-65535)
fn srgb_to_true_rgba16(rgb: Srgb<u8>, a_u8: u8) -> (u32, u32, u32, u32) {
    // Expand 8-bit channels to 16-bit like Go's color.RGBA
    // Go's color.RGBA interface returns 16-bit values where each 8-bit value
    // is expanded by multiplying by 257 (0x101) to fill the full 16-bit range
    // So 255 (0xFF) becomes 65535 (0xFFFF)
    let (r, g, b) = (
        rgb.red as u32 * 257,
        rgb.green as u32 * 257,
        rgb.blue as u32 * 257,
    );
    let a = a_u8 as u32 * 257;
    (r, g, b, a)
}

// --- Color Utility Functions ---

/// Clamps a value between a low and high bound.
///
/// This utility function ensures a value stays within specified bounds,
/// which is useful for color component validation and calculations.
///
/// # Arguments
///
/// * `v` - The value to clamp
/// * `low` - The minimum allowed value
/// * `high` - The maximum allowed value
///
/// # Returns
///
/// The clamped value within the bounds [low, high]
///
/// # Examples
///
/// ```rust
/// use lipgloss::color::clamp;
///
/// assert_eq!(clamp(5, 0, 10), 5);   // Within bounds
/// assert_eq!(clamp(-1, 0, 10), 0);  // Below minimum
/// assert_eq!(clamp(15, 0, 10), 10); // Above maximum
/// ```
pub fn clamp<T: PartialOrd>(v: T, low: T, high: T) -> T {
    if v < low {
        low
    } else if v > high {
        high
    } else {
        v
    }
}

/// Adjusts the alpha value of a color using a 0-1 (clamped) float scale.
/// 0 = transparent, 1 = opaque.
///
/// # Arguments
/// * `color` - The color to adjust
/// * `alpha` - Alpha value from 0.0 (transparent) to 1.0 (opaque)
///
/// # Examples
/// ```rust
/// use lipgloss::color::{Color, alpha};
///
/// let red = Color("#ff0000".to_string());
/// let semi_transparent_red = alpha(&red, 0.5);
/// ```
pub fn alpha<C: TerminalColor>(color: &C, alpha_val: f64) -> Color {
    let (r, g, b, _) = color.rgba();
    let clamped_alpha = clamp(alpha_val, 0.0, 1.0);
    let alpha_u8 = (clamped_alpha * 255.0) as u8;

    // rgba() now returns 8-bit values directly
    let r_u8 = r as u8;
    let g_u8 = g as u8;
    let b_u8 = b as u8;

    Color(format!(
        "#{:02x}{:02x}{:02x}{:02x}",
        r_u8, g_u8, b_u8, alpha_u8
    ))
}

/// Makes a color lighter by a specific percentage (0-1, clamped).
///
/// # Arguments
/// * `color` - The color to lighten
/// * `percent` - Amount to lighten (0.0 = no change, 1.0 = maximum lightening)
///
/// # Examples
/// ```rust
/// use lipgloss::color::{Color, lighten};
///
/// let dark_red = Color("#800000".to_string());
/// let lighter_red = lighten(&dark_red, 0.3);
/// ```
pub fn lighten<C: TerminalColor>(color: &C, percent: f64) -> Color {
    let (r, g, b, _a) = color.rgba();
    let add = 255.0 * clamp(percent, 0.0, 1.0);

    // rgba() now returns 8-bit values directly
    let r_u8 = r as u8;
    let g_u8 = g as u8;
    let b_u8 = b as u8;

    Color(format!(
        "#{:02x}{:02x}{:02x}",
        ((r_u8 as f64 + add).min(255.0)) as u8,
        ((g_u8 as f64 + add).min(255.0)) as u8,
        ((b_u8 as f64 + add).min(255.0)) as u8
    ))
}

/// Makes a color darker by a specific percentage (0-1, clamped).
///
/// # Arguments
/// * `color` - The color to darken
/// * `percent` - Amount to darken (0.0 = no change, 1.0 = maximum darkening)
///
/// # Examples
/// ```rust
/// use lipgloss::color::{Color, darken};
///
/// let bright_red = Color("#ff0000".to_string());
/// let darker_red = darken(&bright_red, 0.3);
/// ```
pub fn darken<C: TerminalColor>(color: &C, percent: f64) -> Color {
    let (r, g, b, _a) = color.rgba();
    let mult = 1.0 - clamp(percent, 0.0, 1.0);

    // rgba() now returns 8-bit values directly
    let r_u8 = r as u8;
    let g_u8 = g as u8;
    let b_u8 = b as u8;

    Color(format!(
        "#{:02x}{:02x}{:02x}",
        (r_u8 as f64 * mult) as u8,
        (g_u8 as f64 * mult) as u8,
        (b_u8 as f64 * mult) as u8
    ))
}

/// Returns the complementary color (180° away on color wheel) of the given color.
/// This is useful for creating a contrasting color.
///
/// # Arguments
/// * `color` - The color to find the complement of
///
/// # Examples
/// ```rust
/// use lipgloss::color::{Color, complementary};
///
/// let blue = Color("#0000ff".to_string());
/// let orange = complementary(&blue); // Should be approximately orange
/// ```
pub fn complementary<C: TerminalColor>(color: &C) -> Color {
    let (r, g, b, _a) = color.rgba();

    // rgba() now returns 8-bit values directly
    let r_u8 = r as u8;
    let g_u8 = g as u8;
    let b_u8 = b as u8;

    // Convert to HSV to rotate hue by 180°
    let srgb = Srgb::new(
        r_u8 as f32 / 255.0,
        g_u8 as f32 / 255.0,
        b_u8 as f32 / 255.0,
    );
    let hsv: Hsv = Hsv::from_color(srgb);

    let mut new_hue = hsv.hue.into_positive_degrees() + 180.0;
    if new_hue >= 360.0 {
        new_hue -= 360.0;
    } else if new_hue < 0.0 {
        new_hue += 360.0;
    }

    let complementary_hsv = Hsv::new(new_hue, hsv.saturation, hsv.value);
    let complementary_srgb: Srgb = Srgb::from_color(complementary_hsv);
    let clamped = complementary_srgb.clamp();

    Color(format!(
        "#{:02x}{:02x}{:02x}",
        (clamped.red * 255.0) as u8,
        (clamped.green * 255.0) as u8,
        (clamped.blue * 255.0) as u8
    ))
}

/// Returns whether the given color is dark (based on the luminance portion of the color as interpreted as HSL).
///
/// # Arguments
/// * `color` - The color to check
///
/// # Examples
/// ```rust
/// use lipgloss::color::{Color, is_dark_color};
///
/// let black = Color("#000000".to_string());
/// let white = Color("#ffffff".to_string());
/// assert!(is_dark_color(&black));
/// assert!(!is_dark_color(&white));
/// ```
pub fn is_dark_color<C: TerminalColor>(color: &C) -> bool {
    let (r, g, b, _a) = color.rgba();

    // Calculate relative luminance (simplified)
    let luminance = 0.299 * (r as f64) + 0.587 * (g as f64) + 0.114 * (b as f64);
    luminance < 127.5 // Midpoint of 0-255
}

/// A function type that returns a color based on whether the terminal has a light or dark background.
///
/// This type alias represents a boxed closure that takes two color references
/// (one for light backgrounds, one for dark backgrounds) and returns the appropriate
/// Color based on the background type.
pub type LightDarkFunc = Box<dyn Fn(&dyn TerminalColor, &dyn TerminalColor) -> Color>;

/// Returns a function that chooses between light and dark colors based on background.
///
/// # Arguments
/// * `is_dark` - Whether the background is dark
///
/// # Examples
/// ```rust
/// use lipgloss::color::{Color, light_dark};
///
/// let light_dark_fn = light_dark(true); // Dark background
/// let red = Color("#ff0000".to_string());
/// let blue = Color("#0000ff".to_string());
/// let chosen = light_dark_fn(&red, &blue); // Will choose blue for dark bg
/// ```
pub fn light_dark(is_dark: bool) -> LightDarkFunc {
    Box::new(move |light: &dyn TerminalColor, dark: &dyn TerminalColor| {
        if is_dark {
            // Convert dark color to our Color type
            let (r, g, b, _a) = dark.rgba();
            Color(format!("#{:02x}{:02x}{:02x}", r as u8, g as u8, b as u8))
        } else {
            // Convert light color to our Color type
            let (r, g, b, _a) = light.rgba();
            Color(format!("#{:02x}{:02x}{:02x}", r as u8, g as u8, b as u8))
        }
    })
}

/// A function type that returns the appropriate color based on the color profile.
///
/// This type alias represents a boxed closure that takes three color references
/// (ANSI, ANSI256, TrueColor) and returns the Color appropriate for the
/// specified color profile.
pub type CompleteFunc =
    Box<dyn Fn(&dyn TerminalColor, &dyn TerminalColor, &dyn TerminalColor) -> Color>;

/// Returns a function that will return the appropriate color based on the given color profile.
///
/// # Arguments
/// * `profile` - The color profile to use for selection
///
/// # Examples
/// ```rust
/// use lipgloss::color::{Color, complete};
/// use lipgloss::renderer::ColorProfileKind;
///
/// let complete_fn = complete(ColorProfileKind::TrueColor);
/// let ansi = Color("1".to_string());
/// let ansi256 = Color("124".to_string());
/// let truecolor = Color("#ff34ac".to_string());
/// let chosen = complete_fn(&ansi, &ansi256, &truecolor); // Will choose truecolor
/// ```
pub fn complete(profile: ColorProfileKind) -> CompleteFunc {
    Box::new(
        move |ansi: &dyn TerminalColor,
              ansi256: &dyn TerminalColor,
              truecolor: &dyn TerminalColor| {
            let chosen_color = match profile {
                ColorProfileKind::ANSI => ansi,
                ColorProfileKind::ANSI256 => ansi256,
                ColorProfileKind::TrueColor => truecolor,
                ColorProfileKind::NoColor => return Color("".to_string()),
            };

            let (r, g, b, _a) = chosen_color.rgba();
            Color(format!("#{:02x}{:02x}{:02x}", r as u8, g as u8, b as u8))
        },
    )
}

/// Optimized hex color parsing with better performance than alternatives.
/// Parses hex color strings in formats: #RGB, #RRGGBB, #RGBA, #RRGGBBAA
///
/// # Arguments
/// * `hex` - Hex color string starting with #
///
/// # Returns
/// * `Some((r, g, b, a))` - RGBA components as u8 values, or None if invalid
///
/// # Examples
/// ```rust
/// use lipgloss::color::parse_hex;
///
/// assert_eq!(parse_hex("#ff0000"), Some((255, 0, 0, 255)));
/// assert_eq!(parse_hex("#f00"), Some((255, 0, 0, 255)));
/// assert_eq!(parse_hex("invalid"), None);
/// ```
pub fn parse_hex(s: &str) -> Option<(u8, u8, u8, u8)> {
    let s = s.trim();
    if s.is_empty() || !s.starts_with('#') {
        return None;
    }

    let hex = &s[1..];

    match hex.len() {
        3 => {
            // #RGB
            let r = u8::from_str_radix(&hex[0..1], 16).ok()?;
            let g = u8::from_str_radix(&hex[1..2], 16).ok()?;
            let b = u8::from_str_radix(&hex[2..3], 16).ok()?;
            Some(((r << 4) | r, (g << 4) | g, (b << 4) | b, 255))
        }
        4 => {
            // #RGBA
            let r = u8::from_str_radix(&hex[0..1], 16).ok()?;
            let g = u8::from_str_radix(&hex[1..2], 16).ok()?;
            let b = u8::from_str_radix(&hex[2..3], 16).ok()?;
            let a = u8::from_str_radix(&hex[3..4], 16).ok()?;
            Some(((r << 4) | r, (g << 4) | g, (b << 4) | b, (a << 4) | a))
        }
        6 => {
            // #RRGGBB
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            Some((r, g, b, 255))
        }
        8 => {
            // #RRGGBBAA
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            let a = u8::from_str_radix(&hex[6..8], 16).ok()?;
            Some((r, g, b, a))
        }
        _ => None,
    }
}