rusticity-term 0.1.5

Terminal UI components for Rusticity
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
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
pub mod apig;
pub mod cfn;
pub mod cloudtrail;
pub mod cw;
pub mod ec2;
pub mod ecr;
mod expanded_view;
pub mod filter;
pub mod iam;
pub mod lambda;
pub mod monitoring;
mod pagination;
pub mod prefs;
mod query_editor;
pub mod s3;
pub mod sqs;
mod status;
pub mod styles;
pub mod table;
pub mod tree;

pub use cw::insights::{DateRangeType, TimeUnit};
pub use cw::{
    CloudWatchLogGroupsState, DetailTab, EventColumn, EventFilterFocus, LogGroupColumn,
    StreamColumn, StreamSort,
};
pub use expanded_view::{format_expansion_text, format_fields};
pub use pagination::{render_paginated_filter, PaginatedFilterConfig};
pub use prefs::Preferences;
pub use query_editor::{render_query_editor, QueryEditorConfig};
pub use status::{first_hint, hint, last_hint, SPINNER_FRAMES};
pub use table::{format_expandable, CURSOR_COLLAPSED, CURSOR_EXPANDED};

pub const PAGE_SIZE_OPTIONS: &[(PageSize, &str)] = &[
    (PageSize::Ten, "10"),
    (PageSize::TwentyFive, "25"),
    (PageSize::Fifty, "50"),
    (PageSize::OneHundred, "100"),
];

pub const PAGE_SIZE_OPTIONS_SMALL: &[(PageSize, &str)] = &[
    (PageSize::Ten, "10"),
    (PageSize::TwentyFive, "25"),
    (PageSize::Fifty, "50"),
];

pub const MAX_DETAIL_COLUMNS: usize = 3;

use self::styles::highlight;
use crate::app::{
    AlarmViewMode, App, CalendarField, CloudTrailDetailFocus, LambdaDetailTab, Service, ViewMode,
};
use crate::cfn::Column as CfnColumn;
use crate::cloudtrail::{CloudTrailEventColumn, EventResourceColumn};
use crate::common::{render_pagination_text, render_scrollbar, translate_column, PageSize};
use crate::cw::alarms::AlarmColumn;
use crate::ec2::Column as Ec2Column;
use crate::ecr::{image, repo};
use crate::iam::{RoleColumn, UserColumn};
use crate::keymap::Mode;
use crate::lambda::{ApplicationColumn, DeploymentColumn, FunctionColumn, ResourceColumn};
use crate::s3::BucketColumn;
use crate::sqs::pipe::Column as SqsPipeColumn;
use crate::sqs::queue::Column as SqsColumn;
use crate::sqs::sub::Column as SqsSubscriptionColumn;
use crate::sqs::tag::Column as SqsTagColumn;
use crate::sqs::trigger::Column as SqsTriggerColumn;
use crate::ui::cfn::{
    DetailTab as CfnDetailTab, OutputColumn, ParameterColumn, ResourceColumn as CfnResourceColumn,
};
use crate::ui::iam::{RoleTab, UserTab};
use crate::ui::lambda::ApplicationDetailTab;
use crate::ui::sqs::QueueDetailTab as SqsQueueDetailTab;
use crate::ui::table::Column as TableColumn;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};

pub fn labeled_field(label: &str, value: impl Into<String>) -> Line<'static> {
    let val = value.into();
    let display = if val.is_empty() { "-".to_string() } else { val };
    Line::from(vec![
        Span::styled(
            format!("{}: ", label),
            Style::default().add_modifier(Modifier::BOLD),
        ),
        Span::raw(display),
    ])
}

/// Calculate the height needed for a block containing lines (lines + 2 for borders)
pub fn block_height(lines: &[Line]) -> u16 {
    lines.len() as u16 + 2
}

/// Calculate the height needed for a block with a given number of lines (lines + 2 for borders)
pub fn block_height_for(line_count: usize) -> u16 {
    line_count as u16 + 2
}

pub fn section_header(text: &str, width: u16) -> Line<'static> {
    let text_len = text.len() as u16;
    // Format: "─ Section Name ───────────────────"
    // dash + space + text + space + dashes = width
    let remaining = width.saturating_sub(text_len + 3);
    let dashes = "".repeat(remaining as usize);
    Line::from(vec![
        Span::raw(""),
        Span::raw(text.to_string()),
        Span::raw(format!(" {}", dashes)),
    ])
}

pub fn tab_style(selected: bool) -> Style {
    if selected {
        highlight()
    } else {
        Style::default()
    }
}

pub fn service_tab_style(selected: bool) -> Style {
    if selected {
        Style::default().bg(Color::Green).fg(Color::Black)
    } else {
        Style::default()
    }
}

pub fn render_tab_spans<'a>(tabs: &[(&'a str, bool)]) -> Vec<Span<'a>> {
    let mut spans = Vec::new();
    for (i, (name, selected)) in tabs.iter().enumerate() {
        if i > 0 {
            spans.push(Span::raw(""));
        }
        spans.push(Span::styled(*name, service_tab_style(*selected)));
    }
    spans
}

use ratatui::{prelude::*, widgets::*};

// Common UI constants
pub const SEARCH_ICON: &str = "─ 🔍 ─";
pub const PREFERENCES_TITLE: &str = "Preferences";

// Filter
pub fn filter_area(filter_text: Vec<Span<'_>>, is_active: bool) -> Paragraph<'_> {
    Paragraph::new(Line::from(filter_text))
        .block(
            Block::default()
                .title(SEARCH_ICON)
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(if is_active {
                    active_border()
                } else {
                    Style::default()
                }),
        )
        .style(Style::default())
}

// Common style helpers
pub fn active_border() -> Style {
    Style::default().fg(Color::Green)
}

pub fn rounded_block() -> Block<'static> {
    Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_type(BorderType::Rounded)
        .border_type(BorderType::Rounded)
}

pub fn format_title(title: &str) -> String {
    format!("{}", title.trim())
}

pub fn titled_block(title: impl Into<String>) -> Block<'static> {
    rounded_block().title(format_title(&title.into()))
}

pub fn titled_rounded_block(title: &'static str) -> Block<'static> {
    titled_block(title)
}

pub fn bold_style() -> Style {
    Style::default().add_modifier(Modifier::BOLD)
}

pub fn cyan_bold() -> Style {
    Style::default()
        .fg(Color::Cyan)
        .add_modifier(Modifier::BOLD)
}

pub fn red_text() -> Style {
    Style::default().fg(Color::Rgb(255, 165, 0))
}

pub fn yellow_text() -> Style {
    Style::default().fg(Color::Yellow)
}

pub fn get_cursor(active: bool) -> &'static str {
    if active {
        ""
    } else {
        ""
    }
}

pub fn render_search_filter(
    frame: &mut Frame,
    area: Rect,
    filter_text: &str,
    is_active: bool,
    selected: usize,
    total_items: usize,
    page_size: usize,
) {
    let cursor = get_cursor(is_active);
    let total_pages = total_items.div_ceil(page_size);
    let current_page = selected / page_size;
    let pagination = render_pagination_text(current_page, total_pages);

    let controls_text = format!(" {}", pagination);
    let filter_width = (area.width as usize).saturating_sub(4);
    let content_len = filter_text.len() + if is_active { cursor.len() } else { 0 };
    let available_space = filter_width.saturating_sub(controls_text.len() + 1);

    let mut spans = vec![];
    if filter_text.is_empty() && !is_active {
        spans.push(Span::styled("Search", Style::default().fg(Color::DarkGray)));
    } else {
        spans.push(Span::raw(filter_text));
    }
    if is_active {
        spans.push(Span::styled(cursor, Style::default().fg(Color::Yellow)));
    }
    if content_len < available_space {
        spans.push(Span::raw(
            " ".repeat(available_space.saturating_sub(content_len)),
        ));
    }
    spans.push(Span::styled(
        controls_text,
        if is_active {
            Style::default()
        } else {
            Style::default().fg(Color::Green)
        },
    ));

    let filter = filter_area(spans, is_active);
    frame.render_widget(filter, area);
}

fn render_toggle(is_on: bool) -> Vec<Span<'static>> {
    if is_on {
        vec![
            Span::styled("", Style::default().fg(Color::Blue)),
            Span::raw(""),
        ]
    } else {
        vec![
            Span::raw(""),
            Span::styled("", Style::default().fg(Color::Black)),
        ]
    }
}

fn render_radio(is_selected: bool) -> (String, Style) {
    if is_selected {
        ("".to_string(), Style::default().fg(Color::Blue))
    } else {
        ("".to_string(), Style::default())
    }
}

// Common UI constants

// Common style helpers
pub fn vertical(
    constraints: impl IntoIterator<Item = Constraint>,
    area: Rect,
) -> std::rc::Rc<[Rect]> {
    Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(area)
}

pub fn horizontal(
    constraints: impl IntoIterator<Item = Constraint>,
    area: Rect,
) -> std::rc::Rc<[Rect]> {
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints(constraints)
        .split(area)
}

// Block helpers
pub fn block(title: &str) -> Block<'_> {
    rounded_block().title(title)
}

pub fn block_with_style(title: &str, style: Style) -> Block<'_> {
    titled_block(title).border_style(style)
}

/// Renders fields in dynamic columns based on available width
/// Returns the height needed for the content
pub fn render_fields_with_dynamic_columns(frame: &mut Frame, area: Rect, fields: Vec<Line>) -> u16 {
    use ratatui::widgets::Paragraph;

    if fields.is_empty() {
        return 0;
    }

    // Calculate max width needed per field
    let field_widths: Vec<u16> = fields
        .iter()
        .map(|line| {
            line.spans
                .iter()
                .map(|span| span.content.len() as u16)
                .sum::<u16>()
                + 2
        })
        .collect();

    let max_field_width = *field_widths.iter().max().unwrap_or(&20);
    let available_width = area.width;

    // Determine how many columns fit (max 3)
    let num_columns = (available_width / max_field_width)
        .max(1)
        .min(MAX_DETAIL_COLUMNS as u16)
        .min(fields.len() as u16) as usize;

    // Distribute fields: first column gets most, others get same or fewer
    let total_fields = fields.len();
    let base_per_column = total_fields / num_columns;
    let extra = total_fields % num_columns;

    let mut columns: Vec<Vec<Line>> = Vec::new();
    let mut field_idx = 0;

    for col in 0..num_columns {
        let fields_in_this_col = if col < extra {
            base_per_column + 1
        } else {
            base_per_column
        };

        let mut column_fields = Vec::new();
        for _ in 0..fields_in_this_col {
            if field_idx < fields.len() {
                column_fields.push(fields[field_idx].clone());
                field_idx += 1;
            }
        }
        columns.push(column_fields);
    }

    // Calculate max rows
    let max_rows = columns.iter().map(|c| c.len()).max().unwrap_or(1) as u16;

    // Create layout
    let constraints: Vec<Constraint> = (0..num_columns)
        .map(|_| Constraint::Percentage(100 / num_columns as u16))
        .collect();

    let column_layout = Layout::default()
        .direction(Direction::Horizontal)
        .constraints(constraints)
        .split(area);

    // Render each column
    for (i, column_fields) in columns.iter().enumerate() {
        if i < column_layout.len() {
            frame.render_widget(Paragraph::new(column_fields.clone()), column_layout[i]);
        }
    }

    max_rows
}

/// Calculates the height needed for fields with dynamic columns (without rendering)
pub fn calculate_dynamic_height(fields: &[Line], width: u16) -> u16 {
    if fields.is_empty() {
        return 0;
    }

    let field_widths: Vec<u16> = fields
        .iter()
        .map(|line| {
            line.spans
                .iter()
                .map(|span| span.content.len() as u16)
                .sum::<u16>()
                + 2
        })
        .collect();

    let max_field_width = *field_widths.iter().max().unwrap_or(&20);
    let num_columns = (width / max_field_width)
        .max(1)
        .min(MAX_DETAIL_COLUMNS as u16)
        .min(fields.len() as u16) as usize;

    let base = fields.len() / num_columns;
    let extra = fields.len() % num_columns;
    let max_rows = if extra > 0 { base + 1 } else { base };

    max_rows as u16
}

// Render a summary section with labeled fields
pub fn render_summary(frame: &mut Frame, area: Rect, title: &str, fields: &[(&str, String)]) {
    let summary_block = titled_block(title);
    let inner = summary_block.inner(area);
    frame.render_widget(summary_block, area);

    let lines: Vec<Line> = fields
        .iter()
        .map(|(label, value)| {
            Line::from(vec![
                Span::styled(*label, Style::default().add_modifier(Modifier::BOLD)),
                Span::raw(value),
            ])
        })
        .collect();

    frame.render_widget(Paragraph::new(lines), inner);
}

// Render tabs with selection highlighting
pub fn render_tabs<T: PartialEq>(frame: &mut Frame, area: Rect, tabs: &[(&str, T)], selected: &T) {
    let spans: Vec<Span> = tabs
        .iter()
        .enumerate()
        .flat_map(|(i, (name, tab))| {
            let mut result = Vec::new();
            if i > 0 {
                result.push(Span::raw(""));
            }
            if tab == selected {
                result.push(Span::styled(*name, tab_style(true)));
            } else {
                result.push(Span::raw(*name));
            }
            result
        })
        .collect();

    frame.render_widget(Paragraph::new(Line::from(spans)), area);
}

pub fn format_duration(seconds: u64) -> String {
    const MINUTE: u64 = 60;
    const HOUR: u64 = 60 * MINUTE;
    const DAY: u64 = 24 * HOUR;
    const WEEK: u64 = 7 * DAY;
    const YEAR: u64 = 365 * DAY;

    if seconds >= YEAR {
        let years = seconds / YEAR;
        let remainder = seconds % YEAR;
        if remainder == 0 {
            format!("{} year{}", years, if years == 1 { "" } else { "s" })
        } else {
            let weeks = remainder / WEEK;
            format!(
                "{} year{} {} week{}",
                years,
                if years == 1 { "" } else { "s" },
                weeks,
                if weeks == 1 { "" } else { "s" }
            )
        }
    } else if seconds >= WEEK {
        let weeks = seconds / WEEK;
        let remainder = seconds % WEEK;
        if remainder == 0 {
            format!("{} week{}", weeks, if weeks == 1 { "" } else { "s" })
        } else {
            let days = remainder / DAY;
            format!(
                "{} week{} {} day{}",
                weeks,
                if weeks == 1 { "" } else { "s" },
                days,
                if days == 1 { "" } else { "s" }
            )
        }
    } else if seconds >= DAY {
        let days = seconds / DAY;
        let remainder = seconds % DAY;
        if remainder == 0 {
            format!("{} day{}", days, if days == 1 { "" } else { "s" })
        } else {
            let hours = remainder / HOUR;
            format!(
                "{} day{} {} hour{}",
                days,
                if days == 1 { "" } else { "s" },
                hours,
                if hours == 1 { "" } else { "s" }
            )
        }
    } else if seconds >= HOUR {
        let hours = seconds / HOUR;
        let remainder = seconds % HOUR;
        if remainder == 0 {
            format!("{} hour{}", hours, if hours == 1 { "" } else { "s" })
        } else {
            let minutes = remainder / MINUTE;
            format!(
                "{} hour{} {} minute{}",
                hours,
                if hours == 1 { "" } else { "s" },
                minutes,
                if minutes == 1 { "" } else { "s" }
            )
        }
    } else if seconds >= MINUTE {
        let minutes = seconds / MINUTE;
        format!("{} minute{}", minutes, if minutes == 1 { "" } else { "s" })
    } else {
        format!("{} second{}", seconds, if seconds == 1 { "" } else { "s" })
    }
}

fn render_column_toggle_string(col_name: &str, is_visible: bool) -> (ListItem<'static>, usize) {
    let mut spans = vec![];
    spans.extend(render_toggle(is_visible));
    spans.push(Span::raw(" "));
    spans.push(Span::raw(col_name.to_string()));
    let text_len = 4 + col_name.len();
    (ListItem::new(Line::from(spans)), text_len)
}

// Helper to render a section header
fn render_section_header(title: &str) -> (ListItem<'static>, usize) {
    let len = title.len();
    (
        ListItem::new(Line::from(Span::styled(
            title.to_string(),
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ))),
        len,
    )
}

// Helper to render a radio button item
fn render_radio_item(label: &str, is_selected: bool, indent: bool) -> (ListItem<'static>, usize) {
    let (radio, style) = render_radio(is_selected);
    let text_len = (if indent { 2 } else { 0 }) + radio.chars().count() + 1 + label.len();
    let mut spans = if indent {
        vec![Span::raw("  ")]
    } else {
        vec![]
    };
    spans.push(Span::styled(radio, style));
    spans.push(Span::raw(format!(" {}", label)));
    (ListItem::new(Line::from(spans)), text_len)
}

// Helper to render page size options
fn render_page_size_section(
    current_size: PageSize,
    sizes: &[(PageSize, &str)],
) -> (Vec<ListItem<'static>>, usize) {
    let mut items = Vec::new();
    let mut max_len = 0;

    let (header, header_len) = render_section_header("Page size");
    items.push(header);
    max_len = max_len.max(header_len);

    for (size, label) in sizes {
        let is_selected = current_size == *size;
        let (item, len) = render_radio_item(label, is_selected, false);
        items.push(item);
        max_len = max_len.max(len);
    }

    (items, max_len)
}

pub fn render(frame: &mut Frame, app: &App) {
    let area = frame.area();

    // Always show tabs row (with profile info), optionally show top bar for breadcrumbs
    let has_tabs = !app.tabs.is_empty();
    let show_breadcrumbs = has_tabs && app.service_selected && {
        // Only show breadcrumbs if we're deeper than the root level
        match app.current_service {
            Service::S3Buckets => app.s3_state.current_bucket.is_some(),
            _ => false,
        }
    };

    let chunks = if show_breadcrumbs {
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(2), // Tabs row (profile info + tabs)
                Constraint::Length(1), // Top bar (breadcrumbs)
                Constraint::Min(0),    // Content
                Constraint::Length(1), // Bottom bar
            ])
            .split(area)
    } else {
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(2), // Tabs row (profile info + tabs)
                Constraint::Min(0),    // Content
                Constraint::Length(1), // Bottom bar
            ])
            .split(area)
    };

    // Always render tabs row (shows profile info)
    render_tabs_row(frame, app, chunks[0]);

    if show_breadcrumbs {
        render_top_bar(frame, app, chunks[1]);
    }

    let content_idx = if show_breadcrumbs { 2 } else { 1 };
    let bottom_idx = if show_breadcrumbs { 3 } else { 2 };

    if !app.service_selected && app.tabs.is_empty() && app.mode == Mode::Normal {
        // Empty screen with message
        let message = vec![
            Line::from(""),
            Line::from(""),
            Line::from(vec![
                Span::raw("Press "),
                Span::styled("", Style::default().fg(Color::Red)),
                Span::raw(" to open Menu"),
            ]),
        ];
        let paragraph = Paragraph::new(message).alignment(Alignment::Center);
        frame.render_widget(paragraph, chunks[content_idx]);
        render_bottom_bar(frame, app, chunks[bottom_idx]);
    } else if !app.service_selected && app.mode == Mode::Normal {
        render_service_picker(frame, app, chunks[content_idx]);
        render_bottom_bar(frame, app, chunks[bottom_idx]);
    } else if app.service_selected {
        render_service(frame, app, chunks[content_idx]);
        render_bottom_bar(frame, app, chunks[bottom_idx]);
    } else {
        // SpaceMenu with no service selected - just render bottom bar
        render_bottom_bar(frame, app, chunks[bottom_idx]);
    }

    // Render modals on top
    match app.mode {
        Mode::SpaceMenu => render_space_menu(frame, area),
        Mode::ServicePicker => render_service_picker(frame, app, area),
        Mode::ColumnSelector => render_column_selector(frame, app, area),
        Mode::ErrorModal => render_error_modal(frame, app, area),
        Mode::HelpModal => render_help_modal(frame, area),
        Mode::RegionPicker => render_region_selector(frame, app, area),
        Mode::ProfilePicker => render_profile_picker(frame, app, area),
        Mode::CalendarPicker => render_calendar_picker(frame, app, area),
        Mode::TabPicker => render_tab_picker(frame, app, area),
        Mode::SessionPicker => render_session_picker(frame, app, area),
        _ => {}
    }
}

fn render_tabs_row(frame: &mut Frame, app: &App, area: Rect) {
    // Split into 2 lines: profile info on top, tabs below
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Length(1)])
        .split(area);

    // Profile info line (highlighted)
    let now = chrono::Utc::now();
    let timestamp = now.format("%Y-%m-%d %H:%M:%S").to_string();

    let (identity_label, identity_value) = if app.config.role_arn.is_empty() {
        ("Identity:", "N/A".to_string())
    } else if let Some(role_part) = app.config.role_arn.split("assumed-role/").nth(1) {
        (
            "Role:",
            role_part.split('/').next().unwrap_or("N/A").to_string(),
        )
    } else if let Some(user_part) = app.config.role_arn.split(":user/").nth(1) {
        ("User:", user_part.to_string())
    } else {
        ("Identity:", "N/A".to_string())
    };

    let region_display = if app.config.region_auto_detected {
        format!(" {} ⚡ ⋮ ", app.config.region)
    } else {
        format!(" {}", app.config.region)
    };

    let info_spans = vec![
        Span::styled(
            "Profile:",
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" {}", app.profile),
            Style::default().fg(Color::White),
        ),
        Span::styled(
            "Account:",
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" {}", app.config.account_id),
            Style::default().fg(Color::White),
        ),
        Span::styled(
            "Region:",
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(region_display, Style::default().fg(Color::White)),
        Span::styled(
            identity_label,
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" {}", identity_value),
            Style::default().fg(Color::White),
        ),
        Span::styled(
            "Timestamp:",
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" {} (UTC)", timestamp),
            Style::default().fg(Color::White),
        ),
    ];

    let info_widget = Paragraph::new(Line::from(info_spans))
        .alignment(Alignment::Right)
        .style(Style::default().bg(Color::DarkGray).fg(Color::White));
    frame.render_widget(info_widget, chunks[0]);

    // Tabs line
    let tab_data: Vec<(&str, bool)> = app
        .tabs
        .iter()
        .enumerate()
        .map(|(i, tab)| (tab.title.as_ref(), i == app.current_tab))
        .collect();
    let spans = render_tab_spans(&tab_data);

    let tabs_widget = Paragraph::new(Line::from(spans));
    frame.render_widget(tabs_widget, chunks[1]);
}

fn render_top_bar(frame: &mut Frame, app: &App, area: Rect) {
    let breadcrumbs_str = app.breadcrumbs();

    // For S3 with prefix, highlight the last part (prefix)
    let breadcrumb_line = if app.current_service == Service::S3Buckets
        && app.s3_state.current_bucket.is_some()
        && !app.s3_state.prefix_stack.is_empty()
    {
        let parts: Vec<&str> = breadcrumbs_str.split("").collect();
        let mut spans = Vec::new();
        for (i, part) in parts.iter().enumerate() {
            if i > 0 {
                spans.push(Span::raw(""));
            }
            if i == parts.len() - 1 {
                // Last part (prefix) - highlight in cyan
                spans.push(Span::styled(
                    *part,
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ));
            } else {
                spans.push(Span::raw(*part));
            }
        }
        Line::from(spans)
    } else {
        Line::from(breadcrumbs_str)
    };

    let breadcrumb_widget =
        Paragraph::new(breadcrumb_line).style(Style::default().fg(Color::White));

    frame.render_widget(breadcrumb_widget, area);
}
fn render_bottom_bar(frame: &mut Frame, app: &App, area: Rect) {
    status::render_bottom_bar(frame, app, area);
}

