sofka 0.13.3

A Kubernetes TUI, reimagined in Rust
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
//! All ratatui rendering.

use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{
    Block, BorderType, Borders, Cell, Clear, Gauge, HighlightSpacing, List, ListItem, ListState,
    Paragraph, Row, Table, Wrap,
};
use unicode_width::UnicodeWidthChar;

use crate::app::{App, Mode, SuggestKind, TRANSFER_MENU_ITEMS};
use crate::{columns, theme};

const VERSION: &str = env!("CARGO_PKG_VERSION");

enum TableCellText<'a> {
    Borrowed(&'a str),
    Owned(String),
}

impl<'a> TableCellText<'a> {
    fn as_str(&self) -> &str {
        match self {
            TableCellText::Borrowed(value) => value,
            TableCellText::Owned(value) => value,
        }
    }

    fn into_cell(self) -> Cell<'a> {
        match self {
            TableCellText::Borrowed(value) => Cell::from(value),
            TableCellText::Owned(value) => Cell::from(value),
        }
    }

    /// Like [`Self::into_cell`], honoring a custom column's alignment.
    fn into_cell_aligned(self, align: Option<Alignment>) -> Cell<'a> {
        let Some(align) = align else {
            return self.into_cell();
        };
        match self {
            TableCellText::Borrowed(value) => Cell::from(Text::from(value).alignment(align)),
            TableCellText::Owned(value) => Cell::from(Text::from(value).alignment(align)),
        }
    }
}

/// Map a view column's configured alignment onto ratatui's.
fn cell_alignment(align: crate::views::Align) -> Alignment {
    match align {
        crate::views::Align::Left => Alignment::Left,
        crate::views::Align::Center => Alignment::Center,
        crate::views::Align::Right => Alignment::Right,
    }
}

pub fn draw(frame: &mut Frame, app: &mut App) {
    // Fill the whole frame with the skin's background first (when enabled), so
    // every view that only sets foreground colors sits on it. Widgets that set
    // their own background (the selection bar, gauges, search highlights) still
    // win where they draw.
    if let Some(bg) = theme::background() {
        let area = frame.area();
        frame.buffer_mut().set_style(area, Style::default().bg(bg));
    }

    // Compact mode (ctrl-e) trades the 7-line header + footer for a single
    // header line, so a small tiled pane is almost all table. The prompt line
    // still appears while typing a command/filter; the status line and hint
    // crumbs are folded away (a flash + sync dot ride in the compact header).
    let compact = app.compact;
    let needs_prompt = matches!(
        app.mode,
        Mode::Command | Mode::Filter | Mode::LogFilter | Mode::DocFilter
    );

    // Fullscreen logs (F): the pane takes the whole frame — no header, status
    // line, or crumbs — so terminal text selection copies clean lines. The
    // prompt line stays while typing a filter, and the lookback prompt still
    // pops up over the logs.
    if app.logs.fullscreen
        && (matches!(app.mode, Mode::Logs | Mode::LogFilter)
            || (app.mode == Mode::Prompt && app.prompt_over_logs()))
    {
        let mut constraints = vec![Constraint::Min(3)];
        if needs_prompt {
            constraints.push(Constraint::Length(1));
        }
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints(constraints)
            .split(frame.area());
        draw_logs(frame, app, chunks[0]);
        if app.mode == Mode::Prompt {
            draw_prompt_popup(frame, app, chunks[0]);
        }
        if needs_prompt {
            draw_prompt(frame, app, chunks[1]);
        }
        return;
    }
    let mut constraints = vec![
        Constraint::Length(if compact { 1 } else { 7 }), // header
        Constraint::Min(3),                              // body
    ];
    let prompt_idx = if !compact || needs_prompt {
        constraints.push(Constraint::Length(1));
        Some(constraints.len() - 1)
    } else {
        None
    };
    let status_idx = if !compact {
        constraints.push(Constraint::Length(1));
        Some(constraints.len() - 1)
    } else {
        None
    };
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(frame.area());

    if compact {
        draw_compact_header(frame, app, chunks[0]);
    } else {
        draw_header(frame, app, chunks[0]);
    }

    match app.mode {
        Mode::Detail => draw_scrollable(frame, &app.detail, chunks[1], theme::sky()),
        Mode::Diff => draw_diff(frame, &app.detail, chunks[1]),
        Mode::Events => draw_scrollable(frame, &app.detail, chunks[1], theme::peach()),
        Mode::Logs | Mode::LogFilter => draw_logs(frame, app, chunks[1]),
        // The lookback prompt opens from the logs view — keep it underneath.
        Mode::Prompt if app.prompt_over_logs() => draw_logs(frame, app, chunks[1]),
        // While typing a doc search, keep drawing the view it was opened from
        // so the matches narrow live under the prompt.
        Mode::DocFilter => match app.doc_filter_return {
            Mode::Diff => draw_diff(frame, &app.detail, chunks[1]),
            Mode::Events => draw_scrollable(frame, &app.detail, chunks[1], theme::peach()),
            Mode::Help => draw_help(frame, app, chunks[1]),
            _ => draw_scrollable(frame, &app.detail, chunks[1], theme::sky()),
        },
        Mode::Help => draw_help(frame, app, chunks[1]),
        Mode::Pulse => draw_pulse(frame, app, chunks[1]),
        Mode::Xray => draw_xray(frame, app, chunks[1]),
        Mode::Explain => draw_explain(frame, app, chunks[1]),
        Mode::Gitops => draw_gitops(frame, app, chunks[1]),
        Mode::Timeline => draw_timeline(frame, app, chunks[1]),
        Mode::PortForwards => draw_port_forwards(frame, app, chunks[1]),
        Mode::Fleet => draw_fleet(frame, app, chunks[1]),
        _ => draw_table(frame, app, chunks[1]),
    }

    match app.mode {
        Mode::Namespaces => draw_namespaces(frame, app, chunks[1]),
        Mode::Contexts => draw_contexts(frame, app, chunks[1]),
        Mode::Containers => draw_containers(frame, app, chunks[1]),
        Mode::SetImage => draw_set_image(frame, app, chunks[1]),
        Mode::Confirm => draw_confirm(frame, app, chunks[1]),
        Mode::Prompt => draw_prompt_popup(frame, app, chunks[1]),
        Mode::Command => draw_palette(frame, app, chunks[1]),
        Mode::FluxMenu => draw_flux_menu(frame, app, chunks[1]),
        Mode::TransferMenu => draw_transfer_menu(frame, app, chunks[1]),
        Mode::Skins => draw_skins(frame, app, chunks[1]),
        Mode::Snapshots => draw_snapshots(frame, app, chunks[1]),
        _ => {}
    }

    if let Some(i) = prompt_idx {
        draw_prompt(frame, app, chunks[i]);
    }
    if let Some(i) = status_idx {
        draw_status(frame, app, chunks[i]);
    }
}

/// Width reserved for the per-kind key-hint column inside the header box:
/// three 13-wide cells (2-char key + space + 10-char label) with 2-space gaps.
const HEADER_HINTS_WIDTH: u16 = 44;
/// Minimum width the info cluster keeps before the hint column may appear.
const HEADER_INFO_MIN: u16 = 44;

fn draw_header(frame: &mut Frame, app: &App, area: Rect) {
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Min(30), Constraint::Length(26)])
        .split(area);

    let ns = if app.all_namespaces() {
        "<all>".to_string()
    } else {
        app.namespace.clone()
    };
    let mut kind = app.resource_title();
    if let Some(scope) = &app.scope_label {
        kind = format!("{kind}{scope}");
    }

    let field = |label: &str, val: String, color| {
        Line::from(vec![
            Span::styled(format!("{label:<12}"), theme::dim()),
            Span::styled(val, Style::default().fg(color)),
        ])
    };

    let mut context_line = field("Context:", app.cluster.context.clone(), theme::mauve());
    if app.readonly {
        context_line.push_span(Span::styled(
            "  [read-only]",
            Style::default().fg(theme::red()),
        ));
    }
    let info = vec![
        context_line,
        field(
            "Cluster:",
            app.cluster.cluster_url.clone(),
            theme::sapphire(),
        ),
        field("Namespace:", ns, theme::green()),
        field("Resource:", kind, theme::peach()),
        field("Count:", app.store.len().to_string(), theme::text()),
    ];

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(theme::border())
        .title(Span::styled(" sofka ", theme::title()));
    let inner = block.inner(cols[0]);
    frame.render_widget(block, cols[0]);

    // Per-kind key hints share the box with the info cluster (k9s-style);
    // narrow terminals collapse back to info-only and keep the full hint
    // line at the bottom instead.
    let hints = header_hints(app);
    if !hints.is_empty() && header_hints_fit(area.width) {
        let sub = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Min(HEADER_INFO_MIN),
                Constraint::Length(HEADER_HINTS_WIDTH),
            ])
            .split(inner);
        frame.render_widget(Paragraph::new(info), sub[0]);
        frame.render_widget(Paragraph::new(hints), sub[1]);
    } else {
        frame.render_widget(Paragraph::new(info), inner);
    }

    // Sophie the Russian Blue: tall pointed ears, a narrow watchful stare
    // (not round cutesy eyes), cool grey-blue coat. Lines are equal width so
    // the right-aligned block stays coherent.
    let logo = vec![
        Line::from(Span::styled(
            "  /\\        /\\ ",
            Style::default().fg(theme::overlay1()),
        )),
        Line::from(Span::styled(
            " /  \\______/  \\",
            Style::default().fg(theme::overlay1()),
        )),
        Line::from(Span::styled(
            "( -        -  )",
            Style::default().fg(theme::green()),
        )),
        Line::from(Span::styled(
            " \\     ᴥ      /",
            Style::default().fg(theme::maroon()),
        )),
        Line::from(Span::styled(
            "  \\    \\__/   /",
            Style::default().fg(theme::overlay1()),
        )),
        Line::from(Span::styled(
            "   '--------'  ",
            Style::default().fg(theme::overlay1()),
        )),
        Line::from(Span::styled(format!("   sofka v{VERSION}"), theme::dim())),
    ];
    frame.render_widget(Paragraph::new(logo).alignment(Alignment::Right), cols[1]);
}

/// The single-line header for compact mode (`ctrl-e`): kind · count ·
/// namespace · context on the left; a transient flash and the live/sync dot on
/// the right. Everything the full header shows that still matters when you've
/// traded it for screen space.
fn draw_compact_header(frame: &mut Frame, app: &App, area: Rect) {
    let ns = if app.all_namespaces() {
        "<all>".to_string()
    } else if app.namespace.is_empty() {
        "<none>".to_string()
    } else {
        app.namespace.clone()
    };
    let mut kind = app.resource_title();
    if let Some(scope) = &app.scope_label {
        kind = format!("{kind}{scope}");
    }

    let mut spans = vec![
        Span::styled(" sofka ", theme::title()),
        Span::styled(kind, Style::default().fg(theme::peach())),
        Span::styled(format!(" [{}]", app.store.len()), theme::dim()),
        Span::styled("  ns:", theme::dim()),
        Span::styled(ns, Style::default().fg(theme::green())),
        Span::styled("  ", theme::dim()),
        Span::styled(
            app.cluster.context.clone(),
            Style::default().fg(theme::mauve()),
        ),
    ];
    if app.readonly {
        spans.push(Span::styled(" [ro]", Style::default().fg(theme::red())));
    }
    // A flash is transient but can carry errors — surface it inline since the
    // status line is hidden in compact mode.
    if !app.flash.is_empty() {
        let style = if app.flash_err {
            Style::default().fg(theme::red())
        } else {
            Style::default().fg(theme::subtext0())
        };
        spans.push(Span::styled("", theme::dim()));
        spans.push(Span::styled(app.flash.clone(), style));
    }

    let (synced, sync_color) = if app.store.synced {
        ("● live", theme::green())
    } else {
        ("○ syncing", theme::yellow())
    };
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Min(10), Constraint::Length(10)])
        .split(area);
    frame.render_widget(Paragraph::new(Line::from(spans)), cols[0]);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            synced,
            Style::default().fg(sync_color),
        )))
        .alignment(Alignment::Right),
        cols[1],
    );
}

/// Whether the frame is wide enough for the header's key-hint column:
/// logo (26) + box borders (2) + info cluster + hints.
fn header_hints_fit(frame_width: u16) -> bool {
    frame_width.saturating_sub(26 + 2) >= HEADER_INFO_MIN + HEADER_HINTS_WIDTH
}

/// One hint row of fixed-width cells (right-aligned key, padded label) so
/// consecutive rows line up into a table. Labels must stay ≤ 10 chars.
fn hint_line(pairs: &[(&str, &str)]) -> Line<'static> {
    let key_style = Style::default()
        .fg(theme::sky())
        .add_modifier(Modifier::BOLD);
    let mut spans = Vec::with_capacity(pairs.len() * 3);
    for (i, (key, label)) in pairs.iter().enumerate() {
        if i > 0 {
            spans.push(Span::raw("  "));
        }
        spans.push(Span::styled(format!("{key:>2}"), key_style));
        spans.push(Span::styled(format!(" {label:<10}"), theme::dim()));
    }
    Line::from(spans)
}

