boxen 0.4.0

A Rust library for creating styled terminal boxes around text with performance optimizations
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
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
//! # Configuration System
//!
//! This module provides comprehensive configuration options for customizing the appearance
//! and behavior of terminal boxes. The configuration system is built around flexible,
//! composable options that allow fine-grained control over every aspect of box rendering.
//!
//! ## Overview
//!
//! The configuration system consists of several key components:
//! - **`BoxenOptions`**: Main configuration struct containing all styling options
//! - **`BoxenBuilder`**: Ergonomic builder pattern for constructing configurations
//! - **Style Enums**: Type-safe options for borders, alignment, positioning, and colors
//! - **Spacing Types**: Flexible spacing configuration for padding and margins
//!
//! ## Quick Start
//!
//! ```rust
//! use ::boxen::{BoxenBuilder, BorderStyle, TextAlignment, Color, TitleAlignment};
//!
//! // Simple box with basic styling
//! let result = BoxenBuilder::new()
//!     .border_style(BorderStyle::Double)
//!     .padding(2)
//!     .text_alignment(TextAlignment::Center)
//!     .render("Hello, World!")
//!     .unwrap();
//!
//! // Advanced box with colors and title
//! let result = BoxenBuilder::new()
//!     .border_style(BorderStyle::Round)
//!     .border_color(Color::Named("blue".to_string()))
//!     .background_color(Color::Named("white".to_string()))
//!     .title("Status Report")
//!     .title_alignment(TitleAlignment::Center)
//!     .width(50)
//!     .margin(1)
//!     .render("System operational")
//!     .unwrap();
//! ```
//!
//! ## Configuration Categories
//!
//! ### Border Configuration
//! - **Style**: Choose from 9 predefined border styles (Single, Double, Rounded, etc.)
//! - **Color**: Optional border coloring with full color palette support
//! - **Dimming**: Reduce border intensity for subtle presentation
//!
//! ### Layout Configuration
//! - **Dimensions**: Fixed width/height or automatic sizing
//! - **Positioning**: Left, center, or right alignment within terminal
//! - **Spacing**: Independent padding and margin control
//! - **Fullscreen**: Optional fullscreen mode with various behaviors
//!
//! ### Content Configuration
//! - **Text Alignment**: Left, center, or right alignment within the box
//! - **Background**: Optional background coloring for content area
//! - **Title**: Optional title with independent alignment control
//!
//! ## Builder Pattern
//!
//! The recommended way to create configurations is through the builder pattern:
//!
//! ```rust
//! use ::boxen::{BoxenBuilder, BorderStyle, TextAlignment, Float};
//!
//! let config = BoxenBuilder::new()
//!     .border_style(BorderStyle::Bold)
//!     .padding(3)
//!     .margin(1)
//!     .text_alignment(TextAlignment::Center)
//!     .float(Float::Center)
//!     .width(60)
//!     .title("Configuration Example")
//!     .build();
//! ```
//!
//! ## Direct Configuration
//!
//! For advanced use cases, you can construct `BoxenOptions` directly:
//!
//! ```rust
//! use ::boxen::{BoxenOptions, BorderStyle, TextAlignment, Spacing, Color, Width, Height};
//!
//! let options = BoxenOptions {
//!     border_style: BorderStyle::Double,
//!     padding: Spacing::from((2, 4, 2, 4)), // top, right, bottom, left
//!     margin: Spacing::from(1),
//!     text_alignment: TextAlignment::Center,
//!     border_color: Some(Color::Named("green".to_string())),
//!     title: Some("Direct Config".to_string()),
//!     width: Some(Width::Fixed(50)),
//!     ..Default::default()
//! };
//! ```
//!
//! ## Spacing System
//!
//! The spacing system provides flexible control over padding and margins:
//!
//! ### Uniform Spacing
//! ```rust
//! use ::boxen::Spacing;
//! let spacing = Spacing::from(2); // 2 units on all sides
//! ```
//!
//! ### Individual Control
//! ```rust
//! use ::boxen::Spacing;
//! let spacing = Spacing::from((1, 2, 1, 2)); // top, right, bottom, left
//! ```
//!
//! ### Direct Field Access
//! ```rust
//! use ::boxen::Spacing;
//! let spacing = Spacing {
//!     top: 2,
//!     right: 3,
//!     bottom: 1,
//!     left: 3,
//! };
//! ```
//!
//! ## Color System
//!
//! Colors can be specified in multiple formats:
//!
//! ### Named Colors
//! ```rust
//! use ::boxen::{BoxenBuilder, Color};
//!
//! let result = BoxenBuilder::new().border_color(Color::Named("red".to_string()));
//! ```
//!
//! ### RGB Values
//! ```rust
//! use ::boxen::{BoxenBuilder, Color};
//!
//! let result = BoxenBuilder::new().border_color(Color::Rgb(255, 128, 0));
//! ```
//!
//! ### Hex Strings
//! ```rust
//! use ::boxen::{BoxenBuilder, Color};
//!
//! let result = BoxenBuilder::new().border_color(Color::Hex("#FF8000".to_string()));
//! ```
//!
//! ## Fullscreen Mode
//!
//! Fullscreen mode provides several behaviors for terminal-wide boxes:
//!
//! ```rust
//! use ::boxen::{BoxenBuilder, FullscreenMode};
//!
//! // Automatically use terminal dimensions
//! let result = BoxenBuilder::new().fullscreen(FullscreenMode::Auto);
//!
//! // Use custom function to calculate dimensions
//! let result = BoxenBuilder::new().fullscreen(FullscreenMode::Custom(|width, height| {
//!     (width - 4, height - 2)
//! }));
//! ```
//!
//! ## Validation and Error Handling
//!
//! All configuration options are validated before rendering:
//!
//! ```rust
//! use ::boxen::BoxenBuilder;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     match BoxenBuilder::new().width(0).render("Invalid") {
//!         Ok(result) => println!("{}", result),
//!         Err(e) => {
//!             println!("Configuration error: {}", e);
//!             // Error includes helpful suggestions for fixing the issue
//!             for recommendation in e.recommendations() {
//!                 println!("💡 {}: {}", recommendation.issue, recommendation.suggestion);
//!             }
//!         }
//!     }
//!     Ok(())
//! }
//! ```
//!
//! ## Performance Considerations
//!
//! - Configuration structs are lightweight and can be cloned efficiently
//! - Builder operations are zero-cost until `build()` or `render()` is called
//! - Default values are optimized for common use cases
//! - Validation is performed only when necessary to avoid overhead
//!
//! ## Thread Safety
//!
//! All configuration types are thread-safe and can be shared between threads
//! or used in concurrent rendering operations.

use crate::error::{BoxenError, BoxenResult};
use crate::terminal::{calculate_border_width, get_terminal_height, get_terminal_width};

/// Width specification for box sizing.
///
/// Supports both fixed width values and dynamic width calculation based on available space.
///
/// # Examples
///
/// ```rust
/// use ::boxen::{builder, Width};
///
/// // Fixed width
/// let fixed = builder().width(50);
///
/// // Dynamic width based on available space
/// let dynamic = builder().width(|available: usize| available.min(80));
///
/// // Or using Into trait
/// let fixed2 = builder().width(Width::from(50));
/// ```
pub enum Width {
    /// Fixed width in columns
    Fixed(usize),
    /// Dynamic width calculated from available space
    Dynamic(std::sync::Arc<dyn Fn(usize) -> usize + Send + Sync>),
}

impl Clone for Width {
    fn clone(&self) -> Self {
        match self {
            Self::Fixed(w) => Self::Fixed(*w),
            Self::Dynamic(f) => Self::Dynamic(f.clone()),
        }
    }
}

impl PartialEq for Width {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Fixed(a), Self::Fixed(b)) => a == b,
            // Dynamic functions can't be compared for equality
            (Self::Dynamic(_), Self::Dynamic(_)) => false,
            _ => false,
        }
    }
}

impl Width {
    /// Create a fixed width
    #[must_use]
    pub const fn fixed(width: usize) -> Self {
        Self::Fixed(width)
    }

    /// Create a dynamic width from a function or closure
    #[must_use]
    pub fn from_fn<F>(f: F) -> Self
    where
        F: Fn(usize) -> usize + Send + Sync + 'static,
    {
        Self::Dynamic(std::sync::Arc::new(f))
    }

    /// Calculate the actual width given available space
    #[must_use]
    pub fn calculate(&self, available: usize) -> usize {
        match self {
            Self::Fixed(w) => *w,
            Self::Dynamic(f) => f(available),
        }
    }
}

impl std::fmt::Debug for Width {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Fixed(w) => write!(f, "Width::Fixed({w})"),
            Self::Dynamic(_) => write!(f, "Width::Dynamic(<fn>)"),
        }
    }
}

impl From<usize> for Width {
    fn from(width: usize) -> Self {
        Self::Fixed(width)
    }
}

impl<F> From<F> for Width
where
    F: Fn(usize) -> usize + Send + Sync + 'static,
{
    fn from(f: F) -> Self {
        Self::Dynamic(std::sync::Arc::new(f))
    }
}

/// Height specification for box sizing.
///
/// Supports both fixed height values and dynamic height calculation based on available space.
///
/// # Examples
///
/// ```rust
/// use ::boxen::{builder, Height};
///
/// // Fixed height
/// let fixed = builder().height(20);
///
/// // Dynamic height based on available space
/// let dynamic = builder().height(|available: usize| available.min(30));
/// ```
pub enum Height {
    /// Fixed height in rows
    Fixed(usize),
    /// Dynamic height calculated from available space
    Dynamic(std::sync::Arc<dyn Fn(usize) -> usize + Send + Sync>),
}

impl Clone for Height {
    fn clone(&self) -> Self {
        match self {
            Self::Fixed(h) => Self::Fixed(*h),
            Self::Dynamic(f) => Self::Dynamic(f.clone()),
        }
    }
}

impl PartialEq for Height {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Fixed(a), Self::Fixed(b)) => a == b,
            // Dynamic functions can't be compared for equality
            (Self::Dynamic(_), Self::Dynamic(_)) => false,
            _ => false,
        }
    }
}

impl Height {
    /// Create a fixed height
    #[must_use]
    pub const fn fixed(height: usize) -> Self {
        Self::Fixed(height)
    }

    /// Create a dynamic height from a function or closure
    #[must_use]
    pub fn from_fn<F>(f: F) -> Self
    where
        F: Fn(usize) -> usize + Send + Sync + 'static,
    {
        Self::Dynamic(std::sync::Arc::new(f))
    }

    /// Calculate the actual height given available space
    #[must_use]
    pub fn calculate(&self, available: usize) -> usize {
        match self {
            Self::Fixed(h) => *h,
            Self::Dynamic(f) => f(available),
        }
    }
}

impl std::fmt::Debug for Height {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Fixed(h) => write!(f, "Height::Fixed({h})"),
            Self::Dynamic(_) => write!(f, "Height::Dynamic(<fn>)"),
        }
    }
}

