telex-tui 0.3.0

A DX-first TUI framework for building AI terminal applications
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
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
use std::cell::RefCell;
use std::rc::Rc;

use crate::widget::Widget;

/// Callback type for event handlers (no arguments).
pub type Callback = Rc<dyn Fn()>;

/// Alignment along the main axis (justify).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Justify {
    /// Items at the start (default).
    #[default]
    Start,
    /// Items at the end.
    End,
    /// Items centered.
    Center,
    /// Items spread with space between them.
    SpaceBetween,
    /// Items spread with space around them.
    SpaceAround,
}

/// Alignment along the cross axis (align).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Align {
    /// Items at the start.
    Start,
    /// Items at the end.
    End,
    /// Items centered.
    Center,
    /// Items stretch to fill (default).
    #[default]
    Stretch,
}

/// Layout mode for stack containers.
///
/// This enum allows switching between different layout algorithms.
/// Currently only Flex is implemented, but this provides the hook
/// for future layout experiments (e.g., percentage-based layouts).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum LayoutMode {
    /// Flex-based layout (default).
    /// Children with flex > 0 share remaining space proportionally.
    /// Children with flex = 0 use their intrinsic/min size.
    #[default]
    Flex,
    // Future: Percent - children specify exact percentages
    // Future: Grid - CSS grid-like layout
}

/// Callback type for selection events (receives selected index).
pub type SelectCallback = Rc<dyn Fn(usize)>;

/// Callback type for text change events (receives new text).
pub type ChangeCallback = Rc<dyn Fn(String)>;

/// Callback type for toggle events (receives new state).
pub type ToggleCallback = Rc<dyn Fn(bool)>;

/// Callback type for cursor position change events (receives line, column).
pub type CursorChangeCallback = Rc<dyn Fn(usize, usize)>;

/// Callback type for cursor position change events in single-line inputs (receives position).
pub type CursorPosCallback = Rc<dyn Fn(usize)>;

/// Path to a node in a tree (indices at each level).
pub type TreePath = Vec<usize>;

/// Callback type for tree selection events (receives path to selected item).
pub type TreeSelectCallback = Rc<dyn Fn(TreePath)>;

/// Callback type for tree activation events (receives path to activated item).
pub type TreeActivateCallback = Rc<dyn Fn(TreePath)>;

/// Callback type for table sort events (receives column index and ascending flag).
pub type SortCallback = Rc<dyn Fn(usize, bool)>;

/// Callback type for table row activation events (receives row index).
pub type RowActivateCallback = Rc<dyn Fn(usize)>;

/// Callback type for command execution events (receives command ID).
pub type CommandCallback = Rc<dyn Fn(&'static str)>;

/// Callback type for canvas drawing (receives mutable draw context).
pub type CanvasDrawCallback = Rc<dyn Fn(&mut crate::canvas::DrawContext)>;

/// Callback type for slider value changes.
pub type SliderCallback = Rc<dyn Fn(f64)>;

/// The core view type - a node in the UI tree.
#[derive(Clone)]
pub enum View {
    /// A text node displaying a string.
    Text(TextNode),
    /// A vertical stack of child views.
    VStack(VStackNode),
    /// A horizontal stack of child views.
    HStack(HStackNode),
    /// A clickable button.
    Button(ButtonNode),
    /// A container with optional border, padding, and flex sizing.
    Box(BoxNode),
    /// Flexible space that expands to fill available space.
    Spacer(SpacerNode),
    /// A selectable list of items.
    List(ListNode),
    /// A single-line text input.
    TextInput(TextInputNode),
    /// A multi-line text area.
    TextArea(TextAreaNode),
    /// A checkbox (toggle).
    Checkbox(CheckboxNode),
    /// A group of radio buttons (mutually exclusive options).
    RadioGroup(RadioGroupNode),
    /// A modal dialog overlay.
    Modal(ModalNode),
    /// A split pane container with two resizable panels.
    Split(SplitNode),
    /// A tabbed interface container.
    Tabs(TabsNode),
    /// A hierarchical tree view.
    Tree(TreeNode),
    /// A data table with columns and rows.
    Table(TableNode),
    /// A progress bar showing completion status.
    ProgressBar(ProgressBarNode),
    /// A status bar displayed at the bottom of the screen.
    StatusBar(StatusBarNode),
    /// A command palette overlay for searching and executing commands.
    CommandPalette(CommandPaletteNode),
    /// A horizontal menu bar with dropdown menus.
    MenuBar(MenuBarNode),
    /// A container for toast notifications.
    ToastContainer(ToastContainerNode),
    /// A form container with validation support.
    Form(FormNode),
    /// A form field with label and error display.
    FormField(FormFieldNode),
    /// A pixel-level canvas using Kitty graphics protocol.
    Canvas(CanvasNode),
    /// An image display using Kitty graphics protocol.
    Image(ImageNode),
    /// An interactive PTY terminal emulator.
    Terminal(TerminalNode),
    /// An error boundary that catches panics in its child view.
    ErrorBoundary(ErrorBoundaryNode),
    /// A user-defined custom widget.
    Custom(CustomNode),
    /// A slider for bounded numeric values.
    Slider(SliderNode),
    /// An empty placeholder.
    Empty,
}

impl std::fmt::Debug for View {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            View::Text(n) => f.debug_tuple("Text").field(n).finish(),
            View::VStack(n) => f.debug_tuple("VStack").field(n).finish(),
            View::HStack(n) => f.debug_tuple("HStack").field(n).finish(),
            View::Button(n) => f
                .debug_struct("Button")
                .field("label", &n.label)
                .field("on_press", &"<callback>")
                .finish(),
            View::Box(n) => f.debug_tuple("Box").field(n).finish(),
            View::Spacer(n) => f.debug_tuple("Spacer").field(n).finish(),
            View::List(n) => f
                .debug_struct("List")
                .field("items", &n.items.len())
                .field("selected", &n.selected)
                .finish(),
            View::TextInput(n) => f
                .debug_struct("TextInput")
                .field("value", &n.value)
                .finish(),
            View::TextArea(n) => f
                .debug_struct("TextArea")
                .field("value", &n.value)
                .field("cursor", &(n.cursor_line, n.cursor_col))
                .finish(),
            View::Checkbox(n) => f
                .debug_struct("Checkbox")
                .field("checked", &n.checked)
                .field("label", &n.label)
                .finish(),
            View::RadioGroup(n) => f
                .debug_struct("RadioGroup")
                .field("selected", &n.selected)
                .field("options", &n.options)
                .finish(),
            View::Modal(n) => f
                .debug_struct("Modal")
                .field("visible", &n.visible)
                .field("title", &n.title)
                .finish(),
            View::Split(n) => f
                .debug_struct("Split")
                .field("orientation", &n.orientation)
                .field("ratio", &n.ratio)
                .finish(),
            View::Tabs(n) => f
                .debug_struct("Tabs")
                .field("tabs", &n.tabs)
                .field("active", &n.active)
                .finish(),
            View::Tree(n) => f
                .debug_struct("Tree")
                .field("items", &n.items.len())
                .field("selected", &n.selected)
                .finish(),
            View::Table(n) => f
                .debug_struct("Table")
                .field("columns", &n.columns.len())
                .field("rows", &n.rows.len())
                .field("selected", &n.selected)
                .finish(),
            View::ProgressBar(n) => f
                .debug_struct("ProgressBar")
                .field("value", &n.value)
                .field("label", &n.label)
                .finish(),
            View::StatusBar(n) => f
                .debug_struct("StatusBar")
                .field("left", &n.left)
                .field("center", &n.center)
                .field("right", &n.right)
                .finish(),
            View::CommandPalette(n) => f
                .debug_struct("CommandPalette")
                .field("visible", &n.visible)
                .field("query", &n.query)
                .field("selected", &n.selected)
                .finish(),
            View::MenuBar(n) => f
                .debug_struct("MenuBar")
                .field("menus", &n.menus.len())
                .field("active_menu", &n.active_menu)
                .finish(),
            View::ToastContainer(n) => f
                .debug_struct("ToastContainer")
                .field("toasts", &n.toasts.len())
                .finish(),
            View::Form(n) => f
                .debug_struct("Form")
                .field("children", &n.children.len())
                .finish(),
            View::FormField(n) => f
                .debug_struct("FormField")
                .field("name", &n.name)
                .field("label", &n.label)
                .finish(),
            View::Canvas(n) => f
                .debug_struct("Canvas")
                .field("width", &n.pixel_width)
                .field("height", &n.pixel_height)
                .finish(),
            View::Image(n) => f
                .debug_struct("Image")
                .field("has_data", &n.source.is_some())
                .finish(),
            View::Terminal(n) => f
                .debug_struct("Terminal")
                .field("rows", &n.rows)
                .field("cols", &n.cols)
                .field("border", &n.border)
                .finish(),
            View::ErrorBoundary(_) => f.debug_struct("ErrorBoundary").finish(),
            View::Custom(_) => f.debug_struct("Custom").finish(),
            View::Slider(n) => f
                .debug_struct("Slider")
                .field("min", &n.min)
                .field("max", &n.max)
                .field("value", &n.value)
                .field("step", &n.step)
                .finish(),
            View::Empty => write!(f, "Empty"),
        }
    }
}

impl View {
    /// Create a text view with the given content.
    pub fn text(content: impl Into<String>) -> Self {
        View::Text(TextNode {
            content: content.into(),
            color: None,
            bg_color: None,
            bold: false,
            italic: false,
            underline: false,
            dim: false,
        })
    }

    /// Create a styled text builder.
    pub fn styled_text(content: impl Into<String>) -> TextBuilder {
        TextBuilder::new(content)
    }

    /// Create a vertical stack builder.
    pub fn vstack() -> VStackBuilder {
        VStackBuilder::new()
    }

    /// Create a horizontal stack builder.
    pub fn hstack() -> HStackBuilder {
        HStackBuilder::new()
    }

    /// Create a button builder.
    pub fn button() -> ButtonBuilder {
        ButtonBuilder::new()
    }

    /// Create a box builder.
    pub fn boxed() -> BoxBuilder {
        BoxBuilder::new()
    }

    /// Create a spacer with flex factor 1 (expands to fill available space).
    pub fn spacer() -> Self {
        View::Spacer(SpacerNode { flex: 1, height: 0 })
    }

    /// Create a spacer with a specific flex factor.
    pub fn spacer_flex(flex: u16) -> Self {
        View::Spacer(SpacerNode { flex, height: 0 })
    }

    /// Create a fixed-height gap (blank lines).
    ///
    /// Unlike `spacer()` which expands to fill space, `gap()` is a fixed height.
    ///
    /// # Example
    /// ```rust,ignore
    /// View::vstack()
    ///     .child(View::text("Header"))
    ///     .child(View::gap(1))  // One blank line
    ///     .child(View::text("Content"))
    ///     .build()
    /// ```
    pub fn gap(height: u16) -> Self {
        View::Spacer(SpacerNode { flex: 0, height })
    }

    /// Create a list builder.
    pub fn list() -> ListBuilder {
        ListBuilder::new()
    }