/// Per-kind action hints for the header (k9s-style): only the verbs that
/// actually do something for the current kind — the full reference stays in
/// `?` help, and mode-specific keys stay on the bottom line. Empty when a
/// full-screen view (logs, detail, help, …) replaces the table.
fn header_hints(app: &App) -> Vec<Line<'static>> {
    if matches!(
        app.mode,
        Mode::Detail
            | Mode::Diff
            | Mode::Events
            | Mode::Logs
            | Mode::LogFilter
            | Mode::DocFilter
            | Mode::Help
            | Mode::Pulse
            | Mode::Xray
            | Mode::Explain
            | Mode::Timeline
            | Mode::Gitops
            | Mode::PortForwards
    ) {
        return Vec::new();
    }
    let mut lines = match app.kind_plural.as_str() {
        "pods" => vec![
            hint_line(&[("", "containers"), ("l", "logs"), ("p", "prev logs")]),
            hint_line(&[("s", "shell"), ("t", "transfer"), ("f", "port-fwd")]),
            hint_line(&[("y", "yaml"), ("d", "describe"), ("E", "events")]),
            hint_line(&[("e", "edit"), ("o", "node"), ("J", "owner")]),
            hint_line(&[("X", "explain"), ("T", "timeline"), ("^d", "delete")]),
        ],
        "deployments" | "statefulsets" => vec![
            hint_line(&[("", "pods"), ("l", "logs"), ("E", "events")]),
            hint_line(&[("s", "scale"), ("r", "restart"), ("i", "image")]),
            hint_line(&[("y", "yaml"), ("d", "describe"), ("e", "edit")]),
            hint_line(&[("X", "explain"), ("T", "timeline"), ("f", "port-fwd")]),
        ],
        "daemonsets" => vec![
            hint_line(&[("", "pods"), ("l", "logs"), ("E", "events")]),
            hint_line(&[("r", "restart"), ("i", "image")]),
            hint_line(&[("y", "yaml"), ("d", "describe"), ("e", "edit")]),
            hint_line(&[("X", "explain"), ("^d", "delete")]),
        ],
        "replicasets" | "jobs" => vec![
            hint_line(&[("", "pods"), ("l", "logs"), ("E", "events")]),
            hint_line(&[("y", "yaml"), ("d", "describe"), ("e", "edit")]),
            hint_line(&[("X", "explain"), ("J", "owner"), ("^d", "delete")]),
        ],
        "services" => vec![
            hint_line(&[("", "pods"), ("f", "port-fwd")]),
            hint_line(&[("y", "yaml"), ("d", "describe"), ("e", "edit")]),
            hint_line(&[("^d", "delete")]),
        ],
        "nodes" => vec![
            hint_line(&[("", "pods"), ("y", "yaml"), ("d", "describe")]),
            hint_line(&[("C", "cordon"), ("U", "uncordon"), ("D", "drain")]),
        ],
        "namespaces" => vec![
            hint_line(&[("", "switch to"), ("y", "yaml"), ("d", "describe")]),
            hint_line(&[("e", "edit"), ("^d", "delete")]),
        ],
        "helm" => vec![
            hint_line(&[("", "history")]),
            hint_line(&[("y", "yaml"), ("d", "describe")]),
            hint_line(&[("^d", "uninstall")]),
        ],
        "helmhistory" => vec![
            hint_line(&[("", "values"), ("r", "rollback")]),
            hint_line(&[("^d", "uninstall")]),
        ],
        "customresourcedefinitions" => vec![
            hint_line(&[("", "resources"), ("y", "yaml"), ("d", "describe")]),
            hint_line(&[("e", "edit"), ("^d", "delete")]),
        ],
        "secrets" => vec![
            hint_line(&[("x", "decode"), ("y", "yaml"), ("d", "describe")]),
            hint_line(&[("e", "edit"), ("E", "events"), ("c", "copy name")]),
            hint_line(&[("^d", "delete")]),
        ],
        _ => vec![
            hint_line(&[("", "yaml"), ("d", "describe"), ("E", "events")]),
            hint_line(&[("e", "edit"), ("c", "copy name")]),
            hint_line(&[("^d", "delete")]),
        ],
    };
    if app.flux_suspendable() {
        lines.push(hint_line(&[("t", "flux menu")]));
    }
    if app.cronjob_kind() {
        lines.push(hint_line(&[("t", "trigger/suspend")]));
    }
    if app.external_secret_kind() {
        lines.push(hint_line(&[("r", "force-sync")]));
    }
    // The header box has 5 inner rows.
    lines.truncate(5);
    lines
}

fn draw_table(frame: &mut Frame, app: &mut App, area: Rect) {
    let show_ns = app.show_namespace_column();
    let metrics_cols = app.metrics_columns();
    let headers: Vec<String> = app.display_headers();
    let pods_view = app.kind_plural == "pods";
    let sort_col = app.sort_column;
    let sort_arrow = if app.sort_desc { "" } else { "" };
    // Offset from a displayed column index back to the view spec's (the spec
    // doesn't know about the prepended NAMESPACE or appended CPU/MEM).
    let ns_off = usize::from(show_ns);
    // Per-column custom alignment, precomputed so cells don't re-borrow app.
    let aligns: Vec<Option<Alignment>> = (0..headers.len())
        .map(|i| {
            i.checked_sub(ns_off)
                .and_then(|si| app.view_spec().align_at(si))
                .map(cell_alignment)
        })
        .collect();
    let align_of = |i: usize| aligns.get(i).copied().flatten();

    let header_row = Row::new(
        headers
            .iter()
            .enumerate()
            .map(|(i, h)| {
                // Active sort column gets a direction arrow in the sorter color
                // (sky, bold), matching k9s; the label inherits the header color.
                if Some(i) == sort_col {
                    let mut line = Line::from(vec![
                        Span::raw(h.clone()),
                        Span::styled(
                            sort_arrow,
                            Style::default()
                                .fg(theme::sorter())
                                .add_modifier(Modifier::BOLD),
                        ),
                    ]);
                    if let Some(a) = align_of(i) {
                        line = line.alignment(a);
                    }
                    Cell::from(line)
                } else {
                    match align_of(i) {
                        Some(a) => Cell::from(Text::from(h.clone()).alignment(a)),
                        None => Cell::from(h.clone()),
                    }
                }
            })
            .collect::<Vec<_>>(),
    )
    .style(theme::header_row());

    // Column indices (fixed for the whole table) for the columns that get
    // their own visibility treatment below, computed once rather than
    // string-compared per cell.
    let name_col = if show_ns { 1 } else { 0 };
    let age_idx = headers.iter().position(|h| h == "AGE");
    let ready_idx = headers.iter().position(|h| h == "READY");
    let restarts_idx = headers.iter().position(|h| h == "RESTARTS");
    let cpu_idx = headers.iter().position(|h| h == "CPU");
    let mem_idx = headers.iter().position(|h| h == "MEM");

    let count = app.row_count();
    let visible_rows = area.height.saturating_sub(3).max(1) as usize;
    if count == 0 {
        *app.table_state.offset_mut() = 0;
    } else {
        if app.table_state.selected().is_some_and(|i| i >= count) {
            app.table_state.select(Some(count - 1));
        }
        let selected = app.table_state.selected();
        let mut offset = app.table_state.offset().min(count.saturating_sub(1));
        if let Some(sel) = selected {
            if sel < offset {
                offset = sel;
            } else if sel >= offset + visible_rows {
                offset = sel + 1 - visible_rows;
            }
        }
        *app.table_state.offset_mut() = offset;
    }
    let offset = app.table_state.offset();
    let selected = app.table_state.selected();

    let visible_objects: Vec<_> = app
        .rows()
        .into_iter()
        .skip(offset)
        .take(visible_rows)
        .collect();
    app.ensure_table_cell_cache(&visible_objects);
    let cell_cache = app.table_cell_cache();
    let spec = app.view_spec();
    let thresholds = app.resolved_thresholds();

    let rows: Vec<Row> = visible_objects
        .iter()
        .map(|obj| {
            let row_key = crate::store::row_key(obj);
            let marked_row = !app.marked.is_empty() && app.marked.contains(&row_key);
            let (base_cells, status_idx) = cell_cache
                .get(&row_key)
                .expect("visible rows are warmed in the table cell cache");
            let mut style_idx = status_idx;
            let mut cells = Vec::with_capacity(headers.len());
            if show_ns {
                cells.push(TableCellText::Borrowed(
                    obj.metadata.namespace.as_deref().unwrap_or_default(),
                ));
                style_idx = status_idx.map(|i| i + 1);
            }
            for (i, cell) in base_cells.iter().enumerate() {
                if let Some(value) = spec.volatile(obj, &app.kind_plural, i) {
                    cells.push(TableCellText::Owned(value));
                } else {
                    cells.push(TableCellText::Borrowed(cell));
                }
            }
            let mut metrics_raw = None;
            if metrics_cols {
                let name = obj.metadata.name.as_deref().unwrap_or_default();
                let key = if pods_view {
                    format!(
                        "{}/{}",
                        obj.metadata.namespace.as_deref().unwrap_or_default(),
                        name
                    )
                } else {
                    name.to_string()
                };
                let (cpu, mem) = app.metrics.get(&key).copied().unwrap_or((0, 0));
                metrics_raw = Some((cpu, mem));
                cells.push(TableCellText::Owned(columns::fmt_cpu(cpu)));
                cells.push(TableCellText::Owned(columns::fmt_mem(mem)));
            }
            // Combined colorer: the whole row takes a k9s-style status tint
            // (errors red, pending peach, completed/terminating dimmed, healthy
            // blue), but a handful of columns keep their own visibility
            // treatment on top: STATUS gets a semantic badge, RESTARTS/CPU/MEM
            // flag outliers, AGE is dimmed (rarely the interesting signal),
            // and NAME highlights the active fuzzy filter's matched chars.
            let status_val = style_idx
                .and_then(|i| cells.get(i))
                .map(TableCellText::as_str)
                .unwrap_or("");
            // A pod is phase=Running the moment its sandbox starts, long before
            // every container passes its readiness probe — until READY is n/n,
            // paint it as transitional, not healthy.
            let running_not_ready = status_val == "Running"
                && ready_idx
                    .and_then(|i| cells.get(i))
                    .is_some_and(|r| !all_ready(r.as_str()));
            let status_key = if running_not_ready {
                "PodInitializing"
            } else {
                status_val
            };
            let row_color = theme::row_color(status_key);
            let status_badge = theme::status_color(status_key);
            let render_cells: Vec<Cell> = cells
                .into_iter()
                .enumerate()
                .map(|(i, c)| {
                    let align = align_of(i);
                    if marked_row {
                        // Marked rows override everything so a bulk selection
                        // stands out.
                        c.into_cell_aligned(align).style(
                            Style::default()
                                .fg(theme::mark())
                                .add_modifier(Modifier::BOLD),
                        )
                    } else if Some(i) == style_idx {
                        c.into_cell_aligned(align)
                            .style(Style::default().fg(status_badge))
                    } else if i == name_col {
                        render_name_cell(app, c.as_str(), row_color)
                    } else if Some(i) == age_idx {
                        c.into_cell_aligned(align).style(theme::dim())
                    } else if Some(i) == restarts_idx {
                        let n: i64 = c.as_str().trim().parse().unwrap_or(0);
                        let color = thresholds
                            .restarts
                            .severity(n)
                            .map(theme::severity_fg)
                            .unwrap_or(row_color);
                        c.into_cell_aligned(align).style(Style::default().fg(color))
                    } else if Some(i) == cpu_idx {
                        let color = metrics_raw
                            .and_then(|(cpu, _)| thresholds.cpu.severity(cpu))
                            .map(theme::severity_fg)
                            .unwrap_or(row_color);
                        c.into_cell_aligned(align).style(Style::default().fg(color))
                    } else if Some(i) == mem_idx {
                        let color = metrics_raw
                            .and_then(|(_, mem)| thresholds.memory.severity(mem))
                            .map(theme::severity_fg)
                            .unwrap_or(row_color);
                        c.into_cell_aligned(align).style(Style::default().fg(color))
                    } else {
                        c.into_cell_aligned(align)
                            .style(Style::default().fg(row_color))
                    }
                })
                .collect();
            Row::new(render_cells)
        })
        .collect();

    let widths: Vec<Constraint> = headers
        .iter()
        .enumerate()
        .map(|(i, h)| {
            // A custom column's configured width wins over the curated rules.
            if let Some(w) = i
                .checked_sub(ns_off)
                .and_then(|si| app.view_spec().width_at(si))
            {
                return Constraint::Length(w);
            }
            match h.as_str() {
                // NAME is the column you actually read — give it most of the
                // remaining space so long pod/deployment names don't truncate
                // while NODE (a full GKE node name) crowds it out.
                "NAME" => Constraint::Fill(6),
                "NAMESPACE" => Constraint::Fill(2),
                "NODE" | "CLAIM" | "VOLUME" | "HOSTS" => Constraint::Fill(1),
                "AGE" => Constraint::Length(7),
                "CPU" | "MEM" => Constraint::Length(8),
                // Wide enough for the long pod reasons (ContainerCreating,
                // CrashLoopBackOff, ImagePullBackOff…) so status is never clipped.
                "STATUS" => Constraint::Length(19),
                "READY" | "RESTARTS" => Constraint::Length(10),
                // CRD view: group domains run long (e.g.
                // "kustomize.toolkit.fluxcd.io"), so give GROUP/KIND/VERSIONS a
                // fixed floor wide enough that real-world values don't clip —
                // Fill(1) alongside NAME's Fill(6) would crush them.
                "GROUP" => Constraint::Length(30),
                "KIND" => Constraint::Length(20),
                "VERSIONS" => Constraint::Length(20),
                "SCOPE" => Constraint::Length(12),
                // Flux views: the Ready condition message and git/chart revision
                // are the columns you read — split the leftover space with NAME.
                "MESSAGE" => Constraint::Fill(4),
                "REVISION" => Constraint::Fill(2),
                "SUSPENDED" => Constraint::Length(9),
                _ => Constraint::Fill(1),
            }
        })
        .collect();

    let kind_label = app.list_title();
    // k9s title: resource name (teal, bold) then a yellow [count].
    let mut title = vec![
        Span::styled(format!(" {kind_label} "), theme::title()),
        Span::styled(format!("[{count}]"), Style::default().fg(theme::counter())),
    ];
    if !app.marked.is_empty() {
        title.push(Span::styled(
            format!("{}", app.marked.len()),
            Style::default().fg(theme::mark()),
        ));
    }
    // Keep the active filter visible after leaving the `/` prompt (esc
    // clears it, `/` re-opens it for editing), and say whether the API or
    // this process is doing the filtering. Malformed input turns red.
    if !app.filter.is_empty() {
        let style = if app.filter_error().is_some() {
            Style::default().fg(theme::red())
        } else {
            Style::default().fg(theme::teal())
        };
        title.push(Span::styled(format!(" /{}", app.filter), style));
        title.push(Span::styled(
            if app.filter_server_side() {
                " ·server"
            } else {
                " ·local"
            },
            theme::dim(),
        ));
    }
    title.push(Span::raw(" "));

    let mut render_state = ratatui::widgets::TableState::default();
    let render_selected = if count > 0 {
        selected.map(|i| i.saturating_sub(offset))
    } else {
        None
    };
    render_state.select(render_selected);
    let table = Table::new(rows, widths)
        .header(header_row)
        .row_highlight_style(theme::selected_row())
        .highlight_symbol("")
        // Always reserve the highlight-symbol column so rows never shift right
        // when a selection appears.
        .highlight_spacing(HighlightSpacing::Always)
        // A little breathing room between columns (default is a single space,
        // easy to lose track of where one column ends and the next starts).
        .column_spacing(2)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(theme::border_focused())
                .title(Line::from(title)),
        );

    frame.render_stateful_widget(table, area, &mut render_state);
}

/// `true` when a `n/m` READY cell has every container ready. Cells that
/// aren't in that shape (statuses without a ready fraction) count as ready so
/// they never trigger the not-ready tint.
fn all_ready(ready: &str) -> bool {
    match ready.split_once('/') {
        Some((r, t)) => r == t,
        None => true,
    }
}