impl From<usize> for Height {
    fn from(height: usize) -> Self {
        Self::Fixed(height)
    }
}

impl<F> From<F> for Height
where
    F: Fn(usize) -> usize + Send + Sync + 'static,
{
    fn from(f: F) -> Self {
        Self::Dynamic(std::sync::Arc::new(f))
    }
}

/// Main configuration struct for boxen styling options.
///
/// `BoxenOptions` contains all the configuration parameters for customizing
/// the appearance and layout of terminal boxes. This struct is typically
/// created using the [`BoxenBuilder`] for a more ergonomic API.
///
/// # Examples
///
/// ## Direct Construction
///
/// ```rust
/// use ::boxen::{BoxenOptions, BorderStyle, TextAlignment, Spacing, Width};
///
/// let options = BoxenOptions {
///     border_style: BorderStyle::Double,
///     padding: Spacing::from(2),
///     text_alignment: TextAlignment::Center,
///     title: Some("My Box".to_string()),
///     width: Some(Width::Fixed(40)),
///     ..Default::default()
/// };
/// ```
///
/// ## Using Builder (Recommended)
///
/// ```rust
/// use ::boxen::{builder, BorderStyle, TextAlignment};
///
/// let result = builder()
///     .border_style(BorderStyle::Double)
///     .padding(2)
///     .text_alignment(TextAlignment::Center)
///     .title("My Box")
///     .width(40)
///     .render("Hello, World!")
///     .unwrap();
/// ```
///
/// # Field Documentation
///
/// - `border_style`: The style of border to draw around the box
/// - `padding`: Internal spacing between the border and content
/// - `margin`: External spacing around the entire box
/// - `text_alignment`: How to align text within the box
/// - `title`: Optional title to display in the top border
/// - `title_alignment`: How to align the title within the top border
/// - `float`: How to position the box within the terminal
/// - `width`: Optional fixed width for the box
/// - `height`: Optional fixed height for the box
/// - `border_color`: Optional color for the border
/// - `background_color`: Optional background color for the content area
/// - `dim_border`: Whether to render the border with reduced intensity
/// - `fullscreen`: Optional fullscreen mode configuration
#[derive(Debug, Clone)]
pub struct BoxenOptions {
    /// The visual style of the border (Single, Double, Rounded, etc.)
    pub border_style: BorderStyle,
    /// Internal spacing between the border and content
    pub padding: Spacing,
    /// External spacing around the entire box
    pub margin: Spacing,
    /// How to align text within the box content area
    pub text_alignment: TextAlignment,
    /// Optional title to display in the top border
    pub title: Option<String>,
    /// How to align the title within the top border
    pub title_alignment: TitleAlignment,
    /// How to position the box within the terminal width
    pub float: Float,
    /// Optional width specification (fixed or dynamic)
    pub width: Option<Width>,
    /// Optional height specification (fixed or dynamic)
    pub height: Option<Height>,
    /// Optional color for the border characters
    pub border_color: Option<Color>,
    /// Optional background color for the content area
    pub background_color: Option<Color>,
    /// Optional color for the title text
    pub title_color: Option<Color>,
    /// Whether to render the border with reduced intensity
    pub dim_border: bool,
    /// Optional fullscreen mode configuration
    pub fullscreen: Option<FullscreenMode>,
}

impl Default for BoxenOptions {
    fn default() -> Self {
        Self {
            border_style: BorderStyle::Single,
            padding: Spacing::default(),
            margin: Spacing::default(),
            text_alignment: TextAlignment::Left,
            title: None,
            title_alignment: TitleAlignment::Left,
            float: Float::Left,
            width: None,
            height: None,
            border_color: None,
            background_color: None,
            title_color: None,
            dim_border: false,
            fullscreen: None,
        }
    }
}

/// Border style definition for box rendering.
///
/// Defines the visual style of the border drawn around the box content.
/// Each style uses different Unicode characters to create distinct visual effects.
///
/// # Examples
///
/// ```rust
/// use ::boxen::{builder, BorderStyle};
///
/// // Single line border (default)
/// let single = builder().border_style(BorderStyle::Single);
///
/// // Double line border for emphasis
/// let double = builder().border_style(BorderStyle::Double);
///
/// // Rounded corners for a softer look
/// let round = builder().border_style(BorderStyle::Round);
///
/// // No border for minimal styling
/// let none = builder().border_style(BorderStyle::None);
/// ```
///
/// # Visual Examples
///
/// ## Single
/// ```text
/// ┌─────┐
/// │Hello│
/// └─────┘
/// ```
///
/// ## Double
/// ```text
/// ╔═════╗
/// ║Hello║
/// ╚═════╝
/// ```
///
/// ## Round
/// ```text
/// ╭─────╮
/// │Hello│
/// ╰─────╯
/// ```
///
/// ## Bold
/// ```text
/// ┏━━━━━┓
/// ┃Hello┃
/// ┗━━━━━┛
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BorderStyle {
    /// No border - content only
    None,
    /// Single line border (default)
    Single,
    /// Double line border
    Double,
    /// Rounded corners
    Round,
    /// Bold/thick lines
    Bold,
    /// Single horizontal, double vertical
    SingleDouble,
    /// Double horizontal, single vertical
    DoubleSingle,
    /// Classic ASCII-style border using +, -, |
    Classic,
    /// Custom border using specified characters
    Custom(BorderChars),
}

/// Border character set for custom borders
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BorderChars {
    /// Character for the top-left corner of the border
    pub top_left: char,
    /// Character for the top-right corner of the border
    pub top_right: char,
    /// Character for the bottom-left corner of the border
    pub bottom_left: char,
    /// Character for the bottom-right corner of the border
    pub bottom_right: char,
    /// Character for the left vertical edge of the border
    pub left: char,
    /// Character for the right vertical edge of the border
    pub right: char,
    /// Character for the top horizontal edge of the border
    pub top: char,
    /// Character for the bottom horizontal edge of the border
    pub bottom: char,
}

/// Spacing configuration for padding and margins.
///
/// Represents spacing values for all four sides of a box. Used for both
/// padding (internal spacing) and margins (external spacing).
///
/// # Examples
///
/// ## Direct Construction
///
/// ```rust
/// use ::boxen::Spacing;
///
/// let spacing = Spacing {
///     top: 1,
///     right: 2,
///     bottom: 1,
///     left: 2,
/// };
/// ```
///
/// ## Using From Implementations
///
/// ```rust
/// use ::boxen::Spacing;
///
/// // Asymmetric spacing (TypeScript-compatible)
/// let asymmetric = Spacing::from(2);  // top: 2, right: 6, bottom: 2, left: 6
///
/// // Explicit values
/// let explicit = Spacing::from((1, 2, 3, 4));  // top, right, bottom, left
///
/// // Horizontal and vertical
/// let symmetric = Spacing::from((3, 1));  // horizontal: 3, vertical: 1
///
/// // Array syntax
/// let array = Spacing::from([2, 4]);  // [horizontal, vertical]
/// let full_array = Spacing::from([1, 2, 3, 4]);  // [top, right, bottom, left]
/// ```
///
/// # TypeScript Compatibility
///
/// When created from a single `usize` value, this struct follows the TypeScript
/// boxen behavior of creating asymmetric spacing with 3x horizontal padding
/// to account for typical terminal character aspect ratios.
#[derive(Debug, Default, Clone, Copy)]
pub struct Spacing {
    /// Top spacing
    pub top: usize,
    /// Right spacing
    pub right: usize,
    /// Bottom spacing
    pub bottom: usize,
    /// Left spacing
    pub left: usize,
}

impl From<usize> for Spacing {
    /// Creates terminal-balanced spacing (3x horizontal, 1x vertical) to match TypeScript behavior.
    ///
    /// ⚠️ **WARNING**: This implementation applies a 3x multiplier to horizontal spacing,
    /// which may be surprising. Consider using explicit constructors instead:
    /// - `Spacing::terminal_balanced(value)` - For terminal-aware spacing (same as this)
    /// - `Spacing::uniform(value)` - For equal spacing on all sides
    ///
    /// Due to terminal character aspect ratios (characters are ~2x taller than wide),
    /// horizontal spacing is automatically scaled 3x to appear visually balanced:
    /// - Vertical (top/bottom): `value`
    /// - Horizontal (left/right): `value * 3`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::Spacing;
    ///
    /// let spacing = Spacing::from(2);
    /// assert_eq!(spacing.top, 2);
    /// assert_eq!(spacing.right, 6);  // 3x horizontal multiplier!
    /// assert_eq!(spacing.bottom, 2);
    /// assert_eq!(spacing.left, 6);   // 3x horizontal multiplier!
    ///
    /// // Prefer explicit constructors for clarity:
    /// let explicit = Spacing::terminal_balanced(2);  // Same result, clearer intent
    /// ```
    fn from(value: usize) -> Self {
        Self::terminal_balanced(value)
    }
}

impl From<(usize, usize, usize, usize)> for Spacing {
    /// Creates spacing from (top, right, bottom, left) tuple
    fn from((top, right, bottom, left): (usize, usize, usize, usize)) -> Self {
        Self {
            top,
            right,
            bottom,
            left,
        }
    }
}

/// Text alignment within the box
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum TextAlignment {
    /// Align text to the left side of the box
    Left,
    /// Center text within the box
    Center,
    /// Align text to the right side of the box
    Right,
}

/// Title alignment within the top border
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum TitleAlignment {
    /// Align title to the left side of the top border
    Left,
    /// Center title within the top border
    Center,
    /// Align title to the right side of the top border
    Right,
}

/// Box positioning relative to terminal
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum Float {
    /// Position box on the left side of the terminal
    Left,
    /// Center box horizontally in the terminal
    Center,
    /// Position box on the right side of the terminal
    Right,
}

/// Color specification for borders and backgrounds
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum Color {
    /// Named color (e.g., "red", "blue", "green")
    Named(String),
    /// Hexadecimal color code (e.g., "#FF0000", "#00FF00")
    Hex(String),
    /// RGB color values (red, green, blue components 0-255)
    Rgb(u8, u8, u8),
}

/// Fullscreen mode configuration
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum FullscreenMode {
    /// Automatically use terminal dimensions
    Auto,
    /// Use custom function to calculate dimensions from terminal size
    Custom(fn(usize, usize) -> (usize, usize)),
}