    /// Create a text input builder.
    pub fn text_input() -> TextInputBuilder {
        TextInputBuilder::new()
    }

    /// Create a checkbox builder.
    pub fn checkbox() -> CheckboxBuilder {
        CheckboxBuilder::new()
    }

    /// Create a radio group builder.
    pub fn radio_group() -> RadioGroupBuilder {
        RadioGroupBuilder::new()
    }

    /// Create a text area builder.
    pub fn text_area() -> TextAreaBuilder {
        TextAreaBuilder::new()
    }

    /// Create a modal dialog builder.
    pub fn modal() -> ModalBuilder {
        ModalBuilder::new()
    }

    /// Create a split pane builder.
    pub fn split() -> SplitBuilder {
        SplitBuilder::new()
    }

    /// Create a tabs builder.
    pub fn tabs() -> TabsBuilder {
        TabsBuilder::new()
    }

    /// Create a tree builder.
    pub fn tree() -> TreeBuilder {
        TreeBuilder::new()
    }

    /// Create a table builder.
    pub fn table() -> TableBuilder {
        TableBuilder::new()
    }

    /// Create a progress bar builder.
    pub fn progress_bar() -> ProgressBarBuilder {
        ProgressBarBuilder::new()
    }

    /// Create a status bar builder.
    pub fn status_bar() -> StatusBarBuilder {
        StatusBarBuilder::new()
    }

    /// Create a command palette builder.
    pub fn command_palette() -> CommandPaletteBuilder {
        CommandPaletteBuilder::new()
    }

    /// Create a menu bar builder.
    pub fn menu_bar() -> MenuBarBuilder {
        MenuBarBuilder::new()
    }

    /// Create a toast container builder.
    pub fn toast_container() -> ToastContainerBuilder {
        ToastContainerBuilder::new()
    }

    /// Create a form builder.
    pub fn form() -> FormBuilder {
        FormBuilder::new()
    }

    /// Create a form field builder.
    pub fn form_field(name: impl Into<String>) -> FormFieldBuilder {
        FormFieldBuilder::new(name)
    }

    /// Create a canvas builder for pixel-level drawing.
    ///
    /// **Experimental Feature**
    ///
    /// Canvas uses the Kitty graphics protocol for actual pixel rendering.
    /// Requires a compatible terminal (Kitty, Ghostty, WezTerm).
    /// Other terminals will show a placeholder message.
    pub fn canvas() -> CanvasBuilder {
        CanvasBuilder::new()
    }

    /// Create an image builder for displaying images.
    ///
    /// **Experimental Feature**
    ///
    /// Displays PNG, JPEG, or GIF images using the Kitty graphics protocol.
    /// GIF animations are handled natively by Kitty.
    /// Requires a compatible terminal (Kitty, Ghostty, WezTerm).
    /// Other terminals will show alt text or a placeholder message.
    pub fn image() -> ImageBuilder {
        ImageBuilder::new()
    }

    /// Create a terminal builder for interactive PTY terminal emulation.
    ///
    /// **Status: Experimental Preview**
    ///
    /// Supports running shell commands (bash, vim, htop, etc.) with full
    /// keyboard input and ANSI color/style rendering.
    ///
    /// # Known Limitations
    ///
    /// - No scrollback buffer
    /// - No terminal resize support
    /// - No copy/paste
    /// - No mouse input
    ///
    /// Use for prototyping and experimentation. Breaking changes likely.
    ///
    /// # Example
    /// ```rust,ignore
    /// let terminal = cx.use_terminal();
    /// if !terminal.is_started() {
    ///     terminal.spawn("bash", &[], 80, 24);
    /// }
    /// View::terminal().handle(terminal).build()
    /// ```
    pub fn terminal() -> TerminalBuilder {
        TerminalBuilder::new()
    }

    /// Create a custom widget view.
    ///
    /// Wraps a user-defined `Widget` implementation in a View.
    /// Use this for custom character-cell rendering that can't be
    /// composed from built-in widgets.
    ///
    /// # Example
    /// ```rust,ignore
    /// let my_widget = Rc::new(RefCell::new(MyWidget::new()));
    /// View::custom(my_widget)
    /// ```
    pub fn custom(widget: Rc<RefCell<dyn Widget>>) -> Self {
        View::Custom(CustomNode { widget })
    }

    /// Create a slider builder for bounded numeric values.
    ///
    /// # Example
    /// ```rust,ignore
    /// View::slider()
    ///     .min(0.0)
    ///     .max(127.0)
    ///     .value(64.0)
    ///     .step(1.0)
    ///     .label("Volume")
    ///     .on_change(move |v| vol.set(v))
    ///     .build()
    /// ```
    pub fn slider() -> SliderBuilder {
        SliderBuilder::new()
    }

    /// Create an error boundary builder.
    ///
    /// An error boundary catches panics in its child view and displays
    /// a fallback view instead of crashing the application.
    ///
    /// # Example
    /// ```rust,ignore
    /// View::error_boundary()
    ///     .child(risky_component_view)
    ///     .fallback(View::text("Something went wrong"))
    ///     .build()
    /// ```
    pub fn error_boundary() -> ErrorBoundaryBuilder {
        ErrorBoundaryBuilder::new()
    }

    /// Create an empty view.
    pub fn empty() -> Self {
        View::Empty
    }

    /// Check if this view is focusable.
    pub fn is_focusable(&self) -> bool {
        match self {
            View::Button(_) => true,
            View::Box(node) => node.scroll,
            View::List(_) => true,
            View::TextInput(_) => true,
            View::TextArea(_) => true,
            View::Checkbox(_) => true,
            View::RadioGroup(_) => true, // RadioGroup is focusable for option selection
            View::Split(_) => false,     // Split is a layout container, not focusable itself
            View::Tabs(_) => true,       // Tabs is focusable for tab switching
            View::Tree(_) => true,       // Tree is focusable for navigation
            View::Table(_) => true,      // Table is focusable for row selection
            View::CommandPalette(_) => true, // Command palette captures all input when visible
            View::MenuBar(_) => true,    // Menu bar is focusable for navigation
            View::FormField(_) => true,  // Form fields are focusable for input
            View::Terminal(_) => true,   // Terminal is focusable for PTY input
            View::Slider(_) => true,    // Slider is focusable for value adjustment
            _ => false,
        }
    }

    /// Get the flex factor of this view (for layout).
    pub fn flex(&self) -> u16 {
        match self {
            View::Box(n) => n.flex,
            View::Spacer(n) => n.flex,
            _ => 0,
        }
    }

    /// Get the minimum height constraint, if any.
    pub fn min_height(&self) -> Option<u16> {
        match self {
            View::Box(n) => n.min_height,
            _ => None,
        }
    }

    /// Get the maximum height constraint, if any.
    pub fn max_height(&self) -> Option<u16> {
        match self {
            View::Box(n) => n.max_height,
            _ => None,
        }
    }

    /// Get the minimum width constraint, if any.
    pub fn min_width(&self) -> Option<u16> {
        match self {
            View::Box(n) => n.min_width,
            _ => None,
        }
    }

    /// Get the maximum width constraint, if any.
    pub fn max_width(&self) -> Option<u16> {
        match self {
            View::Box(n) => n.max_width,
            _ => None,
        }
    }

    /// Calculate the intrinsic (natural) height of this view based on its content.
    /// Returns None for views that have no intrinsic height (flexible).
    pub fn intrinsic_height(&self) -> Option<u16> {
        match self {
            View::Text(n) => Some(n.content.lines().count().max(1) as u16),
            View::Button(_) => Some(1),
            View::Box(n) => {
                let border = if n.border { 2 } else { 0 };
                let padding = n.padding * 2;
                let inner = n
                    .child
                    .as_ref()
                    .and_then(|c| c.intrinsic_height())
                    .unwrap_or(0);
                Some(inner + border + padding)
            }
            View::VStack(n) => {
                if n.children.is_empty() {
                    return Some(0);
                }
                let spacing = if n.children.len() > 1 {
                    n.spacing * (n.children.len() as u16 - 1)
                } else {
                    0
                };
                let children_height: u16 =
                    n.children.iter().filter_map(|c| c.intrinsic_height()).sum();
                Some(children_height + spacing)
            }
            View::HStack(n) => {
                // HStack height is max of children heights
                n.children
                    .iter()
                    .filter_map(|c| c.intrinsic_height())
                    .max()
                    .or(Some(1))
            }
            View::List(n) => Some(n.items.len().max(1) as u16),
            View::TextInput(_) => Some(1),
            View::TextArea(n) => Some(n.rows),
            View::Checkbox(_) => Some(1),
            View::RadioGroup(n) => Some(n.options.len() as u16), // One row per option
            View::Modal(_) => None, // Modal is an overlay, no intrinsic size
            View::Spacer(n) => {
                if n.flex == 0 {
                    Some(n.height) // Fixed-height gap
                } else {
                    None // Flexible spacer expands
                }
            }
            View::Split(_) => None,          // Split fills available space
            View::Tabs(_) => None,           // Tabs fills available space
            View::Tree(_) => None,           // Tree fills available space
            View::Table(_) => None,          // Table fills available space
            View::ProgressBar(_) => Some(1), // Progress bar is 1 row tall
            View::StatusBar(_) => Some(1),   // Status bar is 1 row tall
            View::CommandPalette(_) => None, // Command palette is an overlay
            View::MenuBar(_) => Some(1),     // Menu bar is 1 row tall
            View::ToastContainer(_) => None, // Toast container is an overlay
            View::Form(n) => {
                // Form height is sum of children
                let children_height: u16 =
                    n.children.iter().filter_map(|c| c.intrinsic_height()).sum();
                Some(children_height)
            }
            View::FormField(n) => {
                // Label (1) + input (1) + error (1 if present) = 2-3 rows
                let base_height = 2u16; // Label + input
                let error_height = if n.error.is_some() { 1 } else { 0 };
                Some(base_height + error_height)
            }
            View::Canvas(n) => {
                // Canvas height in cells (pixels / cell_height)
                // Approximate: assume ~20 pixels per cell height
                Some((n.pixel_height / 20).max(1))
            }
            View::Image(n) => {
                // Image height based on detected dimensions or default
                n.cell_height.or(Some(5))
            }
            View::Terminal(n) => {
                // Terminal height is rows + border
                let border = if n.border { 2 } else { 0 };
                Some(n.rows as u16 + border)
            }
            View::ErrorBoundary(n) => n.child.intrinsic_height(),
            View::Custom(n) => n.widget.borrow().height_hint(80), // Use default width hint
            View::Slider(_) => Some(1), // Slider is a single row
            View::Empty => Some(0),
        }
    }