/// Render the NAME cell, highlighting characters that matched the active
/// fuzzy row filter (bold yellow) so a scan across many filtered results is
/// faster — every visible row already matched, this just shows *where*.
/// Falls back to a flat `base`-colored cell when there's no active filter.
fn render_name_cell(app: &App, name: &str, base: Color) -> Cell<'static> {
    let Some(matched) = app.filter_match_indices(name).filter(|idx| !idx.is_empty()) else {
        return Cell::from(name.to_string()).style(Style::default().fg(base));
    };
    let matched: std::collections::HashSet<usize> = matched.into_iter().collect();
    let plain = Style::default().fg(base);
    let hl = Style::default()
        .fg(theme::yellow())
        .add_modifier(Modifier::BOLD);

    let mut spans = Vec::new();
    let mut run = String::new();
    let mut run_matched = false;
    for (i, ch) in name.chars().enumerate() {
        let is_match = matched.contains(&i);
        if !run.is_empty() && is_match != run_matched {
            spans.push(Span::styled(
                std::mem::take(&mut run),
                if run_matched { hl } else { plain },
            ));
        }
        run_matched = is_match;
        run.push(ch);
    }
    if !run.is_empty() {
        spans.push(Span::styled(run, if run_matched { hl } else { plain }));
    }
    Cell::from(Line::from(spans))
}

fn draw_scrollable(
    frame: &mut Frame,
    view: &crate::app::Scrollable,
    area: Rect,
    accent: ratatui::style::Color,
) {
    let inner_h = area.height.saturating_sub(2) as usize;
    let scroll = view.scroll.min(view.lines.len().saturating_sub(1));
    let (start, end) = visible_line_window(view.lines.len(), scroll, inner_h);
    let text: Vec<Line> = view
        .lines
        .iter()
        .skip(start)
        .take(end - start)
        .map(|l| highlight_matches(Line::from(highlight_yaml(l)), &view.filter))
        .collect();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(accent))
        .title(Span::styled(doc_title(view), theme::title()));
    let p = Paragraph::new(text).block(block);
    // Wrap folds long lines; otherwise honor the horizontal offset so content
    // past the right edge can be scrolled into view.
    let p = if view.wrap {
        p.wrap(Wrap { trim: false })
    } else {
        p.scroll((0, view.hscroll.min(u16::MAX as usize) as u16))
    };
    frame.render_widget(p, area);
}

/// Logs view with optional substring filter + match highlighting.
///
/// The layout is computed here, not by ratatui: per-line wrapped heights come
/// from [`wrapped_height`] and the visible rows are cut by [`wrap_line`] —
/// the *same* greedy fill — so the scroll math and the pixels can never
/// disagree (ratatui's `Wrap` word-wraps and counts ANSI escape bytes, which
/// made the follow anchor drift). Only the viewport slice is styled and
/// rendered, so a 100k-line paused buffer costs a row-count walk per frame,
/// not a full restyle; and the display-row offset is a `usize`, immune to the
/// `u16` ceiling of `Paragraph::scroll`.
fn draw_logs(frame: &mut Frame, app: &mut App, area: Rect) {
    // Fullscreen drops the borders (side glyphs would end up in every
    // terminal-selection copy); the title still takes the top row.
    let fullscreen = app.logs.fullscreen;
    let (inner_w, inner_h) = if fullscreen {
        (
            area.width.max(1) as usize,
            area.height.saturating_sub(1) as usize,
        )
    } else {
        (
            area.width.saturating_sub(2).max(1) as usize,
            area.height.saturating_sub(2) as usize,
        )
    };

    let shown: Vec<&String> = app
        .logs
        .view
        .lines
        .iter()
        .filter(|l| app.logs.matches(l))
        .collect();

    let filter = app.logs.filter.clone();
    let active = !filter.is_empty();
    let bad_regex = app.logs.matcher.is_error();
    // Highlight matches only for a plain substring filter — not inverse (`!…`,
    // which hides matches) or regex (`/…/`, whose spans we don't track).
    let is_plain = active
        && !filter.starts_with('!')
        && !(filter.len() >= 2 && filter.starts_with('/') && filter.ends_with('/'));
    let highlight = if is_plain { filter.as_str() } else { "" };

    // Exact display height of every shown line, so follow can anchor the
    // newest line to the *bottom* of the viewport (not the top).
    let heights: Vec<usize> = if app.logs.wrap {
        shown.iter().map(|l| wrapped_height(l, inner_w)).collect()
    } else {
        Vec::new() // 1 row per line; skip the allocation walk
    };
    let total_rows: usize = if app.logs.wrap {
        heights.iter().sum()
    } else {
        shown.len()
    };

    // Record viewport geometry (display rows) so key handlers clamp the scroll
    // in the same units, and the message handler can convert trimmed lines
    // into rows when shifting a paused anchor.
    app.logs.viewport_rows = total_rows;
    app.logs.viewport_h = inner_h;
    app.logs.last_wrap_width = if app.logs.wrap { inner_w } else { 0 };

    // Deepest offset pins the last full page to the viewport bottom; that same
    // value is where `follow` anchors, so pausing freezes exactly in place.
    let max_scroll = total_rows.saturating_sub(inner_h);
    let scroll = if app.logs.follow {
        max_scroll
    } else {
        app.logs.view.scroll.min(max_scroll)
    };
    // While following, remember the bottom-anchored position so that turning
    // autoscroll off freezes exactly here instead of jumping to a stale offset.
    if app.logs.follow {
        app.logs.view.scroll = scroll;
    }

    // Style + wrap only the lines that intersect [scroll, scroll + inner_h).
    let mut rows: Vec<Line> = Vec::with_capacity(inner_h);
    let mut row = 0usize; // display row where the current line starts
    for (i, l) in shown.iter().enumerate() {
        let h = if app.logs.wrap { heights[i] } else { 1 };
        if row + h <= scroll {
            row += h;
            continue;
        }
        if row >= scroll + inner_h {
            break;
        }
        let line = render_log_line(l, highlight);
        if app.logs.wrap {
            for (j, sub) in wrap_line(line, inner_w).into_iter().enumerate() {
                let r = row + j;
                if r < scroll {
                    continue;
                }
                if r >= scroll + inner_h {
                    break;
                }
                rows.push(sub);
            }
        } else {
            rows.push(line);
        }
        row += h;
    }

    let flags = format!(
        "{}{}{}{}",
        if app.logs.stopped {
            " ⏹stopped"
        } else if app.logs.follow {
            " ▶follow"
        } else {
            " ⏸paused"
        },
        if app.logs.wrap { " wrap" } else { "" },
        if app.logs.timestamps { " ts" } else { "" },
        // Provider views manage the window in their own title suffix.
        match app.logs.anchor_label() {
            Some(l) if !app.provider_logs_active() => format!("{l}"),
            _ => String::new(),
        },
    );
    let title = if bad_regex {
        format!(
            " {} · /{} [invalid regex]{} ",
            app.logs.view.title, filter, flags
        )
    } else if active {
        format!(
            " {} · /{} [{}]{} ",
            app.logs.view.title,
            filter,
            shown.len(),
            flags
        )
    } else {
        format!(" {}{} ", app.logs.view.title, flags)
    };

    // The rows are already the exact viewport slice — no Paragraph scroll or
    // wrap, so ratatui can't re-lay-out (and disagree with) the math above.
    let block = if fullscreen {
        // Borderless: `Block::inner` still reserves one row for the top title,
        // matching the fullscreen `inner_h` above.
        Block::default().title(Span::styled(title, theme::title()))
    } else {
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme::green()))
            .title(Span::styled(title, theme::title()))
    };
    frame.render_widget(Paragraph::new(rows).block(block), area);
}

/// Display rows `raw` occupies when char-wrapped to `width` columns: ANSI
/// escapes are zero-width (they're stripped at render time) and East-Asian
/// wide glyphs take two columns. Must stay the exact greedy fill
/// [`wrap_line`] performs — the scroll math depends on them agreeing.
pub(crate) fn wrapped_height(raw: &str, width: usize) -> usize {
    let width = width.max(1);
    // Fast path: plain ASCII with no escapes wraps at exactly `width` chars.
    if raw.is_ascii() && !raw.as_bytes().contains(&0x1b) {
        return raw.len().div_ceil(width).max(1);
    }
    let mut rows = 1usize;
    let mut col = 0usize;
    let mut chars = raw.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Mirror ansi_runs: swallow a whole CSI sequence, or a lone ESC.
            if chars.peek() == Some(&'[') {
                chars.next();
                for pc in chars.by_ref() {
                    if !(pc.is_ascii_digit() || pc == ';') {
                        break;
                    }
                }
            }
            continue;
        }
        let w = UnicodeWidthChar::width(c).unwrap_or(0);
        if col + w > width && col > 0 {
            rows += 1;
            col = 0;
        }
        col += w;
    }
    rows
}

/// Greedily split a styled line into rows of at most `width` display columns,
/// breaking spans mid-way as needed. A wide glyph that doesn't fit in the
/// remaining columns moves whole to the next row. Counterpart of
/// [`wrapped_height`] — keep the fill rules identical.
fn wrap_line(line: Line<'static>, width: usize) -> Vec<Line<'static>> {
    let width = width.max(1);
    let mut out: Vec<Line> = Vec::new();
    let mut cur: Vec<Span> = Vec::new();
    let mut col = 0usize;
    for span in line.spans {
        let style = span.style;
        let mut buf = String::new();
        for c in span.content.chars() {
            let w = UnicodeWidthChar::width(c).unwrap_or(0);
            if col + w > width && col > 0 {
                if !buf.is_empty() {
                    cur.push(Span::styled(std::mem::take(&mut buf), style));
                }
                out.push(Line::from(std::mem::take(&mut cur)));
                col = 0;
            }
            buf.push(c);
            col += w;
        }
        if !buf.is_empty() {
            cur.push(Span::styled(buf, style));
        }
    }
    out.push(Line::from(cur)); // final row; an empty line still takes one row
    out
}

/// Render a log line: an optional `[source]` prefix (pod/container/component)
/// in its own stable color, an optional leading RFC3339 timestamp dimmed (k9s
/// style), then the message body in its severity color with search matches
/// highlighted on top.
fn render_log_line(line: &str, needle: &str) -> Line<'static> {
    // Severity is detected on the ANSI-stripped text so a color-wrapped level
    // token (e.g. "\x1b[33mwarn\x1b[0m") is still recognized.
    let base = if line.as_bytes().contains(&0x1b) {
        log_level_color(&strip_ansi(line))
    } else {
        log_level_color(line)
    };
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut rest = line;

    // 1. Source prefix in its per-source color (bold).
    if let Some((end, color)) = source_prefix(rest) {
        let (prefix, r) = rest.split_at(end);
        spans.push(Span::styled(
            prefix.to_string(),
            Style::default().fg(color).add_modifier(Modifier::BOLD),
        ));
        rest = r;
    }

    // 2. Leading timestamp (from `--timestamps`) dimmed, like k9s.
    if let Some(len) = leading_timestamp(rest) {
        let (ts, r) = rest.split_at(len);
        spans.push(Span::styled(ts.to_string(), theme::dim()));
        rest = r;
    }

    // 3. Message body: honor embedded ANSI colors (from the source app),
    //    falling back to the severity color, with search matches on top.
    spans.extend(render_body(rest, needle, base));
    Line::from(spans)
}

/// Length of a leading RFC3339 timestamp (`2026-06-30T12:52:20.876Z`,
/// `…+02:00`) **only** when it's terminated by whitespace or end-of-line — so a
/// timestamp glued to the message (`…216Zinfo`) is left alone. Hand-rolled to
/// avoid pulling in a regex dependency.
fn leading_timestamp(s: &str) -> Option<usize> {
    let b = s.as_bytes();
    let digit = |i: usize| b.get(i).is_some_and(u8::is_ascii_digit);
    let at = |i: usize, c: u8| b.get(i) == Some(&c);
    // YYYY-MM-DD(T| )HH:MM:SS
    let shape = digit(0)
        && digit(1)
        && digit(2)
        && digit(3)
        && at(4, b'-')
        && digit(5)
        && digit(6)
        && at(7, b'-')
        && digit(8)
        && digit(9)
        && (at(10, b'T') || at(10, b' '))
        && digit(11)
        && digit(12)
        && at(13, b':')
        && digit(14)
        && digit(15)
        && at(16, b':')
        && digit(17)
        && digit(18);
    if !shape {
        return None;
    }
    let mut i = 19;
    if at(i, b'.') {
        i += 1;
        while digit(i) {
            i += 1;
        }
    }
    if at(i, b'Z') || at(i, b'z') {
        i += 1;
    } else if (at(i, b'+') || at(i, b'-'))
        && digit(i + 1)
        && digit(i + 2)
        && at(i + 3, b':')
        && digit(i + 4)
        && digit(i + 5)
    {
        i += 6;
    }
    // Require a whitespace/EOL boundary so glued "…Zinfo" isn't treated as a ts.
    match b.get(i) {
        None => Some(i),
        Some(&c) if c == b' ' || c == b'\t' => Some(i),
        _ => None,
    }
}

/// Detect a leading `[label]` source prefix; returns its byte length (including
/// a trailing space, if any) and a stable color for that label.
fn source_prefix(line: &str) -> Option<(usize, Color)> {
    let rest = line.strip_prefix('[')?;
    let close = rest.find(']')?;
    let label = &rest[..close];
    if label.is_empty() {
        return None;
    }
    // `[` + label + `]` = close + 2 bytes; consume a following space too.
    let mut end = close + 2;
    if line[end..].starts_with(' ') {
        end += 1;
    }
    Some((end, source_color(label)))
}

/// Stable color for a source label (FNV-1a hash into a palette). Excludes the
/// severity colors (red/peach) and the search-highlight yellow so a prefix is
/// never mistaken for a level.
fn source_color(label: &str) -> Color {
    let palette: [Color; 10] = [
        theme::mauve(),
        theme::blue(),
        theme::green(),
        theme::teal(),
        theme::pink(),
        theme::sapphire(),
        theme::lavender(),
        theme::flamingo(),
        theme::sky(),
        theme::rosewater(),
    ];
    let mut h: u32 = 0x811c_9dc5;
    for b in label.bytes() {
        h = (h ^ b as u32).wrapping_mul(0x0100_0193);
    }
    palette[(h as usize) % palette.len()]
}

/// Render a log-line body: split it into runs by any embedded ANSI SGR codes
/// (escape bytes stripped), style each run by its ANSI color — or `base` when
/// it carries none — and overlay search-match highlights.
fn render_body(body: &str, needle: &str, base: Color) -> Vec<Span<'static>> {
    let mut spans = Vec::new();
    for run in ansi_runs(body) {
        let mut style = Style::default().fg(run.color.unwrap_or(base));
        if run.bold {
            style = style.add_modifier(Modifier::BOLD);
        }
        push_highlighted(&mut spans, &run.text, needle, style);
    }
    spans
}