/// Builder pattern for creating `BoxenOptions` with a fluent interface.
///
/// The `BoxenBuilder` provides a convenient and type-safe way to configure box styling
/// options using method chaining. This is the recommended approach for creating boxes
/// with custom styling.
///
/// # Examples
///
/// ## Basic Builder Usage
///
/// ```rust
/// use ::boxen::{builder, BorderStyle, TextAlignment};
///
/// let result = builder()
///     .border_style(BorderStyle::Double)
///     .padding(2)
///     .text_alignment(TextAlignment::Center)
///     .render("Hello, World!")
///     .unwrap();
/// ```
///
/// ## Advanced Configuration
///
/// ```rust
/// use ::boxen::{builder, BorderStyle, TextAlignment, TitleAlignment, Float, Color};
///
/// let result = builder()
///     .border_style(BorderStyle::Round)
///     .padding((2, 4, 2, 4))  // top, right, bottom, left
///     .margin(1)
///     .text_alignment(TextAlignment::Center)
///     .title("Status Report")
///     .title_alignment(TitleAlignment::Center)
///     .float(Float::Center)
///     .width(50)
///     .height(10)
///     .border_color("green")
///     .background_color("#f0f0f0")
///     .dim_border(false)
///     .render("All systems operational")
///     .unwrap();
/// ```
///
/// ## Convenience Methods
///
/// ```rust
/// use ::boxen::builder;
///
/// let result = builder()
///     .spacing(1)              // Sets both padding and margin
///     .colors("red", "white")  // Sets border and background colors
///     .size(40, 8)            // Sets width and height
///     .center_all()           // Centers text, title, and float
///     .title("Centered Box")
///     .render("This box is centered in every way")
///     .unwrap();
/// ```
///
/// # Validation and Error Handling
///
/// The builder validates configuration when `render()` is called, not during method chaining.
/// This allows for efficient configuration building without intermediate validations.
///
/// ```rust
/// use ::boxen::builder;
///
/// let result = builder()
///     .width(10)
///     .padding(20)  // This will cause an error - padding too large for width
///     .render("Test");
///
/// match result {
///     Ok(output) => println!("{}", output),
///     Err(e) => println!("Configuration error: {}", e),
/// }
/// ```
///
/// # Performance
///
/// - Method chaining is zero-cost - no allocations until `render()` is called
/// - Configuration validation is performed once at render time
/// - The builder can be reused by calling `render()` multiple times with different text
///
/// # Auto-Adjustment
///
/// The builder provides methods for automatic configuration adjustment:
///
/// ```rust
/// use ::boxen::builder;
///
/// // Automatically adjust configuration to fix common issues
/// let result = builder()
///     .width(5)     // Too small
///     .padding(10)  // Too large
///     .auto_adjust("Hello, World!")  // Fixes the configuration
///     .render("Hello, World!")
///     .unwrap();
///
/// // Or render with automatic adjustment if needed
/// let result = builder()
///     .width(5)
///     .padding(10)
///     .render_or_adjust("Hello, World!")  // Tries render, auto-adjusts if it fails
///     .unwrap();
/// ```
pub struct BoxenBuilder {
    options: BoxenOptions,
}

impl BoxenBuilder {
    /// Create a new builder with default options.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::BoxenBuilder;
    ///
    /// let builder = BoxenBuilder::new();
    /// let result = builder.render("Hello").unwrap();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            options: BoxenOptions::default(),
        }
    }

    /// Set the border style for the box.
    ///
    /// # Arguments
    ///
    /// * `style` - The border style to use (Single, Double, Round, Bold, etc.)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::{builder, BorderStyle};
    ///
    /// let result = builder()
    ///     .border_style(BorderStyle::Double)
    ///     .render("Double border")
    ///     .unwrap();
    /// ```
    #[must_use]
    pub fn border_style(mut self, style: BorderStyle) -> Self {
        self.options.border_style = style;
        self
    }

    /// Set padding around the text content.
    ///
    /// Padding is the space between the text and the border. Accepts various formats:
    /// - `usize`: Creates asymmetric padding (3x horizontal, 1x vertical) to match TypeScript behavior
    /// - `(usize, usize, usize, usize)`: Explicit (top, right, bottom, left) values
    /// - `(usize, usize)`: Horizontal and vertical values
    /// - `Spacing`: Direct spacing struct
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::{builder, Spacing};
    ///
    /// // Asymmetric padding (TypeScript-compatible)
    /// let result1 = builder().padding(1).render("Text").unwrap();
    ///
    /// // Explicit padding values
    /// let result2 = builder().padding((1, 2, 1, 2)).render("Text").unwrap();
    ///
    /// // Horizontal and vertical
    /// let result3 = builder().padding((3, 1)).render("Text").unwrap();
    /// ```
    #[must_use]
    pub fn padding<T: Into<Spacing>>(mut self, padding: T) -> Self {
        self.options.padding = padding.into();
        self
    }

    /// Set margin around the entire box.
    ///
    /// Margin is the space outside the border. Accepts the same formats as padding.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::builder;
    ///
    /// let result = builder()
    ///     .margin(2)
    ///     .render("Text with margin")
    ///     .unwrap();
    /// ```
    #[must_use]
    pub fn margin<T: Into<Spacing>>(mut self, margin: T) -> Self {
        self.options.margin = margin.into();
        self
    }

    /// Set text alignment
    #[must_use]
    pub fn text_alignment(mut self, alignment: TextAlignment) -> Self {
        self.options.text_alignment = alignment;
        self
    }

    /// Set title text
    #[must_use]
    pub fn title<S: Into<String>>(mut self, title: S) -> Self {
        self.options.title = Some(title.into());
        self
    }

    /// Set title alignment
    #[must_use]
    pub fn title_alignment(mut self, alignment: TitleAlignment) -> Self {
        self.options.title_alignment = alignment;
        self
    }

    /// Set title color
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::builder;
    ///
    /// let result = builder()
    ///     .title("Status")
    ///     .title_color("red")
    ///     .border_color("blue")
    ///     .render("Content")
    ///     .unwrap();
    /// ```
    #[must_use]
    pub fn title_color<C: Into<Color>>(mut self, color: C) -> Self {
        self.options.title_color = Some(color.into());
        self
    }

    /// Set float positioning
    #[must_use]
    pub fn float(mut self, float: Float) -> Self {
        self.options.float = float;
        self
    }

    /// Set box width (fixed or dynamic)
    ///
    /// Accepts either a fixed width value or a closure for dynamic sizing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::builder;
    ///
    /// // Fixed width
    /// let result = builder().width(50).render("Hello").unwrap();
    ///
    /// // Dynamic width: use 80% of available space, minimum 30
    /// let result = builder()
    ///     .width(|available: usize| (available * 4 / 5).max(30))
    ///     .render("Hello")
    ///     .unwrap();
    /// ```
    #[must_use]
    pub fn width<W: Into<Width>>(mut self, width: W) -> Self {
        self.options.width = Some(width.into());
        self
    }

    /// Set box height (fixed or dynamic)
    ///
    /// Accepts either a fixed height value or a closure for dynamic sizing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::builder;
    ///
    /// // Fixed height
    /// let result = builder().height(20).render("Hello").unwrap();
    ///
    /// // Dynamic height: use 50% of available space, minimum 10
    /// let result = builder()
    ///     .height(|available: usize| (available / 2).max(10))
    ///     .render("Hello")
    ///     .unwrap();
    /// ```
    #[must_use]
    pub fn height<H: Into<Height>>(mut self, height: H) -> Self {
        self.options.height = Some(height.into());
        self
    }

    /// Set border color
    #[must_use]
    pub fn border_color<C: Into<Color>>(mut self, color: C) -> Self {
        self.options.border_color = Some(color.into());
        self
    }

    /// Set background color
    #[must_use]
    pub fn background_color<C: Into<Color>>(mut self, color: C) -> Self {
        self.options.background_color = Some(color.into());
        self
    }

    /// Enable dim border
    #[must_use]
    pub fn dim_border(mut self, dim: bool) -> Self {
        self.options.dim_border = dim;
        self
    }

    /// Set fullscreen mode
    #[must_use]
    pub fn fullscreen(mut self, mode: FullscreenMode) -> Self {
        self.options.fullscreen = Some(mode);
        self
    }

    /// Build the final options
    #[must_use]
    pub fn build(self) -> BoxenOptions {
        self.options
    }

    /// Build and render box with the given text.
    ///
    /// This is the final method in the builder chain that validates the configuration
    /// and renders the box. All validation is performed at this stage.
    ///
    /// # Arguments
    ///
    /// * `text` - The text content to render in the box
    ///
    /// # Returns
    ///
    /// Returns `Result<String, BoxenError>` with the rendered box or detailed error information.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::{builder, BorderStyle};
    ///
    /// let result = builder()
    ///     .border_style(BorderStyle::Round)
    ///     .padding(1)
    ///     .render("Hello, World!")
    ///     .unwrap();
    ///
    /// println!("{}", result);
    /// ```
    ///
    /// # Error Handling
    ///
    /// ```rust
    /// use ::boxen::builder;
    ///
    /// let result = builder()
    ///     .width(5)     // Too small
    ///     .padding(10)  // Too large
    ///     .render("Hello");
    ///
    /// match result {
    ///     Ok(output) => println!("{}", output),
    ///     Err(e) => {
    ///         println!("Error: {}", e);
    ///         for rec in e.recommendations() {
    ///             println!("Try: {}", rec.suggestion);
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `BoxenError::InputValidationError` if:
    /// - Text or configuration parameters fail validation (see `boxen` function for details)
    ///
    /// Returns `BoxenError::InvalidDimensions` if:
    /// - Configuration constraints cannot be satisfied
    ///
    /// Returns `BoxenError::ConfigurationError` if:
    /// - Configuration validation fails
    ///
    /// Returns errors from the underlying `boxen` function for rendering failures.
    pub fn render<S: AsRef<str>>(self, text: S) -> BoxenResult<String> {
        let text_ref = text.as_ref();

        // Comprehensive input validation
        crate::error::validation::validate_all_options(text_ref, &self.options)?;

        // Validate configuration constraints
        self.options.validate_constraints()?;

        crate::boxen(text_ref, Some(self.options))
    }

    /// Validate the current builder configuration without building
    ///
    /// # Errors
    ///
    /// Returns `BoxenError::InvalidDimensions` if:
    /// - Width or height constraints cannot be satisfied
    /// - Dimensions are too small for borders and padding
    ///
    /// Returns `BoxenError::TerminalSizeError` if:
    /// - Terminal size cannot be detected when required
    ///
    /// Returns `BoxenError::ConfigurationError` if:
    /// - Configuration options conflict with each other
    #[must_use = "validation result should be checked"]
    pub fn validate(&self) -> BoxenResult<()> {
        self.options.validate_constraints()
    }

    /// Validate configuration with intelligent recommendations
    #[must_use]
    pub fn validate_with_suggestions(&self, text: &str) -> crate::validation::ValidationResult {
        crate::validation::validate_configuration(text, &self.options)
    }

    /// Calculate minimum dimensions required for the given text
    #[must_use]
    pub fn minimum_dimensions(&self, text: &str) -> crate::validation::MinimumDimensions {
        crate::validation::calculate_minimum_dimensions(text, &self.options)
    }

    /// Suggest optimal dimensions for the given text
    #[must_use]
    pub fn suggest_dimensions(&self, text: &str) -> (usize, usize) {
        crate::validation::suggest_optimal_dimensions(text, &self.options)
    }

    /// Auto-adjust configuration to fix common issues
    #[must_use]
    pub fn auto_adjust(mut self, text: &str) -> Self {
        self.options = crate::validation::auto_adjust_options(text, self.options);
        self
    }

    /// Render with auto-adjustment if the current configuration fails
    ///
    /// # Errors
    ///
    /// Returns errors from the underlying `render` function if auto-adjustment cannot fix the configuration.
    /// This method attempts smart recovery before failing, so errors indicate unrecoverable issues.
    pub fn render_or_adjust<S: AsRef<str>>(mut self, text: S) -> BoxenResult<String> {
        let text_ref = text.as_ref();

        // Try comprehensive validation first
        if let Ok(()) = crate::error::validation::validate_all_options(text_ref, &self.options) {
            // Input validation passed, try configuration validation
            let validation = crate::validation::validate_configuration(text_ref, &self.options);
            if validation.is_valid {
                // Configuration is valid, proceed with normal render
                self.render(text_ref)
            } else {
                // Auto-adjust and try again
                self.options = crate::validation::recovery::smart_recovery(text_ref, self.options);
                self.render(text_ref)
            }
        } else {
            // Input validation failed, try smart recovery
            self.options = crate::validation::recovery::smart_recovery(text_ref, self.options);
            self.render(text_ref)
        }
    }

    /// Get detailed validation information with recommendations
    #[must_use]
    pub fn check_configuration(&self, text: &str) -> String {
        use std::fmt::Write;
        let validation = self.validate_with_suggestions(text);
        let min_dims = self.minimum_dimensions(text);
        let (opt_width, opt_height) = self.suggest_dimensions(text);

        let mut message = format!("Configuration Analysis for text: {text:?}\n");
        let _ = writeln!(
            message,
            "Minimum required: {}×{}",
            min_dims.width, min_dims.height
        );
        let _ = writeln!(message, "Suggested optimal: {opt_width}×{opt_height}");

        if validation.is_valid {
            message.push_str("✓ Configuration is valid\n");
        } else {
            message.push_str("✗ Configuration has errors:\n");
            for error in &validation.errors {
                let _ = writeln!(message, "  - {}", error.detailed_message());
            }
        }

        if !validation.warnings.is_empty() {
            message.push_str("⚠ Warnings:\n");
            for warning in &validation.warnings {
                let _ = writeln!(message, "  - {}: {}", warning.issue, warning.suggestion);
            }
        }

        message
    }

    /// Convenience method to set both padding and margin to the same value
    #[must_use]
    pub fn spacing<T: Into<Spacing>>(mut self, spacing: T) -> Self {
        let spacing_value = spacing.into();
        self.options.padding = spacing_value;
        self.options.margin = spacing_value;
        self
    }

    /// Convenience method to set both border and background color
    #[must_use]
    pub fn colors<C1: Into<Color>, C2: Into<Color>>(mut self, border: C1, background: C2) -> Self {
        self.options.border_color = Some(border.into());
        self.options.background_color = Some(background.into());
        self
    }

    /// Convenience method to set both width and height
    #[must_use]
    pub fn size(mut self, width: usize, height: usize) -> Self {
        self.options.width = Some(Width::Fixed(width));
        self.options.height = Some(Height::Fixed(height));
        self
    }

    /// Convenience method to center align both text and title
    #[must_use]
    pub fn center_all(mut self) -> Self {
        self.options.text_alignment = TextAlignment::Center;
        self.options.title_alignment = TitleAlignment::Center;
        self.options.float = Float::Center;
        self
    }
}