    /// Calculate the intrinsic (natural) width of this view based on its content.
    /// Returns None for views that have no intrinsic width (flexible).
    pub fn intrinsic_width(&self) -> Option<u16> {
        match self {
            View::Text(n) => {
                let max_line_width = n.content.lines().map(|l| l.len()).max().unwrap_or(0);
                Some(max_line_width as u16)
            }
            View::Button(n) => {
                // [ label ] = 4 chars for brackets + spaces + label
                Some(n.label.len() as u16 + 4)
            }
            View::Box(n) => {
                let border = if n.border { 2 } else { 0 };
                let padding = n.padding * 2;
                let inner = n
                    .child
                    .as_ref()
                    .and_then(|c| c.intrinsic_width())
                    .unwrap_or(0);
                Some(inner + border + padding)
            }
            View::VStack(n) => {
                // VStack width is max of children widths
                n.children
                    .iter()
                    .filter_map(|c| c.intrinsic_width())
                    .max()
                    .or(Some(1))
            }
            View::HStack(n) => {
                if n.children.is_empty() {
                    return Some(0);
                }
                let spacing = if n.children.len() > 1 {
                    n.spacing * (n.children.len() as u16 - 1)
                } else {
                    0
                };
                let children_width: u16 =
                    n.children.iter().filter_map(|c| c.intrinsic_width()).sum();
                Some(children_width + spacing)
            }
            View::List(n) => {
                // "> " prefix + max item length
                let max_item = n.items.iter().map(|i| i.len()).max().unwrap_or(0);
                Some(max_item as u16 + 2)
            }
            View::TextInput(_) => {
                // TextInput should be sized by its container, not by content
                // Return None to allow flex/container sizing with internal scrolling
                None
            }
            View::TextArea(_) => {
                // TextArea should be sized by its container, not by content
                // Return None to allow flex/container sizing with internal scrolling
                None
            }
            View::Checkbox(n) => {
                // "[x] " + label
                Some(n.label.len() as u16 + 4)
            }
            View::RadioGroup(n) => {
                // "(o) " + longest option
                let max_option = n.options.iter().map(|o| o.len()).max().unwrap_or(0);
                Some(max_option as u16 + 4)
            }
            View::Modal(_) => None, // Modal is an overlay
            View::Spacer(n) => {
                if n.flex == 0 {
                    Some(0) // Fixed-height gap has no width requirement
                } else {
                    None // Flexible spacer expands
                }
            }
            View::Split(_) => None, // Split fills available space
            View::Tabs(_) => None,  // Tabs fills available space
            View::Tree(_) => None,  // Tree fills available space
            View::Table(_) => None, // Table fills available space
            View::ProgressBar(n) => {
                // Label + bar width + percentage
                let label_width = n.label.as_ref().map(|l| l.len() + 1).unwrap_or(0);
                let bar_width = n.width.unwrap_or(10) as usize;
                let percentage_width = if n.show_percentage { 5 } else { 0 };
                Some((label_width + bar_width + percentage_width) as u16)
            }
            View::StatusBar(n) => {
                // Left + center + right sections
                let left_width = n.left.len();
                let center_width = n.center.as_ref().map(|c| c.len()).unwrap_or(0);
                let right_width = n.right.as_ref().map(|r| r.len()).unwrap_or(0);
                // Minimum spacing between sections
                let spacing = if center_width > 0 || right_width > 0 {
                    2
                } else {
                    0
                };
                Some((left_width + center_width + right_width + spacing) as u16)
            }
            View::CommandPalette(_) => None, // Command palette is an overlay
            View::MenuBar(n) => {
                // Sum of menu labels + separators
                let labels_width: usize = n.menus.iter().map(|m| m.label.len() + 3).sum(); // " Label "
                Some(labels_width as u16)
            }
            View::ToastContainer(_) => None, // Toast container is an overlay
            View::Form(n) => {
                // Form width is max of children
                n.children.iter().filter_map(|c| c.intrinsic_width()).max()
            }
            View::FormField(n) => {
                // Width is max of label and input
                let label_width = n.label.len() as u16;
                let input_width = 20u16; // Default minimum input width
                Some(label_width.max(input_width))
            }
            View::Canvas(n) => {
                // Canvas width in cells (pixels / cell_width)
                // Approximate: assume ~10 pixels per cell width
                Some((n.pixel_width / 10).max(1))
            }
            View::Image(n) => {
                // Image width based on detected dimensions or default
                n.cell_width.or(Some(10))
            }
            View::Terminal(n) => {
                // Terminal width is cols + border
                let border = if n.border { 2 } else { 0 };
                Some(n.cols as u16 + border)
            }
            View::ErrorBoundary(n) => n.child.intrinsic_width(),
            View::Custom(n) => n.widget.borrow().width_hint(),
            View::Slider(n) => {
                // Label + brackets + track + value display
                let label_len = n.label.as_ref().map(|l| l.len() + 1).unwrap_or(0) as u16;
                Some(label_len + 20) // Reasonable default width
            }
            View::Empty => Some(0),
        }
    }
}

/// Orientation for split panes.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Orientation {
    /// Panes side by side: [first | second]
    #[default]
    Horizontal,
    /// Panes stacked: [first] / [second]
    Vertical,
}

/// Position of the tab bar.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TabPosition {
    /// Tab bar at the top (default).
    #[default]
    Top,
    /// Tab bar at the bottom.
    Bottom,
}

/// A text node containing string content with optional styling.
#[derive(Debug, Clone)]
pub struct TextNode {
    pub content: String,
    pub color: Option<crossterm::style::Color>,
    pub bg_color: Option<crossterm::style::Color>,
    pub bold: bool,
    pub italic: bool,
    pub underline: bool,
    pub dim: bool,
}

/// A vertical stack container.
#[derive(Debug, Clone)]
pub struct VStackNode {
    pub children: Vec<View>,
    /// Spacing between children (in rows).
    pub spacing: u16,
    /// Justify content along main axis (vertical).
    pub justify: Justify,
    /// Align items along cross axis (horizontal).
    pub align: Align,
    /// Layout algorithm to use.
    pub layout_mode: LayoutMode,
}

/// A horizontal stack container.
#[derive(Debug, Clone)]
pub struct HStackNode {
    pub children: Vec<View>,
    /// Spacing between children (in columns).
    pub spacing: u16,
    /// Justify content along main axis (horizontal).
    pub justify: Justify,
    /// Align items along cross axis (vertical).
    pub align: Align,
    /// Layout algorithm to use.
    pub layout_mode: LayoutMode,
}

/// A container with optional border, padding, and flex sizing.
#[derive(Debug, Clone)]
pub struct BoxNode {
    /// The child view inside the box.
    pub child: Option<std::boxed::Box<View>>,
    /// Whether to draw a border around the box.
    pub border: bool,
    /// Padding inside the box (all sides).
    pub padding: u16,
    /// Flex factor for layout (0 = fixed size, >0 = flexible).
    pub flex: u16,
    /// Whether this box is scrollable.
    pub scroll: bool,
    /// Automatically scroll to show bottom content (for chat-like UIs).
    pub auto_scroll_bottom: bool,
    /// Whether this box participates in focus navigation (default: true for scrollable boxes).
    pub focusable: bool,
    /// Minimum width constraint.
    pub min_width: Option<u16>,
    /// Maximum width constraint.
    pub max_width: Option<u16>,
    /// Minimum height constraint.
    pub min_height: Option<u16>,
    /// Maximum height constraint.
    pub max_height: Option<u16>,
}

/// Flexible space that expands to fill available space.
#[derive(Debug, Clone)]
pub struct SpacerNode {
    /// Flex factor (default 1). If 0, uses fixed height.
    pub flex: u16,
    /// Fixed height in rows (only used when flex is 0).
    pub height: u16,
}

/// A button node.
#[derive(Clone)]
pub struct ButtonNode {
    pub label: String,
    pub on_press: Option<Callback>,
}

/// A selectable list node.
#[derive(Clone)]
pub struct ListNode {
    /// The list items to display.
    pub items: Vec<String>,
    /// Currently selected index.
    pub selected: usize,
    /// Callback when selection changes.
    pub on_select: Option<SelectCallback>,
}

/// A text input node.
#[derive(Clone)]
pub struct TextInputNode {
    /// Current text value.
    pub value: String,
    /// Placeholder text shown when empty.
    pub placeholder: String,
    /// Callback when text changes.
    pub on_change: Option<ChangeCallback>,
    /// Callback when cursor position changes.
    pub on_cursor_change: Option<CursorPosCallback>,
    /// Callback when Enter is pressed (submit).
    pub on_submit: Option<Callback>,
    /// Callback when Up arrow is pressed.
    pub on_key_up: Option<Callback>,
    /// Callback when Down arrow is pressed.
    pub on_key_down: Option<Callback>,
    /// Cursor position within the text.
    pub cursor_pos: usize,
    /// Whether this input should have initial focus.
    pub focused: bool,
}

/// A multi-line text area node.
#[derive(Clone)]
pub struct TextAreaNode {
    /// Current text value (may contain newlines).
    pub value: String,
    /// Placeholder text shown when empty.
    pub placeholder: String,
    /// Callback when text changes.
    pub on_change: Option<ChangeCallback>,
    /// Callback when cursor position changes (line, column).
    pub on_cursor_change: Option<CursorChangeCallback>,
    /// Cursor line position.
    pub cursor_line: usize,
    /// Cursor column position.
    pub cursor_col: usize,
    /// Number of visible rows.
    pub rows: u16,
    /// Width at which to auto-wrap text (None = no wrap, text truncated at display edge).
    pub wrap_width: Option<u16>,
}

/// A checkbox node.
#[derive(Clone)]
pub struct CheckboxNode {
    /// Whether the checkbox is checked.
    pub checked: bool,
    /// Label displayed next to the checkbox.
    pub label: String,
    /// Callback when toggled.
    pub on_toggle: Option<ToggleCallback>,
}

/// A radio group node (mutually exclusive options).
#[derive(Clone)]
pub struct RadioGroupNode {
    /// The available options.
    pub options: Vec<String>,
    /// Index of the currently selected option.
    pub selected: usize,
    /// Optional label for the group.
    pub label: Option<String>,
    /// Callback when selection changes.
    pub on_change: Option<SelectCallback>,
}

/// A modal dialog node.
#[derive(Clone)]
pub struct ModalNode {
    /// Whether the modal is visible.
    pub visible: bool,
    /// Title of the modal (shown in border).
    pub title: String,
    /// The content view inside the modal.
    pub child: Option<std::boxed::Box<View>>,
    /// Callback when modal is dismissed (Escape key).
    pub on_dismiss: Option<Callback>,
    /// Width of the modal (percentage of screen, 0-100).
    pub width_percent: u16,
    /// Height of the modal (percentage of screen, 0-100).
    pub height_percent: u16,
}

/// A split pane container node.
#[derive(Clone)]
pub struct SplitNode {
    /// Orientation of the split (horizontal or vertical).
    pub orientation: Orientation,
    /// First pane content.
    pub first: std::boxed::Box<View>,
    /// Second pane content.
    pub second: std::boxed::Box<View>,
    /// Split ratio (0.0 to 1.0, where 0.5 is equal split).
    pub ratio: f32,
    /// Minimum size for first pane (in cells).
    pub min_first: Option<u16>,
    /// Minimum size for second pane (in cells).
    pub min_second: Option<u16>,
    /// Whether to show a divider line between panes.
    pub show_divider: bool,
}