/// Append `text` to `spans` styled with `base`, highlighting case-insensitive
/// occurrences of `needle` on top.
fn push_highlighted(spans: &mut Vec<Span<'static>>, text: &str, needle: &str, base: Style) {
    if needle.is_empty() {
        if !text.is_empty() {
            spans.push(Span::styled(text.to_string(), base));
        }
        return;
    }
    // Lowercasing is not always length-preserving (e.g. Turkish İ, German ß),
    // so match on the same string we slice to keep byte offsets valid and avoid
    // panicking on a non-char-boundary index for multi-byte log lines.
    let hay = text.to_lowercase();
    let pat = needle.to_lowercase();
    if text.len() != hay.len() {
        // Offsets from `hay` wouldn't be valid in `text`; skip highlighting
        // rather than risk slicing mid-character.
        spans.push(Span::styled(text.to_string(), base));
        return;
    }
    let hl = Style::default()
        .bg(theme::yellow())
        .fg(theme::crust())
        .add_modifier(Modifier::BOLD);
    let mut idx = 0;
    while let Some(pos) = hay[idx..].find(&pat) {
        let start = idx + pos;
        let end = start + pat.len();
        if start > idx {
            spans.push(Span::styled(text[idx..start].to_string(), base));
        }
        spans.push(Span::styled(text[start..end].to_string(), hl));
        idx = end;
    }
    if idx < text.len() {
        spans.push(Span::styled(text[idx..].to_string(), base));
    }
}

/// A run of text sharing one style, extracted from an ANSI-coded string.
struct AnsiRun {
    text: String,
    color: Option<Color>,
    bold: bool,
}

/// Concatenated visible text of `s` with all ANSI escapes removed.
fn strip_ansi(s: &str) -> String {
    ansi_runs(s).into_iter().map(|r| r.text).collect()
}

/// Split a string into styled runs by parsing ANSI SGR (`\x1b[…m`) sequences,
/// dropping the escape bytes. Non-SGR CSI sequences (cursor moves, etc.) are
/// swallowed too. Standard 8/16 foreground colors map onto the active skin so
/// embedded colors stay theme-consistent; 256-color (`38;5;n`) and truecolor
/// (`38;2;r;g;b`) pass through verbatim. A string with no escapes yields a
/// single run.
fn ansi_runs(s: &str) -> Vec<AnsiRun> {
    let mut runs = Vec::new();
    let mut cur = String::new();
    let mut color: Option<Color> = None;
    let mut bold = false;
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' && chars.peek() == Some(&'[') {
            chars.next(); // consume '['
            let mut params = String::new();
            let mut final_byte = None;
            for pc in chars.by_ref() {
                if pc.is_ascii_digit() || pc == ';' {
                    params.push(pc);
                } else {
                    final_byte = Some(pc);
                    break;
                }
            }
            if final_byte == Some('m') {
                if !cur.is_empty() {
                    runs.push(AnsiRun {
                        text: std::mem::take(&mut cur),
                        color,
                        bold,
                    });
                }
                apply_sgr(&params, &mut color, &mut bold);
            }
            continue; // non-'m' CSI (or a truncated one) is dropped
        }
        if c == '\x1b' {
            continue; // lone / non-CSI escape — drop the ESC byte
        }
        cur.push(c);
    }
    if !cur.is_empty() || runs.is_empty() {
        runs.push(AnsiRun {
            text: cur,
            color,
            bold,
        });
    }
    runs
}

/// Apply one SGR parameter list (the digits/semicolons between `\x1b[` and `m`)
/// to the running foreground color and bold flag.
fn apply_sgr(params: &str, color: &mut Option<Color>, bold: &mut bool) {
    if params.is_empty() {
        *color = None; // bare `\x1b[m` == reset
        *bold = false;
        return;
    }
    let mut it = params.split(';');
    while let Some(tok) = it.next() {
        match tok {
            "" | "0" => {
                *color = None;
                *bold = false;
            }
            "1" => *bold = true,
            "22" => *bold = false,
            "39" => *color = None,
            "38" => match it.next() {
                Some("5") => {
                    if let Some(n) = it.next().and_then(|v| v.parse::<u8>().ok()) {
                        *color = Some(Color::Indexed(n));
                    }
                }
                Some("2") => {
                    let r = it.next().and_then(|v| v.parse::<u8>().ok());
                    let g = it.next().and_then(|v| v.parse::<u8>().ok());
                    let b = it.next().and_then(|v| v.parse::<u8>().ok());
                    if let (Some(r), Some(g), Some(b)) = (r, g, b) {
                        *color = Some(Color::Rgb(r, g, b));
                    }
                }
                _ => {}
            },
            other => {
                if let Some(c) = other.parse::<u8>().ok().and_then(ansi_16_color) {
                    *color = Some(c);
                }
                // background (40-49, 100-107) and other attrs are ignored
            }
        }
    }
}

/// Map a standard 8/16-color SGR foreground code onto the active skin, so
/// embedded ANSI colors read consistently with the chosen theme.
fn ansi_16_color(code: u8) -> Option<Color> {
    Some(match code {
        30 => theme::overlay0(),
        31 => theme::red(),
        32 => theme::green(),
        33 => theme::yellow(),
        34 => theme::blue(),
        35 => theme::mauve(),
        36 => theme::teal(),
        37 => theme::subtext1(),
        90 => theme::overlay1(),
        91 => theme::maroon(),
        92 => theme::green(),
        93 => theme::peach(),
        94 => theme::sapphire(),
        95 => theme::pink(),
        96 => theme::sky(),
        97 => theme::text(),
        _ => return None,
    })
}

/// Guess a log line's severity color across common formats: structured JSON
/// (`"level":"warn"`), space/tab-delimited (` warn `), glued-after-timestamp
/// (`…Zwarn`), `level=error`, and the klog prefix (`E0627 …`). Errors red,
/// warnings peach, debug/trace dimmed; info and anything unrecognized stay in
/// the default text color so they read calmly and real problems pop.
fn log_level_color(line: &str) -> Color {
    let l = line.to_ascii_lowercase();
    // Structured logs: read the level field directly (authoritative — a later
    // "…error…" in the message can't override it).
    if let Some(level) = json_field(&l, "level").or_else(|| json_field(&l, "severity")) {
        return level_color(level);
    }
    // klog prefixes (`E0627 …`) put the level at the very start.
    if klog_level(&l, 'e') || klog_level(&l, 'f') {
        return theme::red();
    }
    if klog_level(&l, 'w') {
        return theme::peach();
    }
    // Otherwise the leftmost level marker wins, since the level precedes the
    // message — so a later "…the last error:" can't override a `warn` level.
    let first = |needles: &[&str]| needles.iter().filter_map(|n| l.find(n)).min();
    let candidates = [
        (
            first(&[
                " error",
                "\terror",
                "zerror",
                "level=error",
                " fatal",
                "zfatal",
                " panic",
            ]),
            theme::red(),
        ),
        (
            first(&[" warn", "\twarn", "zwarn", "level=warn"]),
            theme::peach(),
        ),
        (
            first(&[
                " debug",
                "\tdebug",
                "zdebug",
                " trace",
                "ztrace",
                "level=debug",
            ]),
            theme::overlay1(),
        ),
    ];
    candidates
        .into_iter()
        .filter_map(|(pos, color)| pos.map(|p| (p, color)))
        .min_by_key(|(p, _)| *p)
        .map(|(_, color)| color)
        .unwrap_or(theme::text())
}

/// Color for a parsed level token (already lowercased).
fn level_color(level: &str) -> Color {
    if level.starts_with("err")
        || level.starts_with("fatal")
        || level.starts_with("crit")
        || level.starts_with("panic")
    {
        theme::red()
    } else if level.starts_with("warn") {
        theme::peach()
    } else if level.starts_with("debug") || level.starts_with("trace") {
        theme::overlay1()
    } else {
        theme::text() // info, notice, unknown — keep readable
    }
}

/// Read a JSON string field's value, e.g. `json_field(r#"…"level":"warn"…"#,
/// "level") == Some("warn")`. Tolerant of whitespace around the colon. Input is
/// expected already lowercased.
fn json_field<'a>(l: &'a str, key: &str) -> Option<&'a str> {
    let pat = format!("\"{key}\"");
    let i = l.find(&pat)?;
    let rest = l[i + pat.len()..].trim_start();
    let rest = rest.strip_prefix(':')?.trim_start();
    let rest = rest.strip_prefix('"')?;
    let end = rest.find('"')?;
    Some(&rest[..end])
}

/// True if `l` starts with a klog level marker, e.g. `e0627 …` (lowercased).
fn klog_level(l: &str, level: char) -> bool {
    let mut it = l.chars();
    it.next() == Some(level) && it.next().is_some_and(|c| c.is_ascii_digit())
}

/// Unified-diff view with +/- line coloring.
fn draw_diff(frame: &mut Frame, view: &crate::app::Scrollable, area: Rect) {
    let inner_h = area.height.saturating_sub(2) as usize;
    let scroll = view.scroll.min(view.lines.len().saturating_sub(1));
    let (start, end) = visible_line_window(view.lines.len(), scroll, inner_h);
    let lines: Vec<Line> = view
        .lines
        .iter()
        .skip(start)
        .take(end - start)
        .map(|l| {
            let color = match l.chars().next() {
                Some('+') => theme::green(),
                Some('-') => theme::red(),
                _ => theme::overlay1(),
            };
            let line = Line::from(Span::styled(l.clone(), Style::default().fg(color)));
            highlight_matches(line, &view.filter)
        })
        .collect();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme::peach()))
        .title(Span::styled(doc_title(view), theme::title()));
    let p = Paragraph::new(lines).block(block);
    let p = if view.wrap {
        p.wrap(Wrap { trim: false })
    } else {
        p.scroll((0, view.hscroll.min(u16::MAX as usize) as u16))
    };
    frame.render_widget(p, area);
}

fn visible_line_window(len: usize, scroll: usize, height: usize) -> (usize, usize) {
    let start = scroll.min(len);
    let end = start.saturating_add(height).min(len);
    (start, end)
}

/// Doc-view title, extended with the active search query and the current
/// match position (` title · /query [2/5] `, or `[no matches]`), vim-style.
fn doc_title(view: &crate::app::Scrollable) -> String {
    if view.filter.is_empty() {
        return format!(" {} ", view.title);
    }
    let matches = view.match_lines();
    if matches.is_empty() {
        format!(" {} · /{} [no matches] ", view.title, view.filter)
    } else {
        let cur = view.match_idx.min(matches.len() - 1) + 1;
        format!(
            " {} · /{} [{}/{}] ",
            view.title,
            view.filter,
            cur,
            matches.len()
        )
    }
}

/// Overlay search-match highlights on an already-styled line, preserving each
/// span's own style for the unmatched stretches. A needle spanning two spans
/// (e.g. across a YAML key/value boundary) is not highlighted — the line is
/// still *shown* (filtering matches on the raw text), just not marked.
fn highlight_matches(line: Line<'static>, needle: &str) -> Line<'static> {
    if needle.is_empty() {
        return line;
    }
    let mut spans = Vec::with_capacity(line.spans.len());
    for span in line.spans {
        push_highlighted(&mut spans, &span.content, needle, span.style);
    }
    Line::from(spans)
}

/// Concatenated plain text of a styled line, for filtering render-time-built
/// views (help) where no raw string backs the line.
fn line_text(line: &Line) -> String {
    line.spans.iter().map(|s| s.content.as_ref()).collect()
}

/// YAML / `kubectl describe` colorization: comments dimmed, section headers in
/// mauve, keys in sky, and values tinted by kind (numbers, booleans, statuses).
fn highlight_yaml(line: &str) -> Vec<Span<'static>> {
    let trimmed = line.trim_start();

    // Comments.
    if trimmed.starts_with('#') {
        return vec![Span::styled(line.to_string(), theme::dim())];
    }

    // `key: value` — color the key, keep alignment, tint the value.
    if let Some(idx) = line.find(": ") {
        let (key, rest) = line.split_at(idx);
        if is_keyish(key) {
            let after = &rest[2..]; // value text after the first ": "
            let ws = after.len() - after.trim_start().len();
            let value = &after[ws..];
            let mut spans = vec![
                Span::styled(key.to_string(), Style::default().fg(theme::sky())),
                Span::styled(": ".to_string(), theme::dim()),
            ];
            if ws > 0 {
                spans.push(Span::raw(after[..ws].to_string())); // alignment padding
            }
            if !value.is_empty() {
                spans.push(Span::styled(value.to_string(), value_style(value)));
            }
            return spans;
        }
    }

    // Section header, e.g. `Containers:` / `Events:` (a bare key + colon).
    if let Some(head) = trimmed.strip_suffix(':')
        && is_keyish(head)
    {
        return vec![Span::styled(
            line.to_string(),
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        )];
    }

    vec![Span::styled(
        line.to_string(),
        Style::default().fg(theme::text()),
    )]
}

/// A bare identifier (allowing spaces, as in `Start Time`) — used to tell a
/// real key/header from arbitrary text or URLs.
fn is_keyish(s: &str) -> bool {
    let t = s.trim();
    !t.is_empty()
        && t.chars()
            .all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | ' '))
}

/// Tint a value: numbers peach, booleans/null mauve, status words by their
/// status color, everything else default text.
fn value_style(value: &str) -> Style {
    let t = value.trim_end();
    if matches!(
        t,
        "true" | "false" | "null" | "<none>" | "<unset>" | "<unknown>"
    ) {
        return Style::default().fg(theme::mauve());
    }
    if t.parse::<f64>().is_ok() {
        return Style::default().fg(theme::peach());
    }
    let sc = theme::status_color(t);
    if sc != theme::text() {
        return Style::default().fg(sc);
    }
    Style::default().fg(theme::text())
}