impl Default for BoxenBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl From<String> for Color {
    fn from(value: String) -> Self {
        if value.starts_with('#') {
            Color::Hex(value)
        } else {
            Color::Named(value)
        }
    }
}

impl From<&str> for Color {
    /// Creates a color from a string without validation.
    ///
    /// This implementation accepts any string and does not validate whether
    /// the color name is valid or the hex format is correct. For validated
    /// color creation, use `Color::validated(s)` instead.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use boxen::Color;
    ///
    /// // Accepts any string without validation
    /// let color: Color = "red".into();
    /// let invalid: Color = "not_a_color".into(); // No error, but may fail at render time
    /// ```
    fn from(value: &str) -> Self {
        Color::from(value.to_string())
    }
}

impl Color {
    /// Try to create a color from a string, validating named colors and hex format.
    ///
    /// This method validates the color specification and returns an error
    /// if the color name is not recognized or the hex format is invalid.
    ///
    /// # Supported Named Colors
    ///
    /// Standard colors: `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`
    ///
    /// Bright colors: `bright_black`, `bright_red`, `bright_green`, `bright_yellow`,
    /// `bright_blue`, `bright_magenta`, `bright_cyan`, `bright_white`
    ///
    /// # Hex Format
    ///
    /// Hex colors must start with `#` and be exactly 6 characters (e.g., `#FF0000`).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use boxen::Color;
    ///
    /// // Valid named color
    /// let red = Color::validated("red").unwrap();
    ///
    /// // Valid hex color
    /// let orange = Color::validated("#FF8000").unwrap();
    ///
    /// // Invalid color name
    /// assert!(Color::validated("invalid_color").is_err());
    ///
    /// // Invalid hex format
    /// assert!(Color::validated("#GGG").is_err());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `BoxenError::InvalidColor` if:
    /// - The color name is not recognized
    /// - The hex format is invalid (wrong length or invalid characters)
    /// - The string contains whitespace or special characters
    pub fn validated(value: &str) -> Result<Self, crate::error::BoxenError> {
        use crate::error::{BoxenError, ErrorRecommendation};

        // Reject empty strings
        if value.is_empty() {
            return Err(BoxenError::invalid_color(
                "Color string cannot be empty".to_string(),
                value.to_string(),
                vec![ErrorRecommendation::suggestion_only(
                    "Empty color string".to_string(),
                    "Use a valid color name like 'red', 'blue', or a hex code like '#FF0000'"
                        .to_string(),
                )],
            ));
        }

        // Reject strings with whitespace
        if value.contains(char::is_whitespace) {
            return Err(BoxenError::invalid_color(
                "Color string cannot contain whitespace".to_string(),
                value.to_string(),
                vec![ErrorRecommendation::suggestion_only(
                    "Whitespace in color string".to_string(),
                    "Remove any leading, trailing, or embedded whitespace".to_string(),
                )],
            ));
        }

        if value.starts_with('#') {
            // Validate hex format
            let hex = value.trim_start_matches('#');

            if hex.len() != 6 {
                return Err(BoxenError::invalid_color(
                    format!("Invalid hex color format: {value}"),
                    value.to_string(),
                    vec![
                        ErrorRecommendation::suggestion_only(
                            "Invalid hex length".to_string(),
                            "Hex colors must be exactly 6 characters (e.g., #FF0000)".to_string(),
                        ),
                        ErrorRecommendation::with_auto_fix(
                            "Use 6-digit format".to_string(),
                            "Try using the full 6-digit hex format".to_string(),
                            "\"#FF0000\"".to_string(),
                        ),
                    ],
                ));
            }

            if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
                return Err(BoxenError::invalid_color(
                    format!("Invalid hex color format: {value}"),
                    value.to_string(),
                    vec![
                        ErrorRecommendation::suggestion_only(
                            "Invalid hex characters".to_string(),
                            "Hex colors can only contain digits 0-9 and letters A-F".to_string(),
                        ),
                        ErrorRecommendation::with_auto_fix(
                            "Use valid hex color".to_string(),
                            "Try using a valid hex color".to_string(),
                            "\"#FF0000\"".to_string(),
                        ),
                    ],
                ));
            }

            Ok(Color::Hex(value.to_string()))
        } else {
            // Validate named color
            let normalized = value.to_lowercase();
            match normalized.as_str() {
                // Standard terminal colors
                "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "purple"
                | "cyan" | "white" |
                // Bright colors with underscore or no separator
                "bright_black" | "brightblack" | "gray" | "grey" |
                "bright_red" | "brightred" |
                "bright_green" | "brightgreen" |
                "bright_yellow" | "brightyellow" |
                "bright_blue" | "brightblue" |
                "bright_magenta" | "brightmagenta" | "bright_purple" | "brightpurple" |
                "bright_cyan" | "brightcyan" |
                "bright_white" | "brightwhite" => Ok(Color::Named(value.to_string())),
                _ => Err(BoxenError::invalid_color(
                    format!("Unknown color name: {value}"),
                    value.to_string(),
                    vec![
                        ErrorRecommendation::suggestion_only(
                            "Unknown color name".to_string(),
                            "Use a standard color name like 'red', 'blue', 'green', etc."
                                .to_string(),
                        ),
                        ErrorRecommendation::with_auto_fix(
                            "Use standard color".to_string(),
                            "Try using 'red' as a common color".to_string(),
                            "\"red\"".to_string(),
                        ),
                        ErrorRecommendation::suggestion_only(
                            "Alternative: Use hex color".to_string(),
                            "You can also use hex colors like '#FF0000' for red".to_string(),
                        ),
                    ],
                )),
            }
        }
    }
}

// Note: We cannot implement TryFrom<&str> because Rust provides a blanket implementation
// of TryFrom<U> for any T where U: Into<T>. Since we have From<&str>, we automatically
// get TryFrom<&str> that never fails. Use Color::validated() for validation instead.

impl From<(u8, u8, u8)> for Color {
    fn from((r, g, b): (u8, u8, u8)) -> Self {
        Color::Rgb(r, g, b)
    }
}

// Additional convenient From implementations
impl From<(usize, usize)> for Spacing {
    /// Creates spacing from (horizontal, vertical) tuple
    /// Horizontal value is applied to left and right, vertical to top and bottom
    fn from((horizontal, vertical): (usize, usize)) -> Self {
        Self {
            top: vertical,
            right: horizontal,
            bottom: vertical,
            left: horizontal,
        }
    }
}

impl From<[usize; 4]> for Spacing {
    /// Creates spacing from [top, right, bottom, left] array
    fn from([top, right, bottom, left]: [usize; 4]) -> Self {
        Self {
            top,
            right,
            bottom,
            left,
        }
    }
}