/// A tabbed interface container node.
#[derive(Clone)]
pub struct TabsNode {
    /// Tab labels displayed in the tab bar.
    pub tabs: Vec<String>,
    /// Content views for each tab.
    pub children: Vec<View>,
    /// Currently active tab index.
    pub active: usize,
    /// Callback when tab changes.
    pub on_change: Option<SelectCallback>,
    /// Position of the tab bar (top or bottom).
    pub position: TabPosition,
}

/// A single item in a tree view.
#[derive(Clone, Debug)]
pub struct TreeItem {
    /// Display label for this item.
    pub label: String,
    /// Optional icon displayed before the label.
    pub icon: Option<String>,
    /// Child items (empty for leaf nodes).
    pub children: Vec<TreeItem>,
    /// Whether this node is expanded (showing children).
    pub expanded: bool,
}

impl TreeItem {
    /// Create a new tree item with the given label.
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            icon: None,
            children: Vec::new(),
            expanded: false,
        }
    }

    /// Set the icon for this item.
    pub fn icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    /// Add a child item.
    pub fn child(mut self, child: TreeItem) -> Self {
        self.children.push(child);
        self
    }

    /// Set whether this node is expanded.
    pub fn expanded(mut self, expanded: bool) -> Self {
        self.expanded = expanded;
        self
    }

    /// Check if this is a leaf node (no children).
    pub fn is_leaf(&self) -> bool {
        self.children.is_empty()
    }
}

/// A hierarchical tree view node.
#[derive(Clone)]
pub struct TreeNode {
    /// Root-level tree items.
    pub items: Vec<TreeItem>,
    /// Path to the currently selected item.
    pub selected: TreePath,
    /// Callback when selection changes.
    pub on_select: Option<TreeSelectCallback>,
    /// Callback when an item is activated (Enter/Space).
    pub on_activate: Option<TreeActivateCallback>,
}

/// Text alignment for table columns.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TextAlign {
    #[default]
    Left,
    Center,
    Right,
}

/// Column width specification for tables.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum ColumnWidth {
    /// Size to fit content (default).
    #[default]
    Auto,
    /// Fixed width in characters.
    Fixed(u16),
    /// Flex factor for remaining space.
    Flex(u16),
}

/// A column definition for a table.
#[derive(Debug, Clone)]
pub struct TableColumn {
    /// Header text for this column.
    pub header: String,
    /// Width specification.
    pub width: ColumnWidth,
    /// Whether this column is sortable.
    pub sortable: bool,
    /// Text alignment for this column.
    pub align: TextAlign,
}

impl TableColumn {
    /// Create a new table column with the given header.
    pub fn new(header: impl Into<String>) -> Self {
        Self {
            header: header.into(),
            width: ColumnWidth::Auto,
            sortable: false,
            align: TextAlign::Left,
        }
    }

    /// Set the width of this column.
    pub fn width(mut self, width: ColumnWidth) -> Self {
        self.width = width;
        self
    }

    /// Make this column sortable.
    pub fn sortable(mut self, sortable: bool) -> Self {
        self.sortable = sortable;
        self
    }

    /// Set the text alignment for this column.
    pub fn align(mut self, align: TextAlign) -> Self {
        self.align = align;
        self
    }
}

/// A data table node with columns and rows.
#[derive(Clone)]
pub struct TableNode {
    /// Column definitions.
    pub columns: Vec<TableColumn>,
    /// Row data (each row is a Vec of cell strings).
    pub rows: Vec<Vec<String>>,
    /// Currently selected row index.
    pub selected: usize,
    /// Current sort state: (column_index, ascending).
    pub sort: Option<(usize, bool)>,
    /// Callback when selection changes.
    pub on_select: Option<SelectCallback>,
    /// Callback when sort changes.
    pub on_sort: Option<SortCallback>,
    /// Callback when a row is activated (Enter).
    pub on_activate: Option<RowActivateCallback>,
}

/// A progress bar node.
#[derive(Clone)]
pub struct ProgressBarNode {
    /// Progress value from 0.0 to 1.0.
    pub value: f32,
    /// Optional label shown before the bar.
    pub label: Option<String>,
    /// Whether to show percentage after the bar.
    pub show_percentage: bool,
    /// Fixed width of the bar portion (None = expand to fill).
    pub width: Option<u16>,
    /// Character used for the filled portion.
    pub filled_char: char,
    /// Character used for the empty portion.
    pub empty_char: char,
}

/// A status bar node displayed at the bottom of the screen.
#[derive(Clone)]
pub struct StatusBarNode {
    /// Content for the left section.
    pub left: String,
    /// Content for the center section (optional).
    pub center: Option<String>,
    /// Content for the right section (optional).
    pub right: Option<String>,
    /// Background color for the status bar.
    pub bg_color: Option<crossterm::style::Color>,
    /// Foreground color for the status bar.
    pub fg_color: Option<crossterm::style::Color>,
}

/// Builder for VStack views.
#[derive(Debug, Default)]
pub struct VStackBuilder {
    children: Vec<View>,
    spacing: u16,
    justify: Justify,
    align: Align,
    layout_mode: LayoutMode,
}

impl VStackBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn child(mut self, view: View) -> Self {
        self.children.push(view);
        self
    }

    pub fn spacing(mut self, spacing: u16) -> Self {
        self.spacing = spacing;
        self
    }

    /// Set justify (main axis alignment for VStack = vertical).
    pub fn justify(mut self, justify: Justify) -> Self {
        self.justify = justify;
        self
    }

    /// Set align (cross axis alignment for VStack = horizontal).
    pub fn align(mut self, align: Align) -> Self {
        self.align = align;
        self
    }

    /// Set layout mode (algorithm for distributing space).
    pub fn layout_mode(mut self, mode: LayoutMode) -> Self {
        self.layout_mode = mode;
        self
    }

    pub fn build(self) -> View {
        View::VStack(VStackNode {
            children: self.children,
            spacing: self.spacing,
            justify: self.justify,
            align: self.align,
            layout_mode: self.layout_mode,
        })
    }
}

/// Builder for HStack views.
#[derive(Debug, Default)]
pub struct HStackBuilder {
    children: Vec<View>,
    spacing: u16,
    justify: Justify,
    align: Align,
    layout_mode: LayoutMode,
}

impl HStackBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn child(mut self, view: View) -> Self {
        self.children.push(view);
        self
    }

    pub fn spacing(mut self, spacing: u16) -> Self {
        self.spacing = spacing;
        self
    }

    /// Set justify (main axis alignment for HStack = horizontal).
    pub fn justify(mut self, justify: Justify) -> Self {
        self.justify = justify;
        self
    }

    /// Set align (cross axis alignment for HStack = vertical).
    pub fn align(mut self, align: Align) -> Self {
        self.align = align;
        self
    }

    /// Set layout mode (algorithm for distributing space).
    pub fn layout_mode(mut self, mode: LayoutMode) -> Self {
        self.layout_mode = mode;
        self
    }

    pub fn build(self) -> View {
        View::HStack(HStackNode {
            children: self.children,
            spacing: self.spacing,
            justify: self.justify,
            align: self.align,
            layout_mode: self.layout_mode,
        })
    }
}

/// Builder for Button views.
#[derive(Default)]
pub struct ButtonBuilder {
    label: String,
    on_press: Option<Callback>,
}

impl ButtonBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    pub fn on_press(mut self, callback: impl Fn() + 'static) -> Self {
        self.on_press = Some(Rc::new(callback));
        self
    }

    pub fn build(self) -> View {
        View::Button(ButtonNode {
            label: self.label,
            on_press: self.on_press,
        })
    }
}

/// Builder for Box views.
#[derive(Default)]
pub struct BoxBuilder {
    child: Option<View>,
    border: bool,
    padding: u16,
    flex: u16,
    scroll: bool,
    auto_scroll_bottom: bool,
    focusable: Option<bool>,
    min_width: Option<u16>,
    max_width: Option<u16>,
    min_height: Option<u16>,
    max_height: Option<u16>,
}

impl BoxBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn child(mut self, view: View) -> Self {
        self.child = Some(view);
        self
    }

    pub fn border(mut self, border: bool) -> Self {
        self.border = border;
        self
    }

    pub fn padding(mut self, padding: u16) -> Self {
        self.padding = padding;
        self
    }

    pub fn flex(mut self, flex: u16) -> Self {
        self.flex = flex;
        self
    }

    pub fn scroll(mut self, scroll: bool) -> Self {
        self.scroll = scroll;
        self
    }

    /// Enable auto-scrolling to bottom (for chat-like UIs).
    pub fn auto_scroll_bottom(mut self, auto_scroll: bool) -> Self {
        self.auto_scroll_bottom = auto_scroll;
        self
    }

    /// Set whether this box participates in focus navigation.
    /// By default, scrollable boxes are focusable. Use `focusable(false)` to
    /// disable focus for a scrollable box (e.g., auto-scroll chat messages).
    pub fn focusable(mut self, focusable: bool) -> Self {
        self.focusable = Some(focusable);
        self
    }

    pub fn min_width(mut self, width: u16) -> Self {
        self.min_width = Some(width);
        self
    }

    pub fn max_width(mut self, width: u16) -> Self {
        self.max_width = Some(width);
        self
    }

    pub fn min_height(mut self, height: u16) -> Self {
        self.min_height = Some(height);
        self
    }

    pub fn max_height(mut self, height: u16) -> Self {
        self.max_height = Some(height);
        self
    }

    pub fn build(self) -> View {
        // Scrollable boxes are focusable by default so users can scroll back
        let default_focusable = self.scroll || self.auto_scroll_bottom;
        View::Box(BoxNode {
            child: self.child.map(std::boxed::Box::new),
            border: self.border,
            padding: self.padding,
            flex: self.flex,
            scroll: self.scroll,
            auto_scroll_bottom: self.auto_scroll_bottom,
            focusable: self.focusable.unwrap_or(default_focusable),
            min_width: self.min_width,
            max_width: self.max_width,
            min_height: self.min_height,
            max_height: self.max_height,
        })
    }
}

/// Builder for List views.
#[derive(Default)]
pub struct ListBuilder {
    items: Vec<String>,
    selected: usize,
    on_select: Option<SelectCallback>,
}

impl ListBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn items(mut self, items: Vec<String>) -> Self {
        self.items = items;
        self
    }

    pub fn selected(mut self, selected: usize) -> Self {
        self.selected = selected;
        self
    }

    pub fn on_select(mut self, callback: impl Fn(usize) + 'static) -> Self {
        self.on_select = Some(Rc::new(callback));
        self
    }

    pub fn build(self) -> View {
        View::List(ListNode {
            items: self.items,
            selected: self.selected,
            on_select: self.on_select,
        })
    }
}

/// Builder for TextInput views.
#[derive(Default)]
pub struct TextInputBuilder {
    value: String,
    placeholder: String,
    on_change: Option<ChangeCallback>,
    on_cursor_change: Option<CursorPosCallback>,
    on_submit: Option<Callback>,
    on_key_up: Option<Callback>,
    on_key_down: Option<Callback>,
    cursor_pos: usize,
    focused: bool,
}