fn draw_help(frame: &mut Frame, app: &App, area: Rect) {
    let bind = |k: &str, d: &str| {
        Line::from(vec![
            Span::styled(format!("  {k:<14}"), Style::default().fg(theme::yellow())),
            Span::styled(d.to_string(), theme::dim()),
        ])
    };
    let mut lines = vec![
        Line::from(Span::styled("  Navigation", theme::title())),
        bind(
            ":<resource>",
            "command palette — fuzzy over kinds + commands (tab/↑↓)",
        ),
        bind(
            ":<res> <ns>",
            "switch kind and namespace at once (all/* = all namespaces)",
        ),
        bind("[ · ]", "view history — back · forward"),
        bind(":ctx · :pulse", "switch context · cluster-health dashboard"),
        bind(
            ":fleet",
            "cross-context health dashboard (opt-in [fleet] contexts; ⏎ switches)",
        ),
        bind(
            ":xray · :diff",
            "hierarchical tree · live-vs-last-applied diff",
        ),
        bind(":events · E", "events for the selected object"),
        bind(":pf", "view/stop background port-forwards"),
        bind(":skin", "switch color skin live"),
        bind(
            ":reload · :config · :info",
            "reload config · config sources + warnings · runtime diagnostics",
        ),
        bind(
            ":can-i",
            "what you can do here · :can-i <verb> <resource> [ns] checks one action",
        ),
        bind(
            "enter",
            "drill down (deploy→pods, pod→containers, ns→re-scope)",
        ),
        bind("shift-j", "jump to owner (controller)"),
        bind("o", "show node hosting the pod"),
        bind("esc", "go back / pop view / clear filter"),
        bind("j/k g/G", "move · top/bottom"),
        bind("S · I", "sort by column (cycle) · invert direction"),
        bind("w", "toggle wide columns (kubectl -o wide)"),
        bind(
            "ctrl-e",
            "compact mode: collapse header + footer (for tiled panes)",
        ),
        bind(
            "/",
            "filter: fuzzy · !inverse · -l/-f selectors (server-side on ⏎) · col=val cpu>500m age<2h",
        ),
        bind(
            "ctrl-u · ctrl-w",
            "text inputs: clear line (cmd-⌫) · delete word (opt-⌫)",
        ),
        bind("n · 0-9", "namespace switcher · 0 = all namespaces"),
        bind("ctrl-r", "refresh watch"),
        Line::from(""),
        Line::from(Span::styled("  Inspect", theme::title())),
        bind("y · d", "view YAML · describe (kubectl)"),
        bind("l · p", "logs (workload = all pods) · previous logs"),
        bind(
            "shift-l · :vlogs",
            "VictoriaLogs history (autodiscovered or [providers.logs]) — pods/workloads/ns",
        ),
        bind("c", "copy resource name · in doc views: copy the document"),
        bind(
            "/ · n/N",
            "search within YAML/describe/diff/events (highlight in place, n/N to jump); filters help",
        ),
        bind("x", "secrets: show data base64-decoded"),
        bind(
            "shift-x · :explain",
            "explain why the selection is unhealthy (evidence-backed)",
        ),
        bind(
            "shift-t · :timeline",
            "session-local state-change history for the selection",
        ),
        bind(
            ":rightsize",
            "historical right-sizing: P50/P95/P99 usage → suggested requests + patch (needs [providers.metrics])",
        ),
        bind(
            ":gitops · :flux",
            "Flux owner, source, revisions & reconciliation chain (⏎ to jump)",
        ),
        bind(
            ":journal · :audit",
            "session-local log of the mutating actions you've taken",
        ),
        Line::from(""),
        Line::from(Span::styled("  Act", theme::title())),
        bind("e", "edit in $EDITOR (kubectl edit)"),
        bind("s", "shell into pod / scale workload"),
        bind("a", "attach to pod"),
        bind(
            ":debug",
            "pod: ephemeral debug container (d in picker targets one) · node: privileged debug pod",
        ),
        bind(
            ":debug-clean",
            "delete the node debugger pods launched this session",
        ),
        bind(
            ":bundle · :bundle-save",
            "assemble a redacted diagnostic bundle for the selection · write it to a file",
        ),
        bind(
            ":snapshot [fmt] · :snapshots",
            "capture the current view (text/json/yaml) · browse saved snapshots",
        ),
        bind("i", "set container image"),
        bind(
            "r",
            "rollout restart (deploy/sts/ds) · force-sync (external secrets)",
        ),
        bind(
            "f / shift-f",
            "port-forward (pod/svc) — runs in the background",
        ),
        bind(
            "t",
            "pods: file transfer (kubectl cp, in picker targets a container) · flux: suspend/resume/reconcile · cronjobs: trigger/suspend/resume",
        ),
        bind("C · U · D", "nodes: cordon · uncordon · drain"),
        bind("space", "mark/unmark row for bulk actions (esc clears)"),
        bind(
            "ctrl-d · ctrl-k",
            "delete · force-delete (in confirm: f force, c cascade)",
        ),
        Line::from(""),
        Line::from(Span::styled("  Logs view", theme::title())),
        bind(
            "/ · s · w · t",
            "filter (text · /regex/ · !invert) · autoscroll · wrap · timestamps",
        ),
        bind(
            "x · z · c · ctrl-s",
            "stop/resume · clear buffer · copy · save to file",
        ),
        bind("shift-f", "fullscreen (no borders — easy terminal copying)"),
        bind(
            "0 – 5",
            "time anchor: tail · 1m · 5m · 15m · 30m · 1h (re-streams)",
        ),
        bind(
            "shift-t",
            "provider logs: change lookback period (30m, 4h, 2d)",
        ),
        Line::from(""),
        bind(":q / ctrl-c", "quit"),
        bind("?", "toggle help"),
    ];
    // Config-defined plugins, with their (possibly modified) key chords.
    if !app.plugins.is_empty() {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled("  Plugins", theme::title())));
        for p in &app.plugins {
            let key = crate::keys::KeyChord::parse(&p.key)
                .map(|c| c.label())
                .unwrap_or_else(|_| format!("{}?", p.key));
            let scope = if p.scopes.is_empty() {
                "all resources".to_string()
            } else {
                p.scopes.join(", ")
            };
            lines.push(bind(&key, &format!("{} ({scope})", p.name)));
        }
    }
    // Saved bookmarks: their chord (if any) and where they jump.
    if !app.bookmarks.is_empty() {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled("  Bookmarks", theme::title())));
        for b in &app.bookmarks {
            let key = b
                .key
                .as_deref()
                .map(|k| {
                    crate::keys::KeyChord::parse(k)
                        .map(|c| c.label())
                        .unwrap_or_else(|_| format!("{k}?"))
                })
                .unwrap_or_else(|| ":".to_string());
            lines.push(bind(&key, &format!("{}", b.name)));
        }
    }
    // Saved workspaces: their chord (if any), view count, and Tab hint.
    if !app.workspaces.is_empty() {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled("  Workspaces", theme::title())));
        for w in &app.workspaces {
            let key = w
                .key
                .as_deref()
                .map(|k| {
                    crate::keys::KeyChord::parse(k)
                        .map(|c| c.label())
                        .unwrap_or_else(|_| format!("{k}?"))
                })
                .unwrap_or_else(|| ":".to_string());
            lines.push(bind(
                &key,
                &format!("{} ({} views · Tab to cycle)", w.name, w.views.len()),
            ));
        }
    }
    // `/` search: keep only matching binding lines (section headers and
    // spacers match like any other text), highlighting the matched runs.
    let needle = app.help_filter.to_lowercase();
    let (lines, title) = if needle.is_empty() {
        (lines, " Help ".to_string())
    } else {
        let shown: Vec<Line> = lines
            .into_iter()
            .filter(|l| line_text(l).to_lowercase().contains(&needle))
            .map(|l| highlight_matches(l, &app.help_filter))
            .collect();
        let title = format!(" Help · /{} [{}] ", app.help_filter, shown.len());
        (shown, title)
    };
    frame.render_widget(
        Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(theme::border_focused())
                .title(Span::styled(title, theme::title())),
        ),
        area,
    );
}

fn draw_namespaces(frame: &mut Frame, app: &mut App, area: Rect) {
    let names = app.filtered_namespaces();
    let browsing = app.ns_filter.is_empty();
    let items: Vec<ListItem> = names
        .iter()
        .map(|n| {
            if n == "<all>" {
                return ListItem::new(Span::styled(n.clone(), Style::default().fg(theme::teal())));
            }
            // Only tag favourites/recents while browsing (the pinned ordering);
            // a filtered list is ranked by match, so a tag there would mislead.
            let (tag, color) = if !browsing {
                ("", theme::text())
            } else if app.is_favorite_namespace(n) {
                ("", theme::yellow())
            } else if app.is_recent_namespace(n) {
                ("· ", theme::sky())
            } else {
                ("", theme::text())
            };
            ListItem::new(Line::from(vec![
                Span::styled(tag.to_string(), theme::dim()),
                Span::styled(n.clone(), Style::default().fg(color)),
            ]))
        })
        .collect();
    // Show the type-to-filter buffer in the title so it reads like an input.
    let title = if app.ns_filter.is_empty() {
        " Namespaces (★ fav · recent · ⏎ switch) ".to_string()
    } else {
        format!(" Namespaces · /{}_ ", app.ns_filter)
    };
    render_popup_list(
        frame,
        area,
        40,
        60,
        items,
        Span::styled(title, theme::title()),
        &mut app.ns_state,
    );
}

fn draw_contexts(frame: &mut Frame, app: &mut App, area: Rect) {
    let current = app.cluster.context.clone();
    let items: Vec<ListItem> = app
        .filtered_contexts()
        .iter()
        .map(|c| {
            let marker = if *c == current { "" } else { "  " };
            ListItem::new(Span::styled(
                format!("{marker}{c}"),
                Style::default().fg(if *c == current {
                    theme::green()
                } else {
                    theme::text()
                }),
            ))
        })
        .collect();
    // Show the type-to-filter buffer in the title so it reads like an input.
    let title = if app.ctx_filter.is_empty() {
        " Contexts (type to filter · ⏎ switch) ".to_string()
    } else {
        format!(" Contexts · /{}_ ", app.ctx_filter)
    };
    render_popup_list(
        frame,
        area,
        50,
        60,
        items,
        Span::styled(title, theme::title()),
        &mut app.ctx_state,
    );
}

/// Flux suspend/resume / CronJob trigger action menu (`t`). Deliberately a
/// menu rather than a single-key toggle, so acting on a live resource always
/// takes an explicit, visible choice.
fn draw_flux_menu(frame: &mut Frame, app: &mut App, area: Rect) {
    let count = app.marked.len().max(1);
    let target = if count == 1 {
        "current selection".to_string()
    } else {
        format!("{count} marked {}", app.kind_plural)
    };
    let items: Vec<ListItem> = app
        .action_menu_items()
        .iter()
        .map(|label| {
            let color = match *label {
                "Suspend" => theme::peach(),
                "Resume" | "Trigger now" => theme::green(),
                _ => theme::overlay1(),
            };
            ListItem::new(Span::styled(*label, Style::default().fg(color)))
        })
        .collect();
    let subject = if app.cronjob_kind() {
        "CronJob"
    } else {
        "Flux"
    };
    render_popup_list(
        frame,
        area,
        36,
        24,
        items,
        Span::styled(format!(" {subject}: {target} "), theme::title()),
        &mut app.flux_menu_state,
    );
}

/// Pod file-transfer menu (`t` on a pod): download from or upload to the pod
/// via `kubectl cp`, then two prompts for the source and destination paths.
fn draw_transfer_menu(frame: &mut Frame, app: &mut App, area: Rect) {
    let target = match &app.transfer_target {
        Some((_, pod, Some(c))) => format!("{pod}:{c}"),
        Some((_, pod, None)) => pod.clone(),
        None => String::new(),
    };
    let items: Vec<ListItem> = TRANSFER_MENU_ITEMS
        .iter()
        .map(|label| {
            let color = match *label {
                "Download from pod" => theme::green(),
                "Upload to pod" => theme::peach(),
                _ => theme::overlay1(),
            };
            ListItem::new(Span::styled(*label, Style::default().fg(color)))
        })
        .collect();
    render_popup_list(
        frame,
        area,
        36,
        24,
        items,
        Span::styled(format!(" Transfer: {target} "), theme::title()),
        &mut app.transfer_menu_state,
    );
}

/// Background port-forwards (`:pf`). A full-width view, not a popup — closing
/// it (`esc`) does not stop the forwards; only `x`/`s` on a row does.
fn draw_port_forwards(frame: &mut Frame, app: &mut App, area: Rect) {
    let items: Vec<ListItem> = app
        .port_forwards
        .iter()
        .map(|pf| {
            ListItem::new(Line::from(vec![
                Span::styled("", Style::default().fg(theme::green())),
                Span::styled(pf.label(), Style::default().fg(theme::text())),
            ]))
        })
        .collect();
    let title = format!(
        " Port-forwards [{}]  (x/s stop · esc close — others keep running) ",
        app.port_forwards.len()
    );
    render_framed_list(
        frame,
        area,
        items,
        Span::styled(title, theme::title()),
        &mut app.pf_state,
    );
}

fn draw_skins(frame: &mut Frame, app: &mut App, area: Rect) {
    let items: Vec<ListItem> = app
        .skin_list
        .iter()
        .map(|name| {
            ListItem::new(Span::styled(
                name.clone(),
                Style::default().fg(theme::text()),
            ))
        })
        .collect();
    render_popup_list(
        frame,
        area,
        42,
        58,
        items,
        Span::styled(" Skins (enter apply · esc close) ", theme::title()),
        &mut app.skin_state,
    );
}

fn draw_snapshots(frame: &mut Frame, app: &mut App, area: Rect) {
    let items: Vec<ListItem> = app
        .snapshot_list
        .iter()
        .map(|(_, label)| {
            ListItem::new(Span::styled(
                label.clone(),
                Style::default().fg(theme::text()),
            ))
        })
        .collect();
    render_popup_list(
        frame,
        area,
        70,
        70,
        items,
        Span::styled(
            " Snapshots (⏎ open · d delete · esc close) ",
            theme::title(),
        ),
        &mut app.snapshot_state,
    );
}

/// Color a resource utilization percentage against the configured band: close
/// to the base (a request or, more importantly, a limit) is dangerous. A
/// missing base dims to a muted tone so it reads as "not set" rather than
/// "healthy"; a present percentage below the warning line reads green.
fn util_color(pct: Option<i64>, band: crate::thresholds::Band) -> Color {
    use crate::thresholds::Severity;
    match pct {
        None => theme::overlay1(),
        Some(p) => match band.severity(p) {
            Some(Severity::Critical) => theme::red(),
            Some(Severity::Warn) => theme::yellow(),
            None => theme::green(),
        },
    }
}

/// Build the `%req/%lim` utilization cell for one resource, plus the color that
/// reflects the worse (limit-first) utilization. `usage` is `None` when Metrics
/// Server data is unavailable, in which case percentages cannot be computed.
fn util_cell(
    usage: Option<i64>,
    request: Option<i64>,
    limit: Option<i64>,
    band: crate::thresholds::Band,
) -> (String, Color) {
    use crate::columns::{fmt_pct, usage_pct};
    let Some(usage) = usage else {
        return ("-/-".into(), theme::overlay1());
    };
    let req_pct = usage_pct(usage, request);
    let lim_pct = usage_pct(usage, limit);
    let text = format!("{}/{}", fmt_pct(req_pct), fmt_pct(lim_pct));
    (text, util_color(lim_pct.or(req_pct), band))
}

// Numeric column widths for the container table, shared by the header and the
// data rows so they line up exactly. `CPU%`/`MEM%` hold a `%req/%lim` pair.
const C_CPU: usize = 7;
const C_CPU_PCT: usize = 9;
const C_MEM: usize = 8;
const C_MEM_PCT: usize = 9;
const C_GAP: usize = 2;