impl From<[usize; 2]> for Spacing {
    /// Creates spacing from [horizontal, vertical] array
    fn from([horizontal, vertical]: [usize; 2]) -> Self {
        Self {
            top: vertical,
            right: horizontal,
            bottom: vertical,
            left: horizontal,
        }
    }
}

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

    #[test]
    fn test_spacing_horizontal_vertical() {
        let spacing = Spacing {
            top: 1,
            right: 2,
            bottom: 3,
            left: 4,
        };

        assert_eq!(spacing.horizontal(), 6); // left + right = 4 + 2
        assert_eq!(spacing.vertical(), 4); // top + bottom = 1 + 3
    }

    #[test]
    fn test_spacing_is_empty() {
        let empty_spacing = Spacing::default();
        assert!(empty_spacing.is_empty());

        let non_empty_spacing = Spacing {
            top: 1,
            right: 0,
            bottom: 0,
            left: 0,
        };
        assert!(!non_empty_spacing.is_empty());
    }

    #[test]
    fn test_spacing_from_usize() {
        let spacing = Spacing::from(2);
        assert_eq!(spacing.top, 2);
        assert_eq!(spacing.right, 6); // 3x horizontal
        assert_eq!(spacing.bottom, 2);
        assert_eq!(spacing.left, 6); // 3x horizontal
        assert_eq!(spacing.horizontal(), 12);
        assert_eq!(spacing.vertical(), 4);
    }

    #[test]
    fn test_spacing_from_tuple() {
        let spacing = Spacing::from((1, 2, 3, 4));
        assert_eq!(spacing.top, 1);
        assert_eq!(spacing.right, 2);
        assert_eq!(spacing.bottom, 3);
        assert_eq!(spacing.left, 4);
        assert_eq!(spacing.horizontal(), 6);
        assert_eq!(spacing.vertical(), 4);
    }

    #[test]
    fn test_calculate_constraints_default() {
        let options = BoxenOptions::default();
        let constraints = options.calculate_constraints().unwrap();

        assert!(constraints.terminal_width >= 80); // Should have fallback
        assert_eq!(constraints.border_width, 2); // Single border style
        assert!(constraints.max_width <= constraints.terminal_width);
    }

    #[test]
    fn test_calculate_constraints_with_specified_width() {
        let options = BoxenOptions {
            width: Some(Width::Fixed(50)),
            ..Default::default()
        };
        let constraints = options.calculate_constraints().unwrap();

        assert_eq!(constraints.max_width, 50);
    }

    #[test]
    fn test_calculate_constraints_invalid_width() {
        let options = BoxenOptions {
            width: Some(Width::Fixed(1)), // Too small for borders + padding
            padding: Spacing::from(2),    // 6 horizontal padding + 2 border = 8 total
            ..Default::default()
        };

        let result = options.calculate_constraints();
        assert!(result.is_err());
        matches!(result.unwrap_err(), BoxenError::InvalidDimensions { .. });
    }

    #[test]
    fn test_calculate_layout_dimensions_basic() {
        let options = BoxenOptions::default();
        let layout = options.calculate_layout_dimensions(10, 3).unwrap();

        assert_eq!(layout.content_width, 10);
        assert_eq!(layout.content_height, 3);
        assert_eq!(layout.inner_width, 10); // no padding
        assert_eq!(layout.inner_height, 3); // no padding
        assert_eq!(layout.total_width, 12); // 10 + 2 borders
        assert_eq!(layout.total_height, 5); // 3 + 2 borders
    }

    #[test]
    fn test_calculate_layout_dimensions_with_padding() {
        let options = BoxenOptions {
            padding: Spacing::from(1), // 3 horizontal, 1 vertical each side
            ..Default::default()
        };
        let layout = options.calculate_layout_dimensions(10, 3).unwrap();

        assert_eq!(layout.content_width, 10);
        assert_eq!(layout.content_height, 3);
        assert_eq!(layout.inner_width, 16); // 10 + 6 horizontal padding
        assert_eq!(layout.inner_height, 5); // 3 + 2 vertical padding
        assert_eq!(layout.total_width, 18); // 16 + 2 borders
        assert_eq!(layout.total_height, 7); // 5 + 2 borders
    }

    #[test]
    fn test_calculate_layout_dimensions_with_margins() {
        let options = BoxenOptions {
            margin: Spacing::from(1), // 3 horizontal, 1 vertical each side
            ..Default::default()
        };
        let layout = options.calculate_layout_dimensions(10, 3).unwrap();

        assert_eq!(layout.total_width, 18); // 10 + 2 borders + 6 margins
        assert_eq!(layout.total_height, 7); // 3 + 2 borders + 2 margins
    }

    #[test]
    fn test_calculate_layout_dimensions_no_border() {
        let options = BoxenOptions {
            border_style: BorderStyle::None,
            ..Default::default()
        };
        let layout = options.calculate_layout_dimensions(10, 3).unwrap();

        assert_eq!(layout.total_width, 10); // no borders
        assert_eq!(layout.total_height, 3); // no borders
    }

    #[test]
    fn test_calculate_max_content_width() {
        let options = BoxenOptions {
            width: Some(Width::Fixed(50)),
            padding: Spacing::from(1), // 6 horizontal padding
            ..Default::default()
        };

        let max_width = options.calculate_max_content_width().unwrap();
        assert_eq!(max_width, 42); // 50 - 2 borders - 6 padding
    }

    #[test]
    fn test_calculate_max_content_height() {
        let options = BoxenOptions {
            height: Some(Height::Fixed(20)),
            padding: Spacing::from(1), // 2 vertical padding
            ..Default::default()
        };

        let max_height = options.calculate_max_content_height().unwrap();
        assert_eq!(max_height, Some(16)); // 20 - 2 borders - 2 padding
    }

    #[test]
    fn test_calculate_max_content_height_no_constraint() {
        let options = BoxenOptions::default(); // No height specified

        let max_height = options.calculate_max_content_height().unwrap();
        // Should be None or Some value depending on terminal height detection
        // We can't assert a specific value since it depends on the actual terminal
        assert!(max_height.is_none() || max_height.unwrap() > 0);
    }

    #[test]
    fn test_validate_constraints_valid() {
        let options = BoxenOptions {
            width: Some(Width::Fixed(50)),
            height: Some(Height::Fixed(20)),
            padding: Spacing::from(1),
            ..Default::default()
        };

        assert!(options.validate_constraints().is_ok());
    }

    #[test]
    fn test_validate_constraints_invalid() {
        let options = BoxenOptions {
            width: Some(Width::Fixed(5)), // Too small
            padding: Spacing::from(2),    // Large padding
            ..Default::default()
        };

        assert!(options.validate_constraints().is_err());
    }

    #[test]
    fn test_dimension_constraints_with_fullscreen() {
        let options = BoxenOptions {
            fullscreen: Some(FullscreenMode::Auto),
            ..Default::default()
        };

        let constraints = options.calculate_constraints().unwrap();
        // Should use terminal dimensions
        assert!(constraints.max_width > 0);
        assert_eq!(constraints.max_width, constraints.terminal_width);
    }

    #[test]
    fn test_layout_dimensions_edge_cases() {
        // Test with zero content
        let options = BoxenOptions::default();
        let layout = options.calculate_layout_dimensions(0, 0).unwrap();

        assert_eq!(layout.content_width, 0);
        assert_eq!(layout.content_height, 0);
        assert_eq!(layout.total_width, 2); // Just borders
        assert_eq!(layout.total_height, 2); // Just borders
    }

    #[test]
    fn test_spacing_calculations_comprehensive() {
        let spacing = Spacing {
            top: 2,
            right: 4,
            bottom: 1,
            left: 3,
        };

        assert_eq!(spacing.horizontal(), 7); // 4 + 3
        assert_eq!(spacing.vertical(), 3); // 2 + 1
        assert!(!spacing.is_empty());

        let zero_spacing = Spacing::default();
        assert_eq!(zero_spacing.horizontal(), 0);
        assert_eq!(zero_spacing.vertical(), 0);
        assert!(zero_spacing.is_empty());
    }

    #[test]
    fn test_complex_layout_calculation() {
        let options = BoxenOptions {
            border_style: BorderStyle::Double,
            padding: Spacing {
                top: 1,
                right: 2,
                bottom: 1,
                left: 2,
            },
            margin: Spacing {
                top: 0,
                right: 1,
                bottom: 0,
                left: 1,
            },
            width: Some(Width::Fixed(60)),
            height: Some(Height::Fixed(50)), // Use a larger height that should work on most terminals
            ..Default::default()
        };

        let layout = options.calculate_layout_dimensions(40, 5).unwrap(); // Use smaller content height

        // Content: 40x5
        // Inner (content + padding): 44x7 (40+4, 5+2)
        // Total (inner + borders + margins): 48x9 (44+2+2, 7+2+0)
        assert_eq!(layout.content_width, 40);
        assert_eq!(layout.content_height, 5);
        assert_eq!(layout.inner_width, 44);
        assert_eq!(layout.inner_height, 7);
        assert_eq!(layout.total_width, 48);
        assert_eq!(layout.total_height, 9);
    }

    #[test]
    fn test_overflow_handling() {
        // Test when content would exceed terminal width
        let terminal_width = get_terminal_width();
        let options = BoxenOptions {
            padding: Spacing::from(1),
            ..Default::default()
        };

        // Try to create content that would exceed terminal
        let excessive_width = terminal_width + 100;
        let result = options.calculate_layout_dimensions(excessive_width, 5);

        // Should fail with configuration error
        assert!(result.is_err());
        matches!(result.unwrap_err(), BoxenError::ConfigurationError { .. });
    }

    #[test]
    fn test_fullscreen_mode_auto() {
        let options = BoxenOptions {
            fullscreen: Some(FullscreenMode::Auto),
            ..Default::default()
        };

        let constraints = options.calculate_constraints().unwrap();

        // Should use terminal dimensions
        assert_eq!(constraints.max_width, constraints.terminal_width);
        assert_eq!(constraints.max_height, constraints.terminal_height);
    }

    #[test]
    fn test_fullscreen_mode_auto_with_margins() {
        let margin = Spacing::from(2);
        println!(
            "Margin: top={}, right={}, bottom={}, left={}",
            margin.top, margin.right, margin.bottom, margin.left
        );
        println!("Horizontal margin: {}", margin.horizontal());

        let expected_horizontal = margin.horizontal();
        let expected_vertical = margin.vertical();

        let options = BoxenOptions {
            fullscreen: Some(FullscreenMode::Auto),
            margin,
            ..Default::default()
        };

        let constraints = options.calculate_constraints().unwrap();

        // Should account for margins - Spacing::from(2) creates 12 horizontal (left=6, right=6), 4 vertical
        assert_eq!(
            constraints.max_width,
            constraints.terminal_width - expected_horizontal
        );
        if let Some(terminal_height) = constraints.terminal_height {
            assert_eq!(
                constraints.max_height,
                Some(terminal_height - expected_vertical)
            );
        }
    }

    #[test]
    fn test_fullscreen_mode_custom() {
        let custom_func = |width: usize, height: usize| -> (usize, usize) {
            // Use 3/4 of dimensions to ensure we have enough space for borders and padding
            (width * 3 / 4, height * 3 / 4)
        };

        let options = BoxenOptions {
            fullscreen: Some(FullscreenMode::Custom(custom_func)),
            ..Default::default()
        };

        let constraints = options.calculate_constraints().unwrap();

        // Should use custom dimensions
        assert_eq!(constraints.max_width, constraints.terminal_width * 3 / 4);
        if let Some(terminal_height) = constraints.terminal_height {
            assert_eq!(constraints.max_height, Some(terminal_height * 3 / 4));
        }
    }

    #[test]
    fn test_fullscreen_mode_with_padding() {
        let options = BoxenOptions {
            fullscreen: Some(FullscreenMode::Auto),
            padding: Spacing::from(1), // 6 horizontal, 2 vertical
            ..Default::default()
        };

        let max_content_width = options.calculate_max_content_width().unwrap();
        let max_content_height = options.calculate_max_content_height().unwrap();

        // Should account for borders and padding
        let constraints = options.calculate_constraints().unwrap();
        let expected_width = constraints.max_width - 2 - 6; // borders + padding horizontal
        assert_eq!(max_content_width, expected_width);

        if let Some(height) = max_content_height {
            let expected_height = constraints.max_height.unwrap() - 2 - 2; // borders + padding vertical
            assert_eq!(height, expected_height);
        }
    }

    #[test]
    fn test_fullscreen_mode_insufficient_space() {
        // Create a scenario where fullscreen mode doesn't have enough space
        let options = BoxenOptions {
            fullscreen: Some(FullscreenMode::Custom(|_, _| (5, 3))), // Very small dimensions
            padding: Spacing::from(3), // Large padding: 18 horizontal (9*2), 6 vertical (3*2)
            ..Default::default()
        };

        let result = options.calculate_constraints();

        // Should fail due to insufficient space (5 total width < 18 padding + 2 borders = 20)
        assert!(result.is_err());
        matches!(result.unwrap_err(), BoxenError::InvalidDimensions { .. });
    }

    #[test]
    fn test_fullscreen_mode_overrides_width_height() {
        let options = BoxenOptions {
            fullscreen: Some(FullscreenMode::Auto),
            width: Some(Width::Fixed(50)), // Should be ignored in fullscreen mode
            height: Some(Height::Fixed(20)), // Should be ignored in fullscreen mode
            ..Default::default()
        };

        let constraints = options.calculate_constraints().unwrap();

        // Should use terminal dimensions, not specified width/height
        assert_eq!(constraints.max_width, constraints.terminal_width);
        assert_eq!(constraints.max_height, constraints.terminal_height);
    }

    #[test]
    fn test_fullscreen_layout_dimensions() {
        let options = BoxenOptions {
            fullscreen: Some(FullscreenMode::Auto),
            padding: Spacing::from(1), // 6 horizontal, 2 vertical
            margin: Spacing::from(1),  // 6 horizontal, 2 vertical
            ..Default::default()
        };

        // Use small content that should be expanded to fill fullscreen
        let layout = options.calculate_layout_dimensions(10, 3).unwrap();

        // Content should be expanded to fill available space
        let max_content_width = options.calculate_max_content_width().unwrap();
        let max_content_height = options.calculate_max_content_height().unwrap();

        assert_eq!(layout.content_width, max_content_width);
        if let Some(expected_height) = max_content_height {
            assert_eq!(layout.content_height, expected_height);
        }
    }

    // Builder pattern tests
    #[test]
    fn test_builder_new() {
        let builder = BoxenBuilder::new();
        let options = builder.build();

        // Should have default values
        assert!(matches!(options.border_style, BorderStyle::Single));
        assert!(options.padding.is_empty());
        assert!(options.margin.is_empty());
        assert!(matches!(options.text_alignment, TextAlignment::Left));
        assert!(options.title.is_none());
        assert!(matches!(options.title_alignment, TitleAlignment::Left));
        assert!(matches!(options.float, Float::Left));
        assert!(options.width.is_none());
        assert!(options.height.is_none());
        assert!(options.border_color.is_none());
        assert!(options.background_color.is_none());
        assert!(!options.dim_border);
        assert!(options.fullscreen.is_none());
    }

    #[test]
    fn test_builder_default() {
        let builder = BoxenBuilder::default();
        let options = builder.build();

        // Should be same as new()
        assert!(matches!(options.border_style, BorderStyle::Single));
        assert!(options.padding.is_empty());
    }

    #[test]
    fn test_builder_method_chaining() {
        let result = BoxenBuilder::new()
            .border_style(BorderStyle::Double)
            .padding(2)
            .margin((1, 2, 3, 4))
            .text_alignment(TextAlignment::Center)
            .title("Test Title")
            .title_alignment(TitleAlignment::Right)
            .float(Float::Center)
            .width(50)
            .height(20)
            .border_color("red")
            .background_color("#ff0000")
            .dim_border(true)
            .fullscreen(FullscreenMode::Auto)
            .render("Hello World");

        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_border_style() {
        let options = BoxenBuilder::new().border_style(BorderStyle::Round).build();

        assert!(matches!(options.border_style, BorderStyle::Round));
    }

    #[test]
    fn test_builder_padding_from_usize() {
        let options = BoxenBuilder::new().padding(3).build();

        assert_eq!(options.padding.top, 3);
        assert_eq!(options.padding.right, 9); // 3x horizontal
        assert_eq!(options.padding.bottom, 3);
        assert_eq!(options.padding.left, 9); // 3x horizontal
    }

    #[test]
    fn test_builder_padding_from_tuple() {
        let options = BoxenBuilder::new().padding((1, 2, 3, 4)).build();

        assert_eq!(options.padding.top, 1);
        assert_eq!(options.padding.right, 2);
        assert_eq!(options.padding.bottom, 3);
        assert_eq!(options.padding.left, 4);
    }

    #[test]
    fn test_builder_margin_from_usize() {
        let options = BoxenBuilder::new().margin(2).build();

        assert_eq!(options.margin.top, 2);
        assert_eq!(options.margin.right, 6); // 3x horizontal
        assert_eq!(options.margin.bottom, 2);
        assert_eq!(options.margin.left, 6); // 3x horizontal
    }

    #[test]
    fn test_builder_margin_from_tuple() {
        let options = BoxenBuilder::new().margin((5, 6, 7, 8)).build();

        assert_eq!(options.margin.top, 5);
        assert_eq!(options.margin.right, 6);
        assert_eq!(options.margin.bottom, 7);
        assert_eq!(options.margin.left, 8);
    }

    #[test]
    fn test_builder_text_alignment() {
        let options = BoxenBuilder::new()
            .text_alignment(TextAlignment::Right)
            .build();

        assert!(matches!(options.text_alignment, TextAlignment::Right));
    }

    #[test]
    fn test_builder_title() {
        let options = BoxenBuilder::new().title("My Title").build();

        assert_eq!(options.title, Some("My Title".to_string()));
    }

    #[test]
    fn test_builder_title_string() {
        let title = String::from("Dynamic Title");
        let options = BoxenBuilder::new().title(title.clone()).build();

        assert_eq!(options.title, Some(title));
    }

    #[test]
    fn test_builder_title_alignment() {
        let options = BoxenBuilder::new()
            .title_alignment(TitleAlignment::Center)
            .build();

        assert!(matches!(options.title_alignment, TitleAlignment::Center));
    }

    #[test]
    fn test_builder_float() {
        let options = BoxenBuilder::new().float(Float::Right).build();

        assert!(matches!(options.float, Float::Right));
    }

    #[test]
    fn test_builder_dimensions() {
        let options = BoxenBuilder::new().width(80).height(25).build();

        assert_eq!(options.width, Some(Width::Fixed(80)));
        assert_eq!(options.height, Some(Height::Fixed(25)));
    }

    #[test]
    fn test_builder_border_color_string() {
        let options = BoxenBuilder::new().border_color("blue").build();

        if let Some(Color::Named(name)) = options.border_color {
            assert_eq!(name, "blue");
        } else {
            panic!("Expected named color");
        }
    }

    #[test]
    fn test_builder_border_color_hex() {
        let options = BoxenBuilder::new().border_color("#00ff00").build();

        if let Some(Color::Hex(hex)) = options.border_color {
            assert_eq!(hex, "#00ff00");
        } else {
            panic!("Expected hex color");
        }
    }

    #[test]
    fn test_builder_border_color_rgb() {
        let options = BoxenBuilder::new().border_color((255, 128, 0)).build();

        if let Some(Color::Rgb(r, g, b)) = options.border_color {
            assert_eq!((r, g, b), (255, 128, 0));
        } else {
            panic!("Expected RGB color");
        }
    }

    #[test]
    fn test_builder_background_color() {
        let options = BoxenBuilder::new().background_color("yellow").build();

        if let Some(Color::Named(name)) = options.background_color {
            assert_eq!(name, "yellow");
        } else {
            panic!("Expected named color");
        }
    }

    #[test]
    fn test_builder_dim_border() {
        let options = BoxenBuilder::new().dim_border(true).build();

        assert!(options.dim_border);
    }

    #[test]
    fn test_builder_fullscreen_auto() {
        let options = BoxenBuilder::new().fullscreen(FullscreenMode::Auto).build();

        assert!(matches!(options.fullscreen, Some(FullscreenMode::Auto)));
    }

    #[test]
    fn test_builder_fullscreen_custom() {
        let custom_func = |w: usize, h: usize| (w / 2, h / 2);
        let options = BoxenBuilder::new()
            .fullscreen(FullscreenMode::Custom(custom_func))
            .build();

        assert!(matches!(
            options.fullscreen,
            Some(FullscreenMode::Custom(_))
        ));
    }

    #[test]
    fn test_builder_render_success() {
        let result = BoxenBuilder::new()
            .border_style(BorderStyle::Single)
            .padding(1)
            .render("Test content");

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Test content"));
    }

    #[test]
    fn test_builder_render_with_validation_error() {
        let result = BoxenBuilder::new()
            .width(5) // Too small
            .padding(10) // Too large padding
            .render("Test");

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            BoxenError::InvalidDimensions { .. }
        ));
    }

    #[test]
    fn test_builder_validate_success() {
        let builder = BoxenBuilder::new().width(50).padding(2);

        assert!(builder.validate().is_ok());
    }

    #[test]
    fn test_builder_validate_error() {
        let builder = BoxenBuilder::new()
            .width(3) // Too small
            .padding(5); // Too large padding

        assert!(builder.validate().is_err());
    }

    #[test]
    fn test_builder_complex_configuration() {
        let result = BoxenBuilder::new()
            .border_style(BorderStyle::Double)
            .padding((2, 4, 2, 4))
            .margin(1)
            .text_alignment(TextAlignment::Center)
            .title("Complex Box")
            .title_alignment(TitleAlignment::Center)
            .float(Float::Center)
            .width(60)
            .border_color("#0066cc")
            .background_color("white")
            .dim_border(false)
            .render("This is a complex box configuration test");

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("This is a complex box configuration test"));
    }

    #[test]
    fn test_builder_empty_text() {
        let result = BoxenBuilder::new().render("");

        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_multiline_text() {
        let text = "Line 1\nLine 2\nLine 3";
        let result = BoxenBuilder::new().padding(1).render(text);

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Line 1"));
        assert!(output.contains("Line 2"));
        assert!(output.contains("Line 3"));
    }

    #[test]
    fn test_builder_method_chaining_order_independence() {
        // Test that method order doesn't matter
        let options1 = BoxenBuilder::new()
            .width(50)
            .padding(2)
            .border_style(BorderStyle::Round)
            .build();

        let options2 = BoxenBuilder::new()
            .border_style(BorderStyle::Round)
            .padding(2)
            .width(50)
            .build();

        // Both should produce equivalent options
        assert!(matches!(options1.border_style, BorderStyle::Round));
        assert!(matches!(options2.border_style, BorderStyle::Round));
        assert_eq!(options1.width, Some(Width::Fixed(50)));
        assert_eq!(options2.width, Some(Width::Fixed(50)));
        assert_eq!(options1.padding.top, 2);
        assert_eq!(options2.padding.top, 2);
    }

    #[test]
    fn test_builder_overwrite_values() {
        // Test that later calls overwrite earlier ones
        let options = BoxenBuilder::new()
            .width(30)
            .width(50) // Should overwrite the 30
            .padding(1)
            .padding(3) // Should overwrite the 1
            .build();

        assert_eq!(options.width, Some(Width::Fixed(50)));
        assert_eq!(options.padding.top, 3);
        assert_eq!(options.padding.right, 9); // 3x horizontal
    }

    // Test additional From implementations
    #[test]
    fn test_spacing_from_horizontal_vertical_tuple() {
        let spacing = Spacing::from((4, 2));
        assert_eq!(spacing.top, 2);
        assert_eq!(spacing.right, 4);
        assert_eq!(spacing.bottom, 2);
        assert_eq!(spacing.left, 4);
    }

    #[test]
    fn test_spacing_from_array_4() {
        let spacing = Spacing::from([1, 2, 3, 4]);
        assert_eq!(spacing.top, 1);
        assert_eq!(spacing.right, 2);
        assert_eq!(spacing.bottom, 3);
        assert_eq!(spacing.left, 4);
    }

    #[test]
    fn test_spacing_from_array_2() {
        let spacing = Spacing::from([6, 3]);
        assert_eq!(spacing.top, 3);
        assert_eq!(spacing.right, 6);
        assert_eq!(spacing.bottom, 3);
        assert_eq!(spacing.left, 6);
    }

    // Test convenience builder methods
    #[test]
    fn test_builder_spacing_convenience() {
        let options = BoxenBuilder::new().spacing(2).build();

        // Both padding and margin should be set
        assert_eq!(options.padding.top, 2);
        assert_eq!(options.padding.right, 6); // 3x horizontal
        assert_eq!(options.margin.top, 2);
        assert_eq!(options.margin.right, 6); // 3x horizontal
    }

    #[test]
    fn test_builder_colors_convenience() {
        let options = BoxenBuilder::new().colors("red", "#00ff00").build();

        if let Some(Color::Named(border_name)) = options.border_color {
            assert_eq!(border_name, "red");
        } else {
            panic!("Expected named border color");
        }

        if let Some(Color::Hex(bg_hex)) = options.background_color {
            assert_eq!(bg_hex, "#00ff00");
        } else {
            panic!("Expected hex background color");
        }
    }

    #[test]
    fn test_builder_size_convenience() {
        let options = BoxenBuilder::new().size(80, 25).build();

        assert_eq!(options.width, Some(Width::Fixed(80)));
        assert_eq!(options.height, Some(Height::Fixed(25)));
    }

    #[test]
    fn test_builder_center_all_convenience() {
        let options = BoxenBuilder::new().center_all().build();

        assert!(matches!(options.text_alignment, TextAlignment::Center));
        assert!(matches!(options.title_alignment, TitleAlignment::Center));
        assert!(matches!(options.float, Float::Center));
    }

    #[test]
    fn test_builder_with_array_spacing() {
        let options = BoxenBuilder::new()
            .padding([1, 2, 3, 4])
            .margin([5, 6])
            .build();

        assert_eq!(options.padding.top, 1);
        assert_eq!(options.padding.right, 2);
        assert_eq!(options.padding.bottom, 3);
        assert_eq!(options.padding.left, 4);

        assert_eq!(options.margin.top, 6);
        assert_eq!(options.margin.right, 5);
        assert_eq!(options.margin.bottom, 6);
        assert_eq!(options.margin.left, 5);
    }

    #[test]
    fn test_builder_with_tuple_spacing() {
        let options = BoxenBuilder::new()
            .padding((8, 4)) // horizontal, vertical
            .build();

        assert_eq!(options.padding.top, 4);
        assert_eq!(options.padding.right, 8);
        assert_eq!(options.padding.bottom, 4);
        assert_eq!(options.padding.left, 8);
    }

    #[test]
    fn test_builder_convenience_methods_chaining() {
        let result = BoxenBuilder::new()
            .spacing(1)
            .colors("blue", "white")
            .size(60, 10) // Use smaller height to avoid terminal size issues
            .center_all()
            .title("Centered Box")
            .render("This box uses all convenience methods");

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("This box uses all convenience methods"));
    }
}