impl TextInputBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.value = value.into();
        // Default cursor to end of value
        self.cursor_pos = self.value.len();
        self
    }

    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    pub fn on_change(mut self, callback: impl Fn(String) + 'static) -> Self {
        self.on_change = Some(Rc::new(callback));
        self
    }

    pub fn on_cursor_change(mut self, callback: impl Fn(usize) + 'static) -> Self {
        self.on_cursor_change = Some(Rc::new(callback));
        self
    }

    pub fn on_submit(mut self, callback: impl Fn() + 'static) -> Self {
        self.on_submit = Some(Rc::new(callback));
        self
    }

    /// Set callback for when Up arrow is pressed (e.g., for command history).
    pub fn on_key_up(mut self, callback: impl Fn() + 'static) -> Self {
        self.on_key_up = Some(Rc::new(callback));
        self
    }

    /// Set callback for when Down arrow is pressed (e.g., for command history).
    pub fn on_key_down(mut self, callback: impl Fn() + 'static) -> Self {
        self.on_key_down = Some(Rc::new(callback));
        self
    }

    pub fn cursor(mut self, pos: usize) -> Self {
        self.cursor_pos = pos;
        self
    }

    /// Set this input to have initial focus when the app starts.
    pub fn focused(mut self, focused: bool) -> Self {
        self.focused = focused;
        self
    }

    pub fn build(self) -> View {
        View::TextInput(TextInputNode {
            value: self.value.clone(),
            placeholder: self.placeholder,
            on_change: self.on_change,
            on_cursor_change: self.on_cursor_change,
            on_submit: self.on_submit,
            on_key_up: self.on_key_up,
            on_key_down: self.on_key_down,
            cursor_pos: self.cursor_pos.min(self.value.len()),
            focused: self.focused,
        })
    }
}

/// Builder for Checkbox views.
#[derive(Default)]
pub struct CheckboxBuilder {
    checked: bool,
    label: String,
    on_toggle: Option<ToggleCallback>,
}

impl CheckboxBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn checked(mut self, checked: bool) -> Self {
        self.checked = checked;
        self
    }

    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    pub fn on_toggle(mut self, callback: impl Fn(bool) + 'static) -> Self {
        self.on_toggle = Some(Rc::new(callback));
        self
    }

    pub fn build(self) -> View {
        View::Checkbox(CheckboxNode {
            checked: self.checked,
            label: self.label,
            on_toggle: self.on_toggle,
        })
    }
}

/// Builder for RadioGroup views.
#[derive(Default)]
pub struct RadioGroupBuilder {
    options: Vec<String>,
    selected: usize,
    label: Option<String>,
    on_change: Option<SelectCallback>,
}

impl RadioGroupBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the available options.
    pub fn options(mut self, options: Vec<impl Into<String>>) -> Self {
        self.options = options.into_iter().map(|s| s.into()).collect();
        self
    }

    /// Add a single option.
    pub fn option(mut self, option: impl Into<String>) -> Self {
        self.options.push(option.into());
        self
    }

    /// Set the currently selected option index.
    pub fn selected(mut self, selected: usize) -> Self {
        self.selected = selected;
        self
    }

    /// Set an optional label for the group.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Set the callback when selection changes.
    pub fn on_change(mut self, callback: impl Fn(usize) + 'static) -> Self {
        self.on_change = Some(Rc::new(callback));
        self
    }

    pub fn build(self) -> View {
        View::RadioGroup(RadioGroupNode {
            options: self.options,
            selected: self.selected,
            label: self.label,
            on_change: self.on_change,
        })
    }
}

/// Builder for styled Text views.
#[derive(Debug, Default)]
pub struct TextBuilder {
    content: String,
    color: Option<crossterm::style::Color>,
    bg_color: Option<crossterm::style::Color>,
    bold: bool,
    italic: bool,
    underline: bool,
    dim: bool,
}

impl TextBuilder {
    pub fn new(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            ..Default::default()
        }
    }

    /// Set the text color.
    pub fn color(mut self, color: crossterm::style::Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Set the background color.
    pub fn bg(mut self, color: crossterm::style::Color) -> Self {
        self.bg_color = Some(color);
        self
    }

    /// Make the text bold.
    pub fn bold(mut self) -> Self {
        self.bold = true;
        self
    }

    /// Make the text italic.
    pub fn italic(mut self) -> Self {
        self.italic = true;
        self
    }

    /// Underline the text.
    pub fn underline(mut self) -> Self {
        self.underline = true;
        self
    }

    /// Make the text dim/faded.
    pub fn dim(mut self) -> Self {
        self.dim = true;
        self
    }

    pub fn build(self) -> View {
        View::Text(TextNode {
            content: self.content,
            color: self.color,
            bg_color: self.bg_color,
            bold: self.bold,
            italic: self.italic,
            underline: self.underline,
            dim: self.dim,
        })
    }
}

/// Builder for TextArea views.
#[derive(Default)]
pub struct TextAreaBuilder {
    value: String,
    placeholder: String,
    on_change: Option<ChangeCallback>,
    on_cursor_change: Option<CursorChangeCallback>,
    cursor_line: usize,
    cursor_col: usize,
    rows: u16,
    wrap_width: Option<u16>,
}

impl TextAreaBuilder {
    pub fn new() -> Self {
        Self {
            rows: 5, // Default to 5 rows
            ..Default::default()
        }
    }

    /// Set the current text value.
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.value = value.into();
        self
    }

    /// Set the placeholder text shown when empty.
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Set the callback for when text changes.
    pub fn on_change(mut self, callback: impl Fn(String) + 'static) -> Self {
        self.on_change = Some(Rc::new(callback));
        self
    }

    /// Set the callback for when cursor position changes.
    pub fn on_cursor_change(mut self, callback: impl Fn(usize, usize) + 'static) -> Self {
        self.on_cursor_change = Some(Rc::new(callback));
        self
    }

    /// Set the cursor line position.
    pub fn cursor_line(mut self, line: usize) -> Self {
        self.cursor_line = line;
        self
    }

    /// Set the cursor column position.
    pub fn cursor_col(mut self, col: usize) -> Self {
        self.cursor_col = col;
        self
    }

    /// Set the number of visible rows.
    pub fn rows(mut self, rows: u16) -> Self {
        self.rows = rows;
        self
    }

    /// Set the width at which text automatically wraps to the next line.
    /// If not set, text is truncated at the display edge without wrapping.
    pub fn wrap_width(mut self, width: u16) -> Self {
        self.wrap_width = Some(width);
        self
    }

    pub fn build(self) -> View {
        View::TextArea(TextAreaNode {
            value: self.value,
            placeholder: self.placeholder,
            on_change: self.on_change,
            on_cursor_change: self.on_cursor_change,
            cursor_line: self.cursor_line,
            cursor_col: self.cursor_col,
            rows: self.rows,
            wrap_width: self.wrap_width,
        })
    }
}

/// Builder for Modal views.
#[derive(Default)]
pub struct ModalBuilder {
    visible: bool,
    title: String,
    child: Option<View>,
    on_dismiss: Option<Callback>,
    width_percent: u16,
    height_percent: u16,
}

impl ModalBuilder {
    pub fn new() -> Self {
        Self {
            width_percent: 60,
            height_percent: 50,
            ..Default::default()
        }
    }

    /// Set whether the modal is visible.
    pub fn visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// Set the title shown in the modal border.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Set the content of the modal.
    pub fn child(mut self, view: View) -> Self {
        self.child = Some(view);
        self
    }

    /// Set the callback when modal is dismissed (Escape key).
    pub fn on_dismiss(mut self, callback: impl Fn() + 'static) -> Self {
        self.on_dismiss = Some(Rc::new(callback));
        self
    }

    /// Set the width as percentage of screen (0-100).
    pub fn width(mut self, percent: u16) -> Self {
        self.width_percent = percent.min(100);
        self
    }

    /// Set the height as percentage of screen (0-100).
    pub fn height(mut self, percent: u16) -> Self {
        self.height_percent = percent.min(100);
        self
    }

    pub fn build(self) -> View {
        View::Modal(ModalNode {
            visible: self.visible,
            title: self.title,
            child: self.child.map(std::boxed::Box::new),
            on_dismiss: self.on_dismiss,
            width_percent: self.width_percent,
            height_percent: self.height_percent,
        })
    }
}

/// Builder for Split pane views.
#[derive(Default)]
pub struct SplitBuilder {
    orientation: Orientation,
    first: Option<View>,
    second: Option<View>,
    ratio: f32,
    min_first: Option<u16>,
    min_second: Option<u16>,
    show_divider: bool,
}

impl SplitBuilder {
    pub fn new() -> Self {
        Self {
            ratio: 0.5, // Default to equal split
            show_divider: true,
            ..Default::default()
        }
    }

    /// Set the orientation to horizontal (side by side).
    pub fn horizontal(mut self) -> Self {
        self.orientation = Orientation::Horizontal;
        self
    }

    /// Set the orientation to vertical (stacked).
    pub fn vertical(mut self) -> Self {
        self.orientation = Orientation::Vertical;
        self
    }

    /// Set the first pane content.
    pub fn first(mut self, view: View) -> Self {
        self.first = Some(view);
        self
    }

    /// Set the second pane content.
    pub fn second(mut self, view: View) -> Self {
        self.second = Some(view);
        self
    }

    /// Set the split ratio (0.0 to 1.0, where 0.5 is equal split).
    pub fn ratio(mut self, ratio: f32) -> Self {
        self.ratio = ratio.clamp(0.0, 1.0);
        self
    }

    /// Set the minimum size for the first pane (in cells).
    pub fn min_first(mut self, min: u16) -> Self {
        self.min_first = Some(min);
        self
    }

    /// Set the minimum size for the second pane (in cells).
    pub fn min_second(mut self, min: u16) -> Self {
        self.min_second = Some(min);
        self
    }

    /// Set whether to show a divider line between panes.
    pub fn show_divider(mut self, show: bool) -> Self {
        self.show_divider = show;
        self
    }

    pub fn build(self) -> View {
        View::Split(SplitNode {
            orientation: self.orientation,
            first: std::boxed::Box::new(self.first.unwrap_or(View::Empty)),
            second: std::boxed::Box::new(self.second.unwrap_or(View::Empty)),
            ratio: self.ratio,
            min_first: self.min_first,
            min_second: self.min_second,
            show_divider: self.show_divider,
        })
    }
}

/// Builder for Tabs views.
#[derive(Default)]
pub struct TabsBuilder {
    tabs: Vec<String>,
    children: Vec<View>,
    active: usize,
    on_change: Option<SelectCallback>,
    position: TabPosition,
}

impl TabsBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a tab with a label and content view.
    pub fn tab(mut self, label: impl Into<String>, content: View) -> Self {
        self.tabs.push(label.into());
        self.children.push(content);
        self
    }

    /// Set the active tab index.
    pub fn active(mut self, index: usize) -> Self {
        self.active = index;
        self
    }

    /// Set the callback when tab changes.
    pub fn on_change(mut self, callback: impl Fn(usize) + 'static) -> Self {
        self.on_change = Some(Rc::new(callback));
        self
    }

    /// Set the position of the tab bar.
    pub fn position(mut self, position: TabPosition) -> Self {
        self.position = position;
        self
    }

    pub fn build(self) -> View {
        View::Tabs(TabsNode {
            tabs: self.tabs,
            children: self.children,
            active: self.active,
            on_change: self.on_change,
            position: self.position,
        })
    }
}