/// Truncate to `max` display columns with a trailing ellipsis (character-based;
/// container names are ASCII in practice).
fn truncate_cols(s: &str, max: usize) -> String {
    let n = s.chars().count();
    if n <= max {
        return s.to_string();
    }
    match max {
        0 => String::new(),
        _ => {
            let mut t: String = s.chars().take(max - 1).collect();
            t.push('');
            t
        }
    }
}

fn draw_containers(frame: &mut Frame, app: &mut App, area: Rect) {
    let gap = " ".repeat(C_GAP);
    // Keep the name column readable but bounded so long names can't push the
    // numeric columns off the right edge; anything longer is ellipsized.
    let name_cap = (area.width as usize).saturating_sub(40).max(8);
    let util_band = app.resolved_thresholds().utilization;
    let name_width = app
        .container_list
        .iter()
        .map(|name| name.chars().count())
        .max()
        .unwrap_or(4)
        .clamp(4, name_cap);

    let header = Line::from(format!(
        "{name:<name_width$}{gap}{cpu:>C_CPU$}{gap}{cpu_pct:>C_CPU_PCT$}{gap}{mem:>C_MEM$}{gap}{mem_pct:>C_MEM_PCT$}",
        name = "NAME",
        cpu = "CPU",
        cpu_pct = "%R/L",
        mem = "MEM",
        mem_pct = "%R/L",
    ))
    .style(theme::dim());

    let items: Vec<ListItem> = app
        .container_list
        .iter()
        .map(|container| {
            let usage = app.selected_pod_container_metrics(container);
            let (cpu, memory) = usage
                .map(|(cpu, memory)| {
                    (
                        crate::columns::fmt_cpu(cpu),
                        crate::columns::fmt_mem(memory),
                    )
                })
                .unwrap_or_else(|| ("-".into(), "-".into()));
            let res = app
                .container_resources
                .get(container)
                .cloned()
                .unwrap_or_default();
            let (cpu_pct, cpu_pct_color) = util_cell(
                usage.map(|(c, _)| c),
                res.cpu_request,
                res.cpu_limit,
                util_band,
            );
            let (mem_pct, mem_pct_color) = util_cell(
                usage.map(|(_, m)| m),
                res.mem_request,
                res.mem_limit,
                util_band,
            );
            let name = truncate_cols(container, name_width);
            ListItem::new(Line::from(vec![
                Span::styled(
                    format!("{name:<name_width$}"),
                    Style::default().fg(theme::text()),
                ),
                Span::styled(
                    format!("{gap}{cpu:>C_CPU$}"),
                    Style::default().fg(theme::yellow()),
                ),
                Span::styled(
                    format!("{gap}{cpu_pct:>C_CPU_PCT$}"),
                    Style::default().fg(cpu_pct_color),
                ),
                Span::styled(
                    format!("{gap}{memory:>C_MEM$}"),
                    Style::default().fg(theme::teal()),
                ),
                Span::styled(
                    format!("{gap}{mem_pct:>C_MEM_PCT$}"),
                    Style::default().fg(mem_pct_color),
                ),
            ]))
        })
        .collect();

    let qos = if app.container_qos.is_empty() {
        String::new()
    } else {
        format!(" · {}", app.container_qos)
    };
    let title = format!(" Containers{qos} ");
    let footer = " ⏎ logs · p previous · s shell · t transfer · d debug · L provider ";

    // Size the box to its contents: header + rows + borders, and wide enough
    // for the columns, the title, or the footer — whichever needs the most.
    let content_w = 2 // list highlight symbol ("▌ ")
        + name_width
        + C_GAP + C_CPU
        + C_GAP + C_CPU_PCT
        + C_GAP + C_MEM
        + C_GAP + C_MEM_PCT;
    let inner_w = content_w
        .max(title.chars().count())
        .max(footer.chars().count());
    // +2 borders, +1 so the last column doesn't touch the right border.
    let popup_w = (inner_w as u16 + 3).min(area.width);
    let rows = app.container_list.len() as u16;
    let popup_h = (rows + 3).clamp(5, area.height); // header + rows + 2 borders

    let popup = centered_rect_exact(popup_w, popup_h, area);
    clear_region(frame, popup);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(theme::border_focused())
        .title(Span::styled(title, theme::title()))
        .title_bottom(Line::from(Span::styled(footer, theme::dim())).right_aligned());
    let inner = block.inner(popup);
    frame.render_widget(block, popup);

    let [header_area, list_area] =
        Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).areas(inner);
    // Indent the header past the 2-column highlight gutter so it lines up with
    // the rows underneath it.
    frame.render_widget(
        Paragraph::new(header),
        Rect {
            x: header_area.x + 2,
            width: header_area.width.saturating_sub(2),
            ..header_area
        },
    );
    let list = List::new(items)
        .highlight_style(theme::selected_row())
        .highlight_symbol("")
        .highlight_spacing(HighlightSpacing::Always);
    frame.render_stateful_widget(list, list_area, &mut app.container_state);
}

fn draw_prompt_popup(frame: &mut Frame, app: &App, area: Rect) {
    let popup = centered_rect_with_min(60, 34, 44, 8, area);
    clear_region(frame, popup);
    let lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            format!("  {}", app.prompt_label),
            Style::default().fg(theme::text()),
        )),
        Line::from(""),
        Line::from(vec![
            Span::styled("", Style::default().fg(theme::peach())),
            Span::styled(app.prompt_input.clone(), Style::default().fg(theme::text())),
            Span::styled("", Style::default().fg(theme::peach())),
        ]),
        Line::from(""),
        Line::from(Span::styled("  enter: apply    esc: cancel", theme::dim())),
    ];
    frame.render_widget(
        Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme::peach()))
                .title(Span::styled(" Input ", Style::default().fg(theme::peach()))),
        ),
        popup,
    );
}

fn draw_set_image(frame: &mut Frame, app: &mut App, area: Rect) {
    let items: Vec<ListItem> = app
        .container_list
        .iter()
        .enumerate()
        .map(|(i, c)| {
            let img = app.image_values.get(i).map(String::as_str).unwrap_or("");
            ListItem::new(Line::from(vec![
                Span::styled(format!("{c}  "), Style::default().fg(theme::text())),
                Span::styled("", theme::dim()),
                Span::styled(img.to_string(), Style::default().fg(theme::peach())),
            ]))
        })
        .collect();
    render_popup_list(
        frame,
        area,
        70,
        60,
        items,
        Span::styled(" Set Image (⏎ to edit container) ", theme::title()),
        &mut app.container_state,
    );
}

fn draw_confirm(frame: &mut Frame, app: &App, area: Rect) {
    let popup = centered_rect_with_min(50, 20, 56, 7, area);
    clear_region(frame, popup);
    let lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            format!("  {}", app.confirm_label),
            Style::default().fg(theme::text()),
        )),
        Line::from(""),
        Line::from(Span::styled(
            confirm_action_hint(app.confirm_allows_force_toggle(), ConfirmHintStyle::Popup),
            Style::default().fg(theme::yellow()),
        )),
    ];
    frame.render_widget(
        Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme::red()))
                .title(Span::styled(" Confirm ", Style::default().fg(theme::red()))),
        ),
        popup,
    );
}

/// Command-palette suggestion list, anchored bottom-left over the table.
fn draw_palette(frame: &mut Frame, app: &mut App, area: Rect) {
    if app.cmd_suggestions.is_empty() {
        return;
    }
    let shown = app.cmd_suggestions.len().min(12) as u16;
    let h = shown + 2;
    let w = area.width.saturating_sub(4).min(46);
    let rect = Rect {
        x: area.x + 1,
        y: area.y + area.height.saturating_sub(h + 1),
        width: w,
        height: h,
    };
    clear_region(frame, rect);
    let items: Vec<ListItem> = app
        .cmd_suggestions
        .iter()
        .map(|s| match s.kind {
            // Commands stand out (peach `:name` + a tag) so they read as actions
            // rather than resource kinds.
            SuggestKind::Command => ListItem::new(Line::from(vec![
                Span::styled(format!(":{}", s.label), Style::default().fg(theme::peach())),
                Span::styled("  cmd", theme::dim()),
            ])),
            SuggestKind::Resource => ListItem::new(Span::styled(
                s.label.clone(),
                Style::default().fg(theme::text()),
            )),
            // Argument completions echo the header colors (namespace green,
            // context mauve) with a tag, so they read as an argument choice.
            SuggestKind::Namespace => ListItem::new(Line::from(vec![
                Span::styled(s.label.clone(), Style::default().fg(theme::green())),
                Span::styled("  ns", theme::dim()),
            ])),
            SuggestKind::Context => ListItem::new(Line::from(vec![
                Span::styled(s.label.clone(), Style::default().fg(theme::mauve())),
                Span::styled("  ctx", theme::dim()),
            ])),
            // Saved bookmarks read as a distinct, high-value jump (a ★ tag).
            SuggestKind::Bookmark => ListItem::new(Line::from(vec![
                Span::styled(
                    format!("{}", s.label),
                    Style::default().fg(theme::yellow()),
                ),
                Span::styled("  bookmark", theme::dim()),
            ])),
            SuggestKind::Workspace => ListItem::new(Line::from(vec![
                Span::styled(format!("{}", s.label), Style::default().fg(theme::sky())),
                Span::styled("  workspace", theme::dim()),
            ])),
        })
        .collect();
    let mut state = ListState::default();
    state.select(Some(app.cmd_sel));
    render_framed_list(
        frame,
        rect,
        items,
        Span::styled(" commands & resources (tab/↑↓ · ⏎) ", theme::title()),
        &mut state,
    );
}

/// Xray hierarchical tree (owner → children → containers).
fn draw_xray(frame: &mut Frame, app: &mut App, area: Rect) {
    let glyph = |kind: &str| match kind {
        "deployment" => ("", theme::blue()),
        "replicaset" => ("", theme::sapphire()),
        "statefulset" => ("", theme::mauve()),
        "daemonset" => ("", theme::pink()),
        "pod" => ("", theme::green()),
        "container" => ("", theme::teal()),
        _ => ("", theme::peach()),
    };
    let items: Vec<ListItem> = app
        .xray_items
        .iter()
        .map(|it| {
            let (g, color) = glyph(&it.kind);
            let indent = "  ".repeat(it.depth);
            let label = it.container.clone().unwrap_or_else(|| it.name.clone());
            let mut spans = vec![
                Span::raw(indent),
                Span::styled(format!("{g} "), Style::default().fg(color)),
                Span::styled(label, Style::default().fg(theme::text())),
            ];
            if !it.status.is_empty() {
                let sc = theme::status_color(&it.status);
                spans.push(Span::styled(
                    format!("  {}", it.status),
                    Style::default().fg(sc),
                ));
            }
            ListItem::new(Line::from(spans))
        })
        .collect();
    let title = format!(
        " Xray [{}]  (⏎ logs · r refresh · esc back) ",
        app.xray_items.len()
    );
    render_framed_list(
        frame,
        area,
        items,
        Span::styled(title, theme::title()),
        &mut app.xray_state,
    );
}

fn draw_fleet(frame: &mut Frame, app: &mut App, area: Rect) {
    use crate::fleet::FleetStatus;
    let items: Vec<ListItem> = app
        .fleet_rows
        .iter()
        .map(|r| {
            let (glyph, gcolor) = match &r.status {
                FleetStatus::Connecting => ("", theme::overlay1()),
                FleetStatus::Error(_) => ("", theme::red()),
                FleetStatus::Ok if r.is_healthy() => ("", theme::green()),
                FleetStatus::Ok => ("", theme::yellow()),
            };
            let mut spans = vec![
                Span::styled(format!("{glyph} "), Style::default().fg(gcolor)),
                Span::styled(
                    format!("{:<26}", truncate_cols(&r.context, 26)),
                    Style::default().fg(theme::text()),
                ),
            ];
            match &r.status {
                FleetStatus::Connecting => {
                    spans.push(Span::styled("connecting…", theme::dim()));
                }
                FleetStatus::Error(e) => {
                    spans.push(Span::styled(
                        format!("error: {e}"),
                        Style::default().fg(theme::red()),
                    ));
                }
                FleetStatus::Ok => {
                    let nodes_color = if r.nodes_ready == r.nodes_total {
                        theme::green()
                    } else {
                        theme::red()
                    };
                    let pods_color = if r.pods_unhealthy == 0 {
                        theme::subtext0()
                    } else {
                        theme::red()
                    };
                    spans.push(Span::styled(
                        format!("{:<12}", truncate_cols(&r.version, 12)),
                        theme::dim(),
                    ));
                    spans.push(Span::styled(
                        format!("nodes {}/{}", r.nodes_ready, r.nodes_total),
                        Style::default().fg(nodes_color),
                    ));
                    spans.push(Span::styled(
                        format!("   pods {}✗/{}", r.pods_unhealthy, r.pods_total),
                        Style::default().fg(pods_color),
                    ));
                    match r.flux_failed {
                        Some(0) => spans.push(Span::styled(
                            "   flux ok".to_string(),
                            Style::default().fg(theme::green()),
                        )),
                        Some(n) => spans.push(Span::styled(
                            format!("   flux {n}"),
                            Style::default().fg(theme::red()),
                        )),
                        None => spans.push(Span::styled("   flux —".to_string(), theme::dim())),
                    }
                    let (pol, pc) = if r.readonly {
                        ("   read-only", theme::yellow())
                    } else {
                        ("   write", theme::overlay1())
                    };
                    spans.push(Span::styled(pol.to_string(), Style::default().fg(pc)));
                }
            }
            ListItem::new(Line::from(spans))
        })
        .collect();
    let title = format!(
        " Fleet [{}]  (⏎ switch · r refresh · esc back) ",
        app.fleet_rows.len()
    );
    render_framed_list(
        frame,
        area,
        items,
        Span::styled(title, theme::title()),
        &mut app.fleet_state,
    );
}

/// Explain-unhealthy view: a ranked, evidence-backed list of findings for the
/// selected object. Lines carrying a navigation target are marked with a `→`.
/// Render a list of [`crate::explain::Finding`]s (shared by the explain and
/// GitOps views): coloured by level, indented, with a `→` on lines that carry
/// a jump target. Shows `empty_msg` while the findings are still gathering.
fn draw_findings(
    frame: &mut Frame,
    area: Rect,
    title: String,
    findings: &[crate::explain::Finding],
    empty_msg: &str,
    state: &mut ListState,
) {
    use crate::explain::Level;
    let color = |level: Level| match level {
        Level::Heading => theme::yellow(),
        Level::Info => theme::text(),
        Level::Good => theme::green(),
        Level::Warn => theme::peach(),
        Level::Critical => theme::red(),
        Level::Evidence => theme::subtext0(),
    };

    let items: Vec<ListItem> = if findings.is_empty() {
        vec![ListItem::new(Line::from(Span::styled(
            empty_msg.to_string(),
            theme::dim(),
        )))]
    } else {
        findings
            .iter()
            .map(|f| {
                let indent = "  ".repeat(f.indent as usize);
                let mut spans = vec![Span::raw(indent)];
                let style = match f.level {
                    Level::Heading => Style::default()
                        .fg(color(f.level))
                        .add_modifier(Modifier::BOLD),
                    _ => Style::default().fg(color(f.level)),
                };
                spans.push(Span::styled(f.text.clone(), style));
                if f.target.is_some() {
                    spans.push(Span::styled("", theme::dim()));
                }
                ListItem::new(Line::from(spans))
            })
            .collect()
    };

    render_framed_list(
        frame,
        area,
        items,
        Span::styled(title, theme::title()),
        state,
    );
}