/// Dimension constraints for box calculation
#[derive(Debug, Clone)]
pub struct DimensionConstraints {
    /// Maximum allowed width for the box
    pub max_width: usize,
    /// Maximum allowed height for the box (None if unlimited)
    pub max_height: Option<usize>,
    /// Current terminal width in columns
    pub terminal_width: usize,
    /// Current terminal height in rows (None if unknown)
    pub terminal_height: Option<usize>,
    /// Width consumed by borders (0 for no border, 2 for visible borders)
    pub border_width: usize,
}

/// Final calculated layout dimensions
#[derive(Debug, Clone)]
pub struct LayoutDimensions {
    /// Width of the actual text content area
    pub content_width: usize,
    /// Height of the actual text content area
    pub content_height: usize,
    /// Total width including borders, padding, and margins
    pub total_width: usize,
    /// Total height including borders, padding, and margins
    pub total_height: usize,
    /// Width of content area plus padding (excludes borders and margins)
    pub inner_width: usize,
    /// Height of content area plus padding (excludes borders and margins)
    pub inner_height: usize,
}

impl Spacing {
    /// Calculate total horizontal spacing (left + right).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::Spacing;
    ///
    /// let spacing = Spacing::from((1, 2, 3, 4));  // top, right, bottom, left
    /// assert_eq!(spacing.horizontal(), 6);  // right + left = 2 + 4
    /// ```
    #[must_use]
    pub fn horizontal(&self) -> usize {
        self.left + self.right
    }