/// Builder for Tree views.
#[derive(Default)]
pub struct TreeBuilder {
    items: Vec<TreeItem>,
    selected: TreePath,
    on_select: Option<TreeSelectCallback>,
    on_activate: Option<TreeActivateCallback>,
}

impl TreeBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the tree items.
    pub fn items(mut self, items: Vec<TreeItem>) -> Self {
        self.items = items;
        self
    }

    /// Add a single root item.
    pub fn item(mut self, item: TreeItem) -> Self {
        self.items.push(item);
        self
    }

    /// Set the selected path.
    pub fn selected(mut self, path: TreePath) -> Self {
        self.selected = path;
        self
    }

    /// Set the callback when selection changes.
    pub fn on_select(mut self, callback: impl Fn(TreePath) + 'static) -> Self {
        self.on_select = Some(Rc::new(callback));
        self
    }

    /// Set the callback when an item is activated.
    pub fn on_activate(mut self, callback: impl Fn(TreePath) + 'static) -> Self {
        self.on_activate = Some(Rc::new(callback));
        self
    }

    pub fn build(self) -> View {
        View::Tree(TreeNode {
            items: self.items,
            selected: self.selected,
            on_select: self.on_select,
            on_activate: self.on_activate,
        })
    }
}

/// Builder for Table views.
#[derive(Default)]
pub struct TableBuilder {
    columns: Vec<TableColumn>,
    rows: Vec<Vec<String>>,
    selected: usize,
    sort: Option<(usize, bool)>,
    on_select: Option<SelectCallback>,
    on_sort: Option<SortCallback>,
    on_activate: Option<RowActivateCallback>,
}

impl TableBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a column with just a header (auto width, left aligned, not sortable).
    pub fn column(mut self, header: impl Into<String>) -> Self {
        self.columns.push(TableColumn::new(header));
        self
    }

    /// Add a column with full configuration.
    pub fn column_with(mut self, column: TableColumn) -> Self {
        self.columns.push(column);
        self
    }

    /// Set the row data.
    pub fn rows(mut self, rows: Vec<Vec<String>>) -> Self {
        self.rows = rows;
        self
    }

    /// Add a single row.
    pub fn row(mut self, row: Vec<String>) -> Self {
        self.rows.push(row);
        self
    }

    /// Set the selected row index.
    pub fn selected(mut self, index: usize) -> Self {
        self.selected = index;
        self
    }

    /// Set the sort state (column index, ascending).
    pub fn sort(mut self, sort: Option<(usize, bool)>) -> Self {
        self.sort = sort;
        self
    }

    /// Set the sort state with explicit column and direction.
    pub fn sort_by(mut self, column: usize, ascending: bool) -> Self {
        self.sort = Some((column, ascending));
        self
    }

    /// Set the callback when selection changes.
    pub fn on_select(mut self, callback: impl Fn(usize) + 'static) -> Self {
        self.on_select = Some(Rc::new(callback));
        self
    }

    /// Set the callback when sort changes.
    pub fn on_sort(mut self, callback: impl Fn(usize, bool) + 'static) -> Self {
        self.on_sort = Some(Rc::new(callback));
        self
    }

    /// Set the callback when a row is activated.
    pub fn on_activate(mut self, callback: impl Fn(usize) + 'static) -> Self {
        self.on_activate = Some(Rc::new(callback));
        self
    }

    pub fn build(self) -> View {
        View::Table(TableNode {
            columns: self.columns,
            rows: self.rows,
            selected: self.selected,
            sort: self.sort,
            on_select: self.on_select,
            on_sort: self.on_sort,
            on_activate: self.on_activate,
        })
    }
}

/// Builder for ProgressBar views.
#[derive(Debug, Clone)]
pub struct ProgressBarBuilder {
    value: f32,
    label: Option<String>,
    show_percentage: bool,
    width: Option<u16>,
    filled_char: char,
    empty_char: char,
}

impl Default for ProgressBarBuilder {
    fn default() -> Self {
        Self {
            value: 0.0,
            label: None,
            show_percentage: true,
            width: None,
            filled_char: 'â–ˆ',
            empty_char: 'â–‘',
        }
    }
}

impl ProgressBarBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the progress value (0.0 to 1.0).
    pub fn value(mut self, value: f32) -> Self {
        self.value = value.clamp(0.0, 1.0);
        self
    }

    /// Set a label shown before the bar.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Set whether to show percentage after the bar (default: true).
    pub fn show_percentage(mut self, show: bool) -> Self {
        self.show_percentage = show;
        self
    }

    /// Set a fixed width for the bar portion.
    /// If not set, the bar expands to fill available space.
    pub fn width(mut self, width: u16) -> Self {
        self.width = Some(width);
        self
    }

    /// Set the character used for the filled portion (default: â–ˆ).
    pub fn filled_char(mut self, ch: char) -> Self {
        self.filled_char = ch;
        self
    }

    /// Set the character used for the empty portion (default: â–‘).
    pub fn empty_char(mut self, ch: char) -> Self {
        self.empty_char = ch;
        self
    }

    pub fn build(self) -> View {
        View::ProgressBar(ProgressBarNode {
            value: self.value,
            label: self.label,
            show_percentage: self.show_percentage,
            width: self.width,
            filled_char: self.filled_char,
            empty_char: self.empty_char,
        })
    }
}

/// Builder for StatusBar views.
#[derive(Debug, Clone, Default)]
pub struct StatusBarBuilder {
    left: String,
    center: Option<String>,
    right: Option<String>,
    bg_color: Option<crossterm::style::Color>,
    fg_color: Option<crossterm::style::Color>,
}

impl StatusBarBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the left section content.
    pub fn left(mut self, content: impl Into<String>) -> Self {
        self.left = content.into();
        self
    }

    /// Set the center section content.
    pub fn center(mut self, content: impl Into<String>) -> Self {
        self.center = Some(content.into());
        self
    }

    /// Set the right section content.
    pub fn right(mut self, content: impl Into<String>) -> Self {
        self.right = Some(content.into());
        self
    }

    /// Set the background color.
    pub fn bg(mut self, color: crossterm::style::Color) -> Self {
        self.bg_color = Some(color);
        self
    }

    /// Set the foreground (text) color.
    pub fn fg(mut self, color: crossterm::style::Color) -> Self {
        self.fg_color = Some(color);
        self
    }

    pub fn build(self) -> View {
        View::StatusBar(StatusBarNode {
            left: self.left,
            center: self.center,
            right: self.right,
            bg_color: self.bg_color,
            fg_color: self.fg_color,
        })
    }
}

// =============================================================================
// Command Palette
// =============================================================================

/// A command in the command palette.
#[derive(Clone)]
pub struct PaletteCommand {
    /// Unique identifier for the command.
    pub id: &'static str,
    /// Display label.
    pub label: String,
    /// Optional keyboard shortcut display (e.g., "Ctrl+S").
    pub shortcut: Option<String>,
    /// Optional category for grouping.
    pub category: Option<String>,
}

impl PaletteCommand {
    /// Create a new palette command.
    pub fn new(id: &'static str, label: impl Into<String>) -> Self {
        Self {
            id,
            label: label.into(),
            shortcut: None,
            category: None,
        }
    }

    /// Set the shortcut display string.
    pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
        self.shortcut = Some(shortcut.into());
        self
    }

    /// Set the category.
    pub fn category(mut self, category: impl Into<String>) -> Self {
        self.category = Some(category.into());
        self
    }
}

/// A command palette overlay for searching and executing commands.
#[derive(Clone)]
pub struct CommandPaletteNode {
    /// Whether the palette is visible.
    pub visible: bool,
    /// Current search query.
    pub query: String,
    /// Available commands.
    pub commands: Vec<PaletteCommand>,
    /// Currently selected index in the filtered list.
    pub selected: usize,
    /// Callback when query changes.
    pub on_query_change: Option<ChangeCallback>,
    /// Callback when a command is selected (receives command ID).
    pub on_select: Option<CommandCallback>,
    /// Callback when the palette is dismissed.
    pub on_dismiss: Option<Callback>,
    /// Width percentage (0-100).
    pub width_percent: u16,
    /// Height percentage (0-100).
    pub height_percent: u16,
}

/// Builder for CommandPalette views.
#[derive(Default)]
pub struct CommandPaletteBuilder {
    visible: bool,
    query: String,
    commands: Vec<PaletteCommand>,
    selected: usize,
    on_query_change: Option<ChangeCallback>,
    on_select: Option<CommandCallback>,
    on_dismiss: Option<Callback>,
    width_percent: u16,
    height_percent: u16,
}

impl CommandPaletteBuilder {
    pub fn new() -> Self {
        Self {
            width_percent: 50,
            height_percent: 60,
            ..Default::default()
        }
    }

    /// Set whether the palette is visible.
    pub fn visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// Set the current query.
    pub fn query(mut self, query: impl Into<String>) -> Self {
        self.query = query.into();
        self
    }

    /// Set the available commands.
    pub fn commands(mut self, commands: Vec<PaletteCommand>) -> Self {
        self.commands = commands;
        self
    }

    /// Add a single command.
    pub fn command(mut self, command: PaletteCommand) -> Self {
        self.commands.push(command);
        self
    }

    /// Set the selected index.
    pub fn selected(mut self, selected: usize) -> Self {
        self.selected = selected;
        self
    }

    /// Set the callback for query changes.
    pub fn on_query_change(mut self, callback: impl Fn(String) + 'static) -> Self {
        self.on_query_change = Some(Rc::new(callback));
        self
    }

    /// Set the callback for command selection.
    pub fn on_select(mut self, callback: impl Fn(&'static str) + 'static) -> Self {
        self.on_select = Some(Rc::new(callback));
        self
    }

    /// Set the callback when dismissed.
    pub fn on_dismiss(mut self, callback: impl Fn() + 'static) -> Self {
        self.on_dismiss = Some(Rc::new(callback));
        self
    }

    /// Set the width as percentage of screen.
    pub fn width(mut self, percent: u16) -> Self {
        self.width_percent = percent.min(100);
        self
    }

    /// Set the height as percentage of screen.
    pub fn height(mut self, percent: u16) -> Self {
        self.height_percent = percent.min(100);
        self
    }

    pub fn build(self) -> View {
        View::CommandPalette(CommandPaletteNode {
            visible: self.visible,
            query: self.query,
            commands: self.commands,
            selected: self.selected,
            on_query_change: self.on_query_change,
            on_select: self.on_select,
            on_dismiss: self.on_dismiss,
            width_percent: self.width_percent,
            height_percent: self.height_percent,
        })
    }
}

// =============================================================================
// Menu Bar
// =============================================================================

/// A menu in the menu bar.
#[derive(Clone)]
pub struct Menu {
    /// Display label for the menu.
    pub label: String,
    /// Items in this menu.
    pub items: Vec<MenuItemNode>,
}

impl Menu {
    /// Create a new menu with the given label.
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            items: Vec::new(),
        }
    }

    /// Add an item to the menu.
    pub fn item(mut self, item: MenuItemNode) -> Self {
        self.items.push(item);
        self
    }

    /// Add a command item.
    pub fn command(self, id: &'static str, label: impl Into<String>) -> Self {
        self.item(MenuItemNode::Command {
            id,
            label: label.into(),
            shortcut: None,
        })
    }

    /// Add a command item with shortcut display.
    pub fn command_with_shortcut(
        self,
        id: &'static str,
        label: impl Into<String>,
        shortcut: impl Into<String>,
    ) -> Self {
        self.item(MenuItemNode::Command {
            id,
            label: label.into(),
            shortcut: Some(shortcut.into()),
        })
    }

    /// Add a separator.
    pub fn separator(self) -> Self {
        self.item(MenuItemNode::Separator)
    }
}