fn draw_explain(frame: &mut Frame, app: &mut App, area: Rect) {
    let title = if app.explain_items.is_empty() {
        format!(" {} ", app.explain_title)
    } else {
        format!(
            " {}  ({} findings · ⏎/E/l evidence · r refresh) ",
            app.explain_title,
            app.explain_items.len()
        )
    };
    draw_findings(
        frame,
        area,
        title,
        &app.explain_items,
        "gathering evidence…",
        &mut app.explain_state,
    );
}

fn draw_gitops(frame: &mut Frame, app: &mut App, area: Rect) {
    let title = if app.gitops_items.is_empty() {
        format!(" {} ", app.gitops_title)
    } else {
        format!(" {}  (⏎ jump · r refresh · esc back) ", app.gitops_title)
    };
    draw_findings(
        frame,
        area,
        title,
        &app.gitops_items,
        "following the reconciliation chain…",
        &mut app.gitops_state,
    );
}

/// Session-local timeline: the state changes observed for one object while
/// sofka has been watching, oldest first.
fn draw_timeline(frame: &mut Frame, app: &mut App, area: Rect) {
    use crate::timeline::Level;
    let color = |level: Level| match level {
        Level::Info => theme::text(),
        Level::Good => theme::green(),
        Level::Warn => theme::peach(),
        Level::Bad => theme::red(),
    };
    let (target, entries) = match &app.timeline_target {
        Some((plural, rk)) => (rk.clone(), app.timeline.entries(plural, rk)),
        None => (String::new(), None),
    };
    let count = entries.map(|e| e.len()).unwrap_or(0);

    let items: Vec<ListItem> = match entries {
        Some(e) if !e.is_empty() => e
            .iter()
            .map(|entry| {
                ListItem::new(Line::from(vec![
                    Span::styled(
                        format!("{}  ", crate::timeline::clock(entry.at)),
                        theme::dim(),
                    ),
                    Span::styled(entry.text.clone(), Style::default().fg(color(entry.level))),
                ]))
            })
            .collect(),
        _ => vec![ListItem::new(Line::from(Span::styled(
            "no changes observed yet — the timeline records what happens while sofka watches",
            theme::dim(),
        )))],
    };

    let title = format!(" {target} — timeline  ({count} events · session-local) ");
    render_framed_list(
        frame,
        area,
        items,
        Span::styled(title, theme::title()),
        &mut app.timeline_state,
    );
}

/// Pulse dashboard: cluster-health tiles.
fn draw_pulse(frame: &mut Frame, app: &App, area: Rect) {
    let p = &app.pulse;
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(area);
    let cols = |r: Rect| {
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(34),
                Constraint::Percentage(33),
                Constraint::Percentage(33),
            ])
            .split(r)
    };
    let top = cols(rows[0]);
    let bot = cols(rows[1]);

    gauge_tile(frame, top[0], "Nodes Ready", p.nodes_ready, p.nodes_total);
    pods_tile(frame, top[1], p);
    gauge_tile(
        frame,
        top[2],
        "Deployments",
        p.deploys_ready,
        p.deploys_total,
    );
    gauge_tile(frame, bot[0], "StatefulSets", p.sts_ready, p.sts_total);
    gauge_tile(frame, bot[1], "DaemonSets", p.ds_ready, p.ds_total);
    counts_tile(frame, bot[2], p);
}

fn gauge_tile(frame: &mut Frame, area: Rect, label: &str, ready: usize, total: usize) {
    let ratio = if total == 0 {
        1.0
    } else {
        ready as f64 / total as f64
    };
    let color = if total == 0 {
        theme::overlay1()
    } else if ready == total {
        theme::green()
    } else if ratio >= 0.5 {
        theme::yellow()
    } else {
        theme::red()
    };
    let g = Gauge::default()
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(theme::border())
                .title(Span::styled(format!(" {label} "), theme::title())),
        )
        .gauge_style(Style::default().fg(color).bg(theme::surface0()))
        .ratio(ratio.clamp(0.0, 1.0))
        .label(format!("{ready}/{total}"));
    frame.render_widget(g, area);
}

fn pods_tile(frame: &mut Frame, area: Rect, p: &crate::store::Pulse) {
    let row = |label: &str, n: usize, color| {
        Line::from(vec![
            Span::styled(format!("  {label:<11}"), Style::default().fg(color)),
            Span::styled(n.to_string(), Style::default().fg(theme::text())),
        ])
    };
    let lines = vec![
        row("Running", p.pods_running, theme::green()),
        row("Pending", p.pods_pending, theme::yellow()),
        row("Failed", p.pods_failed, theme::red()),
        row("Succeeded", p.pods_succeeded, theme::blue()),
        row("Total", p.pods_total, theme::subtext0()),
    ];
    frame.render_widget(
        Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(theme::border())
                .title(Span::styled(" Pods ", theme::title())),
        ),
        area,
    );
}

fn counts_tile(frame: &mut Frame, area: Rect, p: &crate::store::Pulse) {
    let lines = vec![
        Line::from(vec![
            Span::styled("  PVCs Bound  ", Style::default().fg(theme::teal())),
            Span::styled(
                format!("{}/{}", p.pvc_bound, p.pvc_total),
                Style::default().fg(theme::text()),
            ),
        ]),
        Line::from(vec![
            Span::styled("  Jobs        ", Style::default().fg(theme::mauve())),
            Span::styled(p.jobs_total.to_string(), Style::default().fg(theme::text())),
        ]),
    ];
    frame.render_widget(
        Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(theme::border())
                .title(Span::styled(" Storage / Batch ", theme::title())),
        ),
        area,
    );
}

fn draw_prompt(frame: &mut Frame, app: &App, area: Rect) {
    let line = match app.mode {
        Mode::Command => Line::from(vec![
            Span::styled(
                ":",
                Style::default()
                    .fg(theme::mauve())
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(app.command.clone(), Style::default().fg(theme::text())),
            Span::styled("", Style::default().fg(theme::mauve())),
        ]),
        Mode::Filter => {
            let mut spans = vec![
                Span::styled(
                    "/",
                    Style::default()
                        .fg(theme::teal())
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(app.filter.clone(), Style::default().fg(theme::text())),
                Span::styled("", Style::default().fg(theme::teal())),
            ];
            // Structured-grammar feedback: a parse error, a `-l`/`-f`
            // selector waiting for ⏎ to restart the watch server-side, or
            // confirmation that the watch is already selector-scoped.
            if let Some(err) = app.filter_error() {
                spans.push(Span::styled(
                    format!("{err}"),
                    Style::default().fg(theme::red()),
                ));
            } else if app.filter_selectors_pending() {
                spans.push(Span::styled(
                    "  ⏎ apply server-side",
                    Style::default().fg(theme::yellow()),
                ));
            } else if app.filter_server_side() {
                spans.push(Span::styled("  ·server", theme::dim()));
            }
            Line::from(spans)
        }
        Mode::LogFilter => Line::from(vec![
            Span::styled(
                "log filter (text · /re/ · !invert) /",
                Style::default()
                    .fg(theme::teal())
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(app.logs.filter.clone(), Style::default().fg(theme::text())),
            Span::styled("", Style::default().fg(theme::teal())),
        ]),
        Mode::DocFilter => {
            let query = if app.doc_filter_return == Mode::Help {
                app.help_filter.clone()
            } else {
                app.detail.filter.clone()
            };
            Line::from(vec![
                Span::styled(
                    "search /",
                    Style::default()
                        .fg(theme::teal())
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(query, Style::default().fg(theme::text())),
                Span::styled("", Style::default().fg(theme::teal())),
            ])
        }
        Mode::Confirm => Line::from(Span::styled(
            confirm_action_hint(app.confirm_allows_force_toggle(), ConfirmHintStyle::Prompt),
            Style::default().fg(theme::yellow()),
        )),
        Mode::Logs => {
            let hint = if app.provider_logs_active() {
                "  /filter  s:autoscroll  w:wrap  t:timestamps  F:fullscreen  0-5:since  T:period  x:stop/resume  z:clear  c:copy  ^s:save  esc:back"
            } else {
                "  /filter  s:autoscroll  w:wrap  t:timestamps  F:fullscreen  0-5:since  x:stop/resume  z:clear  c:copy  ^s:save  esc:back"
            };
            Line::from(Span::styled(hint, theme::dim()))
        }
        Mode::Detail | Mode::Events | Mode::Diff => {
            let hint = "  j/k:scroll  h/l:← →  g/G:top/bottom  /:search  n/N:next/prev  w:wrap  c:copy  esc:back";
            Line::from(Span::styled(hint, theme::dim()))
        }
        Mode::Help => Line::from(Span::styled("  /:search  ?/esc:back", theme::dim())),
        Mode::Explain => Line::from(Span::styled(
            "  j/k: move   ⏎: go to resource   E: events   l: logs   r: refresh   esc: back",
            theme::dim(),
        )),
        Mode::Timeline => Line::from(Span::styled(
            "  j/k: move   g/G: top/bottom   esc: back",
            theme::dim(),
        )),
        Mode::Gitops => Line::from(Span::styled(
            "  j/k: move   ⏎: jump to owner/source   r: refresh   esc: back",
            theme::dim(),
        )),
        Mode::FluxMenu => Line::from(Span::styled(
            "  j/k: move   enter: confirm   esc: cancel",
            theme::dim(),
        )),
        Mode::PortForwards => Line::from(Span::styled(
            "  j/k: move   x/s: stop   esc: close (others keep running)",
            theme::dim(),
        )),
        Mode::Snapshots => Line::from(Span::styled(
            "  j/k: move   ⏎: open   d: delete   esc: close",
            theme::dim(),
        )),
        Mode::Fleet => Line::from(Span::styled(
            "  j/k: move   ⏎: switch to context   r: refresh   esc: back",
            theme::dim(),
        )),
        _ => {
            // Per-resource verbs live in the header hint column when it
            // fits; only repeat the full line when the header dropped it.
            let hint = if header_hints_fit(frame.area().width) {
                "  :resource  /filter  S:sort I:invert  w:wide  space:mark  [ ]:history  0:all-ns  ?:help"
            } else {
                "  :resource  /filter  S:sort I:invert  w:wide  ⏎drill  y:yaml d:describe l:logs e:edit s:shell/scale i:image r:restart f:fwd ^d:del  ?:help"
            };
            Line::from(Span::styled(hint, theme::dim()))
        }
    };
    frame.render_widget(Paragraph::new(line), area);
}

fn draw_status(frame: &mut Frame, app: &App, area: Rect) {
    let style = if app.flash_err {
        Style::default().fg(theme::red())
    } else {
        Style::default().fg(theme::subtext0())
    };
    let synced = if app.store.synced {
        "● live"
    } else {
        "○ syncing"
    };
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Min(10), Constraint::Length(12)])
        .split(area);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(format!(" {}", app.flash), style))),
        cols[0],
    );
    let sync_color = if app.store.synced {
        theme::green()
    } else {
        theme::yellow()
    };
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            synced,
            Style::default().fg(sync_color),
        )))
        .alignment(Alignment::Right),
        cols[1],
    );
}

#[derive(Clone, Copy)]
enum ConfirmHintStyle {
    Popup,
    Prompt,
}

fn confirm_action_hint(allows_force: bool, style: ConfirmHintStyle) -> &'static str {
    match (allows_force, style) {
        (true, ConfirmHintStyle::Popup) => {
            "  [y] confirm    [f] toggle force    [c] cascade    [n] cancel"
        }
        (false, ConfirmHintStyle::Popup) => "  [y] confirm    [n] cancel",
        (true, ConfirmHintStyle::Prompt) => {
            "  y/enter: confirm   f: toggle force   c: cascade   n/esc: cancel"
        }
        (false, ConfirmHintStyle::Prompt) => "  y/enter: confirm   n/esc: cancel",
    }
}

/// Clear a popup region before drawing on top of it. `Clear` resets the cells
/// to the terminal default; with the skin background enabled that would punch a
/// transparent hole through the fill, so repaint `base` over the cleared cells.
fn clear_region(frame: &mut Frame, area: Rect) {
    frame.render_widget(Clear, area);
    if let Some(bg) = theme::background() {
        frame.buffer_mut().set_style(area, Style::default().bg(bg));
    }
}

fn render_popup_list<'a, T>(
    frame: &mut Frame,
    area: Rect,
    percent_x: u16,
    percent_y: u16,
    items: Vec<ListItem<'a>>,
    title: T,
    state: &mut ListState,
) where
    T: Into<Line<'a>>,
{
    let popup = centered_rect_with_min(percent_x, percent_y, 32, 8, area);
    clear_region(frame, popup);
    render_framed_list(frame, popup, items, title, state);
}

fn render_framed_list<'a, T>(
    frame: &mut Frame,
    area: Rect,
    items: Vec<ListItem<'a>>,
    title: T,
    state: &mut ListState,
) where
    T: Into<Line<'a>>,
{
    let list = List::new(items)
        .highlight_style(theme::selected_row())
        .highlight_symbol("")
        .highlight_spacing(HighlightSpacing::Always)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(theme::border_focused())
                .title(title.into()),
        );
    frame.render_stateful_widget(list, area, state);
}

/// Center a fixed-size rectangle within `r`, clamped to `r`'s bounds. Used by
/// popups that size themselves to their content rather than a percentage.
fn centered_rect_exact(width: u16, height: u16, r: Rect) -> Rect {
    let width = width.min(r.width);
    let height = height.min(r.height);
    Rect {
        x: r.x + (r.width - width) / 2,
        y: r.y + (r.height - height) / 2,
        width,
        height,
    }
}