fn render_service(frame: &mut Frame, app: &App, area: Rect) {
    match app.current_service {
        Service::CloudWatchLogGroups => {
            if app.view_mode == ViewMode::Events {
                cw::logs::render_events(frame, app, area);
            } else if app.view_mode == ViewMode::Detail {
                cw::logs::render_group_detail(frame, app, area);
            } else {
                cw::logs::render_groups_list(frame, app, area);
            }
        }
        Service::CloudWatchInsights => cw::render_insights(frame, app, area),
        Service::CloudWatchAlarms => cw::render_alarms(frame, app, area),
        Service::CloudTrailEvents => cloudtrail::render_events(frame, app, area),
        Service::Ec2Instances => {
            if app.ec2_state.current_instance.is_some() {
                ec2::render_instance_detail(frame, area, app);
            } else {
                ec2::render_instances(
                    frame,
                    area,
                    &app.ec2_state,
                    &app.ec2_visible_column_ids
                        .iter()
                        .map(|s| s.as_ref())
                        .collect::<Vec<_>>(),
                    app.mode,
                );
            }
        }
        Service::EcrRepositories => ecr::render_repositories(frame, app, area),
        Service::LambdaFunctions => lambda::render_functions(frame, app, area),
        Service::LambdaApplications => lambda::render_applications(frame, app, area),
        Service::S3Buckets => s3::render_buckets(frame, app, area),
        Service::SqsQueues => sqs::render_queues(frame, app, area),
        Service::CloudFormationStacks => cfn::render_stacks(frame, app, area),
        Service::IamUsers => iam::render_users(frame, app, area),
        Service::IamRoles => iam::render_roles(frame, app, area),
        Service::IamUserGroups => iam::render_user_groups(frame, app, area),
        Service::ApiGatewayApis => apig::render_apis(frame, app, area),
    }
}