    /// Calculate total vertical spacing (top + bottom).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::Spacing;
    ///
    /// let spacing = Spacing::from((1, 2, 3, 4));  // top, right, bottom, left
    /// assert_eq!(spacing.vertical(), 4);  // top + bottom = 1 + 3
    /// ```
    #[must_use]
    pub fn vertical(&self) -> usize {
        self.top + self.bottom
    }

    /// Check if all spacing values are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::Spacing;
    ///
    /// let empty = Spacing::default();
    /// assert!(empty.is_empty());
    ///
    /// let non_empty = Spacing::from(1);
    /// assert!(!non_empty.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.top == 0 && self.right == 0 && self.bottom == 0 && self.left == 0
    }

    /// Create uniform spacing with the same value for all sides.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::Spacing;
    ///
    /// let uniform = Spacing::uniform(2);
    /// assert_eq!(uniform.top, 2);
    /// assert_eq!(uniform.right, 2);
    /// assert_eq!(uniform.bottom, 2);
    /// assert_eq!(uniform.left, 2);
    /// ```
    #[must_use]
    pub fn uniform(value: usize) -> Self {
        Self {
            top: value,
            right: value,
            bottom: value,
            left: value,
        }
    }

    /// Create spacing with separate horizontal and vertical values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::Spacing;
    ///
    /// let spacing = Spacing::symmetric(3, 1);  // horizontal: 3, vertical: 1
    /// assert_eq!(spacing.top, 1);
    /// assert_eq!(spacing.right, 3);
    /// assert_eq!(spacing.bottom, 1);
    /// assert_eq!(spacing.left, 3);
    /// ```
    #[must_use]
    pub fn symmetric(horizontal: usize, vertical: usize) -> Self {
        Self {
            top: vertical,
            right: horizontal,
            bottom: vertical,
            left: horizontal,
        }
    }

    /// Create terminal-balanced spacing from a single value.
    ///
    /// Due to terminal character aspect ratios (characters are ~2x taller than wide),
    /// horizontal spacing is automatically scaled 3x to appear visually balanced:
    /// - Vertical (top/bottom): `value`
    /// - Horizontal (left/right): `value * 3`
    ///
    /// This matches the TypeScript boxen behavior for visual consistency.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ::boxen::Spacing;
    ///
    /// let spacing = Spacing::terminal_balanced(2);
    /// assert_eq!(spacing.top, 2);
    /// assert_eq!(spacing.right, 6);  // 3x horizontal
    /// assert_eq!(spacing.bottom, 2);
    /// assert_eq!(spacing.left, 6);   // 3x horizontal
    /// ```
    #[must_use]
    pub fn terminal_balanced(value: usize) -> Self {
        Self {
            top: value,
            right: value * 3,
            bottom: value,
            left: value * 3,
        }
    }
}

impl BoxenOptions {
    /// Helper to create `InvalidDimensions` error with basic recommendations
    fn invalid_dimensions_error(
        message: String,
        width: Option<usize>,
        height: Option<usize>,
    ) -> crate::error::BoxenError {
        use crate::error::{BoxenError, ErrorRecommendation};

        let mut recommendations = vec![];

        if let Some(w) = width {
            recommendations.push(ErrorRecommendation::suggestion_only(
                "Width too small".to_string(),
                format!("Consider increasing width from {w}"),
            ));
        }

        if let Some(h) = height {
            recommendations.push(ErrorRecommendation::suggestion_only(
                "Height too small".to_string(),
                format!("Consider increasing height from {h}"),
            ));
        }

        BoxenError::invalid_dimensions(message, width, height, recommendations)
    }