fn centered_rect_with_min(
    percent_x: u16,
    percent_y: u16,
    min_width: u16,
    min_height: u16,
    r: Rect,
) -> Rect {
    let pct_w = (u32::from(r.width) * u32::from(percent_x.min(100)) / 100) as u16;
    let pct_h = (u32::from(r.height) * u32::from(percent_y.min(100)) / 100) as u16;
    let width = pct_w.max(min_width).min(r.width);
    let height = pct_h.max(min_height).min(r.height);
    Rect {
        x: r.x + (r.width - width) / 2,
        y: r.y + (r.height - height) / 2,
        width,
        height,
    }
}

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

    /// `set_background(true)` fills the whole frame — including cells no widget
    /// draws on and popup regions cleared by `Clear` — with the skin's `base`,
    /// while `false` leaves the terminal background (Reset) untouched.
    #[tokio::test]
    async fn background_fill_paints_base_when_enabled() {
        use crate::app::Suggestion;
        use crate::k8s::Cluster;
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let (tx, _rx) = tokio::sync::mpsc::channel(16);
        let mut app = App::new(Cluster::fake(), tx);
        app.command = "de".into();
        app.mode = Mode::Command; // draw a popup so a Clear region is exercised
        app.cmd_suggestions = vec![Suggestion {
            label: "deployments".into(),
            kind: SuggestKind::Resource,
        }];

        let render = |app: &mut App| {
            let mut term = Terminal::new(TestBackend::new(80, 24)).unwrap();
            term.draw(|f| draw(f, app)).unwrap();
            term.backend().buffer().clone()
        };

        // Assertions avoid the exact palette value (theme state is a shared
        // global that parallel tests mutate); they check the fill *behavior*.
        theme::set_background(false);
        let off = render(&mut app);
        // Off: an untouched corner keeps the terminal default background.
        assert_eq!(off[(0, 0)].bg, ratatui::style::Color::Reset);

        theme::set_background(true);
        let on = render(&mut app);
        // On: the corner (no widget draws there) is now a solid fill, and at
        // least one full row — popup interior included — shares that one color.
        let fill = on[(0, 0)].bg;
        assert_ne!(fill, ratatui::style::Color::Reset);
        assert!(
            (0..on.area.height).any(|y| (0..on.area.width).all(|x| on[(x, y)].bg == fill)),
            "expected a row uniformly filled with the background color"
        );

        theme::set_background(false); // don't leak global state to other tests
    }

    #[test]
    fn all_ready_requires_full_fraction() {
        assert!(all_ready("2/2"));
        assert!(all_ready("0/0"));
        assert!(!all_ready("1/2"));
        assert!(!all_ready("0/1"));
        // Non-fraction cells (other kinds' status columns) never trigger it.
        assert!(all_ready("Ready"));
    }

    /// The scroll math (`wrapped_height`) and the renderer (`wrap_line`) must
    /// produce the same row count for any input, or follow/clamping drifts.
    #[test]
    fn wrapped_height_matches_wrap_line() {
        let cases = [
            "",
            "short",
            "exactly-ten",
            "a much longer plain ascii log line that wraps a few times over",
            // ANSI escapes are zero-width.
            "\x1b[33mwarn\x1b[0m something colorful happened in the reconcile loop",
            // Wide CJK glyphs take two columns and never straddle a break.
            "日本語のログ行 with mixed ascii ワイド文字",
            // Combining mark (zero width) + multi-byte.
            "cafe\u{301} naïve élan über — dash",
            // Lone ESC and non-SGR CSI are swallowed.
            "\x1bodd \x1b[2Kcleared line",
        ];
        for w in [1usize, 3, 10, 37, 120] {
            for raw in cases {
                let rendered = render_log_line(raw, "");
                let rows = wrap_line(rendered, w).len();
                assert_eq!(
                    wrapped_height(raw, w),
                    rows,
                    "height/split disagree for {raw:?} at width {w}"
                );
            }
        }
    }

    #[test]
    fn wrapped_height_counts_columns_not_bytes() {
        assert_eq!(wrapped_height("", 10), 1); // empty line still takes a row
        assert_eq!(wrapped_height("aaaaaaaaaa", 10), 1); // exact fit
        assert_eq!(wrapped_height("aaaaaaaaaab", 10), 2);
        // 5 wide chars = 10 columns → one row at width 10, not "5 chars fit".
        assert_eq!(wrapped_height("五五五五五", 10), 1);
        assert_eq!(wrapped_height("五五五五五五", 10), 2);
        // ANSI escapes don't consume columns.
        assert_eq!(wrapped_height("\x1b[31maaaaaaaaaa\x1b[0m", 10), 1);
    }

    #[test]
    fn visible_line_window_clamps_to_viewport() {
        assert_eq!(visible_line_window(100, 10, 20), (10, 30));
        assert_eq!(visible_line_window(100, 95, 20), (95, 100));
        assert_eq!(visible_line_window(100, 150, 20), (100, 100));
        assert_eq!(visible_line_window(100, 10, 0), (10, 10));
    }

    #[test]
    fn centered_rect_with_min_keeps_popups_readable() {
        let area = Rect {
            x: 10,
            y: 20,
            width: 100,
            height: 20,
        };
        assert_eq!(
            centered_rect_with_min(50, 20, 56, 7, area),
            Rect {
                x: 32,
                y: 26,
                width: 56,
                height: 7,
            }
        );

        let tiny = Rect {
            x: 3,
            y: 4,
            width: 40,
            height: 5,
        };
        assert_eq!(centered_rect_with_min(50, 20, 56, 7, tiny), tiny);
    }

    #[test]
    fn confirm_hint_mentions_force_only_when_supported() {
        assert!(confirm_action_hint(true, ConfirmHintStyle::Popup).contains("toggle force"));
        assert!(confirm_action_hint(true, ConfirmHintStyle::Prompt).contains("toggle force"));
        assert!(!confirm_action_hint(false, ConfirmHintStyle::Popup).contains("toggle force"));
        assert!(!confirm_action_hint(false, ConfirmHintStyle::Prompt).contains("toggle force"));
        assert!(confirm_action_hint(true, ConfirmHintStyle::Popup).contains("cascade"));
        assert!(confirm_action_hint(true, ConfirmHintStyle::Prompt).contains("cascade"));
        assert!(!confirm_action_hint(false, ConfirmHintStyle::Popup).contains("cascade"));
        assert!(!confirm_action_hint(false, ConfirmHintStyle::Prompt).contains("cascade"));
    }

    #[test]
    fn log_levels_colorize() {
        // Space-delimited level, with "error" later in the message: warn wins.
        assert_eq!(
            log_level_color("pod vmagent 2026-06-30T12:00:26.985Z warn lib: the last error: x"),
            theme::peach()
        );
        // Glued-after-timestamp info (config-reloader style) stays default.
        assert_eq!(
            log_level_color("[config-reloader] 2026-06-27T04:56:24.216Zinfo k8s_watch.go:153 x"),
            theme::text()
        );
        // Tab-delimited info.
        assert_eq!(
            log_level_color("ts 2026\tinfo\tVictoriaMetrics added targets"),
            theme::text()
        );
        // Plain error level.
        assert_eq!(
            log_level_color("2026-06-30T12 error connection refused"),
            theme::red()
        );
        // klog prefix.
        assert_eq!(
            log_level_color("E0627 12:00:00.000 controller failed"),
            theme::red()
        );
        assert_eq!(
            log_level_color("W0627 12:00:00.000 retrying"),
            theme::peach()
        );
        // logfmt level=debug.
        assert_eq!(
            log_level_color("msg=hi level=debug caller=x"),
            theme::overlay1()
        );
    }

    #[test]
    fn json_log_levels_colorize() {
        let line = |lvl: &str, msg: &str| {
            format!(
                "[main] {{\"timestamp\":\"2026-06-30T12:52:20.876Z\",\"level\":\"{lvl}\",\"message\":\"{msg}\",\"service\":\"screenshoter\"}}"
            )
        };
        assert_eq!(
            log_level_color(&line("DEBUG", "request_started")),
            theme::overlay1()
        );
        assert_eq!(
            log_level_color(&line("INFO", "request_completed")),
            theme::text()
        );
        assert_eq!(
            log_level_color(&line("WARN", "unauthorized_request")),
            theme::peach()
        );
        assert_eq!(log_level_color(&line("ERROR", "boom")), theme::red());
        // JSON level is authoritative: "error" in the message can't override WARN.
        assert_eq!(
            log_level_color(&line("WARN", "the last error occurred")),
            theme::peach()
        );
        // Whitespace after the colon is tolerated.
        assert_eq!(log_level_color(r#"{"level": "warning"}"#), theme::peach());
        // Non-structured rod lines have no level → default color.
        assert_eq!(log_level_color("[rod] Killed PID: 25258"), theme::text());
    }

    #[test]
    fn source_prefix_detection() {
        // "[rod] " is 6 bytes including the trailing space.
        assert_eq!(source_prefix("[rod] Close ws://x").map(|(e, _)| e), Some(6));
        assert_eq!(
            source_prefix("[main] {\"level\":\"info\"}").map(|(e, _)| e),
            Some(7)
        );
        // No trailing space still detected.
        assert_eq!(source_prefix("[x]done").map(|(e, _)| e), Some(3));
        assert_eq!(source_prefix("no prefix here"), None);
        assert_eq!(source_prefix("[]empty"), None);
    }

    #[test]
    fn source_color_is_stable_and_distinct() {
        // Same label → same color across calls.
        assert_eq!(source_color("rod"), source_color("rod"));
        // Reserved severity/highlight colors are never used for a source.
        for label in ["rod", "main", "istio-proxy", "app", "vmagent"] {
            let c = source_color(label);
            assert_ne!(c, theme::red());
            assert_ne!(c, theme::peach());
            assert_ne!(c, theme::yellow());
        }
        // The two prefixes in the screenshot land on different colors.
        assert_ne!(source_color("rod"), source_color("main"));
    }

    #[test]
    fn render_colors_prefix_then_body() {
        let line = render_log_line("[rod] Killed PID: 25258", "");
        // First span is the colored source prefix, kept verbatim.
        assert_eq!(line.spans[0].content, "[rod] ");
        assert_eq!(line.spans[0].style.fg, Some(source_color("rod")));
    }

    #[test]
    fn leading_timestamp_detection() {
        // Space-terminated RFC3339 → dimmed.
        assert_eq!(
            leading_timestamp("2026-06-30T12:52:20.876Z hello"),
            Some(24)
        );
        assert_eq!(leading_timestamp("2026-06-30T12:52:20Z msg"), Some(20));
        assert_eq!(
            leading_timestamp("2026-06-30T12:52:20.5+02:00 msg"),
            Some(27)
        );
        // Glued to the message (config-reloader style) → NOT a timestamp.
        assert_eq!(
            leading_timestamp("2026-06-27T04:56:24.216Zinfo k8s_watch"),
            None
        );
        // Not a timestamp at all.
        assert_eq!(leading_timestamp("Close ws://127.0.0.1"), None);
    }

    #[test]
    fn strips_and_interprets_ansi() {
        // Caddy-style line: level token wrapped in an SGR color, escapes must
        // not survive into the rendered text.
        let raw = "2026/07/01 08:43:13 \x1b[34mINFO\x1b[0m WAF started";
        let line = render_log_line(raw, "");
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(text, "2026/07/01 08:43:13 INFO WAF started");
        assert!(!text.contains('\x1b') && !text.contains("[34m"));
        // The "INFO" run picked up the ANSI blue → theme blue.
        let info = line.spans.iter().find(|s| s.content == "INFO").unwrap();
        assert_eq!(info.style.fg, Some(theme::blue()));
    }

    #[test]
    fn ansi_runs_plain_string_is_single_run() {
        let runs = ansi_runs("plain text");
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].text, "plain text");
        assert_eq!(runs[0].color, None);
    }

    #[test]
    fn ansi_truecolor_passes_through() {
        let runs = ansi_runs("\x1b[38;2;10;20;30mX\x1b[0m");
        assert_eq!(runs[0].text, "X");
        assert_eq!(runs[0].color, Some(Color::Rgb(10, 20, 30)));
        assert_eq!(strip_ansi("\x1b[1;31mE\x1b[0mrror"), "Error");
    }

    #[test]
    fn render_dims_leading_timestamp() {
        let line = render_log_line("2026-06-30T12:52:20.876Z request done", "");
        assert_eq!(line.spans[0].content, "2026-06-30T12:52:20.876Z");
        assert_eq!(line.spans[0].style.fg, theme::dim().fg);
    }

    #[test]
    fn value_styling() {
        assert_eq!(value_style("3").fg, Some(theme::peach()));
        assert_eq!(value_style("true").fg, Some(theme::mauve()));
        assert_eq!(value_style("<none>").fg, Some(theme::mauve()));
        assert_eq!(value_style("Running").fg, Some(theme::green()));
        assert_eq!(value_style("nginx:1.25").fg, Some(theme::text()));
    }

    #[test]
    fn yaml_highlighting() {
        // Comment dimmed.
        assert_eq!(highlight_yaml("  # note")[0].style.fg, theme::dim().fg);
        // Section header in mauve.
        assert_eq!(
            highlight_yaml("Containers:")[0].style.fg,
            Some(theme::mauve())
        );
        // key: value — key in sky, value tinted by status.
        let spans = highlight_yaml("Status:    Running");
        assert_eq!(spans[0].content, "Status");
        assert_eq!(spans[0].style.fg, Some(theme::sky()));
        assert_eq!(spans.last().unwrap().content, "Running");
        assert_eq!(spans.last().unwrap().style.fg, Some(theme::green()));
    }

    /// Fullscreen logs (`F`) own the entire frame: no header above, no status
    /// line below, and no border glyphs anywhere — so a terminal text
    /// selection copies clean log lines.
    #[tokio::test]
    async fn fullscreen_logs_take_the_whole_frame_without_borders() {
        use crate::k8s::Cluster;
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let (tx, _rx) = tokio::sync::mpsc::channel(16);
        let mut app = App::new(Cluster::fake(), tx);
        app.mode = Mode::Logs;
        app.logs.view.title = "web — logs".into();
        app.logs.view.lines = (0..3).map(|i| format!("log line {i}")).collect();

        let render = |app: &mut App| {
            let mut term = Terminal::new(TestBackend::new(60, 12)).unwrap();
            term.draw(|f| draw(f, app)).unwrap();
            let buffer = term.backend().buffer().clone();
            (0..buffer.area.height)
                .map(|y| {
                    (0..buffer.area.width)
                        .map(|x| buffer[(x, y)].symbol())
                        .collect::<String>()
                })
                .collect::<Vec<String>>()
        };

        // Bordered by default: the pane sits under the 7-line header.
        let normal = render(&mut app);
        assert!(
            normal.iter().any(|r| r.contains('')),
            "normal logs view should draw its border"
        );
        assert!(!normal[0].contains("web — logs"), "header owns the top row");

        app.logs.fullscreen = true;
        let full = render(&mut app);
        assert!(
            full[0].contains("web — logs"),
            "fullscreen title owns the top row: {:?}",
            full[0]
        );
        assert!(
            full.iter().any(|r| r.starts_with("log line")),
            "lines start at column 0 (no left border)"
        );
        for r in &full {
            assert!(
                !r.contains('') && !r.contains('') && !r.contains(''),
                "no border glyphs in fullscreen: {r:?}"
            );
        }
    }
}