fn render_column_selector(frame: &mut Frame, app: &App, area: Rect) {
    let (items, title, max_text_len) = if app.current_service == Service::S3Buckets
        && app.s3_state.current_bucket.is_none()
    {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        let (header, header_len) = render_section_header("Columns");
        all_items.push(header);
        max_len = max_len.max(header_len);

        for col_id in &app.s3_bucket_column_ids {
            if let Some(col) = BucketColumn::from_id(col_id) {
                let is_visible = app.s3_bucket_visible_column_ids.contains(col_id);
                let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                all_items.push(item);
                max_len = max_len.max(len);
            }
        }

        all_items.push(ListItem::new(""));
        let (page_items, page_len) =
            render_page_size_section(app.s3_state.buckets.page_size, PAGE_SIZE_OPTIONS);
        all_items.extend(page_items);
        max_len = max_len.max(page_len);

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::CloudWatchAlarms {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        // Columns section
        let (header, header_len) = render_section_header("Columns");
        all_items.push(header);
        max_len = max_len.max(header_len);

        for col_id in &app.cw_alarm_column_ids {
            let is_visible = app.cw_alarm_visible_column_ids.contains(col_id);
            if let Some(col) = AlarmColumn::from_id(col_id) {
                let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                all_items.push(item);
                max_len = max_len.max(len);
            }
        }

        // View As section
        all_items.push(ListItem::new(""));
        let (header, header_len) = render_section_header("View as");
        all_items.push(header);
        max_len = max_len.max(header_len);

        let (item, len) = render_radio_item(
            "Table",
            app.alarms_state.view_as == AlarmViewMode::Table,
            true,
        );
        all_items.push(item);
        max_len = max_len.max(len);

        let (item, len) = render_radio_item(
            "Cards",
            app.alarms_state.view_as == AlarmViewMode::Cards,
            true,
        );
        all_items.push(item);
        max_len = max_len.max(len);

        // Page Size section
        all_items.push(ListItem::new(""));
        let (page_items, page_len) =
            render_page_size_section(app.alarms_state.table.page_size, PAGE_SIZE_OPTIONS);
        all_items.extend(page_items);
        max_len = max_len.max(page_len);

        // Wrap Lines section
        all_items.push(ListItem::new(""));
        let (header, header_len) = render_section_header("Wrap lines");
        all_items.push(header);
        max_len = max_len.max(header_len);

        let (item, len) = render_column_toggle_string("Wrap lines", app.alarms_state.wrap_lines);
        all_items.push(item);
        max_len = max_len.max(len);

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::CloudTrailEvents {
        if app.cloudtrail_state.current_event.is_some()
            && app.cloudtrail_state.detail_focus == CloudTrailDetailFocus::Resources
        {
            // Resources table in detail view - show resource columns
            let mut all_items: Vec<ListItem> = Vec::new();
            let mut max_len = 0;

            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.cloudtrail_resource_column_ids {
                let is_visible = app.cloudtrail_resource_visible_column_ids.contains(col_id);
                if let Some(col) = EventResourceColumn::from_id(col_id) {
                    let (item, len) = render_column_toggle_string(col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            (all_items, " Preferences ", max_len)
        } else {
            // Main events table
            let mut all_items: Vec<ListItem> = Vec::new();
            let mut max_len = 0;

            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.cloudtrail_event_column_ids {
                let is_visible = app.cloudtrail_event_visible_column_ids.contains(col_id);
                if let Some(col) = CloudTrailEventColumn::from_id(col_id) {
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.cloudtrail_state.table.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);

            (all_items, " Preferences ", max_len)
        }
    } else if app.view_mode == ViewMode::Events
        && app.current_service == Service::CloudWatchLogGroups
    {
        let mut max_len = 0;
        let items: Vec<ListItem> = app
            .cw_log_event_column_ids
            .iter()
            .filter_map(|col_id| {
                EventColumn::from_id(col_id).map(|col| {
                    let is_visible = app.cw_log_event_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(col.name(), is_visible);
                    max_len = max_len.max(len);
                    item
                })
            })
            .collect();
        (items, " Select visible columns (Space to toggle) ", max_len)
    } else if app.view_mode == ViewMode::Detail
        && app.current_service == Service::CloudWatchLogGroups
    {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        let (header, header_len) = render_section_header("Columns");
        all_items.push(header);
        max_len = max_len.max(header_len);

        if app.log_groups_state.detail_tab == DetailTab::Tags {
            // Tags tab columns
            for col_id in &app.cw_log_tag_column_ids {
                if let Some(col) = crate::cw::TagColumn::from_id(col_id) {
                    let is_visible = app.cw_log_tag_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.log_groups_state.tags.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        } else {
            // Log streams tab columns
            for col_id in &app.cw_log_stream_column_ids {
                if let Some(col) = StreamColumn::from_id(col_id) {
                    let is_visible = app.cw_log_stream_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let page_size_enum = match app.log_groups_state.stream_page_size {
                10 => PageSize::Ten,
                25 => PageSize::TwentyFive,
                50 => PageSize::Fifty,
                _ => PageSize::OneHundred,
            };
            let (page_items, page_len) =
                render_page_size_section(page_size_enum, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        }

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::CloudWatchLogGroups {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        let (header, header_len) = render_section_header("Columns");
        all_items.push(header);
        max_len = max_len.max(header_len);

        for col_id in &app.cw_log_group_column_ids {
            if let Some(col) = LogGroupColumn::from_id(col_id) {
                let is_visible = app.cw_log_group_visible_column_ids.contains(col_id);
                let (item, len) = render_column_toggle_string(col.name(), is_visible);
                all_items.push(item);
                max_len = max_len.max(len);
            }
        }

        all_items.push(ListItem::new(""));
        let (page_items, page_len) =
            render_page_size_section(app.log_groups_state.log_groups.page_size, PAGE_SIZE_OPTIONS);
        all_items.extend(page_items);
        max_len = max_len.max(page_len);

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::ApiGatewayApis {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        if app.apig_state.current_api.is_none() {
            // API list view
            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.apig_api_column_ids {
                use crate::apig::api::Column as ApigColumn;
                if let Some(col) = ApigColumn::from_id(col_id) {
                    let is_visible = app.apig_api_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.apig_state.apis.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        } else if let Some(api) = &app.apig_state.current_api {
            // Routes/Resources detail view
            use crate::apig::route::Column as RouteColumn;
            use crate::ui::apig::ApiDetailTab;

            if app.apig_state.detail_tab == ApiDetailTab::Routes {
                // Check if REST API (shows resources) or HTTP/WebSocket (shows routes)
                if api.protocol_type.to_uppercase() == "REST" {
                    // REST API - show resource columns
                    use crate::apig::resource::Column as ResourceColumn;

                    let (header, header_len) = render_section_header("Columns");
                    all_items.push(header);
                    max_len = max_len.max(header_len);

                    for (i, col_id) in app.apig_resource_column_ids.iter().enumerate() {
                        if let Some(col) = ResourceColumn::from_id(col_id) {
                            if i == 0 {
                                // First column (Resource) is always visible - show grayed out toggle
                                let col_name = col.name().to_string();
                                let spans = vec![
                                    Span::styled("", Style::default().fg(Color::DarkGray)),
                                    Span::styled("", Style::default().fg(Color::DarkGray)),
                                    Span::raw(" "),
                                    Span::styled(
                                        col_name.clone(),
                                        Style::default().fg(Color::DarkGray),
                                    ),
                                ];
                                let item = ListItem::new(Line::from(spans));
                                all_items.push(item);
                                max_len = max_len.max(4 + col_name.len());
                            } else {
                                let is_visible =
                                    app.apig_resource_visible_column_ids.contains(col_id);
                                let (item, len) =
                                    render_column_toggle_string(col.name(), is_visible);
                                all_items.push(item);
                                max_len = max_len.max(len);
                            }
                        }
                    }
                } else {
                    // HTTP/WebSocket API - show route columns
                    let (header, header_len) = render_section_header("Columns");
                    all_items.push(header);
                    max_len = max_len.max(header_len);

                    for (i, col_id) in app.apig_route_column_ids.iter().enumerate() {
                        if let Some(col) = RouteColumn::from_id(col_id) {
                            if i == 0 {
                                // First column (Route) is always visible - show grayed out toggle
                                let col_name = col.name().to_string();
                                let spans = vec![
                                    Span::styled("", Style::default().fg(Color::DarkGray)),
                                    Span::styled("", Style::default().fg(Color::DarkGray)),
                                    Span::raw(" "),
                                    Span::styled(
                                        col_name.clone(),
                                        Style::default().fg(Color::DarkGray),
                                    ),
                                ];
                                let item = ListItem::new(Line::from(spans));
                                all_items.push(item);
                                max_len = max_len.max(4 + col_name.len());
                            } else {
                                let is_visible = app.apig_route_visible_column_ids.contains(col_id);
                                let (item, len) =
                                    render_column_toggle_string(col.name(), is_visible);
                                all_items.push(item);
                                max_len = max_len.max(len);
                            }
                        }
                    }
                }
            }
        }

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::EcrRepositories {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        let (header, header_len) = render_section_header("Columns");
        all_items.push(header);
        max_len = max_len.max(header_len);

        if app.ecr_state.current_repository.is_some() {
            // ECR images columns
            for col_id in &app.ecr_image_column_ids {
                if let Some(col) = image::Column::from_id(col_id) {
                    let is_visible = app.ecr_image_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.ecr_state.images.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        } else {
            // ECR repository columns
            for col_id in &app.ecr_repo_column_ids {
                if let Some(col) = repo::Column::from_id(col_id) {
                    let is_visible = app.ecr_repo_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.ecr_state.repositories.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        }

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::Ec2Instances {
        if app.ec2_state.current_instance.is_some()
            && app.ec2_state.detail_tab == ec2::DetailTab::Tags
        {
            let mut all_items: Vec<ListItem> = Vec::new();
            let mut max_len = 0;

            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.ec2_state.tag_column_ids {
                use crate::ec2::tag::Column as TagColumn;
                if let Some(col) = TagColumn::from_id(col_id) {
                    let is_visible = app.ec2_state.tag_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.ec2_state.tags.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);

            (all_items, " Preferences ", max_len)
        } else {
            let mut all_items: Vec<ListItem> = Vec::new();
            let mut max_len = 0;

            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.ec2_column_ids {
                if let Some(col) = Ec2Column::from_id(col_id) {
                    let is_visible = app.ec2_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));

            let (page_items, page_len) =
                render_page_size_section(app.ec2_state.table.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);

            (all_items, " Preferences ", max_len)
        }
    } else if app.current_service == Service::SqsQueues {
        if app.sqs_state.current_queue.is_some()
            && app.sqs_state.detail_tab == SqsQueueDetailTab::LambdaTriggers
        {
            // Triggers tab - columns + page size
            let mut all_items: Vec<ListItem> = Vec::new();
            let mut max_len = 0;

            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.sqs_state.trigger_column_ids {
                if let Some(col) = SqsTriggerColumn::from_id(col_id) {
                    let is_visible = app.sqs_state.trigger_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.sqs_state.triggers.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);

            (all_items, " Preferences ", max_len)
        } else if app.sqs_state.current_queue.is_some()
            && app.sqs_state.detail_tab == SqsQueueDetailTab::SnsSubscriptions
        {
            // SNS Subscriptions tab - columns + page size
            let mut all_items: Vec<ListItem> = Vec::new();
            let mut max_len = 0;

            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.sqs_state.subscription_column_ids {
                if let Some(col) = SqsSubscriptionColumn::from_id(col_id) {
                    let is_visible = app
                        .sqs_state
                        .subscription_visible_column_ids
                        .contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.sqs_state.subscriptions.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);

            (all_items, " Preferences ", max_len)
        } else if app.sqs_state.current_queue.is_some()
            && app.sqs_state.detail_tab == SqsQueueDetailTab::EventBridgePipes
        {
            // EventBridge Pipes tab - columns + page size
            let mut all_items: Vec<ListItem> = Vec::new();
            let mut max_len = 0;

            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.sqs_state.pipe_column_ids {
                if let Some(col) = SqsPipeColumn::from_id(col_id) {
                    let is_visible = app.sqs_state.pipe_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.sqs_state.pipes.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);

            (all_items, " Preferences ", max_len)
        } else if app.sqs_state.current_queue.is_some()
            && app.sqs_state.detail_tab == SqsQueueDetailTab::Tagging
        {
            // Tagging tab - columns + page size
            let mut all_items: Vec<ListItem> = Vec::new();
            let mut max_len = 0;

            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.sqs_state.tag_column_ids {
                if let Some(col) = SqsTagColumn::from_id(col_id) {
                    let is_visible = app.sqs_state.tag_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.sqs_state.tags.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);

            (all_items, " Preferences ", max_len)
        } else if app.sqs_state.current_queue.is_none() {
            // Queue list - columns + page size
            let mut all_items: Vec<ListItem> = Vec::new();
            let mut max_len = 0;

            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.sqs_column_ids {
                if let Some(col) = SqsColumn::from_id(col_id) {
                    let is_visible = app.sqs_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.sqs_state.queues.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);

            (all_items, " Preferences ", max_len)
        } else {
            (vec![], " Preferences ", 0)
        }
    } else if app.current_service == Service::LambdaFunctions {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        let (header, header_len) = render_section_header("Columns");
        all_items.push(header);
        max_len = max_len.max(header_len);

        // Show appropriate columns based on current tab
        if app.lambda_state.current_function.is_some()
            && app.lambda_state.detail_tab == LambdaDetailTab::Code
        {
            // Show layer columns for Code tab
            for col in &app.lambda_state.layer_column_ids {
                let is_visible = app.lambda_state.layer_visible_column_ids.contains(col);
                let (item, len) = render_column_toggle_string(col, is_visible);
                all_items.push(item);
                max_len = max_len.max(len);
            }
        } else if app.lambda_state.detail_tab == LambdaDetailTab::Versions {
            for col in &app.lambda_state.version_column_ids {
                let is_visible = app.lambda_state.version_visible_column_ids.contains(col);
                let (item, len) = render_column_toggle_string(col, is_visible);
                all_items.push(item);
                max_len = max_len.max(len);
            }
        } else if app.lambda_state.detail_tab == LambdaDetailTab::Aliases {
            for col in &app.lambda_state.alias_column_ids {
                let is_visible = app.lambda_state.alias_visible_column_ids.contains(col);
                let (item, len) = render_column_toggle_string(col, is_visible);
                all_items.push(item);
                max_len = max_len.max(len);
            }
        } else {
            for col_id in &app.lambda_state.function_column_ids {
                if let Some(col) = FunctionColumn::from_id(col_id) {
                    let is_visible = app
                        .lambda_state
                        .function_visible_column_ids
                        .contains(col_id);
                    let (item, len) = render_column_toggle_string(col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }
        }

        all_items.push(ListItem::new(""));

        let (page_items, page_len) = render_page_size_section(
            if app.lambda_state.detail_tab == LambdaDetailTab::Versions {
                app.lambda_state.version_table.page_size
            } else {
                app.lambda_state.table.page_size
            },
            PAGE_SIZE_OPTIONS,
        );
        all_items.extend(page_items);
        max_len = max_len.max(page_len);

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::LambdaApplications {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        let (header, header_len) = render_section_header("Columns");
        all_items.push(header);
        max_len = max_len.max(header_len);

        // Show different columns based on current view
        if app.lambda_application_state.current_application.is_some() {
            if app.lambda_application_state.detail_tab == ApplicationDetailTab::Overview {
                // Resources columns
                for col_id in &app.lambda_resource_column_ids {
                    let is_visible = app.lambda_resource_visible_column_ids.contains(col_id);
                    if let Some(col) = ResourceColumn::from_id(col_id) {
                        let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                        all_items.push(item);
                        max_len = max_len.max(len);
                    }
                }

                all_items.push(ListItem::new(""));
                let (page_items, page_len) = render_page_size_section(
                    app.lambda_application_state.resources.page_size,
                    PAGE_SIZE_OPTIONS_SMALL,
                );
                all_items.extend(page_items);
                max_len = max_len.max(page_len);
            } else {
                // Deployments columns
                for col_id in &app.lambda_deployment_column_ids {
                    let is_visible = app.lambda_deployment_visible_column_ids.contains(col_id);
                    if let Some(col) = DeploymentColumn::from_id(col_id) {
                        let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                        all_items.push(item);
                        max_len = max_len.max(len);
                    }
                }

                all_items.push(ListItem::new(""));
                let (page_items, page_len) = render_page_size_section(
                    app.lambda_application_state.deployments.page_size,
                    PAGE_SIZE_OPTIONS_SMALL,
                );
                all_items.extend(page_items);
                max_len = max_len.max(page_len);
            }
        } else {
            // Application list columns
            for col_id in &app.lambda_application_column_ids {
                if let Some(col) = ApplicationColumn::from_id(col_id) {
                    let is_visible = app.lambda_application_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) = render_page_size_section(
                app.lambda_application_state.table.page_size,
                PAGE_SIZE_OPTIONS_SMALL,
            );
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        }

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::CloudFormationStacks {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        // Check if we're in StackInfo tab (tags table)
        if app.cfn_state.current_stack.is_some()
            && app.cfn_state.detail_tab == CfnDetailTab::StackInfo
        {
            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            // Tags only have Key and Value columns
            let tag_columns = ["Key", "Value"];
            for col_name in &tag_columns {
                let (item, len) = render_column_toggle_string(col_name, true);
                all_items.push(item);
                max_len = max_len.max(len);
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.cfn_state.tags.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        } else if app.cfn_state.current_stack.is_some()
            && app.cfn_state.detail_tab == CfnDetailTab::Parameters
        {
            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.cfn_parameter_column_ids {
                let is_visible = app.cfn_parameter_visible_column_ids.contains(col_id);
                if let Some(col) = ParameterColumn::from_id(col_id) {
                    let name = translate_column(col.id(), col.default_name());
                    let (item, len) = render_column_toggle_string(&name, is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.cfn_state.parameters.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        } else if app.cfn_state.current_stack.is_some()
            && app.cfn_state.detail_tab == CfnDetailTab::Outputs
        {
            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.cfn_output_column_ids {
                let is_visible = app.cfn_output_visible_column_ids.contains(col_id);
                if let Some(col) = OutputColumn::from_id(col_id) {
                    let name = translate_column(col.id(), col.default_name());
                    let (item, len) = render_column_toggle_string(&name, is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.cfn_state.outputs.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        } else if app.cfn_state.current_stack.is_some()
            && app.cfn_state.detail_tab == CfnDetailTab::Resources
        {
            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.cfn_resource_column_ids {
                let is_visible = app.cfn_resource_visible_column_ids.contains(col_id);
                if let Some(col) = CfnResourceColumn::from_id(col_id) {
                    let name = translate_column(col.id(), col.default_name());
                    let (item, len) = render_column_toggle_string(&name, is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.cfn_state.resources.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        } else if app.cfn_state.current_stack.is_none() {
            // Stack list view
            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.cfn_column_ids {
                let is_visible = app.cfn_visible_column_ids.contains(col_id);
                if let Some(col) = CfnColumn::from_id(col_id) {
                    let (item, len) = render_column_toggle_string(&col.name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.cfn_state.table.page_size, PAGE_SIZE_OPTIONS);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        }
        // Template tab: no preferences

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::IamUsers {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        // Show different sections based on the current tab in user detail view
        if app.iam_state.current_user.is_some() {
            match app.iam_state.user_tab {
                UserTab::Permissions => {
                    let (header, header_len) = render_section_header("Columns");
                    all_items.push(header);
                    max_len = max_len.max(header_len);

                    for col in &app.iam_policy_column_ids {
                        let is_visible = app.iam_policy_visible_column_ids.contains(col);
                        let mut spans = vec![];
                        spans.extend(render_toggle(is_visible));
                        spans.push(Span::raw(" "));
                        spans.push(Span::raw(col.clone()));
                        let text_len = 4 + col.len();
                        all_items.push(ListItem::new(Line::from(spans)));
                        max_len = max_len.max(text_len);
                    }

                    all_items.push(ListItem::new(""));
                    let (page_items, page_len) = render_page_size_section(
                        app.iam_state.policies.page_size,
                        PAGE_SIZE_OPTIONS_SMALL,
                    );
                    all_items.extend(page_items);
                    max_len = max_len.max(page_len);
                }
                UserTab::Groups => {
                    let (header, header_len) = render_section_header("Columns");
                    all_items.push(header);
                    max_len = max_len.max(header_len);

                    for col in &["Group name", "Attached policies"] {
                        let mut spans = vec![];
                        spans.extend(render_toggle(true));
                        spans.push(Span::raw(" "));
                        spans.push(Span::raw(*col));
                        let text_len = 4 + col.len();
                        all_items.push(ListItem::new(Line::from(spans)));
                        max_len = max_len.max(text_len);
                    }

                    all_items.push(ListItem::new(""));
                    let (page_items, page_len) = render_page_size_section(
                        app.iam_state.user_group_memberships.page_size,
                        PAGE_SIZE_OPTIONS_SMALL,
                    );
                    all_items.extend(page_items);
                    max_len = max_len.max(page_len);
                }
                UserTab::Tags => {
                    let (header, header_len) = render_section_header("Columns");
                    all_items.push(header);
                    max_len = max_len.max(header_len);

                    for col in &["Key", "Value"] {
                        let mut spans = vec![];
                        spans.extend(render_toggle(true));
                        spans.push(Span::raw(" "));
                        spans.push(Span::raw(*col));
                        let text_len = 4 + col.len();
                        all_items.push(ListItem::new(Line::from(spans)));
                        max_len = max_len.max(text_len);
                    }

                    all_items.push(ListItem::new(""));
                    let (page_items, page_len) = render_page_size_section(
                        app.iam_state.user_tags.page_size,
                        PAGE_SIZE_OPTIONS_SMALL,
                    );
                    all_items.extend(page_items);
                    max_len = max_len.max(page_len);
                }
                UserTab::LastAccessed => {
                    let (header, header_len) = render_section_header("Columns");
                    all_items.push(header);
                    max_len = max_len.max(header_len);

                    for col in &["Service", "Policies granting", "Last accessed"] {
                        let mut spans = vec![];
                        spans.extend(render_toggle(true));
                        spans.push(Span::raw(" "));
                        spans.push(Span::raw(*col));
                        let text_len = 4 + col.len();
                        all_items.push(ListItem::new(Line::from(spans)));
                        max_len = max_len.max(text_len);
                    }

                    all_items.push(ListItem::new(""));
                    let (page_items, page_len) = render_page_size_section(
                        app.iam_state.last_accessed_services.page_size,
                        PAGE_SIZE_OPTIONS_SMALL,
                    );
                    all_items.extend(page_items);
                    max_len = max_len.max(page_len);
                }
                _ => {}
            }
        } else if app.iam_state.current_user.is_none() {
            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.iam_user_column_ids {
                if let Some(col) = UserColumn::from_id(col_id) {
                    let is_visible = app.iam_user_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(col.default_name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.iam_state.users.page_size, PAGE_SIZE_OPTIONS_SMALL);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        }

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::IamRoles {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        // Show different columns based on the current tab
        if app.iam_state.current_role.is_some() {
            match app.iam_state.role_tab {
                RoleTab::Permissions => {
                    // Show policy columns
                    let (header, header_len) = render_section_header("Columns");
                    all_items.push(header);
                    max_len = max_len.max(header_len);

                    for col in &app.iam_policy_column_ids {
                        let is_visible = app.iam_policy_visible_column_ids.contains(col);
                        let mut spans = vec![];
                        spans.extend(render_toggle(is_visible));
                        spans.push(Span::raw(" "));
                        spans.push(Span::raw(col.clone()));
                        let text_len = 4 + col.len();
                        all_items.push(ListItem::new(Line::from(spans)));
                        max_len = max_len.max(text_len);
                    }

                    all_items.push(ListItem::new(""));
                    let (page_items, page_len) = render_page_size_section(
                        app.iam_state.policies.page_size,
                        PAGE_SIZE_OPTIONS_SMALL,
                    );
                    all_items.extend(page_items);
                    max_len = max_len.max(page_len);
                }
                RoleTab::Tags => {
                    // Show tag columns (Key, Value)
                    let (header, header_len) = render_section_header("Columns");
                    all_items.push(header);
                    max_len = max_len.max(header_len);

                    for col in &["Key", "Value"] {
                        let mut spans = vec![];
                        spans.extend(render_toggle(true)); // Tags always show both columns
                        spans.push(Span::raw(" "));
                        spans.push(Span::raw(*col));
                        let text_len = 4 + col.len();
                        all_items.push(ListItem::new(Line::from(spans)));
                        max_len = max_len.max(text_len);
                    }

                    all_items.push(ListItem::new(""));
                    let (page_items, page_len) = render_page_size_section(
                        app.iam_state.tags.page_size,
                        PAGE_SIZE_OPTIONS_SMALL,
                    );
                    all_items.extend(page_items);
                    max_len = max_len.max(page_len);
                }
                RoleTab::LastAccessed => {
                    let (header, header_len) = render_section_header("Columns");
                    all_items.push(header);
                    max_len = max_len.max(header_len);

                    for col in &["Service", "Policies granting", "Last accessed"] {
                        let mut spans = vec![];
                        spans.extend(render_toggle(true));
                        spans.push(Span::raw(" "));
                        spans.push(Span::raw(*col));
                        let text_len = 4 + col.len();
                        all_items.push(ListItem::new(Line::from(spans)));
                        max_len = max_len.max(text_len);
                    }

                    all_items.push(ListItem::new(""));
                    let (page_items, page_len) = render_page_size_section(
                        app.iam_state.last_accessed_services.page_size,
                        PAGE_SIZE_OPTIONS_SMALL,
                    );
                    all_items.extend(page_items);
                    max_len = max_len.max(page_len);
                }
                _ => {
                    // Other tabs don't have column preferences
                }
            }
        } else {
            // Role list view - show role columns
            let (header, header_len) = render_section_header("Columns");
            all_items.push(header);
            max_len = max_len.max(header_len);

            for col_id in &app.iam_role_column_ids {
                if let Some(col) = RoleColumn::from_id(col_id) {
                    let is_visible = app.iam_role_visible_column_ids.contains(col_id);
                    let (item, len) = render_column_toggle_string(col.default_name(), is_visible);
                    all_items.push(item);
                    max_len = max_len.max(len);
                }
            }

            all_items.push(ListItem::new(""));
            let (page_items, page_len) =
                render_page_size_section(app.iam_state.roles.page_size, PAGE_SIZE_OPTIONS_SMALL);
            all_items.extend(page_items);
            max_len = max_len.max(page_len);
        }

        (all_items, " Preferences ", max_len)
    } else if app.current_service == Service::IamUserGroups {
        let mut all_items: Vec<ListItem> = Vec::new();
        let mut max_len = 0;

        let (header, header_len) = render_section_header("Columns");
        all_items.push(header);
        max_len = max_len.max(header_len);

        for col in &app.iam_group_column_ids {
            let is_visible = app.iam_group_visible_column_ids.contains(col);
            let mut spans = vec![];
            spans.extend(render_toggle(is_visible));
            spans.push(Span::raw(" "));
            spans.push(Span::raw(col.clone()));
            let text_len = 4 + col.len();
            all_items.push(ListItem::new(Line::from(spans)));
            max_len = max_len.max(text_len);
        }

        all_items.push(ListItem::new(""));
        let (page_items, page_len) =
            render_page_size_section(app.iam_state.groups.page_size, PAGE_SIZE_OPTIONS_SMALL);
        all_items.extend(page_items);
        max_len = max_len.max(page_len);

        (all_items, " Preferences ", max_len)
    } else {
        // Fallback for unknown services
        (vec![], " Preferences ", 0)
    };

    // Calculate popup size based on content
    let item_count = items.len();

    // Width: based on content + padding
    let width = (max_text_len + 10).clamp(30, 100) as u16; // +10 for padding, min 30, max 100

    // Height: fit all items if possible, otherwise use max available and show scrollbar
    let height = (item_count as u16 + 2).max(8); // +2 for borders, min 8
    let max_height = area.height.saturating_sub(4);
    let actual_height = height.min(max_height);
    let popup_area = centered_rect_absolute(width, actual_height, area);

    // Check if scrollbar is needed
    let needs_scrollbar = height > max_height;

    // Preferences should always have green border (active state)
    let border_color = Color::Green;

    let list = List::new(items)
        .block(
            Block::default()
                .title(format_title(title.trim()))
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(border_color)),
        )
        .highlight_style(Style::default().bg(Color::DarkGray))
        .highlight_symbol("");

    let mut state = ListState::default();
    state.select(Some(app.column_selector_index));

    frame.render_widget(Clear, popup_area);
    frame.render_stateful_widget(list, popup_area, &mut state);

    // Render scrollbar only if content doesn't fit
    if needs_scrollbar {
        render_scrollbar(
            frame,
            popup_area.inner(Margin {
                vertical: 1,
                horizontal: 0,
            }),
            item_count,
            app.column_selector_index,
        );
    }
}

fn render_error_modal(frame: &mut Frame, app: &App, area: Rect) {
    let popup_area = centered_rect(80, 60, area);

    frame.render_widget(Clear, popup_area);
    frame.render_widget(
        Block::default()
            .title(format_title("Error"))
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_type(BorderType::Rounded)
            .border_style(red_text())
            .style(Style::default().bg(Color::Black)),
        popup_area,
    );

    let inner = popup_area.inner(Margin {
        vertical: 1,
        horizontal: 1,
    });

    let error_text = app.error_message.as_deref().unwrap_or("Unknown error");

    let chunks = vertical(
        [
            Constraint::Length(2), // Header
            Constraint::Min(0),    // Error text (scrollable)
            Constraint::Length(2), // Help text
        ],
        inner,
    );

    // Header
    let header = Paragraph::new("AWS Error")
        .alignment(Alignment::Center)
        .style(red_text().add_modifier(Modifier::BOLD));
    frame.render_widget(header, chunks[0]);

    // Scrollable error text with border
    let error_lines: Vec<Line> = error_text
        .lines()
        .skip(app.error_scroll)
        .flat_map(|line| {
            let width = chunks[1].width.saturating_sub(4) as usize; // Account for borders + padding
            if line.len() <= width {
                vec![Line::from(line)]
            } else {
                line.chars()
                    .collect::<Vec<_>>()
                    .chunks(width)
                    .map(|chunk| Line::from(chunk.iter().collect::<String>()))
                    .collect()
            }
        })
        .collect();

    let error_paragraph = Paragraph::new(error_lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(active_border()),
        )
        .style(Style::default().fg(Color::White));

    frame.render_widget(error_paragraph, chunks[1]);

    // Render scrollbar if needed
    let total_lines: usize = error_text
        .lines()
        .map(|line| {
            let width = chunks[1].width.saturating_sub(4) as usize;
            if line.len() <= width {
                1
            } else {
                line.len().div_ceil(width)
            }
        })
        .sum();
    let visible_lines = chunks[1].height.saturating_sub(2) as usize;
    if total_lines > visible_lines {
        render_scrollbar(
            frame,
            chunks[1].inner(Margin {
                vertical: 1,
                horizontal: 0,
            }),
            total_lines,
            app.error_scroll,
        );
    }

    // Help text
    let help_spans = vec![
        first_hint("^r", "retry"),
        hint("y", "copy"),
        hint("↑↓,^u,^d", "scroll"),
        last_hint("q,⎋", "close"),
    ]
    .into_iter()
    .flatten()
    .collect::<Vec<_>>();
    let help = Paragraph::new(Line::from(help_spans)).alignment(Alignment::Center);

    frame.render_widget(help, chunks[2]);
}

fn render_space_menu(frame: &mut Frame, area: Rect) {
    let items = vec![
        Line::from(vec![
            Span::styled("o", Style::default().fg(Color::Yellow)),
            Span::raw(" services"),
        ]),
        Line::from(vec![
            Span::styled("t", Style::default().fg(Color::Yellow)),
            Span::raw(" tabs"),
        ]),
        Line::from(vec![
            Span::styled("c", Style::default().fg(Color::Yellow)),
            Span::raw(" close"),
        ]),
        Line::from(vec![
            Span::styled("r", Style::default().fg(Color::Yellow)),
            Span::raw(" regions"),
        ]),
        Line::from(vec![
            Span::styled("s", Style::default().fg(Color::Yellow)),
            Span::raw(" sessions"),
        ]),
        Line::from(vec![
            Span::styled("h", Style::default().fg(Color::Yellow)),
            Span::raw(" help"),
        ]),
    ];

    let menu_height = items.len() as u16 + 2; // +2 for borders
    let menu_area = bottom_right_rect(30, menu_height, area);

    let paragraph = Paragraph::new(items)
        .block(
            Block::default()
                .title(format_title("Menu"))
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(Color::Cyan)),
        )
        .style(Style::default().bg(Color::Black));

    frame.render_widget(Clear, menu_area);
    frame.render_widget(paragraph, menu_area);
}

fn render_service_picker(frame: &mut Frame, app: &App, area: Rect) {
    let popup_area = centered_rect(60, 60, area);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(0)])
        .split(popup_area);

    let is_active = app.mode == Mode::ServicePicker;
    let filter_text = if app.service_picker.filter_active {
        vec![
            Span::raw(&app.service_picker.filter),
            Span::styled("", Style::default().fg(Color::Green)),
        ]
    } else {
        vec![Span::raw(&app.service_picker.filter)]
    };
    let active_color = Color::Green;
    let inactive_color = Color::White;
    let filter = Paragraph::new(Line::from(filter_text))
        .block(
            Block::default()
                .title(SEARCH_ICON)
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(if app.service_picker.filter_active {
                    active_color
                } else {
                    inactive_color
                })),
        )
        .style(Style::default());

    let filtered = app.filtered_services();
    let items: Vec<ListItem> = filtered.iter().map(|s| ListItem::new(*s)).collect();

    let list = List::new(items)
        .block(
            Block::default()
                .title(format_title("AWS Services"))
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(if is_active && !app.service_picker.filter_active {
                    active_border()
                } else {
                    Style::default().fg(Color::White)
                }),
        )
        .highlight_style(Style::default().bg(Color::DarkGray))
        .highlight_symbol("");

    let mut state = ListState::default();
    state.select(Some(app.service_picker.selected));

    frame.render_widget(Clear, popup_area);
    frame.render_widget(filter, chunks[0]);
    frame.render_stateful_widget(list, chunks[1], &mut state);
}

fn render_tab_picker(frame: &mut Frame, app: &App, area: Rect) {
    let popup_area = centered_rect(80, 60, area);

    // Split into filter, list and preview
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(0)])
        .split(popup_area);

    // Filter input
    let filter_text = if app.tab_filter.is_empty() {
        "Type to filter tabs...".to_string()
    } else {
        app.tab_filter.clone()
    };
    let filter_style = if app.tab_filter.is_empty() {
        Style::default().fg(Color::DarkGray)
    } else {
        Style::default()
    };
    let filter = Paragraph::new(filter_text).style(filter_style).block(
        Block::default()
            .title(SEARCH_ICON)
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(Color::Yellow)),
    );
    frame.render_widget(Clear, main_chunks[0]);
    frame.render_widget(filter, main_chunks[0]);

    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(main_chunks[1]);

    // Tab list - use filtered tabs
    let filtered_tabs = app.get_filtered_tabs();
    let items: Vec<ListItem> = filtered_tabs
        .iter()
        .map(|(_, tab)| ListItem::new(tab.breadcrumb.clone()))
        .collect();

    let list = List::new(items)
        .block(
            Block::default()
                .title(format_title(&format!(
                    "Tabs ({}/{})",
                    filtered_tabs.len(),
                    app.tabs.len()
                )))
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(active_border()),
        )
        .highlight_style(Style::default().bg(Color::DarkGray))
        .highlight_symbol("");

    let mut state = ListState::default();
    state.select(Some(app.tab_picker_selected));

    frame.render_widget(Clear, chunks[0]);
    frame.render_stateful_widget(list, chunks[0], &mut state);

    // Preview pane
    frame.render_widget(Clear, chunks[1]);

    let preview_block = Block::default()
        .title(format_title("Preview"))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::Cyan));

    let preview_inner = preview_block.inner(chunks[1]);
    frame.render_widget(preview_block, chunks[1]);

    if let Some(&(_, tab)) = filtered_tabs.get(app.tab_picker_selected) {
        // Render preview using the tab's service context
        // Note: This may show stale state if the tab's service differs from current_service
        render_service_preview(frame, app, tab.service, preview_inner);
    }
}

fn render_service_preview(frame: &mut Frame, app: &App, service: Service, area: Rect) {
    match service {
        Service::CloudWatchLogGroups => {
            if app.view_mode == ViewMode::Events {
                cw::logs::render_events(frame, app, area);
            } else if app.view_mode == ViewMode::Detail {
                cw::logs::render_group_detail(frame, app, area);
            } else {
                cw::logs::render_groups_list(frame, app, area);
            }
        }
        Service::CloudWatchInsights => cw::render_insights(frame, app, area),
        Service::CloudWatchAlarms => cw::render_alarms(frame, app, area),
        Service::CloudTrailEvents => cloudtrail::render_events(frame, app, area),
        Service::Ec2Instances => {
            if app.ec2_state.current_instance.is_some() {
                ec2::render_instance_detail(frame, area, app);
            } else {
                ec2::render_instances(
                    frame,
                    area,
                    &app.ec2_state,
                    &app.ec2_visible_column_ids
                        .iter()
                        .map(|s| s.as_ref())
                        .collect::<Vec<_>>(),
                    app.mode,
                );
            }
        }
        Service::EcrRepositories => ecr::render_repositories(frame, app, area),
        Service::LambdaFunctions => lambda::render_functions(frame, app, area),
        Service::LambdaApplications => lambda::render_applications(frame, app, area),
        Service::S3Buckets => s3::render_buckets(frame, app, area),
        Service::SqsQueues => sqs::render_queues(frame, app, area),
        Service::CloudFormationStacks => cfn::render_stacks(frame, app, area),
        Service::IamUsers => iam::render_users(frame, app, area),
        Service::IamRoles => iam::render_roles(frame, app, area),
        Service::IamUserGroups => iam::render_user_groups(frame, app, area),
        Service::ApiGatewayApis => apig::render_apis(frame, app, area),
    }
}

fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(r);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}

fn centered_rect_absolute(width: u16, height: u16, r: Rect) -> Rect {
    let x = (r.width.saturating_sub(width)) / 2;
    let y = (r.height.saturating_sub(height)) / 2;
    Rect {
        x: r.x + x,
        y: r.y + y,
        width: width.min(r.width),
        height: height.min(r.height),
    }
}

fn bottom_right_rect(width: u16, height: u16, r: Rect) -> Rect {
    let x = r.width.saturating_sub(width + 1);
    let y = r.height.saturating_sub(height + 1);
    Rect {
        x: r.x + x,
        y: r.y + y,
        width: width.min(r.width),
        height: height.min(r.height),
    }
}

fn render_help_modal(frame: &mut Frame, area: Rect) {
    let help_text = vec![
        Line::from(vec![Span::styled("", red_text()), Span::raw("  Escape")]),
        Line::from(vec![
            Span::styled("", red_text()),
            Span::raw("  Enter/Return"),
        ]),
        Line::from(vec![Span::styled("⇤⇥ ", red_text()), Span::raw("  Tab")]),
        Line::from(vec![Span::styled("", red_text()), Span::raw("  Space")]),
        Line::from(vec![Span::styled("^r ", red_text()), Span::raw("  Ctrl+r")]),
        Line::from(vec![Span::styled("^w ", red_text()), Span::raw("  Ctrl+w")]),
        Line::from(vec![Span::styled("^o ", red_text()), Span::raw("  Ctrl+o")]),
        Line::from(vec![Span::styled("^p ", red_text()), Span::raw("  Ctrl+p")]),
        Line::from(vec![
            Span::styled("^u ", red_text()),
            Span::raw("  Ctrl+u (page up)"),
        ]),
        Line::from(vec![
            Span::styled("^d ", red_text()),
            Span::raw("  Ctrl+d (page down)"),
        ]),
        Line::from(vec![
            Span::styled("[] ", red_text()),
            Span::raw("  [ and ] (switch tabs)"),
        ]),
        Line::from(vec![
            Span::styled("↑↓ ", red_text()),
            Span::raw("  Arrow up/down"),
        ]),
        Line::from(vec![
            Span::styled("←→ ", red_text()),
            Span::raw("  Arrow left/right"),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled("Press ", Style::default()),
            Span::styled("", red_text()),
            Span::styled(" or ", Style::default()),
            Span::styled("", red_text()),
            Span::styled(" to close", Style::default()),
        ]),
    ];

    // Find max line width
    let max_width = help_text
        .iter()
        .map(|line| {
            line.spans
                .iter()
                .map(|span| span.content.len())
                .sum::<usize>()
        })
        .max()
        .unwrap_or(80) as u16;

    // Content dimensions + borders + padding
    let content_width = max_width + 6; // +6 for borders and 1 char padding on each side
    let content_height = help_text.len() as u16 + 2; // +2 for borders

    // Center the dialog
    let popup_width = content_width.min(area.width.saturating_sub(4));
    let popup_height = content_height.min(area.height.saturating_sub(4));

    let popup_area = Rect {
        x: area.x + (area.width.saturating_sub(popup_width)) / 2,
        y: area.y + (area.height.saturating_sub(popup_height)) / 2,
        width: popup_width,
        height: popup_height,
    };

    let paragraph = Paragraph::new(help_text)
        .block(
            Block::default()
                .title(Span::styled(
                    " Help ",
                    Style::default().add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(active_border())
                .padding(Padding::horizontal(1)),
        )
        .wrap(Wrap { trim: false });

    frame.render_widget(Clear, popup_area);
    frame.render_widget(paragraph, popup_area);
}

fn render_region_selector(frame: &mut Frame, app: &App, area: Rect) {
    let popup_area = centered_rect(60, 60, area);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(0)])
        .split(popup_area);

    // Filter input at top
    let filter_text = if app.region_filter_active {
        vec![
            Span::from(&app.region_filter),
            Span::styled("", Style::default().fg(Color::Green)),
        ]
    } else {
        vec![Span::from(&app.region_filter)]
    };
    let filter = filter_area(filter_text, app.region_filter_active);

    // Filtered list below
    let filtered = app.get_filtered_regions();
    let items: Vec<ListItem> = filtered
        .iter()
        .map(|r| {
            let latency_str = match r.latency_ms {
                Some(ms) => format!(" ({}ms)", ms),
                None => String::new(),
            };
            let opt_in = if r.opt_in { "[opt-in] " } else { "" };
            let display = format!(
                "{}{}{} {}{}",
                r.group, r.name, r.code, opt_in, latency_str
            );
            ListItem::new(display)
        })
        .collect();

    let list = List::new(items)
        .block(
            Block::default()
                .title(format_title("Regions"))
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(active_border()),
        )
        .highlight_style(Style::default().bg(Color::DarkGray).fg(Color::White))
        .highlight_symbol("");

    frame.render_widget(Clear, popup_area);
    frame.render_widget(filter, chunks[0]);
    frame.render_stateful_widget(
        list,
        chunks[1],
        &mut ratatui::widgets::ListState::default().with_selected(Some(app.region_picker_selected)),
    );
}

fn render_profile_picker(frame: &mut Frame, app: &App, area: Rect) {
    crate::aws::render_profile_picker(frame, app, area, centered_rect);
}

fn render_session_picker(frame: &mut Frame, app: &App, area: Rect) {
    crate::session::render_session_picker(frame, app, area, centered_rect);
}

fn render_calendar_picker(frame: &mut Frame, app: &App, area: Rect) {
    use ratatui::widgets::calendar::{CalendarEventStore, Monthly};

    let popup_area = centered_rect(50, 50, area);

    let date = app
        .calendar_date
        .unwrap_or_else(|| time::OffsetDateTime::now_utc().date());

    let field_name = match app.calendar_selecting {
        CalendarField::StartDate => "Start Date",
        CalendarField::EndDate => "End Date",
    };

    let events = CalendarEventStore::today(
        Style::default()
            .add_modifier(Modifier::BOLD)
            .bg(Color::Blue),
    );

    let calendar = Monthly::new(date, events)
        .block(
            Block::default()
                .title(format_title(&format!("Select {}", field_name)))
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_type(BorderType::Rounded)
                .border_style(active_border()),
        )
        .show_weekdays_header(Style::new().bold().yellow())
        .show_month_header(Style::new().bold().green());

    frame.render_widget(Clear, popup_area);
    frame.render_widget(calendar, popup_area);
}

// Render JSON content with syntax highlighting and scrollbar
pub fn render_json_highlighted(
    frame: &mut Frame,
    area: Rect,
    json_text: &str,
    scroll_offset: usize,
    title: &str,
    is_active: bool,
) {
    let total_lines = json_text.lines().count();
    let line_num_width = total_lines.to_string().len().max(2);

    let lines: Vec<Line> = json_text
        .lines()
        .enumerate()
        .skip(scroll_offset)
        .map(|(idx, line)| {
            let mut spans = Vec::new();

            // Add line number gutter
            let line_num = format!("{:>width$} │ ", idx + 1, width = line_num_width);
            spans.push(Span::styled(line_num, Style::default().fg(Color::DarkGray)));

            let trimmed = line.trim_start();
            let indent = line.len() - trimmed.len();

            if indent > 0 {
                spans.push(Span::raw(" ".repeat(indent)));
            }

            if trimmed.starts_with('"') && trimmed.contains(':') {
                if let Some(colon_pos) = trimmed.find(':') {
                    spans.push(Span::styled(
                        &trimmed[..colon_pos],
                        Style::default().fg(Color::Blue),
                    ));
                    spans.push(Span::raw(&trimmed[colon_pos..]));
                } else {
                    spans.push(Span::raw(trimmed));
                }
            } else if trimmed.starts_with('"') {
                spans.push(Span::styled(trimmed, Style::default().fg(Color::Green)));
            } else if trimmed.starts_with("true") || trimmed.starts_with("false") {
                spans.push(Span::styled(trimmed, Style::default().fg(Color::Yellow)));
            } else if trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) {
                spans.push(Span::styled(trimmed, Style::default().fg(Color::Magenta)));
            } else {
                spans.push(Span::raw(trimmed));
            }

            Line::from(spans)
        })
        .collect();

    let block = titled_block(title).border_style(if is_active {
        active_border()
    } else {
        Style::default()
    });

    frame.render_widget(Paragraph::new(lines).block(block), area);

    if total_lines > 0 {
        render_scrollbar(
            frame,
            area.inner(Margin {
                vertical: 1,
                horizontal: 0,
            }),
            total_lines,
            scroll_offset,
        );
    }
}

// Render a tags tab with description and table
pub fn render_tags_section<F>(frame: &mut Frame, area: Rect, render_table: F)
where
    F: FnOnce(&mut Frame, Rect),
{
    render_table(frame, area);
}

// Render a permissions tab with description and policies table
pub fn render_permissions_section<F>(
    frame: &mut Frame,
    area: Rect,
    _description: &str,
    render_table: F,
) where
    F: FnOnce(&mut Frame, Rect),
{
    render_table(frame, area);
}

// Render a last accessed tab with description, note, and table
pub fn render_last_accessed_section<F>(
    frame: &mut Frame,
    area: Rect,
    _description: &str,
    _note: &str,
    render_table: F,
) where
    F: FnOnce(&mut Frame, Rect),
{
    render_table(frame, area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::Service;
    use crate::app::Tab;
    use crate::ecr::image::Image as EcrImage;
    use crate::ecr::repo::Repository as EcrRepository;
    use crate::keymap::Action;
    use crate::lambda;
    use crate::ui::cw::logs::filtered_log_groups;
    use crate::ui::table::Column;

    fn test_app() -> App {
        App::new_without_client("test".to_string(), Some("us-east-1".to_string()))
    }

    fn test_app_no_region() -> App {
        App::new_without_client("test".to_string(), None)
    }

    #[test]
    fn test_expanded_content_wrapping_marks_continuation_lines() {
        // Simulate the wrapping logic
        let max_width = 50;
        let col_name = "Message: ";
        let value = "This is a very long message that will definitely exceed the maximum width and need to be wrapped";
        let full_line = format!("{}{}", col_name, value);

        let mut lines = Vec::new();

        if full_line.len() <= max_width {
            lines.push((full_line, true));
        } else {
            let first_chunk_len = max_width.min(full_line.len());
            lines.push((full_line[..first_chunk_len].to_string(), true));

            let mut remaining = &full_line[first_chunk_len..];
            while !remaining.is_empty() {
                let take = max_width.min(remaining.len());
                lines.push((remaining[..take].to_string(), false));
                remaining = &remaining[take..];
            }
        }

        // First line should be marked as first (true)
        assert!(lines[0].1);
        // Continuation lines should be marked as continuation (false)
        assert!(!lines[1].1);
        assert!(lines.len() > 1);
    }

    #[test]
    fn test_expanded_content_short_line_not_wrapped() {
        let max_width = 100;
        let col_name = "Timestamp: ";
        let value = "2025-03-13 19:49:30 (UTC)";
        let full_line = format!("{}{}", col_name, value);

        let mut lines = Vec::new();

        if full_line.len() <= max_width {
            lines.push((full_line.clone(), true));
        } else {
            let first_chunk_len = max_width.min(full_line.len());
            lines.push((full_line[..first_chunk_len].to_string(), true));

            let mut remaining = &full_line[first_chunk_len..];
            while !remaining.is_empty() {
                let take = max_width.min(remaining.len());
                lines.push((remaining[..take].to_string(), false));
                remaining = &remaining[take..];
            }
        }

        // Should only have one line
        assert_eq!(lines.len(), 1);
        assert!(lines[0].1);
        assert_eq!(lines[0].0, full_line);
    }

    #[test]
    fn test_tabs_display_with_separator() {
        // Test that tabs are formatted with ⋮ separator
        let tabs = [
            Tab {
                service: Service::CloudWatchLogGroups,
                title: "CloudWatch › Log Groups".to_string(),
                breadcrumb: "CloudWatch › Log Groups".to_string(),
            },
            Tab {
                service: Service::CloudWatchInsights,
                title: "CloudWatch › Logs Insights".to_string(),
                breadcrumb: "CloudWatch › Logs Insights".to_string(),
            },
        ];

        let mut spans = Vec::new();
        for (i, tab) in tabs.iter().enumerate() {
            if i > 0 {
                spans.push(Span::raw(""));
            }
            spans.push(Span::raw(tab.title.clone()));
        }

        // Should have 3 spans: Tab1, separator, Tab2
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[1].content, "");
    }

    #[test]
    fn test_current_tab_highlighted() {
        let tabs = [
            crate::app::Tab {
                service: Service::CloudWatchLogGroups,
                title: "CloudWatch › Log Groups".to_string(),
                breadcrumb: "CloudWatch › Log Groups".to_string(),
            },
            crate::app::Tab {
                service: Service::CloudWatchInsights,
                title: "CloudWatch › Logs Insights".to_string(),
                breadcrumb: "CloudWatch › Logs Insights".to_string(),
            },
        ];
        let current_tab = 1;

        let mut spans = Vec::new();
        for (i, tab) in tabs.iter().enumerate() {
            if i > 0 {
                spans.push(Span::raw(""));
            }
            if i == current_tab {
                spans.push(Span::styled(
                    tab.title.clone(),
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                ));
            } else {
                spans.push(Span::raw(tab.title.clone()));
            }
        }

        // Current tab (index 2 in spans) should have yellow color
        assert_eq!(spans[2].style.fg, Some(Color::Yellow));
        assert!(spans[2].style.add_modifier.contains(Modifier::BOLD));
        // First tab should have no styling
        assert_eq!(spans[0].style.fg, None);
    }

    #[test]
    fn test_lambda_application_update_complete_shows_green_checkmark() {
        let app = crate::lambda::Application {
            name: "test-stack".to_string(),
            arn: "arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/abc123"
                .to_string(),
            description: "Test stack".to_string(),
            status: "UPDATE_COMPLETE".to_string(),
            last_modified: "2025-10-31 12:00:00 (UTC)".to_string(),
        };

        let col = ApplicationColumn::Status;
        let (text, style) = col.render(&app);
        assert_eq!(text, "✅ UPDATE_COMPLETE");
        assert_eq!(style.fg, Some(Color::Green));
    }

    #[test]
    fn test_lambda_application_create_complete_shows_green_checkmark() {
        let app = crate::lambda::Application {
            name: "test-stack".to_string(),
            arn: "arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/abc123"
                .to_string(),
            description: "Test stack".to_string(),
            status: "CREATE_COMPLETE".to_string(),
            last_modified: "2025-10-31 12:00:00 (UTC)".to_string(),
        };

        let col = ApplicationColumn::Status;
        let (text, style) = col.render(&app);
        assert_eq!(text, "✅ CREATE_COMPLETE");
        assert_eq!(style.fg, Some(Color::Green));
    }

    #[test]
    fn test_lambda_application_other_status_shows_default() {
        let app = crate::lambda::Application {
            name: "test-stack".to_string(),
            arn: "arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/abc123"
                .to_string(),
            description: "Test stack".to_string(),
            status: "UPDATE_IN_PROGRESS".to_string(),
            last_modified: "2025-10-31 12:00:00 (UTC)".to_string(),
        };

        let col = ApplicationColumn::Status;
        let (text, style) = col.render(&app);
        assert_eq!(text, "ℹ️  UPDATE_IN_PROGRESS");
        assert_eq!(style.fg, Some(ratatui::style::Color::LightBlue));
    }

    #[test]
    fn test_lambda_application_status_complete() {
        let app = crate::lambda::Application {
            name: "test-stack".to_string(),
            arn: "arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/abc123"
                .to_string(),
            description: "Test stack".to_string(),
            status: "UPDATE_COMPLETE".to_string(),
            last_modified: "2025-10-31 12:00:00 (UTC)".to_string(),
        };

        let col = ApplicationColumn::Status;
        let (text, style) = col.render(&app);
        assert_eq!(text, "✅ UPDATE_COMPLETE");
        assert_eq!(style.fg, Some(ratatui::style::Color::Green));
    }

    #[test]
    fn test_lambda_application_status_failed() {
        let app = crate::lambda::Application {
            name: "test-stack".to_string(),
            arn: "arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/abc123"
                .to_string(),
            description: "Test stack".to_string(),
            status: "UPDATE_FAILED".to_string(),
            last_modified: "2025-10-31 12:00:00 (UTC)".to_string(),
        };

        let col = ApplicationColumn::Status;
        let (text, style) = col.render(&app);
        assert_eq!(text, "❌ UPDATE_FAILED");
        assert_eq!(style.fg, Some(ratatui::style::Color::Red));
    }

    #[test]
    fn test_lambda_application_status_rollback() {
        let app = crate::lambda::Application {
            name: "test-stack".to_string(),
            arn: "arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/abc123"
                .to_string(),
            description: "Test stack".to_string(),
            status: "UPDATE_ROLLBACK_IN_PROGRESS".to_string(),
            last_modified: "2025-10-31 12:00:00 (UTC)".to_string(),
        };

        let col = ApplicationColumn::Status;
        let (text, style) = col.render(&app);
        assert_eq!(text, "❌ UPDATE_ROLLBACK_IN_PROGRESS");
        assert_eq!(style.fg, Some(ratatui::style::Color::Red));
    }

    #[test]
    fn test_tab_picker_shows_breadcrumb_and_preview() {
        let tabs = [
            crate::app::Tab {
                service: crate::app::Service::CloudWatchLogGroups,
                title: "CloudWatch › Log Groups".to_string(),
                breadcrumb: "CloudWatch › Log Groups".to_string(),
            },
            crate::app::Tab {
                service: crate::app::Service::CloudWatchAlarms,
                title: "CloudWatch > Alarms".to_string(),
                breadcrumb: "CloudWatch > Alarms".to_string(),
            },
        ];

        // Tab picker should show breadcrumb in list
        let selected_idx = 1;
        let selected_tab = &tabs[selected_idx];
        assert_eq!(selected_tab.breadcrumb, "CloudWatch > Alarms");
        assert_eq!(selected_tab.title, "CloudWatch > Alarms");

        // Preview should show both service and tab name
        assert!(selected_tab.breadcrumb.contains("CloudWatch"));
        assert!(selected_tab.breadcrumb.contains("Alarms"));
    }

    #[test]
    fn test_tab_picker_has_active_border() {
        // Tab picker should have green border like other active controls
        let border_style = Style::default().fg(Color::Green);
        let border_type = BorderType::Plain;

        // Verify green color is used
        assert_eq!(border_style.fg, Some(Color::Green));
        // Verify plain border type
        assert_eq!(border_type, BorderType::Plain);
    }

    #[test]
    fn test_tab_picker_title_is_tabs() {
        // Tab picker should be titled "Tabs" not "Open Tabs"
        let title = " Tabs ";
        assert_eq!(title.trim(), "Tabs");
        assert!(!title.contains("Open"));
    }

    #[test]
    fn test_s3_bucket_tabs_no_count_in_tabs() {
        // S3 bucket type tabs should not show counts (only in table title)
        let general_purpose_tab = "General purpose buckets (All AWS Regions)";
        let directory_tab = "Directory buckets";

        // Verify no count in tab labels
        assert!(!general_purpose_tab.contains("(0)"));
        assert!(!general_purpose_tab.contains("(1)"));
        assert!(!directory_tab.contains("(0)"));
        assert!(!directory_tab.contains("(1)"));

        // Count should only appear in table title
        let table_title = " General purpose buckets (42) ";
        assert!(table_title.contains("(42)"));
    }

    #[test]
    fn test_s3_bucket_column_preferences_shows_bucket_columns() {
        use crate::app::S3BucketColumn;

        let app = test_app();

        // Should have 3 bucket columns (Name, Region, CreationDate)
        assert_eq!(app.s3_bucket_column_ids.len(), 3);
        assert_eq!(app.s3_bucket_visible_column_ids.len(), 3);

        // Verify column names
        assert_eq!(S3BucketColumn::Name.name(), "Name");
        assert_eq!(S3BucketColumn::Region.name(), "Region");
        assert_eq!(S3BucketColumn::CreationDate.name(), "Creation date");
    }

    #[test]
    fn test_s3_bucket_columns_not_cloudwatch_columns() {
        let app = test_app();

        // S3 bucket columns should be different from CloudWatch log group columns
        let bucket_col_names: Vec<String> = app
            .s3_bucket_column_ids
            .iter()
            .filter_map(|id| BucketColumn::from_id(id).map(|c| c.name()))
            .collect();
        let log_col_names: Vec<String> = app
            .cw_log_group_column_ids
            .iter()
            .filter_map(|id| LogGroupColumn::from_id(id).map(|c| c.name().to_string()))
            .collect();

        // Verify they're different
        assert_ne!(bucket_col_names, log_col_names);

        // Verify S3 columns don't contain CloudWatch-specific terms
        assert!(!bucket_col_names.contains(&"Log group".to_string()));
        assert!(!bucket_col_names.contains(&"Stored bytes".to_string()));

        // Verify S3 columns contain S3-specific terms
        assert!(bucket_col_names.contains(&"Creation date".to_string()));

        // Region should NOT be in bucket columns (shown only when expanded)
        assert!(!bucket_col_names.contains(&"AWS Region".to_string()));
    }

    #[test]
    fn test_s3_bucket_column_toggle() {
        use crate::app::Service;

        let mut app = test_app();
        app.current_service = Service::S3Buckets;

        // Initially 3 columns visible
        assert_eq!(app.s3_bucket_visible_column_ids.len(), 3);

        // Simulate toggling off the Region column (index 1)
        let col = app.s3_bucket_column_ids[1];
        if let Some(pos) = app
            .s3_bucket_visible_column_ids
            .iter()
            .position(|c| *c == col)
        {
            app.s3_bucket_visible_column_ids.remove(pos);
        }

        assert_eq!(app.s3_bucket_visible_column_ids.len(), 2);
        assert!(!app
            .s3_bucket_visible_column_ids
            .contains(&"column.s3.bucket.region"));

        // Toggle it back on
        app.s3_bucket_visible_column_ids.push(col);
        assert_eq!(app.s3_bucket_visible_column_ids.len(), 3);
        assert!(app
            .s3_bucket_visible_column_ids
            .contains(&"column.s3.bucket.region"));
    }

    #[test]
    fn test_s3_preferences_dialog_title() {
        // S3 bucket preferences should be titled "Preferences" without hints
        let title = " Preferences ";
        assert_eq!(title.trim(), "Preferences");
        assert!(!title.contains("Space"));
        assert!(!title.contains("toggle"));
    }

    #[test]
    fn test_column_selector_mode_has_hotkey_hints() {
        // ColumnSelector mode should show hotkey hints in status bar
        let help = " ↑↓: scroll | ␣: toggle | esc: close ";

        // Verify key hints are present
        assert!(help.contains("␣: toggle"));
        assert!(help.contains("↑↓: scroll"));
        assert!(help.contains("esc: close"));

        // Should NOT contain unavailable keys
        assert!(!help.contains(""));
        assert!(!help.contains("^w"));
    }

    #[test]
    fn test_date_range_title_no_hints() {
        // Date range title should not contain hints
        let title = " Date range ";

        // Should NOT contain hints
        assert!(!title.contains("Tab to switch"));
        assert!(!title.contains("Space to change"));
        assert!(!title.contains("("));
        assert!(!title.contains(")"));
    }

    #[test]
    fn test_event_filter_mode_has_hints_in_status_bar() {
        // EventFilterInput mode should show hints in status bar
        let help = " tab: switch | ␣: change unit | enter: apply | esc: cancel | ctrl+w: close ";

        // Verify key hints are present
        assert!(help.contains("tab: switch"));
        assert!(help.contains("␣: change unit"));
        assert!(help.contains("enter: apply"));
        assert!(help.contains("esc: cancel"));
    }

    #[test]
    fn test_s3_preferences_shows_all_columns() {
        let app = test_app();

        // Should have 3 bucket columns (Name, Region, CreationDate)
        assert_eq!(app.s3_bucket_column_ids.len(), 3);

        // All should be visible by default
        assert_eq!(app.s3_bucket_visible_column_ids.len(), 3);

        // Verify all column names
        let names: Vec<String> = app
            .s3_bucket_column_ids
            .iter()
            .filter_map(|id| BucketColumn::from_id(id).map(|c| c.name()))
            .collect();
        assert_eq!(names, vec!["Name", "Region", "Creation date"]);
    }

    #[test]
    fn test_s3_preferences_has_active_border() {
        use ratatui::style::Color;

        // S3 preferences should have green border (active state)
        let border_color = Color::Green;
        assert_eq!(border_color, Color::Green);

        // Not cyan (inactive)
        assert_ne!(border_color, Color::Cyan);
    }

    #[test]
    fn test_s3_table_loses_focus_when_preferences_shown() {
        use crate::app::Service;
        use crate::keymap::Mode;
        use ratatui::style::Color;

        let mut app = test_app();
        app.current_service = Service::S3Buckets;

        // When in Normal mode, table should be active (green)
        app.mode = Mode::Normal;
        let is_active = app.mode != Mode::ColumnSelector;
        let border_color = if is_active {
            Color::Green
        } else {
            Color::White
        };
        assert_eq!(border_color, Color::Green);

        // When in ColumnSelector mode, table should be inactive (white)
        app.mode = Mode::ColumnSelector;
        let is_active = app.mode != Mode::ColumnSelector;
        let border_color = if is_active {
            Color::Green
        } else {
            Color::White
        };
        assert_eq!(border_color, Color::White);
    }

    #[test]
    fn test_s3_object_tabs_cleared_before_render() {
        // Tabs should be cleared before rendering to prevent artifacts
        // This is verified by the Clear widget being rendered before tabs
    }

    #[test]
    fn test_s3_properties_tab_shows_bucket_info() {
        use crate::app::{S3ObjectTab, Service};

        let mut app = test_app();
        app.current_service = Service::S3Buckets;
        app.s3_state.current_bucket = Some("test-bucket".to_string());
        app.s3_state.object_tab = S3ObjectTab::Properties;

        // Properties tab should be selectable
        assert_eq!(app.s3_state.object_tab, S3ObjectTab::Properties);

        // Properties scroll should start at 0
        assert_eq!(app.s3_state.properties_scroll, 0);
    }

    #[test]
    fn test_s3_properties_scrolling() {
        use crate::app::{S3ObjectTab, Service};

        let mut app = test_app();
        app.current_service = Service::S3Buckets;
        app.s3_state.current_bucket = Some("test-bucket".to_string());
        app.s3_state.object_tab = S3ObjectTab::Properties;

        // Initial scroll should be 0
        assert_eq!(app.s3_state.properties_scroll, 0);

        // Scroll down
        app.s3_state.properties_scroll = app.s3_state.properties_scroll.saturating_add(1);
        assert_eq!(app.s3_state.properties_scroll, 1);

        app.s3_state.properties_scroll = app.s3_state.properties_scroll.saturating_add(1);
        assert_eq!(app.s3_state.properties_scroll, 2);

        // Scroll up
        app.s3_state.properties_scroll = app.s3_state.properties_scroll.saturating_sub(1);
        assert_eq!(app.s3_state.properties_scroll, 1);

        app.s3_state.properties_scroll = app.s3_state.properties_scroll.saturating_sub(1);
        assert_eq!(app.s3_state.properties_scroll, 0);

        // Should not go below 0
        app.s3_state.properties_scroll = app.s3_state.properties_scroll.saturating_sub(1);
        assert_eq!(app.s3_state.properties_scroll, 0);
    }

    #[test]
    fn test_s3_parent_prefix_cleared_before_render() {
        // Parent prefix area should be cleared to prevent artifacts
        // Verified by Clear widget being rendered before parent text
    }

    #[test]
    fn test_s3_empty_region_defaults_to_us_east_1() {
        let _app = App::new_without_client("test".to_string(), Some("us-east-1".to_string()));

        // When bucket region is empty, should default to us-east-1
        let empty_region = "";
        let bucket_region = if empty_region.is_empty() {
            "us-east-1"
        } else {
            empty_region
        };
        assert_eq!(bucket_region, "us-east-1");

        // When bucket region is set, should use it
        let set_region = "us-west-2";
        let bucket_region = if set_region.is_empty() {
            "us-east-1"
        } else {
            set_region
        };
        assert_eq!(bucket_region, "us-west-2");
    }

    #[test]
    fn test_s3_properties_has_multiple_blocks() {
        // Properties tab should have 12 separate blocks
        let block_count = 12;
        assert_eq!(block_count, 12);

        // Blocks: Bucket overview, Tags, Default encryption, Intelligent-Tiering,
        // Server access logging, CloudTrail, Event notifications, EventBridge,
        // Transfer acceleration, Object Lock, Requester pays, Static website hosting
    }

    #[test]
    fn test_s3_properties_tables_use_common_component() {
        // Tables should use ratatui Table widget
        // Tags table: Key, Value columns
        let tags_columns = ["Key", "Value"];
        assert_eq!(tags_columns.len(), 2);

        // Intelligent-Tiering table: 5 columns
        let tiering_columns = [
            "Name",
            "Status",
            "Scope",
            "Days to Archive",
            "Days to Deep Archive",
        ];
        assert_eq!(tiering_columns.len(), 5);

        // Event notifications table: 5 columns
        let events_columns = [
            "Name",
            "Event types",
            "Filters",
            "Destination type",
            "Destination",
        ];
        assert_eq!(events_columns.len(), 5);
    }

    #[test]
    fn test_s3_properties_field_format() {
        // Each field should have bold label followed by value
        use ratatui::style::{Modifier, Style};
        use ratatui::text::{Line, Span};

        let label = Line::from(vec![Span::styled(
            "AWS Region",
            Style::default().add_modifier(Modifier::BOLD),
        )]);
        let value = Line::from("us-east-1");

        // Verify label is bold
        assert!(label.spans[0].style.add_modifier.contains(Modifier::BOLD));

        // Verify value is plain text
        assert!(!value.spans[0].style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn test_s3_properties_has_scrollbar() {
        // Properties tab should have vertical scrollbar
        let total_height = 7 + 5 + 6 + 5 + 4 + 4 + 5 + 4 + 4 + 4 + 4 + 4;
        assert_eq!(total_height, 56);

        // If total height exceeds area, scrollbar should be shown
        let area_height = 40;
        assert!(total_height > area_height);
    }

    #[test]
    fn test_s3_bucket_region_fetched_on_open() {
        // When bucket region is empty, it should be fetched before loading objects
        // This prevents PermanentRedirect errors

        // Simulate empty region
        let empty_region = "";
        assert!(empty_region.is_empty());

        // After fetch, region should be populated
        let fetched_region = "us-west-2";
        assert!(!fetched_region.is_empty());
    }

    #[test]
    fn test_s3_filter_space_used_when_hidden() {
        // When filter is hidden (non-Objects tabs), its space should be used by content
        // Objects tab: 4 chunks (prefix, tabs, filter, content)
        // Other tabs: 3 chunks (prefix, tabs, content)

        let objects_chunks = 4;
        let other_chunks = 3;

        assert_eq!(objects_chunks, 4);
        assert_eq!(other_chunks, 3);
        assert!(other_chunks < objects_chunks);
    }

    #[test]
    fn test_s3_properties_scrollable() {
        let mut app = test_app();

        // Properties should be scrollable
        assert_eq!(app.s3_state.properties_scroll, 0);

        // Scroll down
        app.s3_state.properties_scroll += 1;
        assert_eq!(app.s3_state.properties_scroll, 1);

        // Scroll up
        app.s3_state.properties_scroll = app.s3_state.properties_scroll.saturating_sub(1);
        assert_eq!(app.s3_state.properties_scroll, 0);
    }

    #[test]
    fn test_s3_properties_scrollbar_conditional() {
        // Scrollbar should only show when content exceeds viewport
        let content_height = 40;
        let small_viewport = 20;
        let large_viewport = 50;

        // Should show scrollbar
        assert!(content_height > small_viewport);

        // Should not show scrollbar
        assert!(content_height < large_viewport);
    }

    #[test]
    fn test_s3_tabs_visible_with_styling() {
        use ratatui::style::{Color, Modifier, Style};
        use ratatui::text::Span;

        // Active tab should be yellow, bold, and underlined
        let active_style = Style::default()
            .fg(Color::Yellow)
            .add_modifier(Modifier::BOLD | Modifier::UNDERLINED);
        let active_tab = Span::styled("Objects", active_style);
        assert_eq!(active_tab.style.fg, Some(Color::Yellow));
        assert!(active_tab.style.add_modifier.contains(Modifier::BOLD));
        assert!(active_tab.style.add_modifier.contains(Modifier::UNDERLINED));

        // Inactive tab should be gray
        let inactive_style = Style::default().fg(Color::Gray);
        let inactive_tab = Span::styled("Properties", inactive_style);
        assert_eq!(inactive_tab.style.fg, Some(Color::Gray));
    }

    #[test]
    fn test_s3_properties_field_labels_bold() {
        use ratatui::style::{Modifier, Style};
        use ratatui::text::{Line, Span};

        // Field labels should be bold, values should not
        let label = Span::styled(
            "AWS Region: ",
            Style::default().add_modifier(Modifier::BOLD),
        );
        let value = Span::raw("us-east-1");
        let line = Line::from(vec![label.clone(), value.clone()]);

        // Verify label is bold
        assert!(label.style.add_modifier.contains(Modifier::BOLD));

        // Verify value is not bold
        assert!(!value.style.add_modifier.contains(Modifier::BOLD));

        // Verify line has both parts
        assert_eq!(line.spans.len(), 2);
    }

    #[test]
    fn test_session_picker_dialog_opaque() {
        // Session picker dialog should use Clear widget to be opaque
        // This prevents background content from showing through
    }

    #[test]
    fn test_status_bar_hotkey_format() {
        // Status bar should use ⋮ separator, ^ for ctrl, uppercase for shift+char, and highlight keys in red

        // Test separator
        let separator = "";
        assert_eq!(separator, "");

        // Test ctrl format
        let ctrl_key = "^r";
        assert!(ctrl_key.starts_with("^"));
        assert!(!ctrl_key.contains("ctrl+"));
        assert!(!ctrl_key.contains("ctrl-"));

        // Test shift+char format (uppercase)
        let shift_key = "^R";
        assert!(shift_key.contains("^R"));
        assert!(!shift_key.contains("shift+"));
        assert!(!shift_key.contains("shift-"));

        // Test that old formats are not used
        let old_separator = " | ";
        assert_ne!(separator, old_separator);
    }

    #[test]
    fn test_space_key_uses_unicode_symbol() {
        // Space key should use ␣ (U+2423 OPEN BOX) symbol, not "space" text
        let space_symbol = "";
        assert_eq!(space_symbol, "");
        assert_eq!(space_symbol.len(), 3); // UTF-8 bytes

        // Should not use text "space"
        assert_ne!(space_symbol, "space");
        assert_ne!(space_symbol, "SPC");
    }

    #[test]
    fn test_region_hotkey_uses_space_menu() {
        // Region should use ␣→r (space menu), not ^R (Ctrl+Shift+R)
        let region_hotkey = "␣→r";
        assert_eq!(region_hotkey, "␣→r");

        // Should not use ^R for region
        assert_ne!(region_hotkey, "^R");
        assert_ne!(region_hotkey, "ctrl+shift+r");
    }

    #[test]
    fn test_no_incorrect_hotkey_patterns_in_ui() {
        // This test validates that common hotkey mistakes are not present in the UI code
        let source = include_str!("mod.rs");

        // Split at #[cfg(test)] to only check non-test code
        let ui_code = if let Some(pos) = source.find("#[cfg(test)]") {
            &source[..pos]
        } else {
            source
        };

        // Check for "space" text instead of ␣ symbol in hotkeys
        let space_text_pattern = r#"Span::styled("space""#;
        assert!(
            !ui_code.contains(space_text_pattern),
            "Found 'space' text in hotkey - should use ␣ symbol instead"
        );

        // Check for ^R followed by region (should be ␣→r)
        let lines_with_ctrl_shift_r: Vec<_> = ui_code
            .lines()
            .enumerate()
            .filter(|(_, line)| {
                line.contains(r#"Span::styled("^R""#) && line.contains("Color::Red")
            })
            .collect();

        assert!(
            lines_with_ctrl_shift_r.is_empty(),
            "Found ^R in hotkeys (should use ␣→r for region): {:?}",
            lines_with_ctrl_shift_r
        );
    }

    #[test]
    fn test_region_only_in_space_menu_not_status_bar() {
        // Region switching should ONLY be in Space menu, NOT in status bar hotkeys
        let source = include_str!("mod.rs");

        // Find the space menu section
        let space_menu_start = source
            .find("fn render_space_menu")
            .expect("render_space_menu function not found");
        let space_menu_end = space_menu_start
            + source[space_menu_start..]
                .find("fn render_service_picker")
                .expect("render_service_picker not found");
        let space_menu_code = &source[space_menu_start..space_menu_end];

        // Verify region IS in space menu
        assert!(
            space_menu_code.contains(r#"Span::raw(" regions")"#),
            "Region must be in Space menu"
        );

        // Find status bar section (render_bottom_bar)
        let status_bar_start = source
            .find("fn render_bottom_bar")
            .expect("render_bottom_bar function not found");
        let status_bar_end = status_bar_start
            + source[status_bar_start..]
                .find("\nfn render_")
                .expect("Next function not found");
        let status_bar_code = &source[status_bar_start..status_bar_end];

        // Verify region is NOT in status bar
        assert!(
            !status_bar_code.contains(" region ⋮ "),
            "Region hotkey must NOT be in status bar - it's only in Space menu!"
        );
        assert!(
            !status_bar_code.contains("␣→r"),
            "Region hotkey (␣→r) must NOT be in status bar - it's only in Space menu!"
        );
        assert!(
            !status_bar_code.contains("^R"),
            "Region hotkey (^R) must NOT be in status bar - it's only in Space menu!"
        );
    }

    #[test]
    fn test_s3_bucket_preview_permanent_redirect_handled() {
        // PermanentRedirect errors should be silently handled
        // Empty preview should be inserted to prevent retry
        let error_msg = "PermanentRedirect";
        assert!(error_msg.contains("PermanentRedirect"));

        // Verify empty preview prevents retry
        let mut preview_map: std::collections::HashMap<String, Vec<crate::app::S3Object>> =
            std::collections::HashMap::new();
        preview_map.insert("bucket".to_string(), vec![]);
        assert!(preview_map.contains_key("bucket"));
    }

    #[test]
    fn test_s3_objects_hint_is_open() {
        // Hint should say "open" not "open folder" or "drill down"
        let hint = "open";
        assert_eq!(hint, "open");
        assert_ne!(hint, "drill down");
        assert_ne!(hint, "open folder");
    }

    #[test]
    fn test_s3_service_tabs_use_cyan() {
        // Service tabs should use cyan color when active
        let active_color = Color::Cyan;
        assert_eq!(active_color, Color::Cyan);
        assert_ne!(active_color, Color::Yellow);
    }

    #[test]
    fn test_s3_column_names_use_orange() {
        // Column names should use orange (LightRed) color
        let column_color = Color::LightRed;
        assert_eq!(column_color, Color::LightRed);
    }

    #[test]
    fn test_s3_bucket_errors_shown_in_expanded_rows() {
        // Bucket errors should be stored and displayed in expanded rows
        let mut errors: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        errors.insert("bucket".to_string(), "Error message".to_string());
        assert!(errors.contains_key("bucket"));
        assert_eq!(errors.get("bucket").unwrap(), "Error message");
    }

    #[test]
    fn test_cloudwatch_alarms_page_input() {
        // Page input should work for CloudWatch alarms
        let mut app = test_app();
        app.current_service = Service::CloudWatchAlarms;
        app.page_input = "2".to_string();

        // Verify page input is set
        assert_eq!(app.page_input, "2");
    }

    #[test]
    fn test_tabs_row_shows_profile_info() {
        // Tabs row should show profile, account, region, identity, and timestamp
        let profile = "default";
        let account = "123456789012";
        let region = "us-west-2";
        let identity = "role:/MyRole";

        let info = format!(
            "Profile: {} ⋮ Account: {} ⋮ Region: {} ⋮ Identity: {}",
            profile, account, region, identity
        );
        assert!(info.contains("Profile:"));
        assert!(info.contains("Account:"));
        assert!(info.contains("Region:"));
        assert!(info.contains("Identity:"));
        assert!(info.contains(""));
    }

    #[test]
    fn test_tabs_row_profile_labels_are_bold() {
        // Profile info labels should use bold modifier
        let label_style = Style::default()
            .fg(Color::White)
            .add_modifier(Modifier::BOLD);
        assert!(label_style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn test_profile_info_not_duplicated() {
        // Profile info should only appear once (in tabs row, not in top bar)
        // Top bar should only show breadcrumbs
        let breadcrumbs = "CloudWatch > Alarms";
        assert!(!breadcrumbs.contains("Profile:"));
        assert!(!breadcrumbs.contains("Account:"));
    }

    #[test]
    fn test_s3_column_headers_are_cyan() {
        // All table column headers should use Cyan color
        let header_style = Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD);
        assert_eq!(header_style.fg, Some(Color::Cyan));
        assert!(header_style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn test_s3_nested_objects_can_be_expanded() {
        // Nested objects (second level folders) should be expandable
        // Visual index should map to actual object including nested items
        let mut app = test_app();
        app.current_service = Service::S3Buckets;
        app.s3_state.current_bucket = Some("bucket".to_string());

        // Add a top-level folder
        app.s3_state.objects.push(crate::app::S3Object {
            key: "folder1/".to_string(),
            size: 0,
            last_modified: String::new(),
            is_prefix: true,
            storage_class: String::new(),
        });

        // Expand it
        app.s3_state
            .expanded_prefixes
            .insert("folder1/".to_string());

        // Add nested folder in preview
        let nested = vec![crate::app::S3Object {
            key: "folder1/subfolder/".to_string(),
            size: 0,
            last_modified: String::new(),
            is_prefix: true,
            storage_class: String::new(),
        }];
        app.s3_state
            .prefix_preview
            .insert("folder1/".to_string(), nested);

        // Visual index 1 should be the nested folder
        app.s3_state.selected_object = 1;

        // Should be able to expand nested folder
        assert!(app.s3_state.current_bucket.is_some());
    }

    #[test]
    fn test_s3_nested_folder_shows_expand_indicator() {
        use crate::app::{S3Object, Service};

        let mut app = test_app();
        app.current_service = Service::S3Buckets;
        app.s3_state.current_bucket = Some("test-bucket".to_string());

        // Add parent folder
        app.s3_state.objects = vec![S3Object {
            key: "parent/".to_string(),
            size: 0,
            last_modified: "2024-01-01T00:00:00Z".to_string(),
            is_prefix: true,
            storage_class: String::new(),
        }];

        // Expand parent and add nested folder
        app.s3_state.expanded_prefixes.insert("parent/".to_string());
        app.s3_state.prefix_preview.insert(
            "parent/".to_string(),
            vec![S3Object {
                key: "parent/child/".to_string(),
                size: 0,
                last_modified: "2024-01-01T00:00:00Z".to_string(),
                is_prefix: true,
                storage_class: String::new(),
            }],
        );

        // Nested folder should show ▶ when collapsed
        let child = &app.s3_state.prefix_preview.get("parent/").unwrap()[0];
        let is_expanded = app.s3_state.expanded_prefixes.contains(&child.key);
        let indicator = if is_expanded { "" } else { "" };
        assert_eq!(indicator, "");

        // After expanding, should show ▼
        app.s3_state
            .expanded_prefixes
            .insert("parent/child/".to_string());
        let is_expanded = app.s3_state.expanded_prefixes.contains(&child.key);
        let indicator = if is_expanded { "" } else { "" };
        assert_eq!(indicator, "");
    }

    #[test]
    fn test_tabs_row_always_visible() {
        // Tabs row should always be visible (shows profile info)
        // Even when on service picker
        let app = test_app();
        assert!(!app.service_selected); // On service picker
                                        // Tabs row should still render with profile info
    }

    #[test]
    fn test_no_duplicate_breadcrumbs_at_root() {
        // When at root level (e.g., CloudWatch › Alarms), don't show duplicate breadcrumb
        let mut app = test_app();
        app.current_service = Service::CloudWatchAlarms;
        app.service_selected = true;
        app.tabs.push(crate::app::Tab {
            service: Service::CloudWatchAlarms,
            title: "CloudWatch > Alarms".to_string(),
            breadcrumb: "CloudWatch > Alarms".to_string(),
        });

        // At root level, breadcrumb should not be shown separately
        // (it's already in the tab)
        assert_eq!(app.breadcrumbs(), "CloudWatch > Alarms");
    }

    #[test]
    fn test_preferences_headers_use_cyan_underline() {
        // Preferences section headers should use cyan with underline, not box drawing
        let header_style = Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD | Modifier::UNDERLINED);
        assert_eq!(header_style.fg, Some(Color::Cyan));
        assert!(header_style.add_modifier.contains(Modifier::BOLD));
        assert!(header_style.add_modifier.contains(Modifier::UNDERLINED));

        // Should not use box drawing characters
        let header_text = "Columns";
        assert!(!header_text.contains(""));
    }

    #[test]
    fn test_alarm_pagination_shows_actual_pages() {
        // Pagination should show "Page X of Y", not page size selector
        let page_size = 10;
        let total_items = 25;
        let total_pages = (total_items + page_size - 1) / page_size;
        let current_page = 1;

        let pagination = format!("Page {} of {}", current_page, total_pages);
        assert_eq!(pagination, "Page 1 of 3");
        assert!(!pagination.contains("[1]"));
        assert!(!pagination.contains("[2]"));
    }

    #[test]
    fn test_mode_indicator_uses_insert_not_input() {
        // Mode indicator should say "INSERT" not "INPUT"
        let mode_text = " INSERT ";
        assert_eq!(mode_text, " INSERT ");
        assert_ne!(mode_text, " INPUT ");
    }

    #[test]
    fn test_service_picker_shows_insert_mode_when_typing() {
        // Service picker should show INSERT mode when filter is not empty
        let mut app = test_app();
        app.mode = Mode::ServicePicker;
        app.service_picker.filter = "cloud".to_string();

        // Should show INSERT mode
        assert!(!app.service_picker.filter.is_empty());
    }

    #[test]
    fn test_log_events_no_horizontal_scrollbar() {
        // Log events should not show horizontal scrollbar
        // Only vertical scrollbar for navigating events
        // Message column truncates with ellipsis, expand to see full content
        let app = test_app();

        // Log events only have 2 columns: Timestamp and Message
        // No horizontal scrolling needed - message truncates
        assert_eq!(app.cw_log_event_visible_column_ids.len(), 2);

        // Horizontal scroll offset should not be used for events
        assert_eq!(app.log_groups_state.event_horizontal_scroll, 0);
    }

    #[test]
    fn test_log_events_expansion_stays_visible_when_scrolling() {
        // Expanded log event should stay visible when scrolling to other events
        // Same behavior as CloudWatch Alarms
        let mut app = test_app();

        // Expand event at index 0
        app.log_groups_state.expanded_event = Some(0);
        app.log_groups_state.event_scroll_offset = 0;

        // Scroll to event 1
        app.log_groups_state.event_scroll_offset = 1;

        // Expanded event should still be set and visible
        assert_eq!(app.log_groups_state.expanded_event, Some(0));
    }

    #[test]
    fn test_log_events_right_arrow_expands() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::Events;

        app.log_groups_state.log_events = vec![rusticity_core::LogEvent {
            timestamp: chrono::Utc::now(),
            message: "Test log message".to_string(),
        }];
        app.log_groups_state.event_scroll_offset = 0;

        assert_eq!(app.log_groups_state.expanded_event, None);

        // Right arrow - should expand
        app.handle_action(Action::NextPane);
        assert_eq!(app.log_groups_state.expanded_event, Some(0));
    }

    #[test]
    fn test_log_events_left_arrow_collapses() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::Events;

        app.log_groups_state.log_events = vec![rusticity_core::LogEvent {
            timestamp: chrono::Utc::now(),
            message: "Test log message".to_string(),
        }];
        app.log_groups_state.event_scroll_offset = 0;
        app.log_groups_state.expanded_event = Some(0);

        // Left arrow - should collapse
        app.handle_action(Action::PrevPane);
        assert_eq!(app.log_groups_state.expanded_event, None);
    }

    #[test]
    fn test_log_events_expanded_content_replaces_tabs() {
        // Expanded content should replace tabs with spaces to avoid rendering artifacts
        let message_with_tabs = "[INFO]\t2025-10-22T13:41:37.601Z\tb2227e1c";
        let cleaned = message_with_tabs.replace('\t', "    ");

        assert!(!cleaned.contains('\t'));
        assert!(cleaned.contains("    "));
        assert_eq!(cleaned, "[INFO]    2025-10-22T13:41:37.601Z    b2227e1c");
    }

    #[test]
    fn test_log_events_navigation_skips_expanded_overlay() {
        // When navigating down from an expanded event, selection should skip to next event
        // Empty rows are added to table to reserve space, but navigation uses event indices
        let mut app = test_app();

        // Expand event at index 0
        app.log_groups_state.expanded_event = Some(0);
        app.log_groups_state.event_scroll_offset = 0;

        // Navigate down - should go to event 1, not expanded overlay lines
        app.log_groups_state.event_scroll_offset = 1;

        // Selection is now on event 1
        assert_eq!(app.log_groups_state.event_scroll_offset, 1);

        // Expanded event 0 is still expanded
        assert_eq!(app.log_groups_state.expanded_event, Some(0));
    }

    #[test]
    fn test_log_events_empty_rows_reserve_space_for_overlay() {
        // Empty rows are added to table for expanded content to prevent overlay from covering next events
        // This ensures selection highlight is visible on the correct row
        let message = "Long message that will wrap across multiple lines when expanded";
        let max_width = 50;

        // Calculate how many lines this would take
        let full_line = format!("Message: {}", message);
        let line_count = full_line.len().div_ceil(max_width);

        // Should be at least 2 lines for this message
        assert!(line_count >= 2);

        // Empty rows equal to line_count should be added to reserve space
        // This prevents the overlay from covering the next event's selection highlight
    }

    #[test]
    fn test_preferences_title_no_hints() {
        // All preferences dialogs should have clean titles without hints
        // Hints should be in status bar instead
        let s3_title = " Preferences ";
        let events_title = " Preferences ";
        let alarms_title = " Preferences ";

        assert_eq!(s3_title.trim(), "Preferences");
        assert_eq!(events_title.trim(), "Preferences");
        assert_eq!(alarms_title.trim(), "Preferences");

        // No hints in titles
        assert!(!s3_title.contains("Space"));
        assert!(!events_title.contains("Space"));
        assert!(!alarms_title.contains("Tab"));
    }

    #[test]
    fn test_page_navigation_works_for_events() {
        // Page navigation (e.g., "2P") should work for log events
        let mut app = test_app();
        app.view_mode = ViewMode::Events;

        // Simulate having 50 events
        app.log_groups_state.event_scroll_offset = 0;

        // Navigate to page 2 (page_size = 20, so target_index = 20)
        let page = 2;
        let page_size = 20;
        let target_index = (page - 1) * page_size;

        assert_eq!(target_index, 20);

        // After navigation, page_input should be cleared
        app.page_input.clear();
        assert!(app.page_input.is_empty());
    }

    #[test]
    fn test_status_bar_shows_tab_hint_for_alarms_preferences() {
        // Alarms preferences should show Tab hint in status bar (has multiple sections)
        // Other preferences don't need Tab hint
        let app = test_app();

        // Alarms has sections: Columns, View As, Page Size, Wrap Lines
        // So it needs Tab navigation hint
        assert_eq!(app.current_service, Service::CloudWatchLogGroups);

        // When current_service is CloudWatchAlarms, Tab hint should be shown
        // This is checked in the status bar rendering logic
    }

    #[test]
    fn test_column_selector_shows_correct_columns_per_service() {
        use crate::app::Service;

        // S3 Buckets should show bucket columns
        let mut app = test_app();
        app.current_service = Service::S3Buckets;
        let bucket_col_names: Vec<String> = app
            .s3_bucket_column_ids
            .iter()
            .filter_map(|id| BucketColumn::from_id(id).map(|c| c.name()))
            .collect();
        assert_eq!(bucket_col_names, vec!["Name", "Region", "Creation date"]);

        // CloudWatch Log Groups should show log group columns
        app.current_service = Service::CloudWatchLogGroups;
        let log_col_names: Vec<String> = app
            .cw_log_group_column_ids
            .iter()
            .filter_map(|id| LogGroupColumn::from_id(id).map(|c| c.name().to_string()))
            .collect();
        assert_eq!(
            log_col_names,
            vec![
                "Log group",
                "Log class",
                "Retention",
                "Stored bytes",
                "Creation time",
                "ARN"
            ]
        );

        // CloudWatch Alarms should show alarm columns
        app.current_service = Service::CloudWatchAlarms;
        assert!(!app.cw_alarm_column_ids.is_empty());
        if let Some(col) = AlarmColumn::from_id(app.cw_alarm_column_ids[0]) {
            assert!(col.name().contains("Name") || col.name().contains("Alarm"));
        }
    }

    #[test]
    fn test_log_groups_preferences_shows_all_six_columns() {
        use crate::app::Service;

        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;

        // Verify all 6 columns exist
        assert_eq!(app.cw_log_group_column_ids.len(), 6);

        // Verify each column by name
        let col_names: Vec<String> = app
            .cw_log_group_column_ids
            .iter()
            .filter_map(|id| LogGroupColumn::from_id(id).map(|c| c.name().to_string()))
            .collect();
        assert!(col_names.iter().any(|n| n == "Log group"));
        assert!(col_names.iter().any(|n| n == "Log class"));
        assert!(col_names.iter().any(|n| n == "Retention"));
        assert!(col_names.iter().any(|n| n == "Stored bytes"));
        assert!(col_names.iter().any(|n| n == "Creation time"));
        assert!(col_names.iter().any(|n| n == "ARN"));
    }

    #[test]
    fn test_stream_preferences_shows_all_columns() {
        use crate::app::ViewMode;

        let mut app = test_app();
        app.view_mode = ViewMode::Detail;

        // Verify stream columns exist
        assert!(!app.cw_log_stream_column_ids.is_empty());
        assert_eq!(app.cw_log_stream_column_ids.len(), 7);
    }

    #[test]
    fn test_event_preferences_shows_all_columns() {
        use crate::app::ViewMode;

        let mut app = test_app();
        app.view_mode = ViewMode::Events;

        // Verify event columns exist
        assert!(!app.cw_log_event_column_ids.is_empty());
        assert_eq!(app.cw_log_event_column_ids.len(), 5);
    }

    #[test]
    fn test_alarm_preferences_shows_all_columns() {
        use crate::app::Service;

        let mut app = test_app();
        app.current_service = Service::CloudWatchAlarms;

        // Verify alarm columns exist
        assert!(!app.cw_alarm_column_ids.is_empty());
        assert_eq!(app.cw_alarm_column_ids.len(), 16);
    }

    #[test]
    fn test_column_selector_has_scrollbar() {
        // Column selector should have scrollbar when items don't fit
        // This is rendered in render_column_selector after the list widget
        let item_count = 6; // Log groups has 6 columns
        assert!(item_count > 0);

        // Scrollbar should be rendered with vertical right orientation
        // with up/down arrows
    }

    #[test]
    fn test_preferences_scrollbar_only_when_needed() {
        // Scrollbar should only appear when content exceeds available height
        let item_count = 6;
        let height = (item_count as u16 + 2).max(8); // +2 for borders
        let max_height_fits = 20; // Large enough to fit all items
        let max_height_doesnt_fit = 5; // Too small to fit all items

        // When content fits, no scrollbar needed
        let needs_scrollbar_fits = height > max_height_fits;
        assert!(!needs_scrollbar_fits);

        // When content doesn't fit, scrollbar needed
        let needs_scrollbar_doesnt_fit = height > max_height_doesnt_fit;
        assert!(needs_scrollbar_doesnt_fit);
    }

    #[test]
    fn test_preferences_height_no_extra_padding() {
        // Height should be item_count + 2 (for borders), not + 4
        let item_count = 6;
        let height = (item_count as u16 + 2).max(8);
        assert_eq!(height, 8); // 6 + 2 = 8

        // Should not have extra empty lines
        assert_ne!(height, 10); // Not 6 + 4
    }

    #[test]
    fn test_preferences_uses_absolute_sizing() {
        // Preferences should use centered_rect_absolute, not centered_rect (percentages)
        // This ensures width/height are in characters, not percentages
        let width = 50u16; // 50 characters
        let height = 10u16; // 10 lines

        // These are absolute values, not percentages
        assert!(width <= 100); // Reasonable character width
        assert!(height <= 50); // Reasonable line height
    }

    #[test]
    fn test_profile_picker_shows_sort_indicator() {
        // Profile picker should show sort on Profile column ascending
        let sort_column = "Profile";
        let sort_direction = "ASC";

        assert_eq!(sort_column, "Profile");
        assert_eq!(sort_direction, "ASC");

        // Verify arrow would be added
        let arrow = if sort_direction == "ASC" {
            ""
        } else {
            ""
        };
        assert_eq!(arrow, "");
    }

    #[test]
    fn test_session_picker_shows_sort_indicator() {
        // Session picker should show sort on Timestamp column descending
        let sort_column = "Timestamp";
        let sort_direction = "DESC";

        assert_eq!(sort_column, "Timestamp");
        assert_eq!(sort_direction, "DESC");

        // Verify arrow would be added
        let arrow = if sort_direction == "ASC" {
            ""
        } else {
            ""
        };
        assert_eq!(arrow, "");
    }

    #[test]
    fn test_profile_picker_sorted_ascending() {
        let mut app = test_app_no_region();
        app.available_profiles = vec![
            crate::app::AwsProfile {
                name: "zebra".to_string(),
                region: None,
                account: None,
                role_arn: None,
                source_profile: None,
            },
            crate::app::AwsProfile {
                name: "alpha".to_string(),
                region: None,
                account: None,
                role_arn: None,
                source_profile: None,
            },
        ];

        let filtered = app.get_filtered_profiles();
        assert_eq!(filtered[0].name, "alpha");
        assert_eq!(filtered[1].name, "zebra");
    }

    #[test]
    fn test_session_picker_sorted_descending() {
        let mut app = test_app_no_region();
        // Sessions should be added in descending timestamp order (newest first)
        app.sessions = vec![
            crate::session::Session {
                id: "2".to_string(),
                timestamp: "2024-01-02 10:00:00 UTC".to_string(),
                profile: "new".to_string(),
                region: "us-east-1".to_string(),
                account_id: "123".to_string(),
                role_arn: String::new(),
                tabs: vec![],
            },
            crate::session::Session {
                id: "1".to_string(),
                timestamp: "2024-01-01 10:00:00 UTC".to_string(),
                profile: "old".to_string(),
                region: "us-east-1".to_string(),
                account_id: "123".to_string(),
                role_arn: String::new(),
                tabs: vec![],
            },
        ];

        let filtered = app.get_filtered_sessions();
        // Sessions are already sorted descending by timestamp (newest first)
        assert_eq!(filtered[0].profile, "new");
        assert_eq!(filtered[1].profile, "old");
    }

    #[test]
    fn test_ecr_encryption_type_aes256_renders_as_aes_dash_256() {
        let repo = EcrRepository {
            name: "test-repo".to_string(),
            uri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/test-repo".to_string(),
            created_at: "2024-01-01".to_string(),
            tag_immutability: "MUTABLE".to_string(),
            encryption_type: "AES256".to_string(),
        };

        let formatted = match repo.encryption_type.as_ref() {
            "AES256" => "AES-256".to_string(),
            "KMS" => "KMS".to_string(),
            other => other.to_string(),
        };

        assert_eq!(formatted, "AES-256");
    }

    #[test]
    fn test_ecr_encryption_type_kms_unchanged() {
        let repo = EcrRepository {
            name: "test-repo".to_string(),
            uri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/test-repo".to_string(),
            created_at: "2024-01-01".to_string(),
            tag_immutability: "MUTABLE".to_string(),
            encryption_type: "KMS".to_string(),
        };

        let formatted = match repo.encryption_type.as_ref() {
            "AES256" => "AES-256".to_string(),
            "KMS" => "KMS".to_string(),
            other => other.to_string(),
        };

        assert_eq!(formatted, "KMS");
    }

    #[test]
    fn test_ecr_repo_filter_active_removes_table_focus() {
        let mut app = test_app_no_region();
        app.current_service = Service::EcrRepositories;
        app.mode = Mode::FilterInput;
        app.ecr_state.repositories.items = vec![EcrRepository {
            name: "test-repo".to_string(),
            uri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/test-repo".to_string(),
            created_at: "2024-01-01".to_string(),
            tag_immutability: "MUTABLE".to_string(),
            encryption_type: "AES256".to_string(),
        }];

        // When in FilterInput mode, table should not be active
        assert_eq!(app.mode, Mode::FilterInput);
        // This would be checked in render logic: is_active: app.mode != Mode::FilterInput
    }

    #[test]
    fn test_ecr_image_filter_active_removes_table_focus() {
        let mut app = test_app_no_region();
        app.current_service = Service::EcrRepositories;
        app.ecr_state.current_repository = Some("test-repo".to_string());
        app.mode = Mode::FilterInput;
        app.ecr_state.images.items = vec![EcrImage {
            tag: "v1.0.0".to_string(),
            artifact_type: "application/vnd.docker.container.image.v1+json".to_string(),
            pushed_at: "2024-01-01".to_string(),
            size_bytes: 104857600,
            uri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/test-repo:v1.0.0".to_string(),
            digest: "sha256:abc123".to_string(),
            last_pull_time: "2024-01-02".to_string(),
        }];

        // When in FilterInput mode, table should not be active
        assert_eq!(app.mode, Mode::FilterInput);
        // This would be checked in render logic: is_active: app.mode != Mode::FilterInput
    }

    #[test]
    fn test_ecr_filter_escape_returns_to_normal_mode() {
        let mut app = test_app_no_region();
        app.current_service = Service::EcrRepositories;
        app.mode = Mode::FilterInput;
        app.ecr_state.repositories.filter = "test".to_string();

        // Simulate Escape key (CloseMenu action)
        app.handle_action(crate::keymap::Action::CloseMenu);

        assert_eq!(app.mode, Mode::Normal);
    }

    #[test]
    fn test_ecr_repos_no_scrollbar_when_all_fit() {
        // ECR repos table should not show scrollbar when all paginated items fit
        let mut app = test_app_no_region();
        app.current_service = Service::EcrRepositories;
        app.ecr_state.repositories.items = (0..50)
            .map(|i| EcrRepository {
                name: format!("repo{}", i),
                uri: format!("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo{}", i),
                created_at: "2024-01-01".to_string(),
                tag_immutability: "MUTABLE".to_string(),
                encryption_type: "AES256".to_string(),
            })
            .collect();

        // With 50 repos on page and typical terminal height, scrollbar should not appear
        // Scrollbar logic: row_count > (area_height - 3)
        let row_count = 50;
        let typical_area_height: u16 = 60;
        let available_height = typical_area_height.saturating_sub(3);

        assert!(
            row_count <= available_height as usize,
            "50 repos should fit without scrollbar"
        );
    }

    #[test]
    fn test_lambda_default_columns() {
        let app = test_app_no_region();

        assert_eq!(app.lambda_state.function_visible_column_ids.len(), 6);
        assert_eq!(
            app.lambda_state.function_visible_column_ids[0],
            "column.lambda.function.name"
        );
        assert_eq!(
            app.lambda_state.function_visible_column_ids[1],
            "column.lambda.function.runtime"
        );
        assert_eq!(
            app.lambda_state.function_visible_column_ids[2],
            "column.lambda.function.code_size"
        );
        assert_eq!(
            app.lambda_state.function_visible_column_ids[3],
            "column.lambda.function.memory_mb"
        );
        assert_eq!(
            app.lambda_state.function_visible_column_ids[4],
            "column.lambda.function.timeout_seconds"
        );
        assert_eq!(
            app.lambda_state.function_visible_column_ids[5],
            "column.lambda.function.last_modified"
        );
    }

    #[test]
    fn test_lambda_all_columns_available() {
        let all_columns = lambda::FunctionColumn::ids();

        assert_eq!(all_columns.len(), 9);
        assert!(all_columns.contains(&"column.lambda.function.name"));
        assert!(all_columns.contains(&"column.lambda.function.description"));
        assert!(all_columns.contains(&"column.lambda.function.package_type"));
        assert!(all_columns.contains(&"column.lambda.function.runtime"));
        assert!(all_columns.contains(&"column.lambda.function.architecture"));
        assert!(all_columns.contains(&"column.lambda.function.code_size"));
        assert!(all_columns.contains(&"column.lambda.function.memory_mb"));
        assert!(all_columns.contains(&"column.lambda.function.timeout_seconds"));
        assert!(all_columns.contains(&"column.lambda.function.last_modified"));
    }

    #[test]
    fn test_lambda_filter_active_removes_table_focus() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.mode = Mode::FilterInput;
        app.lambda_state.table.items = vec![lambda::Function {
            arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
            application: None,
            name: "test-function".to_string(),
            description: "Test function".to_string(),
            package_type: "Zip".to_string(),
            runtime: "python3.12".to_string(),
            architecture: "x86_64".to_string(),
            code_size: 1024,
            code_sha256: "test-sha256".to_string(),
            memory_mb: 128,
            timeout_seconds: 3,
            last_modified: "2024-01-01T00:00:00.000+0000".to_string(),
            layers: vec![],
        }];

        assert_eq!(app.mode, Mode::FilterInput);
    }

    #[test]
    fn test_lambda_default_page_size() {
        let app = test_app_no_region();

        assert_eq!(app.lambda_state.table.page_size, PageSize::Fifty);
        assert_eq!(app.lambda_state.table.page_size.value(), 50);
    }

    #[test]
    fn test_lambda_pagination() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.lambda_state.table.page_size = PageSize::Ten;
        app.lambda_state.table.items = (0..25)
            .map(|i| crate::app::LambdaFunction {
                arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
                application: None,
                name: format!("function-{}", i),
                description: format!("Function {}", i),
                package_type: "Zip".to_string(),
                runtime: "python3.12".to_string(),
                architecture: "x86_64".to_string(),
                code_size: 1024,
                code_sha256: "test-sha256".to_string(),
                memory_mb: 128,
                timeout_seconds: 3,
                last_modified: "2024-01-01T00:00:00.000+0000".to_string(),
                layers: vec![],
            })
            .collect();

        let page_size = app.lambda_state.table.page_size.value();
        let total_pages = app.lambda_state.table.items.len().div_ceil(page_size);

        assert_eq!(page_size, 10);
        assert_eq!(total_pages, 3);
    }

    #[test]
    fn test_lambda_filter_by_name() {
        let mut app = test_app_no_region();
        app.lambda_state.table.items = vec![
            crate::app::LambdaFunction {
                arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
                application: None,
                name: "api-handler".to_string(),
                description: "API handler".to_string(),
                package_type: "Zip".to_string(),
                runtime: "python3.12".to_string(),
                architecture: "x86_64".to_string(),
                code_size: 1024,
                code_sha256: "test-sha256".to_string(),
                memory_mb: 128,
                timeout_seconds: 3,
                last_modified: "2024-01-01T00:00:00.000+0000".to_string(),
                layers: vec![],
            },
            crate::app::LambdaFunction {
                arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
                application: None,
                name: "data-processor".to_string(),
                description: "Data processor".to_string(),
                package_type: "Zip".to_string(),
                runtime: "nodejs20.x".to_string(),
                architecture: "arm64".to_string(),
                code_size: 2048,
                code_sha256: "test-sha256".to_string(),
                memory_mb: 256,
                timeout_seconds: 30,
                last_modified: "2024-01-02T00:00:00.000+0000".to_string(),
                layers: vec![],
            },
        ];
        app.lambda_state.table.filter = "api".to_string();

        let filtered: Vec<_> = app
            .lambda_state
            .table
            .items
            .iter()
            .filter(|f| {
                app.lambda_state.table.filter.is_empty()
                    || f.name
                        .to_lowercase()
                        .contains(&app.lambda_state.table.filter.to_lowercase())
                    || f.description
                        .to_lowercase()
                        .contains(&app.lambda_state.table.filter.to_lowercase())
                    || f.runtime
                        .to_lowercase()
                        .contains(&app.lambda_state.table.filter.to_lowercase())
            })
            .collect();

        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].name, "api-handler");
    }

    #[test]
    fn test_lambda_filter_by_runtime() {
        let mut app = test_app_no_region();
        app.lambda_state.table.items = vec![
            crate::app::LambdaFunction {
                arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
                application: None,
                name: "python-func".to_string(),
                description: "Python function".to_string(),
                package_type: "Zip".to_string(),
                runtime: "python3.12".to_string(),
                architecture: "x86_64".to_string(),
                code_size: 1024,
                code_sha256: "test-sha256".to_string(),
                memory_mb: 128,
                timeout_seconds: 3,
                last_modified: "2024-01-01T00:00:00.000+0000".to_string(),
                layers: vec![],
            },
            crate::app::LambdaFunction {
                arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
                application: None,
                name: "node-func".to_string(),
                description: "Node function".to_string(),
                package_type: "Zip".to_string(),
                runtime: "nodejs20.x".to_string(),
                architecture: "arm64".to_string(),
                code_size: 2048,
                code_sha256: "test-sha256".to_string(),
                memory_mb: 256,
                timeout_seconds: 30,
                last_modified: "2024-01-02T00:00:00.000+0000".to_string(),
                layers: vec![],
            },
        ];
        app.lambda_state.table.filter = "python".to_string();

        let filtered: Vec<_> = app
            .lambda_state
            .table
            .items
            .iter()
            .filter(|f| {
                app.lambda_state.table.filter.is_empty()
                    || f.name
                        .to_lowercase()
                        .contains(&app.lambda_state.table.filter.to_lowercase())
                    || f.description
                        .to_lowercase()
                        .contains(&app.lambda_state.table.filter.to_lowercase())
                    || f.runtime
                        .to_lowercase()
                        .contains(&app.lambda_state.table.filter.to_lowercase())
            })
            .collect();

        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].runtime, "python3.12");
    }

    #[test]
    fn test_lambda_page_size_changes_in_preferences() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.lambda_state.table.page_size = PageSize::Fifty;

        // Simulate opening preferences and changing page size
        app.mode = Mode::ColumnSelector;
        // Index for page size options: 0=Columns header, 1-9=columns, 10=empty, 11=PageSize header, 12=10, 13=25, 14=50, 15=100
        app.column_selector_index = 12; // 10 resources
        app.handle_action(crate::keymap::Action::ToggleColumn);

        assert_eq!(app.lambda_state.table.page_size, PageSize::Ten);
    }

    #[test]
    fn test_lambda_preferences_shows_page_sizes() {
        let app = test_app_no_region();
        let mut app = app;
        app.current_service = Service::LambdaFunctions;

        // Verify all page sizes are available
        let page_sizes = vec![
            PageSize::Ten,
            PageSize::TwentyFive,
            PageSize::Fifty,
            PageSize::OneHundred,
        ];

        for size in page_sizes {
            app.lambda_state.table.page_size = size;
            assert_eq!(app.lambda_state.table.page_size, size);
        }
    }

    #[test]
    fn test_lambda_pagination_respects_page_size() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.lambda_state.table.items = (0..100)
            .map(|i| crate::app::LambdaFunction {
                arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
                application: None,
                name: format!("function-{}", i),
                description: format!("Function {}", i),
                package_type: "Zip".to_string(),
                runtime: "python3.12".to_string(),
                architecture: "x86_64".to_string(),
                code_size: 1024,
                code_sha256: "test-sha256".to_string(),
                memory_mb: 128,
                timeout_seconds: 3,
                last_modified: "2024-01-01T00:00:00.000+0000".to_string(),
                layers: vec![],
            })
            .collect();

        // Test with page size 10
        app.lambda_state.table.page_size = PageSize::Ten;
        let page_size = app.lambda_state.table.page_size.value();
        let total_pages = app.lambda_state.table.items.len().div_ceil(page_size);
        assert_eq!(page_size, 10);
        assert_eq!(total_pages, 10);

        // Test with page size 25
        app.lambda_state.table.page_size = PageSize::TwentyFive;
        let page_size = app.lambda_state.table.page_size.value();
        let total_pages = app.lambda_state.table.items.len().div_ceil(page_size);
        assert_eq!(page_size, 25);
        assert_eq!(total_pages, 4);

        // Test with page size 50
        app.lambda_state.table.page_size = PageSize::Fifty;
        let page_size = app.lambda_state.table.page_size.value();
        let total_pages = app.lambda_state.table.items.len().div_ceil(page_size);
        assert_eq!(page_size, 50);
        assert_eq!(total_pages, 2);
    }

    #[test]
    fn test_lambda_next_preferences_cycles_sections() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.mode = Mode::ColumnSelector;

        // Start at columns section
        app.column_selector_index = 0;
        app.handle_action(crate::keymap::Action::NextPreferences);

        // Should jump to page size section (9 columns + 1 empty + 1 header = 11)
        assert_eq!(app.column_selector_index, 11);

        // Next should cycle back to columns
        app.handle_action(crate::keymap::Action::NextPreferences);
        assert_eq!(app.column_selector_index, 0);
    }

    #[test]
    fn test_lambda_drill_down_on_enter() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.service_selected = true;
        app.mode = Mode::Normal;
        app.lambda_state.table.items = vec![crate::app::LambdaFunction {
            arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
            application: None,
            name: "test-function".to_string(),
            description: "Test function".to_string(),
            package_type: "Zip".to_string(),
            runtime: "python3.12".to_string(),
            architecture: "x86_64".to_string(),
            code_size: 1024,
            code_sha256: "test-sha256".to_string(),
            memory_mb: 128,
            timeout_seconds: 3,
            last_modified: "2024-01-01 00:00:00 (UTC)".to_string(),
            layers: vec![],
        }];
        app.lambda_state.table.selected = 0;

        // Drill down into function
        app.handle_action(crate::keymap::Action::Select);

        assert_eq!(
            app.lambda_state.current_function,
            Some("test-function".to_string())
        );
        assert_eq!(app.lambda_state.detail_tab, LambdaDetailTab::Code);
    }

    #[test]
    fn test_lambda_go_back_from_detail() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.lambda_state.current_function = Some("test-function".to_string());

        app.handle_action(crate::keymap::Action::GoBack);

        assert_eq!(app.lambda_state.current_function, None);
    }

    #[test]
    fn test_lambda_detail_tab_cycling() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.lambda_state.current_function = Some("test-function".to_string());
        app.lambda_state.detail_tab = LambdaDetailTab::Code;

        app.handle_action(crate::keymap::Action::NextDetailTab);
        assert_eq!(app.lambda_state.detail_tab, LambdaDetailTab::Monitor);

        app.handle_action(crate::keymap::Action::NextDetailTab);
        assert_eq!(app.lambda_state.detail_tab, LambdaDetailTab::Configuration);

        app.handle_action(crate::keymap::Action::NextDetailTab);
        assert_eq!(app.lambda_state.detail_tab, LambdaDetailTab::Aliases);

        app.handle_action(crate::keymap::Action::NextDetailTab);
        assert_eq!(app.lambda_state.detail_tab, LambdaDetailTab::Versions);

        app.handle_action(crate::keymap::Action::NextDetailTab);
        assert_eq!(app.lambda_state.detail_tab, LambdaDetailTab::Code);
    }

    #[test]
    fn test_lambda_breadcrumbs_with_function_name() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.service_selected = true;

        // List view
        let breadcrumb = app.breadcrumbs();
        assert_eq!(breadcrumb, "Lambda > Functions");

        // Detail view
        app.lambda_state.current_function = Some("my-function".to_string());
        let breadcrumb = app.breadcrumbs();
        assert_eq!(breadcrumb, "Lambda > my-function");
    }

    #[test]
    fn test_lambda_console_url() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.config.region = "us-east-1".to_string();

        // List view
        let url = app.get_console_url();
        assert_eq!(
            url,
            "https://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1#/functions"
        );

        // Detail view
        app.lambda_state.current_function = Some("my-function".to_string());
        let url = app.get_console_url();
        assert_eq!(
            url,
            "https://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1#/functions/my-function"
        );
    }

    #[test]
    fn test_lambda_last_modified_format() {
        let func = crate::app::LambdaFunction {
            arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
            application: None,
            name: "test-function".to_string(),
            description: "Test function".to_string(),
            package_type: "Zip".to_string(),
            runtime: "python3.12".to_string(),
            architecture: "x86_64".to_string(),
            code_size: 1024,
            code_sha256: "test-sha256".to_string(),
            memory_mb: 128,
            timeout_seconds: 3,
            last_modified: "2024-01-01 12:30:45 (UTC)".to_string(),
            layers: vec![],
        };

        // Verify format matches our (UTC) pattern
        assert!(func.last_modified.contains("(UTC)"));
        assert!(func.last_modified.contains("2024-01-01"));
    }

    #[test]
    fn test_lambda_expand_on_right_arrow() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.service_selected = true;
        app.mode = Mode::Normal;
        app.lambda_state.table.items = vec![crate::app::LambdaFunction {
            arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
            application: None,
            name: "test-function".to_string(),
            description: "Test function".to_string(),
            package_type: "Zip".to_string(),
            runtime: "python3.12".to_string(),
            architecture: "x86_64".to_string(),
            code_size: 1024,
            code_sha256: "test-sha256".to_string(),
            memory_mb: 128,
            timeout_seconds: 3,
            last_modified: "2024-01-01 00:00:00 (UTC)".to_string(),
            layers: vec![],
        }];
        app.lambda_state.table.selected = 0;

        app.handle_action(crate::keymap::Action::NextPane);

        assert_eq!(app.lambda_state.table.expanded_item, Some(0));
    }

    #[test]
    fn test_lambda_collapse_on_left_arrow() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.service_selected = true;
        app.mode = Mode::Normal;
        app.lambda_state.current_function = None; // In list view
        app.lambda_state.table.expanded_item = Some(0);

        app.handle_action(crate::keymap::Action::PrevPane);

        assert_eq!(app.lambda_state.table.expanded_item, None);
    }

    #[test]
    fn test_lambda_filter_activation() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.service_selected = true;
        app.mode = Mode::Normal;

        app.handle_action(crate::keymap::Action::StartFilter);

        assert_eq!(app.mode, Mode::FilterInput);
    }

    #[test]
    fn test_lambda_filter_backspace() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.mode = Mode::FilterInput;
        app.lambda_state.table.filter = "test".to_string();

        app.handle_action(crate::keymap::Action::FilterBackspace);

        assert_eq!(app.lambda_state.table.filter, "tes");
    }

    #[test]
    fn test_lambda_sorted_by_last_modified_desc() {
        let func1 = crate::app::LambdaFunction {
            arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
            application: None,
            name: "func1".to_string(),
            description: String::new(),
            package_type: "Zip".to_string(),
            runtime: "python3.12".to_string(),
            architecture: "x86_64".to_string(),
            code_size: 1024,
            code_sha256: "test-sha256".to_string(),
            memory_mb: 128,
            timeout_seconds: 3,
            last_modified: "2024-01-01 00:00:00 (UTC)".to_string(),
            layers: vec![],
        };
        let func2 = crate::app::LambdaFunction {
            arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
            application: None,
            name: "func2".to_string(),
            description: String::new(),
            package_type: "Zip".to_string(),
            runtime: "python3.12".to_string(),
            architecture: "x86_64".to_string(),
            code_size: 1024,
            code_sha256: "test-sha256".to_string(),
            memory_mb: 128,
            timeout_seconds: 3,
            last_modified: "2024-12-31 00:00:00 (UTC)".to_string(),
            layers: vec![],
        };

        let mut functions = [func1.clone(), func2.clone()].to_vec();
        functions.sort_by(|a, b| b.last_modified.cmp(&a.last_modified));

        // func2 should be first (newer)
        assert_eq!(functions[0].name, "func2");
        assert_eq!(functions[1].name, "func1");
    }

    #[test]
    fn test_lambda_code_properties_has_sha256() {
        let func = crate::app::LambdaFunction {
            arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
            application: None,
            name: "test-function".to_string(),
            description: "Test".to_string(),
            package_type: "Zip".to_string(),
            runtime: "python3.12".to_string(),
            architecture: "x86_64".to_string(),
            code_size: 2600,
            code_sha256: "HHn6CTPhEnmSfX9I/dozcFFLQXUTDFapBAkzjVj9UxE=".to_string(),
            memory_mb: 128,
            timeout_seconds: 3,
            last_modified: "2024-01-01 00:00:00 (UTC)".to_string(),
            layers: vec![],
        };

        assert!(!func.code_sha256.is_empty());
        assert_eq!(
            func.code_sha256,
            "HHn6CTPhEnmSfX9I/dozcFFLQXUTDFapBAkzjVj9UxE="
        );
    }

    #[test]
    fn test_lambda_name_column_has_expand_symbol() {
        let func = crate::app::LambdaFunction {
            arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
            application: None,
            name: "test-function".to_string(),
            description: "Test".to_string(),
            package_type: "Zip".to_string(),
            runtime: "python3.12".to_string(),
            architecture: "x86_64".to_string(),
            code_size: 1024,
            code_sha256: "test-sha256".to_string(),
            memory_mb: 128,
            timeout_seconds: 3,
            last_modified: "2024-01-01 00:00:00 (UTC)".to_string(),
            layers: vec![],
        };

        // Test collapsed state
        let symbol_collapsed = crate::ui::table::CURSOR_COLLAPSED;
        let rendered_collapsed = format!("{} {}", symbol_collapsed, func.name);
        assert!(rendered_collapsed.contains(symbol_collapsed));
        assert!(rendered_collapsed.contains("test-function"));

        // Test expanded state
        let symbol_expanded = crate::ui::table::CURSOR_EXPANDED;
        let rendered_expanded = format!("{} {}", symbol_expanded, func.name);
        assert!(rendered_expanded.contains(symbol_expanded));
        assert!(rendered_expanded.contains("test-function"));

        // Verify symbols are different
        assert_ne!(symbol_collapsed, symbol_expanded);
    }

    #[test]
    fn test_lambda_last_modified_column_width() {
        // Verify width is sufficient for "2025-10-31 08:37:46 (UTC)" (25 chars)
        let timestamp = "2025-10-31 08:37:46 (UTC)";
        assert_eq!(timestamp.len(), 25);

        // Column width should be at least 27 to have some padding
        let width = 27u16;
        assert!(width >= timestamp.len() as u16);
    }

    #[test]
    fn test_lambda_code_properties_has_info_and_kms_sections() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.lambda_state.current_function = Some("test-function".to_string());
        app.lambda_state.detail_tab = LambdaDetailTab::Code;
        app.lambda_state.table.items = vec![crate::app::LambdaFunction {
            arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
            application: None,
            name: "test-function".to_string(),
            description: "Test".to_string(),
            package_type: "Zip".to_string(),
            runtime: "python3.12".to_string(),
            architecture: "x86_64".to_string(),
            code_size: 2600,
            code_sha256: "HHn6CTPhEnmSfX9I/dozcFFLQXUTDFapBAkzjVj9UxE=".to_string(),
            memory_mb: 128,
            timeout_seconds: 3,
            last_modified: "2024-01-01 00:00:00 (UTC)".to_string(),
            layers: vec![],
        }];

        // Verify we're in Code tab
        assert_eq!(app.lambda_state.detail_tab, LambdaDetailTab::Code);

        // Verify function exists
        assert!(app.lambda_state.current_function.is_some());
        assert_eq!(app.lambda_state.table.items.len(), 1);

        // Info section should have: Package size, SHA256 hash, Last modified
        let func = &app.lambda_state.table.items[0];
        assert!(!func.code_sha256.is_empty());
        assert!(!func.last_modified.is_empty());
        assert!(func.code_size > 0);
    }

    #[test]
    fn test_lambda_pagination_navigation() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.service_selected = true;
        app.mode = Mode::Normal;
        app.lambda_state.table.page_size = PageSize::Ten;

        // Create 25 functions
        app.lambda_state.table.items = (0..25)
            .map(|i| crate::app::LambdaFunction {
                arn: "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(),
                application: None,
                name: format!("function-{}", i),
                description: "Test".to_string(),
                package_type: "Zip".to_string(),
                runtime: "python3.12".to_string(),
                architecture: "x86_64".to_string(),
                code_size: 1024,
                code_sha256: "test-sha256".to_string(),
                memory_mb: 128,
                timeout_seconds: 3,
                last_modified: "2024-01-01 00:00:00 (UTC)".to_string(),
                layers: vec![],
            })
            .collect();

        // Start at index 0 (page 0)
        app.lambda_state.table.selected = 0;
        let page_size = app.lambda_state.table.page_size.value();
        let current_page = app.lambda_state.table.selected / page_size;
        assert_eq!(current_page, 0);
        assert_eq!(app.lambda_state.table.selected % page_size, 0);

        // Navigate to index 10 (page 1)
        app.lambda_state.table.selected = 10;
        let current_page = app.lambda_state.table.selected / page_size;
        assert_eq!(current_page, 1);
        assert_eq!(app.lambda_state.table.selected % page_size, 0);

        // Navigate to index 15 (page 1, item 5)
        app.lambda_state.table.selected = 15;
        let current_page = app.lambda_state.table.selected / page_size;
        assert_eq!(current_page, 1);
        assert_eq!(app.lambda_state.table.selected % page_size, 5);
    }

    #[test]
    fn test_lambda_pagination_with_100_functions() {
        let mut app = test_app_no_region();
        app.current_service = Service::LambdaFunctions;
        app.service_selected = true;
        app.mode = Mode::Normal;
        app.lambda_state.table.page_size = PageSize::Fifty;

        // Create 100 functions (simulating real scenario)
        app.lambda_state.table.items = (0..100)
            .map(|i| crate::app::LambdaFunction {
                arn: format!("arn:aws:lambda:us-east-1:123456789012:function:func-{}", i),
                application: None,
                name: format!("function-{:03}", i),
                description: format!("Function {}", i),
                package_type: "Zip".to_string(),
                runtime: "python3.12".to_string(),
                architecture: "x86_64".to_string(),
                code_size: 1024 + i,
                code_sha256: format!("sha256-{}", i),
                memory_mb: 128,
                timeout_seconds: 3,
                last_modified: "2024-01-01 00:00:00 (UTC)".to_string(),
                layers: vec![],
            })
            .collect();

        let page_size = app.lambda_state.table.page_size.value();
        assert_eq!(page_size, 50);

        // Page 0: items 0-49
        app.lambda_state.table.selected = 0;
        let current_page = app.lambda_state.table.selected / page_size;
        assert_eq!(current_page, 0);

        app.lambda_state.table.selected = 49;
        let current_page = app.lambda_state.table.selected / page_size;
        assert_eq!(current_page, 0);

        // Page 1: items 50-99
        app.lambda_state.table.selected = 50;
        let current_page = app.lambda_state.table.selected / page_size;
        assert_eq!(current_page, 1);

        app.lambda_state.table.selected = 99;
        let current_page = app.lambda_state.table.selected / page_size;
        assert_eq!(current_page, 1);

        // Verify pagination text
        let filtered_count = app.lambda_state.table.items.len();
        let total_pages = filtered_count.div_ceil(page_size);
        assert_eq!(total_pages, 2);
    }

    #[test]
    fn test_pagination_color_matches_border_color() {
        use ratatui::style::{Color, Style};

        // When active (not in FilterInput mode), pagination should be green, border white
        let is_filter_input = false;
        let pagination_style = if is_filter_input {
            Style::default()
        } else {
            Style::default().fg(Color::Green)
        };
        let border_style = if is_filter_input {
            Style::default().fg(Color::Yellow)
        } else {
            Style::default()
        };
        assert_eq!(pagination_style.fg, Some(Color::Green));
        assert_eq!(border_style.fg, None); // White (default)

        // When in FilterInput mode, pagination should be white (default), border yellow
        let is_filter_input = true;
        let pagination_style = if is_filter_input {
            Style::default()
        } else {
            Style::default().fg(Color::Green)
        };
        let border_style = if is_filter_input {
            Style::default().fg(Color::Yellow)
        } else {
            Style::default()
        };
        assert_eq!(pagination_style.fg, None); // White (default)
        assert_eq!(border_style.fg, Some(Color::Yellow));
    }

    #[test]
    fn test_lambda_application_expansion_indicator() {
        // Lambda applications should show expansion indicator like ECR repos
        let app_name = "my-application";

        // Collapsed state
        let collapsed = crate::ui::table::format_expandable(app_name, false);
        assert!(collapsed.contains(crate::ui::table::CURSOR_COLLAPSED));
        assert!(collapsed.contains(app_name));

        // Expanded state
        let expanded = crate::ui::table::format_expandable(app_name, true);
        assert!(expanded.contains(crate::ui::table::CURSOR_EXPANDED));
        assert!(expanded.contains(app_name));
    }

    #[test]
    fn test_ecr_repository_selection_uses_table_state_page_size() {
        // ECR should use TableState's page_size, not hardcoded value
        let mut app = test_app_no_region();
        app.current_service = Service::EcrRepositories;

        // Create 100 repositories
        app.ecr_state.repositories.items = (0..100)
            .map(|i| crate::ecr::repo::Repository {
                name: format!("repo{}", i),
                uri: format!("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo{}", i),
                created_at: "2024-01-01".to_string(),
                tag_immutability: "MUTABLE".to_string(),
                encryption_type: "AES256".to_string(),
            })
            .collect();

        // Set page size to 25
        app.ecr_state.repositories.page_size = crate::common::PageSize::TwentyFive;

        // Select item 30 (should be on page 1, index 5 within page)
        app.ecr_state.repositories.selected = 30;

        let page_size = app.ecr_state.repositories.page_size.value();
        let selected_index = app.ecr_state.repositories.selected % page_size;

        assert_eq!(page_size, 25);
        assert_eq!(selected_index, 5); // 30 % 25 = 5
    }

    #[test]
    fn test_ecr_repository_selection_indicator_visible() {
        // Verify selection indicator calculation matches table rendering
        let mut app = test_app_no_region();
        app.current_service = Service::EcrRepositories;
        app.mode = crate::keymap::Mode::Normal;

        app.ecr_state.repositories.items = vec![
            crate::ecr::repo::Repository {
                name: "repo1".to_string(),
                uri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/repo1".to_string(),
                created_at: "2024-01-01".to_string(),
                tag_immutability: "MUTABLE".to_string(),
                encryption_type: "AES256".to_string(),
            },
            crate::ecr::repo::Repository {
                name: "repo2".to_string(),
                uri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/repo2".to_string(),
                created_at: "2024-01-02".to_string(),
                tag_immutability: "IMMUTABLE".to_string(),
                encryption_type: "KMS".to_string(),
            },
        ];

        app.ecr_state.repositories.selected = 1;

        let page_size = app.ecr_state.repositories.page_size.value();
        let selected_index = app.ecr_state.repositories.selected % page_size;

        // Should be active (not in FilterInput mode)
        let is_active = app.mode != crate::keymap::Mode::FilterInput;

        assert_eq!(selected_index, 1);
        assert!(is_active);
    }

    #[test]
    fn test_ecr_repository_shows_expandable_indicator() {
        // ECR repository name column should use format_expandable to show ► indicator
        let repo = crate::ecr::repo::Repository {
            name: "test-repo".to_string(),
            uri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/test-repo".to_string(),
            created_at: "2024-01-01".to_string(),
            tag_immutability: "MUTABLE".to_string(),
            encryption_type: "AES256".to_string(),
        };

        // Collapsed state should show ►
        let collapsed = crate::ui::table::format_expandable(&repo.name, false);
        assert!(collapsed.contains(crate::ui::table::CURSOR_COLLAPSED));
        assert!(collapsed.contains("test-repo"));

        // Expanded state should show ▼
        let expanded = crate::ui::table::format_expandable(&repo.name, true);
        assert!(expanded.contains(crate::ui::table::CURSOR_EXPANDED));
        assert!(expanded.contains("test-repo"));
    }

    #[test]
    fn test_lambda_application_expanded_status_formatting() {
        // Status in expanded content should show emoji for complete states
        let app = lambda::Application {
            name: "test-app".to_string(),
            arn: "arn:aws:cloudformation:us-east-1:123456789012:stack/test-app/abc123".to_string(),
            description: "Test application".to_string(),
            status: "UpdateComplete".to_string(),
            last_modified: "2024-01-01 00:00:00 (UTC)".to_string(),
        };

        let status_upper = app.status.to_uppercase();
        let formatted = if status_upper.contains("UPDATECOMPLETE")
            || status_upper.contains("UPDATE_COMPLETE")
        {
            "✅ Update complete"
        } else if status_upper.contains("CREATECOMPLETE")
            || status_upper.contains("CREATE_COMPLETE")
        {
            "✅ Create complete"
        } else {
            &app.status
        };

        assert_eq!(formatted, "✅ Update complete");

        // Test CREATE_COMPLETE
        let app2 = lambda::Application {
            status: "CreateComplete".to_string(),
            ..app
        };
        let status_upper = app2.status.to_uppercase();
        let formatted = if status_upper.contains("UPDATECOMPLETE")
            || status_upper.contains("UPDATE_COMPLETE")
        {
            "✅ Update complete"
        } else if status_upper.contains("CREATECOMPLETE")
            || status_upper.contains("CREATE_COMPLETE")
        {
            "✅ Create complete"
        } else {
            &app2.status
        };
        assert_eq!(formatted, "✅ Create complete");
    }

    #[test]
    fn test_pagination_shows_1_when_empty() {
        let result = render_pagination_text(0, 0);
        assert_eq!(result, "[1]");
    }

    #[test]
    fn test_pagination_shows_current_page() {
        let result = render_pagination_text(0, 3);
        assert_eq!(result, "[1] 2 3");

        let result = render_pagination_text(1, 3);
        assert_eq!(result, "1 [2] 3");
    }

    #[test]
    fn test_cloudformation_section_heights_match_content() {
        // Test that section heights are calculated based on content, not fixed
        // Overview: 14 fields + 2 borders = 16
        let overview_fields = 14;
        let overview_height = overview_fields + 2;
        assert_eq!(overview_height, 16);

        // Tags (empty): 4 lines + 2 borders = 6
        let tags_empty_lines = 4;
        let tags_empty_height = tags_empty_lines + 2;
        assert_eq!(tags_empty_height, 6);

        // Stack policy (empty): 5 lines + 2 borders = 7
        let policy_empty_lines = 5;
        let policy_empty_height = policy_empty_lines + 2;
        assert_eq!(policy_empty_height, 7);

        // Rollback (empty): 6 lines + 2 borders = 8
        let rollback_empty_lines = 6;
        let rollback_empty_height = rollback_empty_lines + 2;
        assert_eq!(rollback_empty_height, 8);

        // Notifications (empty): 4 lines + 2 borders = 6
        let notifications_empty_lines = 4;
        let notifications_empty_height = notifications_empty_lines + 2;
        assert_eq!(notifications_empty_height, 6);
    }

    #[test]
    fn test_log_groups_uses_table_state() {
        let mut app = test_app_no_region();
        app.current_service = Service::CloudWatchLogGroups;

        // Verify log_groups uses TableState
        assert_eq!(app.log_groups_state.log_groups.items.len(), 0);
        assert_eq!(app.log_groups_state.log_groups.selected, 0);
        assert_eq!(app.log_groups_state.log_groups.filter, "");
        assert_eq!(
            app.log_groups_state.log_groups.page_size,
            crate::common::PageSize::Fifty
        );
    }

    #[test]
    fn test_log_groups_filter_and_pagination() {
        let mut app = test_app_no_region();
        app.current_service = Service::CloudWatchLogGroups;

        // Add test log groups
        app.log_groups_state.log_groups.items = vec![
            rusticity_core::LogGroup {
                name: "/aws/lambda/function1".to_string(),
                creation_time: None,
                stored_bytes: Some(1024),
                retention_days: None,
                log_class: None,
                arn: None,
                log_group_arn: None,
                deletion_protection_enabled: None,
            },
            rusticity_core::LogGroup {
                name: "/aws/lambda/function2".to_string(),
                creation_time: None,
                stored_bytes: Some(2048),
                retention_days: None,
                log_class: None,
                arn: None,
                log_group_arn: None,
                deletion_protection_enabled: None,
            },
            rusticity_core::LogGroup {
                name: "/aws/ecs/service1".to_string(),
                creation_time: None,
                stored_bytes: Some(4096),
                retention_days: None,
                log_class: None,
                arn: None,
                log_group_arn: None,
                deletion_protection_enabled: None,
            },
        ];

        // Test filtering
        app.log_groups_state.log_groups.filter = "lambda".to_string();
        let filtered = filtered_log_groups(&app);
        assert_eq!(filtered.len(), 2);

        // Test pagination
        let page_size = app.log_groups_state.log_groups.page_size.value();
        assert_eq!(page_size, 50);
    }

    #[test]
    fn test_log_groups_expandable_indicators() {
        let group = rusticity_core::LogGroup {
            name: "/aws/lambda/test".to_string(),
            creation_time: None,
            stored_bytes: Some(1024),
            retention_days: None,
            log_class: None,
            arn: None,
            log_group_arn: None,
            deletion_protection_enabled: None,
        };

        // Test collapsed state (►)
        let collapsed = crate::ui::table::format_expandable(&group.name, false);
        assert!(collapsed.starts_with(""));
        assert!(collapsed.contains("/aws/lambda/test"));

        // Test expanded state (▼)
        let expanded = crate::ui::table::format_expandable(&group.name, true);
        assert!(expanded.starts_with(""));
        assert!(expanded.contains("/aws/lambda/test"));
    }

    #[test]
    fn test_log_groups_visual_boundaries() {
        // Verify visual boundary constants exist
        assert_eq!(crate::ui::table::CURSOR_COLLAPSED, "");
        assert_eq!(crate::ui::table::CURSOR_EXPANDED, "");

        // The visual boundaries │ and ╰ are rendered in render_table()
        // They are added as prefixes to expanded content lines
        let continuation = "";
        let last_line = "";

        assert_eq!(continuation, "");
        assert_eq!(last_line, "");
    }

    #[test]
    fn test_log_groups_right_arrow_expands() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::List;

        app.log_groups_state.log_groups.items = vec![rusticity_core::LogGroup {
            name: "/aws/lambda/test".to_string(),
            creation_time: None,
            stored_bytes: Some(1024),
            retention_days: None,
            log_class: None,
            arn: None,
            log_group_arn: None,
            deletion_protection_enabled: None,
        }];
        app.log_groups_state.log_groups.selected = 0;

        assert_eq!(app.log_groups_state.log_groups.expanded_item, None);

        // Right arrow - should expand
        app.handle_action(Action::NextPane);
        assert_eq!(app.log_groups_state.log_groups.expanded_item, Some(0));

        // Left arrow - should collapse
        app.handle_action(Action::PrevPane);
        assert_eq!(app.log_groups_state.log_groups.expanded_item, None);
    }

    #[test]
    fn test_log_streams_right_arrow_expands() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::Detail;

        app.log_groups_state.log_streams = vec![rusticity_core::LogStream {
            name: "stream-1".to_string(),
            creation_time: None,
            last_event_time: None,
        }];
        app.log_groups_state.selected_stream = 0;

        assert_eq!(app.log_groups_state.expanded_stream, None);

        // Right arrow - should expand
        app.handle_action(Action::NextPane);
        assert_eq!(app.log_groups_state.expanded_stream, Some(0));

        // Left arrow - should collapse
        app.handle_action(Action::PrevPane);
        assert_eq!(app.log_groups_state.expanded_stream, None);
    }

    #[test]
    fn test_log_events_border_style_no_double_border() {
        // Verify that log events don't use BorderType::Double
        // The new style only uses Green fg color for active state
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::Events;

        // Border style should only be Green fg when active, not Double border type
        // This is a regression test to ensure we don't reintroduce Double borders
        assert_eq!(app.view_mode, ViewMode::Events);
    }

    #[test]
    fn test_log_group_detail_border_style_no_double_border() {
        // Verify that log group detail doesn't use BorderType::Double
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::Detail;

        // Border style should only be Green fg when active, not Double border type
        assert_eq!(app.view_mode, ViewMode::Detail);
    }

    #[test]
    fn test_expansion_uses_intermediate_field_indicator() {
        // Verify that expanded content uses ├ for intermediate fields
        // This is tested by checking the constants exist
        // The actual rendering logic uses:
        // - ├ for field starts (lines with ": ")
        // - │ for continuation lines
        // - ╰ for the last line

        let intermediate = "";
        let continuation = "";
        let last = "";

        assert_eq!(intermediate, "");
        assert_eq!(continuation, "");
        assert_eq!(last, "");
    }

    #[test]
    fn test_log_streams_expansion_renders() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::Detail;

        app.log_groups_state.log_streams = vec![rusticity_core::LogStream {
            name: "test-stream".to_string(),
            creation_time: None,
            last_event_time: None,
        }];
        app.log_groups_state.selected_stream = 0;
        app.log_groups_state.expanded_stream = Some(0);

        // Verify expansion is set
        assert_eq!(app.log_groups_state.expanded_stream, Some(0));

        // Verify stream exists
        assert_eq!(app.log_groups_state.log_streams.len(), 1);
        assert_eq!(app.log_groups_state.log_streams[0].name, "test-stream");
    }

    #[test]
    fn test_log_streams_filter_layout_single_line() {
        // Verify that filter, exact match, and show expired are on the same line
        // This is a visual test - we verify the constraint is Length(3) not Length(4)
        let _app = App::new_without_client("test".to_string(), Some("us-east-1".to_string()));

        // Filter area should be 3 lines (1 for content + 2 for borders)
        // not 4 lines (2 for content + 2 for borders)
        let expected_filter_height = 3;
        assert_eq!(expected_filter_height, 3);
    }

    #[test]
    fn test_table_navigation_at_page_boundary() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::List;
        app.mode = Mode::Normal;

        // Create 100 log groups
        for i in 0..100 {
            app.log_groups_state
                .log_groups
                .items
                .push(rusticity_core::LogGroup {
                    name: format!("/aws/lambda/function{}", i),
                    creation_time: None,
                    stored_bytes: Some(1024),
                    retention_days: None,
                    log_class: None,
                    arn: None,
                    log_group_arn: None,
                    deletion_protection_enabled: None,
                });
        }

        // Set page size to 50
        app.log_groups_state.log_groups.page_size = crate::common::PageSize::Fifty;

        // Go to item 49 (last on page 1, 0-indexed)
        app.log_groups_state.log_groups.selected = 49;

        // Press down - should go to item 50 (first on page 2)
        app.handle_action(Action::NextItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 50);

        // Press up - should go back to item 49
        app.handle_action(Action::PrevItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 49);

        // Go to item 50 again
        app.handle_action(Action::NextItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 50);

        // Press up again - should still go to 49
        app.handle_action(Action::PrevItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 49);
    }

    #[test]
    fn test_table_navigation_at_end() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::List;
        app.mode = Mode::Normal;

        // Create 100 log groups
        for i in 0..100 {
            app.log_groups_state
                .log_groups
                .items
                .push(rusticity_core::LogGroup {
                    name: format!("/aws/lambda/function{}", i),
                    creation_time: None,
                    stored_bytes: Some(1024),
                    retention_days: None,
                    log_class: None,
                    arn: None,
                    log_group_arn: None,
                    deletion_protection_enabled: None,
                });
        }

        // Go to last item (99)
        app.log_groups_state.log_groups.selected = 99;

        // Press down - should stay at 99
        app.handle_action(Action::NextItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 99);

        // Press up - should go to 98
        app.handle_action(Action::PrevItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 98);
    }

    #[test]
    fn test_table_viewport_scrolling() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::List;
        app.mode = Mode::Normal;

        // Create 100 log groups
        for i in 0..100 {
            app.log_groups_state
                .log_groups
                .items
                .push(rusticity_core::LogGroup {
                    name: format!("/aws/lambda/function{}", i),
                    creation_time: None,
                    stored_bytes: Some(1024),
                    retention_days: None,
                    log_class: None,
                    arn: None,
                    log_group_arn: None,
                    deletion_protection_enabled: None,
                });
        }

        // Set page size to 50
        app.log_groups_state.log_groups.page_size = crate::common::PageSize::Fifty;

        // Start at item 49 (last visible on first viewport)
        app.log_groups_state.log_groups.selected = 49;
        app.log_groups_state.log_groups.scroll_offset = 0;

        // Press down - should go to item 50 and scroll viewport
        app.handle_action(Action::NextItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 50);
        assert_eq!(app.log_groups_state.log_groups.scroll_offset, 1); // Scrolled by 1

        // Press up - should go back to item 49 WITHOUT scrolling back
        app.handle_action(Action::PrevItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 49);
        assert_eq!(app.log_groups_state.log_groups.scroll_offset, 1); // Still at 1, not 0

        // Press up again - should go to 48, still no scroll
        app.handle_action(Action::PrevItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 48);
        assert_eq!(app.log_groups_state.log_groups.scroll_offset, 1); // Still at 1

        // Keep going up until we hit the top of viewport (item 1)
        for _ in 0..47 {
            app.handle_action(Action::PrevItem);
        }
        assert_eq!(app.log_groups_state.log_groups.selected, 1);
        assert_eq!(app.log_groups_state.log_groups.scroll_offset, 1); // Still at 1

        // One more up - should scroll viewport up
        app.handle_action(Action::PrevItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 0);
        assert_eq!(app.log_groups_state.log_groups.scroll_offset, 0); // Scrolled to 0
    }

    #[test]
    fn test_table_up_from_last_row() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::List;
        app.mode = Mode::Normal;

        // Create 100 log groups
        for i in 0..100 {
            app.log_groups_state
                .log_groups
                .items
                .push(rusticity_core::LogGroup {
                    name: format!("/aws/lambda/function{}", i),
                    creation_time: None,
                    stored_bytes: Some(1024),
                    retention_days: None,
                    log_class: None,
                    arn: None,
                    log_group_arn: None,
                    deletion_protection_enabled: None,
                });
        }

        // Set page size to 50
        app.log_groups_state.log_groups.page_size = crate::common::PageSize::Fifty;

        // Go to last row (99) with scroll showing last page
        app.log_groups_state.log_groups.selected = 99;
        app.log_groups_state.log_groups.scroll_offset = 50; // Showing items 50-99

        // Press up - should go to item 98 WITHOUT scrolling
        app.handle_action(Action::PrevItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 98);
        assert_eq!(app.log_groups_state.log_groups.scroll_offset, 50); // Should NOT scroll

        // Press up again - should go to 97, still no scroll
        app.handle_action(Action::PrevItem);
        assert_eq!(app.log_groups_state.log_groups.selected, 97);
        assert_eq!(app.log_groups_state.log_groups.scroll_offset, 50); // Should NOT scroll
    }

    #[test]
    fn test_table_up_from_last_visible_row() {
        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::List;
        app.mode = Mode::Normal;

        // Create 100 log groups
        for i in 0..100 {
            app.log_groups_state
                .log_groups
                .items
                .push(rusticity_core::LogGroup {
                    name: format!("/aws/lambda/function{}", i),
                    creation_time: None,
                    stored_bytes: Some(1024),
                    retention_days: None,
                    log_class: None,
                    arn: None,
                    log_group_arn: None,
                    deletion_protection_enabled: None,
                });
        }

        // Set page size to 50
        app.log_groups_state.log_groups.page_size = crate::common::PageSize::Fifty;

        // Simulate: at item 49 (last visible), press down to get to item 50
        app.log_groups_state.log_groups.selected = 49;
        app.log_groups_state.log_groups.scroll_offset = 0;
        app.handle_action(Action::NextItem);

        // Now at item 50, scroll_offset = 1 (showing items 1-50)
        assert_eq!(app.log_groups_state.log_groups.selected, 50);
        assert_eq!(app.log_groups_state.log_groups.scroll_offset, 1);

        // Item 50 is now the last visible row
        // Press up - should move to item 49 WITHOUT scrolling
        app.handle_action(Action::PrevItem);
        assert_eq!(
            app.log_groups_state.log_groups.selected, 49,
            "Selection should move to 49"
        );
        assert_eq!(
            app.log_groups_state.log_groups.scroll_offset, 1,
            "Should NOT scroll up"
        );
    }

    #[test]
    fn test_cloudformation_up_from_last_visible_row() {
        let mut app = test_app();
        app.current_service = Service::CloudFormationStacks;
        app.service_selected = true;
        app.mode = Mode::Normal;

        // Create 100 stacks
        for i in 0..100 {
            app.cfn_state.table.items.push(crate::cfn::Stack {
                name: format!("Stack{}", i),
                stack_id: format!("id{}", i),
                status: "CREATE_COMPLETE".to_string(),
                created_time: "2024-01-01 00:00:00 (UTC)".to_string(),
                updated_time: "2024-01-01 00:00:00 (UTC)".to_string(),
                deleted_time: String::new(),
                description: "Test".to_string(),
                drift_status: "NOT_CHECKED".to_string(),
                last_drift_check_time: "-".to_string(),
                status_reason: String::new(),
                detailed_status: "CREATE_COMPLETE".to_string(),
                root_stack: String::new(),
                parent_stack: String::new(),
                termination_protection: false,
                iam_role: String::new(),
                tags: Vec::new(),
                stack_policy: String::new(),
                rollback_monitoring_time: String::new(),
                rollback_alarms: Vec::new(),
                notification_arns: Vec::new(),
            });
        }

        // Set page size to 50
        app.cfn_state.table.page_size = crate::common::PageSize::Fifty;

        // Simulate: at item 49 (last visible), press down to get to item 50
        app.cfn_state.table.selected = 49;
        app.cfn_state.table.scroll_offset = 0;
        app.handle_action(Action::NextItem);

        // Now at item 50, scroll_offset should be 1
        assert_eq!(app.cfn_state.table.selected, 50);
        assert_eq!(app.cfn_state.table.scroll_offset, 1);

        // Press up - should move to item 49 WITHOUT scrolling
        app.handle_action(Action::PrevItem);
        assert_eq!(
            app.cfn_state.table.selected, 49,
            "Selection should move to 49"
        );
        assert_eq!(
            app.cfn_state.table.scroll_offset, 1,
            "Should NOT scroll up - this is the bug!"
        );
    }

    #[test]
    fn test_cloudformation_up_from_actual_last_row() {
        let mut app = test_app();
        app.current_service = Service::CloudFormationStacks;
        app.service_selected = true;
        app.mode = Mode::Normal;

        // Create 88 stacks (like in the user's screenshot)
        for i in 0..88 {
            app.cfn_state.table.items.push(crate::cfn::Stack {
                name: format!("Stack{}", i),
                stack_id: format!("id{}", i),
                status: "CREATE_COMPLETE".to_string(),
                created_time: "2024-01-01 00:00:00 (UTC)".to_string(),
                updated_time: "2024-01-01 00:00:00 (UTC)".to_string(),
                deleted_time: String::new(),
                description: "Test".to_string(),
                drift_status: "NOT_CHECKED".to_string(),
                last_drift_check_time: "-".to_string(),
                status_reason: String::new(),
                detailed_status: "CREATE_COMPLETE".to_string(),
                root_stack: String::new(),
                parent_stack: String::new(),
                termination_protection: false,
                iam_role: String::new(),
                tags: Vec::new(),
                stack_policy: String::new(),
                rollback_monitoring_time: String::new(),
                rollback_alarms: Vec::new(),
                notification_arns: Vec::new(),
            });
        }

        // Set page size to 50
        app.cfn_state.table.page_size = crate::common::PageSize::Fifty;

        // Simulate being on page 2 (showing items 38-87, which is the last page)
        // User is at item 87 (the actual last row)
        app.cfn_state.table.selected = 87;
        app.cfn_state.table.scroll_offset = 38; // Showing last 50 items

        // Press up - should move to item 86 WITHOUT scrolling
        app.handle_action(Action::PrevItem);
        assert_eq!(
            app.cfn_state.table.selected, 86,
            "Selection should move to 86"
        );
        assert_eq!(
            app.cfn_state.table.scroll_offset, 38,
            "Should NOT scroll - scroll_offset should stay at 38"
        );
    }

    #[test]
    fn test_iam_users_default_columns() {
        let app = test_app();
        assert_eq!(app.iam_user_visible_column_ids.len(), 11);
        assert!(app
            .iam_user_visible_column_ids
            .contains(&"column.iam.user.user_name"));
        assert!(app
            .iam_user_visible_column_ids
            .contains(&"column.iam.user.path"));
        assert!(app
            .iam_user_visible_column_ids
            .contains(&"column.iam.user.arn"));
    }

    #[test]
    fn test_iam_users_all_columns() {
        let app = test_app();
        assert_eq!(app.iam_user_column_ids.len(), 14);
        assert!(app
            .iam_user_column_ids
            .contains(&"column.iam.user.creation_time"));
        assert!(app
            .iam_user_column_ids
            .contains(&"column.iam.user.console_access"));
        assert!(app
            .iam_user_column_ids
            .contains(&"column.iam.user.signing_certs"));
    }

    #[test]
    fn test_iam_users_filter() {
        let mut app = test_app();
        app.current_service = Service::IamUsers;

        // Add test users
        app.iam_state.users.items = vec![
            crate::iam::IamUser {
                user_name: "alice".to_string(),
                path: "/".to_string(),
                groups: "admins".to_string(),
                last_activity: "2024-01-01".to_string(),
                mfa: "Enabled".to_string(),
                password_age: "30 days".to_string(),
                console_last_sign_in: "2024-01-01".to_string(),
                access_key_id: "AKIA...".to_string(),
                active_key_age: "60 days".to_string(),
                access_key_last_used: "2024-01-01".to_string(),
                arn: "arn:aws:iam::123456789012:user/alice".to_string(),
                creation_time: "2023-01-01".to_string(),
                console_access: "Enabled".to_string(),
                signing_certs: "0".to_string(),
            },
            crate::iam::IamUser {
                user_name: "bob".to_string(),
                path: "/".to_string(),
                groups: "developers".to_string(),
                last_activity: "2024-01-02".to_string(),
                mfa: "Disabled".to_string(),
                password_age: "45 days".to_string(),
                console_last_sign_in: "2024-01-02".to_string(),
                access_key_id: "AKIA...".to_string(),
                active_key_age: "90 days".to_string(),
                access_key_last_used: "2024-01-02".to_string(),
                arn: "arn:aws:iam::123456789012:user/bob".to_string(),
                creation_time: "2023-02-01".to_string(),
                console_access: "Enabled".to_string(),
                signing_certs: "1".to_string(),
            },
        ];

        // No filter - should return all users
        let filtered = crate::ui::iam::filtered_iam_users(&app);
        assert_eq!(filtered.len(), 2);

        // Filter by name
        app.iam_state.users.filter = "alice".to_string();
        let filtered = crate::ui::iam::filtered_iam_users(&app);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].user_name, "alice");

        // Case insensitive filter
        app.iam_state.users.filter = "BOB".to_string();
        let filtered = crate::ui::iam::filtered_iam_users(&app);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].user_name, "bob");
    }

    #[test]
    fn test_iam_users_pagination() {
        let mut app = test_app();
        app.current_service = Service::IamUsers;

        // Add 30 test users
        for i in 0..30 {
            app.iam_state.users.items.push(crate::iam::IamUser {
                user_name: format!("user{}", i),
                path: "/".to_string(),
                groups: String::new(),
                last_activity: "-".to_string(),
                mfa: "Disabled".to_string(),
                password_age: "-".to_string(),
                console_last_sign_in: "-".to_string(),
                access_key_id: "-".to_string(),
                active_key_age: "-".to_string(),
                access_key_last_used: "-".to_string(),
                arn: format!("arn:aws:iam::123456789012:user/user{}", i),
                creation_time: "2023-01-01".to_string(),
                console_access: "Disabled".to_string(),
                signing_certs: "0".to_string(),
            });
        }

        // Default page size is 25
        app.iam_state.users.page_size = crate::common::PageSize::TwentyFive;

        let filtered = crate::ui::iam::filtered_iam_users(&app);
        assert_eq!(filtered.len(), 30);

        // Pagination should work
        let page_size = app.iam_state.users.page_size.value();
        assert_eq!(page_size, 25);
    }

    #[test]
    fn test_iam_users_expansion() {
        let mut app = test_app();
        app.current_service = Service::IamUsers;
        app.service_selected = true;
        app.mode = Mode::Normal;

        app.iam_state.users.items = vec![crate::iam::IamUser {
            user_name: "testuser".to_string(),
            path: "/admin/".to_string(),
            groups: "admins,developers".to_string(),
            last_activity: "2024-01-01".to_string(),
            mfa: "Enabled".to_string(),
            password_age: "30 days".to_string(),
            console_last_sign_in: "2024-01-01 10:00:00".to_string(),
            access_key_id: "AKIAIOSFODNN7EXAMPLE".to_string(),
            active_key_age: "60 days".to_string(),
            access_key_last_used: "2024-01-01 09:00:00".to_string(),
            arn: "arn:aws:iam::123456789012:user/admin/testuser".to_string(),
            creation_time: "2023-01-01 00:00:00".to_string(),
            console_access: "Enabled".to_string(),
            signing_certs: "2".to_string(),
        }];

        // Expand first item
        app.handle_action(Action::NextPane);
        assert_eq!(app.iam_state.users.expanded_item, Some(0));

        // Collapse
        app.handle_action(Action::PrevPane);
        assert_eq!(app.iam_state.users.expanded_item, None);
    }

    #[test]
    fn test_iam_users_in_service_picker() {
        let app = test_app();
        assert!(app.service_picker.services.contains(&"IAM › Users"));
    }

    #[test]
    fn test_iam_users_service_selection() {
        let mut app = test_app();
        app.mode = Mode::ServicePicker;
        let filtered = app.filtered_services();
        let selected_idx = filtered.iter().position(|&s| s == "IAM › Users").unwrap();
        app.service_picker.selected = selected_idx;

        app.handle_action(Action::Select);

        assert_eq!(app.current_service, Service::IamUsers);
        assert!(app.service_selected);
        assert_eq!(app.tabs.len(), 1);
        assert_eq!(app.tabs[0].service, Service::IamUsers);
        assert_eq!(app.tabs[0].title, "IAM › Users");
    }

    #[test]
    fn test_api_gateway_in_service_picker() {
        let app = test_app();
        assert!(app.service_picker.services.contains(&"API Gateway › APIs"));
    }

    #[test]
    fn test_api_gateway_service_selection() {
        let mut app = test_app();
        app.mode = Mode::ServicePicker;
        let filtered = app.filtered_services();
        let selected_idx = filtered
            .iter()
            .position(|&s| s == "API Gateway › APIs")
            .unwrap();
        app.service_picker.selected = selected_idx;

        app.handle_action(Action::Select);

        assert_eq!(app.current_service, Service::ApiGatewayApis);
        assert!(app.service_selected);
        assert_eq!(app.tabs.len(), 1);
        assert_eq!(app.tabs[0].service, Service::ApiGatewayApis);
        assert_eq!(app.tabs[0].title, "API Gateway › APIs");
    }

    #[test]
    fn test_format_duration_seconds() {
        assert_eq!(format_duration(1), "1 second");
        assert_eq!(format_duration(30), "30 seconds");
    }

    #[test]
    fn test_format_duration_minutes() {
        assert_eq!(format_duration(60), "1 minute");
        assert_eq!(format_duration(120), "2 minutes");
        assert_eq!(format_duration(3600 - 1), "59 minutes");
    }

    #[test]
    fn test_format_duration_hours() {
        assert_eq!(format_duration(3600), "1 hour");
        assert_eq!(format_duration(7200), "2 hours");
        assert_eq!(format_duration(3600 + 1800), "1 hour 30 minutes");
        assert_eq!(format_duration(7200 + 60), "2 hours 1 minute");
    }

    #[test]
    fn test_format_duration_days() {
        assert_eq!(format_duration(86400), "1 day");
        assert_eq!(format_duration(172800), "2 days");
        assert_eq!(format_duration(86400 + 3600), "1 day 1 hour");
        assert_eq!(format_duration(172800 + 7200), "2 days 2 hours");
    }

    #[test]
    fn test_format_duration_weeks() {
        assert_eq!(format_duration(604800), "1 week");
        assert_eq!(format_duration(1209600), "2 weeks");
        assert_eq!(format_duration(604800 + 86400), "1 week 1 day");
        assert_eq!(format_duration(1209600 + 172800), "2 weeks 2 days");
    }

    #[test]
    fn test_format_duration_years() {
        assert_eq!(format_duration(31536000), "1 year");
        assert_eq!(format_duration(63072000), "2 years");
        assert_eq!(format_duration(31536000 + 604800), "1 year 1 week");
        assert_eq!(format_duration(63072000 + 1209600), "2 years 2 weeks");
    }

    #[test]
    fn test_tab_style_selected() {
        let style = tab_style(true);
        assert_eq!(style, highlight());
    }

    #[test]
    fn test_tab_style_not_selected() {
        let style = tab_style(false);
        assert_eq!(style, Style::default());
    }

    #[test]
    fn test_render_tab_spans_single_tab() {
        let tabs = [("Tab1", true)];
        let spans = render_tab_spans(&tabs);
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].content, "Tab1");
        assert_eq!(spans[0].style, service_tab_style(true));
    }

    #[test]
    fn test_render_tab_spans_multiple_tabs() {
        let tabs = [("Tab1", true), ("Tab2", false), ("Tab3", false)];
        let spans = render_tab_spans(&tabs);
        assert_eq!(spans.len(), 5); // Tab1, separator, Tab2, separator, Tab3
        assert_eq!(spans[0].content, "Tab1");
        assert_eq!(spans[0].style, service_tab_style(true));
        assert_eq!(spans[1].content, "");
        assert_eq!(spans[2].content, "Tab2");
        assert_eq!(spans[2].style, Style::default());
        assert_eq!(spans[3].content, "");
        assert_eq!(spans[4].content, "Tab3");
        assert_eq!(spans[4].style, Style::default());
    }

    #[test]
    fn test_render_tab_spans_no_separator_for_first() {
        let tabs = [("First", false), ("Second", true)];
        let spans = render_tab_spans(&tabs);
        assert_eq!(spans.len(), 3); // First, separator, Second
        assert_eq!(spans[0].content, "First");
        assert_eq!(spans[1].content, "");
        assert_eq!(spans[2].content, "Second");
        assert_eq!(spans[2].style, service_tab_style(true));
    }

    #[test]
    fn test_calculate_dynamic_height_empty() {
        let fields: Vec<Line> = vec![];
        assert_eq!(calculate_dynamic_height(&fields, 100), 0);
    }

    #[test]
    fn test_calculate_dynamic_height_single_column() {
        let fields = vec![
            Line::from("Field 1"),
            Line::from("Field 2"),
            Line::from("Field 3"),
        ];
        // Width 30, fields ~9 chars, should fit 3 columns, 3 fields / 3 = 1 row
        assert_eq!(calculate_dynamic_height(&fields, 30), 1);
    }

    #[test]
    fn test_calculate_dynamic_height_two_columns() {
        let fields = vec![
            Line::from("Field 1"),
            Line::from("Field 2"),
            Line::from("Field 3"),
            Line::from("Field 4"),
            Line::from("Field 5"),
        ];
        // Width 20, fields ~9 chars, should fit 2 columns, 5 fields / 2 = 3 rows (3,2)
        assert_eq!(calculate_dynamic_height(&fields, 20), 3);
    }

    #[test]
    fn test_calculate_dynamic_height_three_columns() {
        let fields = vec![
            Line::from("F1"),
            Line::from("F2"),
            Line::from("F3"),
            Line::from("F4"),
            Line::from("F5"),
            Line::from("F6"),
            Line::from("F7"),
            Line::from("F8"),
            Line::from("F9"),
            Line::from("F10"),
        ];
        // Width 20, short fields ~4 chars, should fit 5 columns, 10 fields / 5 = 2 rows
        // But if max_field_width is calculated differently, adjust expectation
        let result = calculate_dynamic_height(&fields, 20);
        // With 10 fields at width 20: max_field_width = 4 (2 + 2), columns = 20/4 = 5
        // But with MAX_DETAIL_COLUMNS=3, columns = min(5, 3, 10) = 3
        // 10 fields / 3 columns = 3 base, 1 extra = 4 rows
        assert_eq!(result, 4);
    }

    #[test]
    fn test_calculate_dynamic_height_even_distribution() {
        let fields = vec![
            Line::from("A"),
            Line::from("B"),
            Line::from("C"),
            Line::from("D"),
        ];
        // Width 100, should fit many columns, but MAX_DETAIL_COLUMNS=3
        // 4 fields / 3 columns = 1 base, 1 extra = 2 rows
        assert_eq!(calculate_dynamic_height(&fields, 100), 2);
    }

    #[test]
    fn test_ec2_tags_preferences_shows_tag_columns() {
        let mut app = crate::app::App::new_without_client("default".to_string(), None);
        app.current_service = crate::app::Service::Ec2Instances;
        app.ec2_state.current_instance = Some("i-123".to_string());
        app.ec2_state.detail_tab = ec2::DetailTab::Tags;
        app.mode = crate::keymap::Mode::ColumnSelector;

        // Render to a test backend to verify column selector shows tag columns
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();

        terminal
            .draw(|f| {
                render(f, &app);
            })
            .unwrap();

        let buffer = terminal.backend().buffer().clone();
        let content = buffer
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect::<String>();

        // Should show "Key" and "Value" columns, not "Log stream"
        assert!(content.contains("Key"));
        assert!(content.contains("Value"));
        assert!(!content.contains("Log stream"));
    }

    #[test]
    fn test_cloudwatch_detail_preferences_shows_stream_columns() {
        let mut app = crate::app::App::new_without_client("default".to_string(), None);
        app.current_service = crate::app::Service::CloudWatchLogGroups;
        app.view_mode = crate::app::ViewMode::Detail;
        app.mode = crate::keymap::Mode::ColumnSelector;

        use ratatui::backend::TestBackend;
        use ratatui::Terminal;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();

        terminal
            .draw(|f| {
                render(f, &app);
            })
            .unwrap();

        let buffer = terminal.backend().buffer().clone();
        let content = buffer
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect::<String>();

        // Should show "Log stream" for CloudWatch
        assert!(content.contains("Log stream"));
    }

    #[test]
    fn test_ec2_instances_preferences_shows_instance_columns() {
        let mut app = crate::app::App::new_without_client("default".to_string(), None);
        app.current_service = crate::app::Service::Ec2Instances;
        app.mode = crate::keymap::Mode::ColumnSelector;

        use ratatui::backend::TestBackend;
        use ratatui::Terminal;
        let backend = TestBackend::new(120, 40);
        let mut terminal = Terminal::new(backend).unwrap();

        terminal
            .draw(|f| {
                render(f, &app);
            })
            .unwrap();

        let buffer = terminal.backend().buffer().clone();
        let content = buffer
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect::<String>();

        // Should show EC2 instance columns, not tag columns
        assert!(content.contains("Columns"));
        assert!(!content.contains("Log stream"));
    }

    #[test]
    fn test_section_header_has_leading_dash() {
        let line = section_header("Default encryption", 50);
        let text = line
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<String>();

        // Should start with "─ "
        assert!(text.starts_with(""));
        // Should contain the section name
        assert!(text.contains("Default encryption"));
        // Should end with dashes
        assert!(text.ends_with(''));
    }

    #[test]
    fn test_section_header_width_calculation() {
        let width = 60;
        let line = section_header("Test Section", width);
        let text = line
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<String>();

        // Total character count should match width (not byte count)
        assert_eq!(text.chars().count(), width as usize);
        // Format: "─ Test Section ───...─"
        assert!(text.starts_with("─ Test Section "));
    }

    #[test]
    fn test_cloudwatch_log_groups_no_breadcrumb_in_detail_view() {
        use crate::app::{Service, ViewMode};
        use rusticity_core::LogGroup;

        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::Detail;
        app.tabs.push(crate::app::Tab {
            service: Service::CloudWatchLogGroups,
            title: "CloudWatch › Log Groups".to_string(),
            breadcrumb: "CloudWatch › Log Groups".to_string(),
        });

        // Add a log group
        app.log_groups_state.log_groups.items = vec![LogGroup {
            name: "/aws/lambda/test".to_string(),
            creation_time: None,
            stored_bytes: None,
            retention_days: None,
            log_class: None,
            arn: None,
            log_group_arn: None,
            deletion_protection_enabled: None,
        }];

        // Breadcrumb should not be shown in UI (show_breadcrumbs should be false)
        let show_breadcrumbs = !app.tabs.is_empty()
            && app.service_selected
            && match app.current_service {
                Service::S3Buckets => app.s3_state.current_bucket.is_some(),
                _ => false,
            };

        assert!(!show_breadcrumbs);
    }

    #[test]
    fn test_cloudwatch_log_groups_no_breadcrumb_in_events_view() {
        use crate::app::{Service, ViewMode};

        let mut app = test_app();
        app.current_service = Service::CloudWatchLogGroups;
        app.service_selected = true;
        app.view_mode = ViewMode::Events;
        app.tabs.push(crate::app::Tab {
            service: Service::CloudWatchLogGroups,
            title: "CloudWatch › Log Groups".to_string(),
            breadcrumb: "CloudWatch › Log Groups".to_string(),
        });

        // Breadcrumb should not be shown in UI
        let show_breadcrumbs = !app.tabs.is_empty()
            && app.service_selected
            && match app.current_service {
                Service::S3Buckets => app.s3_state.current_bucket.is_some(),
                _ => false,
            };

        assert!(!show_breadcrumbs);
    }

    #[test]
    fn test_title_format_with_leading_dash() {
        // format_title returns "─ Title ─"
        // Ratatui block renders: ╭<title>╮
        // Result: ╭─ Title ─╮

        let title = format_title("APIs (2)");
        assert_eq!(title, "─ APIs (2) ─");

        let title = format_title("Preferences");
        assert_eq!(title, "─ Preferences ─");

        let title = format_title("CloudTrail Events");
        assert_eq!(title, "─ CloudTrail Events ─");

        let title = format_title("AWS Services");
        assert_eq!(title, "─ AWS Services ─");
    }

    #[test]
    fn test_titled_block_renders_correctly() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let backend = TestBackend::new(40, 3);
        let mut terminal = Terminal::new(backend).unwrap();

        terminal
            .draw(|frame| {
                let block = titled_block("AWS Services");
                let area = frame.area();
                frame.render_widget(block, area);
            })
            .unwrap();

        let buffer = terminal.backend().buffer();
        let first_line = buffer.content()[0..40]
            .iter()
            .map(|cell| cell.symbol())
            .collect::<String>();

        // Should render as: ╭─ AWS Services ─...
        assert!(
            first_line.starts_with("╭─ AWS Services ─"),
            "Expected '╭─ AWS Services ─' but got '{}'",
            first_line
        );
    }

    #[test]
    fn test_titled_block_cloudtrail_renders_correctly() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let backend = TestBackend::new(50, 3);
        let mut terminal = Terminal::new(backend).unwrap();

        terminal
            .draw(|frame| {
                let block = titled_block("CloudTrail Events");
                let area = frame.area();
                frame.render_widget(block, area);
            })
            .unwrap();

        let buffer = terminal.backend().buffer();
        let first_line = buffer.content()[0..50]
            .iter()
            .map(|cell| cell.symbol())
            .collect::<String>();

        // Should render as: ╭─ CloudTrail Events ─...
        assert!(
            first_line.starts_with("╭─ CloudTrail Events ─"),
            "Expected '╭─ CloudTrail Events ─' but got '{}'",
            first_line
        );
    }
}