    /// Helper to create `ConfigurationError` with basic recommendations
    fn configuration_error(message: String) -> crate::error::BoxenError {
        use crate::error::{BoxenError, ErrorRecommendation};

        let recommendations = vec![ErrorRecommendation::suggestion_only(
            "Configuration conflict".to_string(),
            "Check your width, height, padding, and margin settings".to_string(),
        )];

        BoxenError::configuration_error(message, recommendations)
    }
    /// Calculate dimension constraints based on terminal size and options
    ///
    /// # Errors
    ///
    /// Returns `BoxenError::InvalidDimensions` if:
    /// - Specified width is too small for margins, borders, and padding
    /// - Specified height is too small for margins, borders, and padding
    /// - Fullscreen mode dimensions are insufficient for the configuration
    ///
    /// Returns `BoxenError::TerminalSizeError` if:
    /// - Terminal size cannot be detected and no explicit dimensions are provided
    /// - Terminal dimensions are smaller than the required margins
    pub fn calculate_constraints(&self) -> BoxenResult<DimensionConstraints> {
        let terminal_width = get_terminal_width();
        let terminal_height = get_terminal_height();
        let border_width = calculate_border_width(&self.border_style);

        // Handle fullscreen mode first
        if let Some(fullscreen_mode) = &self.fullscreen {
            return self.calculate_fullscreen_constraints(
                fullscreen_mode,
                terminal_width,
                terminal_height,
                border_width,
            );
        }

        let _total_horizontal_overhead =
            border_width + self.padding.horizontal() + self.margin.horizontal();

        // Calculate maximum available width
        let max_width = if let Some(ref width_spec) = self.width {
            // Calculate the actual width from the specification
            let specified_width = width_spec.calculate(terminal_width);

            // When width is specified, it represents the total box width including margins
            // So we need to subtract margins to get the available width for content + borders + padding
            let available_width_for_content = if specified_width > self.margin.horizontal() {
                specified_width - self.margin.horizontal()
            } else {
                return Err(Self::invalid_dimensions_error(
                    format!(
                        "Width {} is too small for margins {}",
                        specified_width,
                        self.margin.horizontal()
                    ),
                    Some(specified_width),
                    self.height
                        .as_ref()
                        .map(|h| h.calculate(terminal_height.unwrap_or(24))),
                ));
            };

            // Validate that we have enough space for borders and padding
            if available_width_for_content < border_width + self.padding.horizontal() {
                return Err(Self::invalid_dimensions_error(
                    format!("Width {specified_width} is too small for borders and padding"),
                    Some(specified_width),
                    self.height
                        .as_ref()
                        .map(|h| h.calculate(terminal_height.unwrap_or(24))),
                ));
            }

            available_width_for_content
        } else {
            // Use terminal width minus margins (borders and padding will be subtracted later)
            if terminal_width < self.margin.horizontal() {
                return Err(BoxenError::terminal_size_error(
                    "Failed to detect terminal dimensions".to_string(),
                    vec![
                        crate::error::ErrorRecommendation::suggestion_only(
                            "Terminal detection failed".to_string(),
                            "Specify explicit width and height instead of using fullscreen mode"
                                .to_string(),
                        ),
                        crate::error::ErrorRecommendation::with_auto_fix(
                            "Use fixed dimensions".to_string(),
                            "Set explicit dimensions".to_string(),
                            ".width(80).height(24)".to_string(),
                        ),
                    ],
                ));
            }
            terminal_width - self.margin.horizontal()
        };

        // Calculate maximum available height
        let max_height = if let Some(ref height_spec) = self.height {
            // Calculate the actual height from the specification
            let specified_height = height_spec.calculate(terminal_height.unwrap_or(24));

            // When height is specified, it represents the total box height including margins
            // So we need to subtract margins to get the available height for content + borders + padding
            if specified_height > self.margin.vertical() {
                Some(specified_height - self.margin.vertical())
            } else {
                return Err(Self::invalid_dimensions_error(
                    format!(
                        "Height {} is too small for margins {}",
                        specified_height,
                        self.margin.vertical()
                    ),
                    None,
                    Some(specified_height),
                ));
            }
        } else {
            // Don't apply height constraints unless explicitly specified by user
            None
        };

        Ok(DimensionConstraints {
            max_width,
            max_height,
            terminal_width,
            terminal_height,
            border_width,
        })
    }

    /// Calculate final layout dimensions for given content
    ///
    /// # Errors
    ///
    /// Returns `BoxenError::ConfigurationError` if:
    /// - Calculated box dimensions exceed terminal size
    /// - Box width exceeds the specified or available width limit
    /// - Box height exceeds the specified or available height limit
    ///
    /// Returns errors from `calculate_constraints` if dimension constraints cannot be calculated.
    pub fn calculate_layout_dimensions(
        &self,
        content_width: usize,
        content_height: usize,
    ) -> BoxenResult<LayoutDimensions> {
        let constraints = self.calculate_constraints()?;

        // In fullscreen mode, expand content to fill available space
        let (final_content_width, final_content_height) = if self.fullscreen.is_some() {
            let max_content_width = self.calculate_max_content_width()?;
            let max_content_height = self.calculate_max_content_height()?;

            let expanded_width = max_content_width;
            let expanded_height = if let Some(max_height) = max_content_height {
                max_height
            } else {
                content_height // Use original height if no height constraint
            };

            (expanded_width, expanded_height)
        } else {
            (content_width, content_height)
        };

        // Calculate inner dimensions (content + padding)
        let inner_width = final_content_width + self.padding.horizontal();
        let inner_height = final_content_height + self.padding.vertical();

        // Calculate box dimensions without margins (for constraint validation)
        let box_width = inner_width + constraints.border_width;
        let box_height = inner_height
            + (if matches!(self.border_style, BorderStyle::None) {
                0
            } else {
                2
            }); // top and bottom borders

        // Calculate total dimensions (box + margins)
        let total_width = box_width + self.margin.horizontal();
        let total_height = box_height + self.margin.vertical();

        // Validate against constraints
        // In fullscreen mode, ignore specified width and use terminal width as limit
        let width_limit = if self.fullscreen.is_some() {
            constraints.terminal_width // In fullscreen mode, use terminal width as limit
        } else if let Some(ref width_spec) = self.width {
            width_spec.calculate(constraints.terminal_width)
        } else {
            constraints.max_width + self.margin.horizontal()
        };

        if total_width > width_limit {
            return Err(Self::configuration_error(format!(
                "Calculated box width ({total_width}) exceeds maximum available width ({width_limit})"
            )));
        }

        // For height validation, compare box height (without margins) against max_height (which already has margins subtracted)
        if let Some(max_height) = constraints.max_height {
            if box_height > max_height {
                return Err(Self::configuration_error(format!(
                    "Calculated box height ({box_height}) exceeds maximum available height ({max_height})"
                )));
            }
        }

        // Validate against terminal constraints
        if total_width > constraints.terminal_width {
            return Err(Self::configuration_error(format!(
                "Box width ({}) exceeds terminal width ({})",
                total_width, constraints.terminal_width
            )));
        }

        if let Some(terminal_height) = constraints.terminal_height {
            if total_height > terminal_height {
                return Err(Self::configuration_error(format!(
                    "Box height ({total_height}) exceeds terminal height ({terminal_height})"
                )));
            }
        }

        Ok(LayoutDimensions {
            content_width: final_content_width,
            content_height: final_content_height,
            total_width,
            total_height,
            inner_width,
            inner_height,
        })
    }

    /// Calculate the maximum content width available given the current options
    ///
    /// # Errors
    ///
    /// Returns `BoxenError::InvalidDimensions` if:
    /// - Available width is too small for borders and padding
    /// - Width constraints cannot be satisfied
    ///
    /// Returns errors from `calculate_constraints` if dimension constraints cannot be calculated.
    pub fn calculate_max_content_width(&self) -> BoxenResult<usize> {
        let constraints = self.calculate_constraints()?;
        let total_overhead = constraints.border_width + self.padding.horizontal();

        if constraints.max_width < total_overhead {
            return Err(Self::invalid_dimensions_error(
                format!(
                    "Width {} is too small for borders and padding",
                    constraints.max_width
                ),
                Some(constraints.max_width),
                None,
            ));
        }

        Ok(constraints.max_width - total_overhead)
    }

    /// Calculate the maximum content height available given the current options
    ///
    /// # Errors
    ///
    /// Returns `BoxenError::InvalidDimensions` if:
    /// - Available height is too small for borders and padding
    /// - Height constraints cannot be satisfied
    ///
    /// Returns errors from `calculate_constraints` if dimension constraints cannot be calculated.
    pub fn calculate_max_content_height(&self) -> BoxenResult<Option<usize>> {
        let constraints = self.calculate_constraints()?;

        if let Some(max_height) = constraints.max_height {
            let vertical_overhead = self.padding.vertical()
                + (if matches!(self.border_style, BorderStyle::None) {
                    0
                } else {
                    2
                });

            if max_height < vertical_overhead {
                return Err(Self::invalid_dimensions_error(
                    format!("Height {max_height} is too small for borders and padding"),
                    None,
                    Some(max_height),
                ));
            }

            Ok(Some(max_height - vertical_overhead))
        } else {
            Ok(None)
        }
    }

    /// Calculate constraints for fullscreen mode
    fn calculate_fullscreen_constraints(
        &self,
        fullscreen_mode: &FullscreenMode,
        terminal_width: usize,
        terminal_height: Option<usize>,
        border_width: usize,
    ) -> BoxenResult<DimensionConstraints> {
        let (target_width, target_height) = match fullscreen_mode {
            FullscreenMode::Auto => {
                // Use full terminal dimensions
                (terminal_width, terminal_height)
            }
            FullscreenMode::Custom(func) => {
                // Use custom function to calculate dimensions
                let height = terminal_height.unwrap_or(24); // Fallback height
                let (custom_width, custom_height) = func(terminal_width, height);
                (custom_width, Some(custom_height))
            }
        };

        // In fullscreen mode, the target dimensions represent the total box size
        // We need to calculate the available space for content
        let max_width = if target_width > self.margin.horizontal() {
            target_width - self.margin.horizontal()
        } else {
            return Err(Self::invalid_dimensions_error(
                format!("Target width {target_width} is too small for margins"),
                Some(target_width),
                target_height,
            ));
        };

        let max_height = if let Some(height) = target_height {
            if height > self.margin.vertical() {
                Some(height - self.margin.vertical())
            } else {
                return Err(Self::invalid_dimensions_error(
                    format!("Target height {height} is too small for margins"),
                    Some(target_width),
                    Some(height),
                ));
            }
        } else {
            None
        };

        // Validate that we have enough space for borders and padding
        if max_width < border_width + self.padding.horizontal() {
            return Err(Self::invalid_dimensions_error(
                "Insufficient space for borders and padding".to_string(),
                Some(target_width),
                target_height,
            ));
        }

        if let Some(height) = max_height {
            let vertical_border_overhead = if matches!(self.border_style, BorderStyle::None) {
                0
            } else {
                2
            };
            if height < vertical_border_overhead + self.padding.vertical() {
                return Err(Self::invalid_dimensions_error(
                    "Insufficient space for vertical borders and padding".to_string(),
                    Some(target_width),
                    Some(height + self.margin.vertical()),
                ));
            }
        }

        Ok(DimensionConstraints {
            max_width,
            max_height,
            terminal_width,
            terminal_height,
            border_width,
        })
    }

    /// Validate that the current options are compatible with terminal constraints
    ///
    /// # Errors
    ///
    /// Returns errors from `calculate_constraints`, `calculate_max_content_width`, and
    /// `calculate_max_content_height` if any validation checks fail.
    pub fn validate_constraints(&self) -> BoxenResult<()> {
        let _constraints = self.calculate_constraints()?;
        let _max_content_width = self.calculate_max_content_width()?;
        let _max_content_height = self.calculate_max_content_height()?;
        Ok(())
    }
}