/// An item in a menu.
#[derive(Clone)]
pub enum MenuItemNode {
    /// A command with ID, label, and optional shortcut display.
    Command {
        id: &'static str,
        label: String,
        shortcut: Option<String>,
    },
    /// A visual separator.
    Separator,
}

/// A horizontal menu bar with dropdown menus.
#[derive(Clone)]
pub struct MenuBarNode {
    /// The menus in the menu bar.
    pub menus: Vec<Menu>,
    /// Currently active (open) menu index, if any.
    pub active_menu: Option<usize>,
    /// Currently highlighted menu index (for keyboard navigation when no menu is open).
    pub highlighted_menu: usize,
    /// Currently selected item in the active menu.
    pub selected_item: usize,
    /// Callback when a command is selected.
    pub on_select: Option<CommandCallback>,
    /// Callback when the active menu changes (opens/closes).
    pub on_menu_change: Option<SelectCallback>,
    /// Callback when the highlighted menu changes (arrow key navigation).
    pub on_highlight_change: Option<SelectCallback>,
    /// Callback when the selected item within a menu changes.
    pub on_item_change: Option<SelectCallback>,
}

/// Builder for MenuBar views.
#[derive(Default)]
pub struct MenuBarBuilder {
    menus: Vec<Menu>,
    active_menu: Option<usize>,
    highlighted_menu: usize,
    selected_item: usize,
    on_select: Option<CommandCallback>,
    on_menu_change: Option<SelectCallback>,
    on_highlight_change: Option<SelectCallback>,
    on_item_change: Option<SelectCallback>,
}

impl MenuBarBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a menu to the menu bar.
    pub fn menu(mut self, menu: Menu) -> Self {
        self.menus.push(menu);
        self
    }

    /// Set the active menu index (which menu has its dropdown open).
    pub fn active_menu(mut self, index: Option<usize>) -> Self {
        self.active_menu = index;
        self
    }

    /// Set the highlighted menu index (for keyboard navigation).
    pub fn highlighted_menu(mut self, index: usize) -> Self {
        self.highlighted_menu = index;
        self
    }

    /// Set the selected item in the active menu.
    pub fn selected_item(mut self, index: usize) -> Self {
        self.selected_item = index;
        self
    }

    /// Set the callback for command selection.
    pub fn on_select(mut self, callback: impl Fn(&'static str) + 'static) -> Self {
        self.on_select = Some(Rc::new(callback));
        self
    }

    /// Set the callback for menu changes (opens/closes dropdown).
    pub fn on_menu_change(mut self, callback: impl Fn(usize) + 'static) -> Self {
        self.on_menu_change = Some(Rc::new(callback));
        self
    }

    /// Set the callback for highlight changes (arrow key navigation).
    pub fn on_highlight_change(mut self, callback: impl Fn(usize) + 'static) -> Self {
        self.on_highlight_change = Some(Rc::new(callback));
        self
    }

    /// Set the callback for item selection changes within a menu.
    pub fn on_item_change(mut self, callback: impl Fn(usize) + 'static) -> Self {
        self.on_item_change = Some(Rc::new(callback));
        self
    }

    pub fn build(self) -> View {
        View::MenuBar(MenuBarNode {
            menus: self.menus,
            active_menu: self.active_menu,
            highlighted_menu: self.highlighted_menu,
            selected_item: self.selected_item,
            on_select: self.on_select,
            on_menu_change: self.on_menu_change,
            on_highlight_change: self.on_highlight_change,
            on_item_change: self.on_item_change,
        })
    }
}

// =============================================================================
// Toast Container
// =============================================================================

/// Position for toast notifications.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ToastPosition {
    /// Top-right corner.
    TopRight,
    /// Top-left corner.
    TopLeft,
    /// Bottom-right corner (default).
    #[default]
    BottomRight,
    /// Bottom-left corner.
    BottomLeft,
}

/// Severity level for visual rendering of toasts.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ToastLevelView {
    /// Informational (default).
    #[default]
    Info,
    /// Success.
    Success,
    /// Warning.
    Warning,
    /// Error.
    Error,
}

/// A toast item for rendering.
#[derive(Clone)]
pub struct ToastItem {
    /// The message to display.
    pub message: String,
    /// Severity level.
    pub level: ToastLevelView,
    /// Progress (0.0 to 1.0) for fade-out animation.
    pub progress: f32,
}

/// A container for displaying toast notifications.
#[derive(Clone)]
pub struct ToastContainerNode {
    /// The toasts to display.
    pub toasts: Vec<ToastItem>,
    /// Position of the toast container.
    pub position: ToastPosition,
    /// Maximum number of visible toasts.
    pub max_visible: usize,
    /// Width of each toast (in characters).
    pub width: u16,
}

/// Builder for ToastContainer views.
#[derive(Default)]
pub struct ToastContainerBuilder {
    toasts: Vec<ToastItem>,
    position: ToastPosition,
    max_visible: usize,
    width: u16,
}

impl ToastContainerBuilder {
    pub fn new() -> Self {
        Self {
            toasts: Vec::new(),
            position: ToastPosition::BottomRight,
            max_visible: 5,
            width: 40,
        }
    }

    /// Set the toasts to display.
    pub fn toasts(mut self, toasts: Vec<ToastItem>) -> Self {
        self.toasts = toasts;
        self
    }

    /// Add a toast from the toast queue system.
    pub fn from_queue(mut self, queue: &crate::toast::ToastQueue) -> Self {
        let toasts = queue.collect();
        self.toasts = toasts
            .into_iter()
            .map(|t| {
                let progress = t.remaining_fraction();
                let level = match t.level {
                    crate::toast::ToastLevel::Info => ToastLevelView::Info,
                    crate::toast::ToastLevel::Success => ToastLevelView::Success,
                    crate::toast::ToastLevel::Warning => ToastLevelView::Warning,
                    crate::toast::ToastLevel::Error => ToastLevelView::Error,
                };
                ToastItem {
                    message: t.message,
                    level,
                    progress,
                }
            })
            .collect();
        self
    }

    /// Set the position of the toast container.
    pub fn position(mut self, position: ToastPosition) -> Self {
        self.position = position;
        self
    }

    /// Set the maximum number of visible toasts.
    pub fn max_visible(mut self, max: usize) -> Self {
        self.max_visible = max;
        self
    }

    /// Set the width of each toast.
    pub fn width(mut self, width: u16) -> Self {
        self.width = width;
        self
    }

    pub fn build(self) -> View {
        View::ToastContainer(ToastContainerNode {
            toasts: self.toasts,
            position: self.position,
            max_visible: self.max_visible,
            width: self.width,
        })
    }
}

// =============================================================================
// Form
// =============================================================================

/// Callback type for form submission (receives all field values).
pub type FormSubmitCallback = Rc<dyn Fn(std::collections::HashMap<String, String>)>;

/// A form container that manages field validation.
#[derive(Clone)]
pub struct FormNode {
    /// Child views (typically FormField nodes).
    pub children: Vec<View>,
    /// Callback when form is submitted (all fields valid).
    pub on_submit: Option<FormSubmitCallback>,
    /// Spacing between children.
    pub spacing: u16,
}

/// Builder for Form views.
#[derive(Default)]
pub struct FormBuilder {
    children: Vec<View>,
    on_submit: Option<FormSubmitCallback>,
    spacing: u16,
}

impl FormBuilder {
    pub fn new() -> Self {
        Self {
            spacing: 1,
            ..Default::default()
        }
    }

    /// Add a child view (typically a FormField).
    pub fn child(mut self, view: View) -> Self {
        self.children.push(view);
        self
    }

    /// Set spacing between children.
    pub fn spacing(mut self, spacing: u16) -> Self {
        self.spacing = spacing;
        self
    }

    /// Set the submit callback.
    pub fn on_submit(
        mut self,
        callback: impl Fn(std::collections::HashMap<String, String>) + 'static,
    ) -> Self {
        self.on_submit = Some(Rc::new(callback));
        self
    }

    pub fn build(self) -> View {
        View::Form(FormNode {
            children: self.children,
            on_submit: self.on_submit,
            spacing: self.spacing,
        })
    }
}

// =============================================================================
// Form Field
// =============================================================================

/// A form field with label, input, and error display.
#[derive(Clone)]
pub struct FormFieldNode {
    /// Field name (identifier).
    pub name: String,
    /// Display label.
    pub label: String,
    /// Current value.
    pub value: String,
    /// Placeholder text.
    pub placeholder: String,
    /// Error message (if validation failed).
    pub error: Option<String>,
    /// Whether this is a password field (mask input).
    pub password: bool,
    /// Callback when value changes.
    pub on_change: Option<ChangeCallback>,
    /// Callback when field loses focus (for validation).
    pub on_blur: Option<Callback>,
    /// Cursor position.
    pub cursor_pos: usize,
}

/// Builder for FormField views.
#[derive(Default)]
pub struct FormFieldBuilder {
    name: String,
    label: String,
    value: String,
    placeholder: String,
    error: Option<String>,
    password: bool,
    on_change: Option<ChangeCallback>,
    on_blur: Option<Callback>,
    cursor_pos: usize,
}

impl FormFieldBuilder {
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        Self {
            label: name.clone(),
            name,
            ..Default::default()
        }
    }

    /// Set the display label.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Set the current value.
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.value = value.into();
        self.cursor_pos = self.value.len();
        self
    }

    /// Set the placeholder text.
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Set the error message.
    pub fn error(mut self, error: Option<String>) -> Self {
        self.error = error;
        self
    }

    /// Set whether this is a password field.
    pub fn password(mut self, password: bool) -> Self {
        self.password = password;
        self
    }

    /// Set the change callback.
    pub fn on_change(mut self, callback: impl Fn(String) + 'static) -> Self {
        self.on_change = Some(Rc::new(callback));
        self
    }

    /// Set the blur callback.
    pub fn on_blur(mut self, callback: impl Fn() + 'static) -> Self {
        self.on_blur = Some(Rc::new(callback));
        self
    }

    /// Set the cursor position.
    pub fn cursor(mut self, pos: usize) -> Self {
        self.cursor_pos = pos;
        self
    }

    pub fn build(self) -> View {
        View::FormField(FormFieldNode {
            name: self.name,
            label: self.label,
            value: self.value.clone(),
            placeholder: self.placeholder,
            error: self.error,
            password: self.password,
            on_change: self.on_change,
            on_blur: self.on_blur,
            cursor_pos: self.cursor_pos.min(self.value.len()),
        })
    }
}

// =============================================================================
// Canvas Widget
// =============================================================================

/// A canvas node for pixel-level drawing using Kitty graphics protocol.
#[derive(Clone)]
pub struct CanvasNode {
    /// Width in pixels.
    pub pixel_width: u16,
    /// Height in pixels.
    pub pixel_height: u16,
    /// Callback to draw on the canvas.
    pub on_draw: Option<CanvasDrawCallback>,
    /// Unique ID for this canvas (for Kitty image caching).
    pub id: u32,
}

/// Builder for Canvas views.
pub struct CanvasBuilder {
    pixel_width: u16,
    pixel_height: u16,
    on_draw: Option<CanvasDrawCallback>,
    id: u32,
}

impl Default for CanvasBuilder {
    fn default() -> Self {
        use std::sync::atomic::{AtomicU32, Ordering};
        static NEXT_ID: AtomicU32 = AtomicU32::new(1);

        Self {
            pixel_width: 100,
            pixel_height: 50,
            on_draw: None,
            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
        }
    }
}

impl CanvasBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the canvas width in pixels.
    pub fn width(mut self, width: u16) -> Self {
        self.pixel_width = width;
        self
    }

    /// Set the canvas height in pixels.
    pub fn height(mut self, height: u16) -> Self {
        self.pixel_height = height;
        self
    }

    /// Set the draw callback.
    ///
    /// This callback receives a `DrawContext` and is called each render
    /// to draw the canvas content.
    pub fn on_draw<F>(mut self, callback: F) -> Self
    where
        F: Fn(&mut crate::canvas::DrawContext) + 'static,
    {
        self.on_draw = Some(Rc::new(callback));
        self
    }

    /// Set a specific canvas ID (for manual caching control).
    pub fn id(mut self, id: u32) -> Self {
        self.id = id;
        self
    }

    pub fn build(self) -> View {
        View::Canvas(CanvasNode {
            pixel_width: self.pixel_width,
            pixel_height: self.pixel_height,
            on_draw: self.on_draw,
            id: self.id,
        })
    }
}

// =============================================================================
// Image Widget
// =============================================================================

/// An image node for displaying images using Kitty graphics protocol.
#[derive(Clone)]
pub struct ImageNode {
    /// Image data source (bytes or file path).
    pub source: Option<crate::image::ImageSource>,
    /// Unique ID for this image (for Kitty caching).
    pub id: u32,
    /// Explicit width in cells (overrides auto-detection).
    pub cell_width: Option<u16>,
    /// Explicit height in cells (overrides auto-detection).
    pub cell_height: Option<u16>,
    /// Alt text for accessibility / fallback display.
    pub alt: Option<String>,
}

/// Builder for Image views.
pub struct ImageBuilder {
    source: Option<crate::image::ImageSource>,
    id: u32,
    cell_width: Option<u16>,
    cell_height: Option<u16>,
    alt: Option<String>,
}

impl Default for ImageBuilder {
    fn default() -> Self {
        Self {
            source: None,
            id: crate::image::next_image_id(),
            cell_width: None,
            cell_height: None,
            alt: None,
        }
    }
}

impl ImageBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the image data from raw bytes.
    ///
    /// Supports PNG, JPEG, and GIF formats. Kitty auto-detects the format.
    /// GIF animations are handled natively by Kitty.
    ///
    /// # Example
    /// ```rust,ignore
    /// View::image()
    ///     .data(include_bytes!("logo.png"))
    ///     .build()
    /// ```
    pub fn data(mut self, bytes: &[u8]) -> Self {
        self.source = Some(crate::image::ImageSource::Data(bytes.to_vec()));

        // Try to detect dimensions for layout
        if let Some((w, h)) = crate::image::detect_image_dimensions(bytes) {
            let (cw, ch) = crate::image::pixels_to_cells(w, h);
            if self.cell_width.is_none() {
                self.cell_width = Some(cw);
            }
            if self.cell_height.is_none() {
                self.cell_height = Some(ch);
            }
        }

        self
    }

    /// Set the image source from a file path.
    ///
    /// The file is loaded at render time.
    ///
    /// # Example
    /// ```rust,ignore
    /// View::image()
    ///     .file("assets/animation.gif")
    ///     .build()
    /// ```
    pub fn file(mut self, path: impl Into<String>) -> Self {
        self.source = Some(crate::image::ImageSource::File(path.into()));
        self
    }

    /// Set explicit width in terminal cells.
    pub fn width(mut self, cells: u16) -> Self {
        self.cell_width = Some(cells);
        self
    }

    /// Set explicit height in terminal cells.
    pub fn height(mut self, cells: u16) -> Self {
        self.cell_height = Some(cells);
        self
    }

    /// Set a specific image ID (for manual caching control).
    pub fn id(mut self, id: u32) -> Self {
        self.id = id;
        self
    }

    /// Set alt text for accessibility or fallback display.
    pub fn alt(mut self, text: impl Into<String>) -> Self {
        self.alt = Some(text.into());
        self
    }

    pub fn build(self) -> View {
        View::Image(ImageNode {
            source: self.source,
            id: self.id,
            cell_width: self.cell_width,
            cell_height: self.cell_height,
            alt: self.alt,
        })
    }
}

/// Node representing an interactive PTY terminal emulator.
///
/// **Experimental Preview** - See `View::terminal()` for limitations.
#[derive(Clone)]
pub struct TerminalNode {
    /// Handle to the running PTY process.
    pub handle: crate::terminal_state::TerminalHandle,
    /// Visible rows (defaults to 24).
    pub rows: usize,
    /// Visible columns (defaults to 80).
    pub cols: usize,
    /// Show border around terminal.
    pub border: bool,
    /// Title displayed in border (if border is enabled).
    pub title: Option<String>,
    /// Callback invoked when the PTY process exits.
    pub on_exit: Option<Callback>,
}

/// Builder for Terminal views.
pub struct TerminalBuilder {
    handle: Option<crate::terminal_state::TerminalHandle>,
    rows: usize,
    cols: usize,
    border: bool,
    title: Option<String>,
    on_exit: Option<Callback>,
}

impl Default for TerminalBuilder {
    fn default() -> Self {
        Self {
            handle: None,
            rows: 24,
            cols: 80,
            border: true,
            title: Some("Terminal".to_string()),
            on_exit: None,
        }
    }
}

impl TerminalBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the terminal handle (required).
    ///
    /// Get a handle from `cx.use_terminal()` in your component.
    pub fn handle(mut self, handle: crate::terminal_state::TerminalHandle) -> Self {
        self.handle = Some(handle);
        self
    }

    /// Set the number of visible rows (default: 24).
    pub fn rows(mut self, rows: usize) -> Self {
        self.rows = rows;
        self
    }

    /// Set the number of visible columns (default: 80).
    pub fn cols(mut self, cols: usize) -> Self {
        self.cols = cols;
        self
    }

    /// Enable or disable border (default: true).
    pub fn border(mut self, border: bool) -> Self {
        self.border = border;
        self
    }

    /// Set the border title (default: "Terminal").
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set a callback to be invoked when the PTY process exits.
    pub fn on_exit(mut self, callback: impl Fn() + 'static) -> Self {
        self.on_exit = Some(Rc::new(callback));
        self
    }

    pub fn build(self) -> View {
        View::Terminal(TerminalNode {
            handle: self.handle.expect("Terminal requires a handle (from cx.use_terminal())"),
            rows: self.rows,
            cols: self.cols,
            border: self.border,
            title: self.title,
            on_exit: self.on_exit,
        })
    }
}

// ========== Error Boundary ==========

/// An error boundary that catches panics in its child view.
///
/// During rendering, if the child view panics, the fallback view is
/// displayed instead. This prevents a single misbehaving component
/// from crashing the entire application.
#[derive(Clone)]
pub struct ErrorBoundaryNode {
    /// The child view to render (may panic).
    pub child: Box<View>,
    /// The fallback view shown when the child panics.
    pub fallback: Box<View>,
}

/// Builder for error boundary views.
#[derive(Default)]
pub struct ErrorBoundaryBuilder {
    child: Option<View>,
    fallback: Option<View>,
}

impl ErrorBoundaryBuilder {
    pub fn new() -> Self {
        Self {
            child: None,
            fallback: None,
        }
    }

    /// Set the child view (the view that might panic).
    pub fn child(mut self, child: View) -> Self {
        self.child = Some(child);
        self
    }

    /// Set the fallback view (shown when child panics).
    pub fn fallback(mut self, fallback: View) -> Self {
        self.fallback = Some(fallback);
        self
    }

    pub fn build(self) -> View {
        View::ErrorBoundary(ErrorBoundaryNode {
            child: Box::new(self.child.unwrap_or(View::Empty)),
            fallback: Box::new(
                self.fallback
                    .unwrap_or_else(|| View::text("[error boundary: child panicked]")),
            ),
        })
    }
}

// ========== Custom Widget ==========

/// A node wrapping a user-defined custom widget.
///
/// Uses `Rc<RefCell<dyn Widget>>` because:
/// - `Rc` enables Clone (View derives Clone) without requiring Widget: Clone
/// - `RefCell` allows interior mutability for focus handling
#[derive(Clone)]
pub struct CustomNode {
    pub widget: Rc<RefCell<dyn Widget>>,
}

// ========== Slider ==========

/// A slider for bounded numeric values (e.g., MIDI CC, volume, brightness).
#[derive(Clone)]
pub struct SliderNode {
    pub min: f64,
    pub max: f64,
    pub value: f64,
    pub step: f64,
    pub label: Option<String>,
    pub on_change: Option<SliderCallback>,
    pub color: Option<crossterm::style::Color>,
}

/// Builder for slider views.
#[derive(Default)]
pub struct SliderBuilder {
    min: f64,
    max: f64,
    value: f64,
    step: f64,
    label: Option<String>,
    on_change: Option<SliderCallback>,
    color: Option<crossterm::style::Color>,
}

impl SliderBuilder {
    pub fn new() -> Self {
        Self {
            min: 0.0,
            max: 100.0,
            value: 0.0,
            step: 1.0,
            label: None,
            on_change: None,
            color: None,
        }
    }

    pub fn min(mut self, min: f64) -> Self {
        self.min = min;
        self
    }

    pub fn max(mut self, max: f64) -> Self {
        self.max = max;
        self
    }

    pub fn value(mut self, value: f64) -> Self {
        self.value = value;
        self
    }

    pub fn step(mut self, step: f64) -> Self {
        self.step = step;
        self
    }

    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    pub fn on_change(mut self, callback: impl Fn(f64) + 'static) -> Self {
        self.on_change = Some(Rc::new(callback));
        self
    }

    pub fn color(mut self, color: crossterm::style::Color) -> Self {
        self.color = Some(color);
        self
    }

    pub fn build(self) -> View {
        View::Slider(SliderNode {
            min: self.min,
            max: self.max,
            value: self.value.clamp(self.min, self.max),
            step: self.step,
            label: self.label,
            on_change: self.on_change,
            color: self.color,
        })
    }
}