mnml-rs 0.2.13

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
//! The `Pane::Request` view — two modes:
//!
//! * **Response (default)** — read-only summary of the last send: status,
//!   headers, pretty body, `@assert` results, `@capture`s. `r` re-fires.
//! * **Edit** — interactive form: URL, method, headers, body editable in
//!   place. Tab toggles modes; in Edit, Shift-Tab / Tab cycle the focused
//!   field (URL → Method → Headers → Body → URL); Tab inside Body inserts a
//!   literal `\t` (for typing indented JSON / XML); typing / backspace /
//!   arrows / Home / End edit; Space on Method cycles HTTP verbs;
//!   `r` re-fires with the edited values.
//!
//! Long lines clip (no wrap yet).

use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use crate::app::App;
use crate::layout::PaneId;
use crate::pane::Pane;
use crate::request_pane::{EditField, RunState};
use crate::ui::theme;

/// Section header chip — matches the app-wide `modal_panel` title
/// look (cyan bg + bg_dark fg + BOLD). Was used for inline
/// `response`/`ai` labels before the three-zone bordered layout
/// took over the section-title role; retained for potential
/// future use inside sub-sections (e.g. Response body vs. headers).
#[allow(dead_code)]
fn section_header_chip(text: &'static str, t: theme::Theme) -> Line<'static> {
    Line::from(Span::styled(
        text,
        Style::default()
            .fg(t.bg_dark)
            .bg(t.cyan)
            .add_modifier(Modifier::BOLD),
    ))
}

/// Verb → chip color. Shared between the edit-row method chip and
/// the response-summary method chip so a new HTTP verb only needs to
/// land in one place.
fn method_color(method: &str, t: theme::Theme) -> ratatui::style::Color {
    match method.to_uppercase().as_str() {
        "GET" => t.green,
        "POST" => t.orange,
        "PUT" => t.blue,
        "PATCH" => t.cyan,
        "DELETE" => t.red,
        "HEAD" => t.yellow,
        "OPTIONS" => t.purple,
        _ => t.fg,
    }
}

/// One-line HTTP header row rendered as `<key in cyan bold> : <value>`.
/// Used everywhere a header list shows up (Edit-tab Headers section,
/// request-line summary in the response panel, actual response
/// headers) so the same styling reads across all three sites. (#11)
fn header_row(key: &str, value: &str, t: theme::Theme) -> Line<'static> {
    Line::from(vec![
        Span::styled("  ", Style::default().bg(t.bg_dark)),
        Span::styled(
            key.to_string(),
            Style::default()
                .fg(t.cyan)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(": ", Style::default().fg(t.comment).bg(t.bg_dark)),
        Span::styled(value.to_string(), Style::default().fg(t.fg).bg(t.bg_dark)),
    ])
}

/// Case-insensitive substring match on either the key or the value.
/// Empty filter always matches. Used to hide header rows that don't
/// match the pane's `/` filter query (#11).
fn header_matches_filter(key: &str, value: &str, q_lower: &str) -> bool {
    if q_lower.is_empty() {
        return true;
    }
    key.to_ascii_lowercase().contains(q_lower) || value.to_ascii_lowercase().contains(q_lower)
}

/// Snap `idx` down to the nearest UTF-8 char boundary in `s`. Used
/// by [`colored_line`] to keep `str` slicing safe when tree-sitter
/// returns byte offsets that land mid-multi-byte. (Nightly's
/// `floor_char_boundary` isn't available on stable yet.)
fn floor_boundary(s: &str, mut idx: usize) -> usize {
    while idx > 0 && !s.is_char_boundary(idx) {
        idx -= 1;
    }
    idx
}

/// Count filter matches across request headers + response headers +
/// response body lines. Returns `(matched, total)` for the filter
/// chip's hit indicator. Returns `None` when the filter is empty. (#11)
/// Body walk is capped at 20 000 lines so pathological 10 MB+ JSON
/// bodies don't tie up the render loop; the counter shows the sum
/// up to that cap (`total` reflects actual work, not headline size).
fn compute_filter_hits(rp: &crate::request_pane::RequestPane) -> Option<(usize, usize)> {
    const BODY_LINE_CAP: usize = 20_000;
    let q = rp.filter.trim().to_ascii_lowercase();
    if q.is_empty() {
        return None;
    }
    let mut matched = 0usize;
    let mut total = 0usize;
    for (k, v) in &rp.request.headers {
        total += 1;
        if header_matches_filter(k, v, &q) {
            matched += 1;
        }
    }
    if let RunState::Done(r) = &rp.state {
        for (k, v) in &r.headers {
            total += 1;
            if header_matches_filter(k, v, &q) {
                matched += 1;
            }
        }
        for line in r.body.lines().take(BODY_LINE_CAP) {
            total += 1;
            if line.to_ascii_lowercase().contains(&q) {
                matched += 1;
            }
        }
    }
    Some((matched, total))
}

/// Filter chip row rendered at the top of the response section when
/// the pane's `/` filter is active. Placeholder reads `/ filter` when
/// unfocused, `type to filter…` when focused. `▏` cursor marks focus.
/// Matches the sidebar-filter idiom across the app (#11).
fn filter_row(
    filter: &str,
    focused: bool,
    hits: Option<(usize, usize)>,
    t: theme::Theme,
) -> Line<'static> {
    let display = if filter.is_empty() {
        if focused {
            "type to filter headers + body…".to_string()
        } else {
            "/ filter response".to_string()
        }
    } else {
        filter.to_string()
    };
    let fg = if !filter.is_empty() {
        t.fg
    } else if focused {
        t.cyan
    } else {
        t.comment
    };
    let cursor = if focused { "" } else { "" };
    let search_glyph = "\u{f002}";
    let mut spans = vec![
        Span::styled("  ", Style::default().bg(t.bg_dark)),
        Span::styled(
            format!("{search_glyph} "),
            Style::default().fg(t.comment).bg(t.bg_dark),
        ),
        Span::styled(display, Style::default().fg(fg).bg(t.bg_dark)),
        Span::styled(cursor, Style::default().fg(t.cyan).bg(t.bg_dark)),
    ];
    // Hit count chip — shows only when the filter is set. Colors track
    // whether there's a match (cyan) or none (red).
    if !filter.is_empty()
        && let Some((matched, total)) = hits
    {
        let count_color = if matched > 0 { t.cyan } else { t.red };
        spans.push(Span::styled(
            format!("   {matched}/{total}"),
            Style::default()
                .fg(count_color)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        ));
    }
    Line::from(spans)
}

/// Convert a source line + tree-sitter colored spans into a ratatui
/// `Line` with per-token coloring on `bg_dark`. Bytes not covered by
/// any span render with the base `fg` color. Used to syntax-highlight
/// JSON response bodies. (#11)
fn colored_line(
    src: &str,
    spans: &[crate::highlight::ColoredSpan],
    base_fg: ratatui::style::Color,
    t: theme::Theme,
) -> Line<'static> {
    if spans.is_empty() {
        return Line::from(Span::styled(
            src.to_string(),
            Style::default().fg(base_fg).bg(t.bg_dark),
        ));
    }
    // Walk sorted spans and emit interleaved text — uncovered bytes
    // in `base_fg`, covered runs in their span color. Robust against
    // overlapping spans by ordering + skipping any span that ends
    // before the current cursor. All byte boundaries snap down to
    // the nearest UTF-8 char boundary so spans that end mid-multi-
    // byte (CJK, emoji in a JSON string) never slice a codepoint
    // in half.
    let mut ordered: Vec<crate::highlight::ColoredSpan> = spans.to_vec();
    ordered.sort_by_key(|(s, _, _)| *s);
    let mut out: Vec<Span<'static>> = Vec::new();
    let mut cursor = 0usize;
    let src_len = src.len();
    for (s, e, color) in ordered {
        let s = floor_boundary(src, s.min(src_len));
        let e = floor_boundary(src, e.min(src_len));
        if e <= cursor {
            continue;
        }
        if s > cursor {
            out.push(Span::styled(
                src[cursor..s].to_string(),
                Style::default().fg(base_fg).bg(t.bg_dark),
            ));
        }
        let start = s.max(cursor);
        out.push(Span::styled(
            src[start..e].to_string(),
            Style::default().fg(color).bg(t.bg_dark),
        ));
        cursor = e;
    }
    if cursor < src_len {
        out.push(Span::styled(
            src[cursor..].to_string(),
            Style::default().fg(base_fg).bg(t.bg_dark),
        ));
    }
    Line::from(out)
}

/// Same rendering shape as `colored_line`, but any `{{VAR}}` token in
/// `src` overrides the JSON syntax coloring — resolved vars render
/// cyan-bold, unresolved red-bold — and each token registers a click
/// rect via `click_out`. Kept separate from `colored_line` so the
/// non-JSON body / URL paths (which don't need the syntax layer)
/// don't pay the extra tokenization cost. 2026-07-07.
#[allow(clippy::too_many_arguments)]
fn colored_line_with_vars(
    src: &str,
    spans: &[crate::highlight::ColoredSpan],
    base_fg: ratatui::style::Color,
    t: theme::Theme,
    envset: &crate::http::template::EnvSet,
    resolved_style: Style,
    unresolved_style: Style,
    base_x: u16,
    row_y: u16,
    click_out: Option<&mut Vec<(Rect, String)>>,
) -> Line<'static> {
    let tokens = tokenize_vars(src, envset);
    if tokens.is_empty() {
        return colored_line(src, spans, base_fg, t);
    }
    // Sort JSON syntax spans once so we can walk them alongside the
    // character cursor. Overlapping/nested spans win by "innermost
    // last" — same convention `colored_line` uses.
    let mut ordered: Vec<crate::highlight::ColoredSpan> = spans.to_vec();
    ordered.sort_by_key(|(s, _, _)| *s);
    let base_style = Style::default().fg(base_fg).bg(t.bg_dark);
    // Walk chars — for each, compute the current style (var wins
    // over JSON), collect into runs of identical style. Emit one
    // span per run.
    let mut out: Vec<Span<'static>> = Vec::new();
    let mut run = String::new();
    let mut run_style = base_style;
    let mut first = true;
    // Emit-a-click-rect helper (each token → one rect over its full
    // char range on this line). Pre-compute char offsets so rects
    // land on the right screen column.
    let mut click_out_ref = click_out;
    for tok in &tokens {
        let before = &src[..tok.start];
        let width = src[tok.start..tok.end].chars().count() as u16;
        if let Some(v) = click_out_ref.as_deref_mut() {
            v.push((
                Rect {
                    x: base_x + before.chars().count() as u16,
                    y: row_y,
                    width,
                    height: 1,
                },
                tok.name.clone(),
            ));
        }
    }
    // Two-pointer walk over sorted tokens + sorted spans so per-char
    // lookup is amortized O(1) instead of O(n_tokens + n_spans).
    // 2026-07-11 perf follow-up from the earlier render review —
    // minified single-line JSON with dozens of tree-sitter spans + a
    // handful of `{{VAR}}` tokens went quadratic in char count.
    let mut byte = 0usize;
    let mut tok_idx = 0usize; // next token whose end might still be reached
    let mut span_scan_idx = 0usize; // next span whose start might still be reached
    while byte < src.len() {
        let ch = src[byte..].chars().next().unwrap();
        let ch_bytes = ch.len_utf8();
        // Advance tok_idx past tokens that end at-or-before this byte.
        // Tokens are non-overlapping, produced in start-order.
        while tok_idx < tokens.len() && tokens[tok_idx].end <= byte {
            tok_idx += 1;
        }
        let style = if tok_idx < tokens.len()
            && byte >= tokens[tok_idx].start
            && byte < tokens[tok_idx].end
        {
            if tokens[tok_idx].resolved {
                resolved_style
            } else {
                unresolved_style
            }
        } else {
            // Walk spans starting at-or-before byte. Later match wins
            // (innermost-nest). `span_scan_idx` advances as `byte`
            // moves; but a nested span from an earlier start may still
            // be "open" at this byte, so we can't strictly monotone
            // the walk without an active-set. Compromise: keep the
            // early-exit on `s > byte` (spans past cursor stop the
            // walk), and start each byte's walk from
            // `span_scan_idx` (spans that end at-or-before us are
            // permanently done). Preserves correctness; amortized
            // ~O(1) per byte on non-nested spans.
            while span_scan_idx < ordered.len() && ordered[span_scan_idx].1 <= byte {
                span_scan_idx += 1;
            }
            let mut winning_color = None;
            for (s, e, color) in &ordered[span_scan_idx..] {
                if *s > byte {
                    break;
                }
                if byte >= *s && byte < *e {
                    winning_color = Some(*color);
                }
            }
            match winning_color {
                Some(c) => Style::default().fg(c).bg(t.bg_dark),
                None => base_style,
            }
        };
        if !first && style != run_style {
            out.push(Span::styled(std::mem::take(&mut run), run_style));
        }
        run.push(ch);
        run_style = style;
        first = false;
        byte += ch_bytes;
    }
    if !run.is_empty() {
        out.push(Span::styled(run, run_style));
    }
    Line::from(out)
}

/// `+ <label>` action row — matches the "+ New note" / "+ New session"
/// / "+ New request" chip idiom used across the activity-bar panels
/// (Notes, Sessions, HTTP). Green fg + BOLD reads as "additive
/// affordance" everywhere in the app. Extracted so Params / Vars /
/// Auth-set rows all read the same. (#11)
/// Which HTTP-tab is calling `render_kv_table` — controls `EditField`
/// registration and the hover-key lookup for the row-highlight.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KvTableKind {
    Params,
    Headers,
    /// #23 v3 — env var table (Vars tab). Rows come from the
    /// active .env file; commits write back through
    /// `write_env_var` / `http_delete_env_key`.
    Vars,
}

/// Excel-cell key/value table shared by the Params and Headers tabs.
///
/// Renders top border → header row → data rows (each with row
/// separator) → optional draft row → bottom border → `+ Add row`
/// chip (when no draft) or a hint line (when drafting).
///
/// Registers click rects into `params_rows_local` for:
/// - data rows — full row width, keyed on the row's name (click
///   anywhere on the row → delete).
/// - `+ Add row` — full area width, empty-string key.
/// - `✓` draft cell — 3 cells, `"\0COMMIT"` sentinel key.
///
/// Sentinels start with `\0` because HTTP header names + URL query
/// keys forbid the null byte, so no user data can collide with the
/// prefix. Was `__NAME:` / `__VAL:` etc. — a legitimately named
/// `__COMMIT__` header would have collided.
///
/// The `key_color_default` param lets Params (fg-BOLD) and Headers
/// (cyan-BOLD) render their key columns in their preferred color
/// without duplicating the rest of the 180-line render.
#[allow(clippy::too_many_arguments)]
pub(crate) fn render_kv_table(
    rows: &mut Vec<Line<'static>>,
    fields: &mut Vec<(Rect, PaneId, EditField)>,
    area: Rect,
    t: theme::Theme,
    dim: Style,
    data: &[(String, String)],
    draft: Option<&crate::request_pane::InlineKvDraft>,
    kv_edit: Option<&crate::request_pane::KvValueEdit>,
    kind: KvTableKind,
    hover_key: Option<&str>,
    pane_id: PaneId,
    // When `false`, the whole-row EditField click rect is skipped so
    // clicks on the secondary side of a split-edit view don't
    // silently steal keyboard focus into a buffer that isn't
    // visually focused. Fix 2026-07-07 (code-reviewer follow-up).
    // Primary side always passes `true`.
    focused: bool,
    params_rows_local: &mut Vec<(Rect, String, KvTableKind)>,
    // When `Some`, `{{VAR}}` tokens inside VALUE cells render in
    // env-resolved cyan / unresolved red instead of the plain value
    // style, and each token's click rect is pushed onto `var_clicks`
    // (using row-index y — the caller translates to screen y like it
    // does for the other rect vecs). None ⇒ old plain rendering.
    envset: Option<&crate::http::template::EnvSet>,
    var_clicks: Option<&mut Vec<(Rect, String)>>,
) {
    const TABLE_MAX_W: u16 = 100;
    const TABLE_RIGHT_PAD: u16 = 3;
    let _table_x = area.x.saturating_add(2);
    let table_w = area
        .width
        .saturating_sub(2)
        .saturating_sub(TABLE_RIGHT_PAD)
        .clamp(20, TABLE_MAX_W);
    let x_col_w: u16 = 3;
    let inner_w = table_w.saturating_sub(x_col_w).saturating_sub(4);
    let name_w = (inner_w * 35 / 100).max(8);
    let value_w = inner_w.saturating_sub(name_w);

    // Field the row's fallback click focuses. Params rows map to
    // `Url` because query params live in the URL — a click that
    // misses the cell-level rects lands on the URL field, which
    // is the natural edit target for anything param-related.
    let edit_field = match kind {
        KvTableKind::Params => EditField::Url,
        KvTableKind::Headers => EditField::Headers,
        // Vars rows are file-backed; there's no in-pane edit
        // field. Fall back to Url so the tab-cycle stays valid
        // (any click that misses cell rects doesn't panic).
        KvTableKind::Vars => EditField::Url,
    };
    let register = |fields: &mut Vec<(Rect, PaneId, EditField)>, row_y: u16| {
        if !focused {
            return;
        }
        fields.push((
            Rect {
                x: area.x,
                y: row_y,
                width: area.width,
                height: 1,
            },
            pane_id,
            edit_field,
        ));
    };

    let make_border = |left: char, sep: char, right: char, fill: char| -> Line<'static> {
        let n_seg: String = std::iter::repeat_n(fill, (name_w + 2) as usize).collect();
        let v_seg: String = std::iter::repeat_n(fill, (value_w + 2) as usize).collect();
        let x_seg: String = std::iter::repeat_n(fill, x_col_w as usize).collect();
        Line::from(vec![
            Span::styled("  ", Style::default().bg(t.bg_dark)),
            Span::styled(
                format!("{}{}{}{}{}{}{}", left, n_seg, sep, v_seg, sep, x_seg, right),
                Style::default().fg(t.bg3).bg(t.bg_dark),
            ),
        ])
    };
    // Shared border cell + row assembler. `value_spans` covers the
    // value column only (already truncated + not padded); the assembler
    // adds the trailing padding to fill `value_w`. Value-column width
    // (in cells) is derived from the spans' `.content` char count so
    // vars-highlighted callers can pass multiple spans without messing
    // up the layout.
    let assemble_row = |key_text: String,
                        key_style: Style,
                        value_spans: Vec<Span<'static>>,
                        x_glyph: &str,
                        x_style: Style|
     -> Line<'static> {
        let mut key_s = key_text;
        if key_s.chars().count() > name_w as usize {
            let truncated: String = key_s.chars().take(name_w as usize).collect();
            key_s = truncated;
        }
        let pad_k = (name_w as usize).saturating_sub(key_s.chars().count());
        let value_cells: usize = value_spans.iter().map(|s| s.content.chars().count()).sum();
        let pad_v = (value_w as usize).saturating_sub(value_cells);
        let border = Span::styled("", Style::default().fg(t.bg3).bg(t.bg_dark));
        let mut spans = vec![
            Span::styled("  ", Style::default().bg(t.bg_dark)),
            border.clone(),
            Span::styled(" ", Style::default().bg(t.bg_dark)),
            Span::styled(key_s, key_style),
            Span::styled(" ".repeat(pad_k), Style::default().bg(t.bg_dark)),
            Span::styled(" ", Style::default().bg(t.bg_dark)),
            border.clone(),
            Span::styled(" ", Style::default().bg(t.bg_dark)),
        ];
        spans.extend(value_spans);
        spans.extend(vec![
            Span::styled(" ".repeat(pad_v), Style::default().bg(t.bg_dark)),
            Span::styled(" ", Style::default().bg(t.bg_dark)),
            border.clone(),
            Span::styled(x_glyph.to_string(), x_style),
            border,
        ]);
        Line::from(spans)
    };
    // Back-compat wrapper: builds a single-span value + delegates to
    // `assemble_row`. Used by all callers that don't participate in
    // var-highlighting (header row, draft rows, non-data pieces).
    let make_row = |key_text: String,
                    val_text: String,
                    key_style: Style,
                    val_style: Style,
                    x_glyph: &str,
                    x_style: Style|
     -> Line<'static> {
        let mut val_s = val_text;
        if val_s.chars().count() > value_w as usize {
            let truncated: String = val_s.chars().take(value_w as usize).collect();
            val_s = truncated;
        }
        assemble_row(
            key_text,
            key_style,
            vec![Span::styled(val_s, val_style)],
            x_glyph,
            x_style,
        )
    };
    let key_color_default = match kind {
        KvTableKind::Params => t.fg,
        KvTableKind::Headers => t.cyan,
        KvTableKind::Vars => t.cyan,
    };

    // Top border + header + header separator.
    rows.push(make_border('', '', '', ''));
    let hdr_style = Style::default()
        .fg(t.comment)
        .bg(t.bg_dark)
        .add_modifier(Modifier::BOLD);
    rows.push(make_row(
        "Name".to_string(),
        "Value".to_string(),
        hdr_style,
        hdr_style,
        "   ",
        Style::default().bg(t.bg_dark),
    ));
    rows.push(make_border('', '', '', ''));

    // Data rows.
    // Check whether this table's active kv_edit targets a row we're
    // about to render — matched by (kind, original_key).
    let edit_target = kv_edit.filter(|e| {
        matches!(
            (kind, e.kind),
            (KvTableKind::Params, crate::request_pane::KvEditKind::Params)
                | (
                    KvTableKind::Headers,
                    crate::request_pane::KvEditKind::Headers
                )
                | (KvTableKind::Vars, crate::request_pane::KvEditKind::Vars)
        )
    });
    // Column offsets used to build cell-level click rects.
    // Row layout (from x = area.x): 2 pad + 1 border + 1 space +
    // name_w + 1 pad + 1 space + 1 border + 1 space + value_w +
    // 1 pad + 1 space + 1 border + 3 X + 1 border
    let name_col_x_off: u16 = 2 + 1 + 1;
    let value_col_x_off: u16 = 2 + 1 + 1 + name_w + 1 + 1 + 1;
    let x_col_x_off: u16 = value_col_x_off + value_w + 1 + 1 + 1;
    // Var-highlighting styles reused across all data rows in this
    // table. Cyan+bold for resolved, red+bold for unresolved — same
    // treatment used by the URL box.
    let var_resolved_style = Style::default()
        .fg(t.cyan)
        .bg(t.bg_dark)
        .add_modifier(Modifier::BOLD);
    let var_unresolved_style = Style::default()
        .fg(t.red)
        .bg(t.bg_dark)
        .add_modifier(Modifier::BOLD);
    // Single-owner mutable ref for click accumulation. Wrapped so the
    // per-row closures below can push through it without cloning.
    let mut click_out_wrap = var_clicks;
    for (i, (k, v)) in data.iter().enumerate() {
        let is_hover = hover_key == Some(k.as_str());
        let row_is_editing = edit_target.map(|e| e.original_key == *k).unwrap_or(false);
        let editing_name = row_is_editing && edit_target.map(|e| e.editing_name).unwrap_or(false);
        let editing_value = row_is_editing && !editing_name;
        let name_display = if editing_name {
            format!("{}", edit_target.unwrap().buffer)
        } else {
            k.clone()
        };
        let key_style = if editing_name {
            Style::default()
                .fg(t.yellow)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD)
        } else if is_hover {
            Style::default()
                .fg(t.cyan)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
                .fg(key_color_default)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD)
        };
        let val_display = if editing_value {
            format!("{}", edit_target.unwrap().buffer)
        } else {
            v.clone()
        };
        let val_style = if editing_value {
            Style::default()
                .fg(t.yellow)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(t.fg).bg(t.bg_dark)
        };
        let x_style = Style::default().fg(t.red).bg(t.bg_dark);
        let row_y = rows.len() as u16;
        // Build the value cell's spans. When var-highlighting is
        // active (Params / Headers with an envset), split the value on
        // `{{VAR}}` tokens and colorize each; register click rects at
        // the value-cell x offset in row-index coords (the caller
        // translates y to screen).
        let use_vars = !editing_value && envset.is_some();
        let value_spans: Vec<Span<'static>> = if use_vars {
            let mut truncated = val_display.clone();
            if truncated.chars().count() > value_w as usize {
                let clipped: String = truncated.chars().take(value_w as usize).collect();
                truncated = clipped;
            }
            let plain_style = val_style;
            let click_target = click_out_wrap.as_deref_mut();
            build_var_spans(
                &truncated,
                envset.unwrap(),
                plain_style,
                var_resolved_style,
                var_unresolved_style,
                area.x.saturating_add(value_col_x_off),
                row_y,
                click_target,
            )
        } else {
            let mut truncated = val_display.clone();
            if truncated.chars().count() > value_w as usize {
                let clipped: String = truncated.chars().take(value_w as usize).collect();
                truncated = clipped;
            }
            vec![Span::styled(truncated, val_style)]
        };
        rows.push(assemble_row(
            name_display,
            key_style,
            value_spans,
            "",
            x_style,
        ));
        // Cell-level click rects: name cell → rename edit,
        // value cell → value edit, X cell → delete. Each carries the
        // KvTableKind so the click handler routes to the right
        // params/headers/vars path even when this table renders on
        // the SECONDARY side of a side-by-side edit split (fix
        // 2026-07-07 — was: click handler read rp.edit_tab which
        // reflected the primary side only, misrouting secondary
        // Headers clicks to Params).
        params_rows_local.push((
            Rect {
                x: area.x.saturating_add(name_col_x_off),
                y: row_y,
                width: name_w,
                height: 1,
            },
            format!("\0NAME{k}"),
            kind,
        ));
        params_rows_local.push((
            Rect {
                x: area.x.saturating_add(value_col_x_off),
                y: row_y,
                width: value_w,
                height: 1,
            },
            format!("\0VAL{k}"),
            kind,
        ));
        params_rows_local.push((
            Rect {
                x: area.x.saturating_add(x_col_x_off),
                y: row_y,
                width: 3,
                height: 1,
            },
            format!("\0DEL{k}"),
            kind,
        ));
        register(fields, row_y);
        if i + 1 < data.len() || draft.is_some() {
            rows.push(make_border('', '', '', ''));
        }
    }

    // Draft row.
    if let Some(draft) = draft {
        let key_display = if draft.key.is_empty() && !draft.on_value {
            "".to_string()
        } else if draft.key.is_empty() {
            "(name)".to_string()
        } else if !draft.on_value {
            format!("{}", draft.key)
        } else {
            draft.key.clone()
        };
        let val_display = if draft.value.is_empty() && draft.on_value {
            "".to_string()
        } else if draft.value.is_empty() {
            "(value)".to_string()
        } else if draft.on_value {
            format!("{}", draft.value)
        } else {
            draft.value.clone()
        };
        let key_style = if draft.on_value {
            Style::default().fg(t.comment).bg(t.bg_dark)
        } else {
            Style::default()
                .fg(t.yellow)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD)
        };
        let val_style = if draft.on_value {
            Style::default()
                .fg(t.yellow)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(t.comment).bg(t.bg_dark)
        };
        let draft_y = rows.len() as u16;
        let ready = !draft.key.trim().is_empty() && !draft.value.trim().is_empty();
        let check_color = if ready { t.green } else { t.comment };
        rows.push(make_row(
            key_display,
            val_display,
            key_style,
            val_style,
            "",
            Style::default()
                .fg(check_color)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        ));
        // ✓ cell sits in the same X column as the data-row ✕ cell.
        // Reuse `x_col_x_off` — the earlier hand-computed offset
        // was 2 cells too far left, so the visible ✓ hit dead
        // space and clicks 2 columns to its left fired commit.
        let check_rect = Rect {
            x: area.x.saturating_add(x_col_x_off),
            y: draft_y,
            width: 3,
            height: 1,
        };
        params_rows_local.push((check_rect, "\0COMMIT".to_string(), kind));
    }
    rows.push(make_border('', '', '', ''));

    // `+ Add row` chip (idle) or hint line (drafting).
    if draft.is_none() {
        let add_y = rows.len() as u16;
        rows.push(add_action_row("Add row", t));
        params_rows_local.push((
            Rect {
                x: area.x,
                y: add_y,
                width: area.width,
                height: 1,
            },
            String::new(),
            kind,
        ));
        register(fields, add_y);
    } else {
        let hint_y = rows.len() as u16;
        rows.push(Line::from(vec![Span::styled(
            "    (Tab · `:`  ·  Enter → add + new row  ·  Shift+Enter → done  ·  Esc → cancel)"
                .to_string(),
            dim,
        )]));
        register(fields, hint_y);
    }
}

fn add_action_row(label: &str, t: theme::Theme) -> Line<'static> {
    Line::from(vec![
        Span::styled("  ", Style::default().bg(t.bg_dark)),
        Span::styled(
            format!("+ {label}"),
            Style::default()
                .fg(t.green)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        ),
    ])
}

pub fn draw(
    frame: &mut Frame,
    app: &mut App,
    pane_id: PaneId,
    area: Rect,
    focused: bool,
) -> Option<(u16, u16)> {
    if area.width == 0 || area.height == 0 {
        return None;
    }
    let t = theme::cur();
    // Backfill so any negative-space cells within `area` render the
    // pane's own bg color, matching the previous impl.
    frame.render_widget(
        Paragraph::new("").style(Style::default().bg(t.bg_dark)),
        area,
    );
    // Detach the click-target registries so the draw fns below can push
    // into them while `rp` is borrowed from `app.panes`. Restored at
    // the bottom (and at the early-return below).
    let mut fields = std::mem::take(&mut app.rects.request_fields);
    let Some(Pane::Request(rp)) = app.panes.get_mut(pane_id) else {
        app.rects.request_fields = fields;
        return None;
    };

    // ── caret position to return.
    //
    // Two sources can set it:
    //   * `draw_url_box` writes ABSOLUTE screen coords for the URL
    //     field's caret. Goes into `caret_abs`.
    //   * `draw_edit` writes a ROW-INDEX y (0-based within the
    //     tabs_rect content area) for Body/Headers/etc. fields.
    //     Goes into `caret` and is translated later.
    //
    // Splitting the two slots avoids the earlier ambiguity where
    // `y < edit_h` was used as a discriminator — URL box `inner.y`
    // is an absolute screen coord that can numerically land in the
    // row-index range (`0..edit_h`), which caused the URL caret to
    // be re-translated and end up in empty space below Body.
    let mut caret: Option<(u16, u16)> = None;
    let mut caret_abs: Option<(u16, u16)> = None;

    // Edit-tab chip rects — collected with `y` = row index within the
    // Request zone, translated to a screen-y after we know that
    // zone's inner rect.
    let mut edit_tabs_local: Vec<(Rect, PaneId, crate::request_pane::EditTab)> = Vec::new();
    app.rects
        .request_edit_tabs
        .retain(|(_, p, _)| *p != pane_id);

    let show_ws = app.config.ui.show_whitespace;
    let workspace = app.workspace.clone();
    let env_override = app.http_env_override.clone();
    // Env resolution used to colorize `{{VAR}}` tokens (cyan when
    // resolved, red when missing) + build click rects for
    // jump-to-definition. Computed once per frame so tokenize_vars
    // doesn't re-load the env file for every span.
    // mouse-round-7 SEV-2 2026-07-11 — use the config-default variant
    // so a workspace TOML `[http] default_env = "dev"` populates the
    // envset even without `MNML_ENV` or `--env dev`. Was: URL tokens
    // rendered "not defined" while the Vars panel (which reads the
    // file directly with a "dev" fallback) showed them resolved.
    let envset = crate::http::template::EnvSet::select_with_config_default(
        &workspace,
        env_override.as_deref(),
        app.config.http.default_env.as_deref(),
    );
    let mut var_click_rects: Vec<(Rect, String)> = Vec::new();
    let mut vars_rows_local: Vec<(Rect, String, KvTableKind)> = Vec::new();
    let mut params_rows_local: Vec<(Rect, String, KvTableKind)> = Vec::new();
    let mut auth_rows_local: Vec<(Rect, String)> = Vec::new();

    // ── Layout: full-width top strip (Method / URL / Send / Save /
    // Clear) above two content zones (Request-tabs + Response) and
    // a pinned AI strip at the bottom. Bruno-style — the URL bar
    // spans the WHOLE pane width regardless of split orientation,
    // instead of being squeezed into the Request block's left
    // panel when Horizontal is selected.
    //
    // Row breakdown:
    //   top_bar (3 rows) — Method / URL / Send / Save / Clear
    //   Request + Response — split by orientation:
    //     Vertical  : Request top ~55%, Response bottom ~45%
    //     Horizontal: Request left ~50%, Response right ~50%
    //   ai (3 rows, always full width, always at the bottom)
    // Top pad: a blank row above the Method/URL top bar. Cheap
    // separation between the pane's tab strip and the URL row —
    // the top bar looked squashed against the tab strip without it.
    let top_pad = if area.height >= 8 { 1u16 } else { 0u16 };
    let top_bar_height = 3u16.min(area.height.saturating_sub(top_pad));
    let ai_height = 3u16.min(
        area.height
            .saturating_sub(top_pad)
            .saturating_sub(top_bar_height),
    );
    let middle_h = area
        .height
        .saturating_sub(top_pad)
        .saturating_sub(top_bar_height)
        .saturating_sub(ai_height);
    let top_bar_rect = Rect {
        x: area.x,
        y: area.y.saturating_add(top_pad),
        width: area.width,
        height: top_bar_height,
    };
    let ai_rect = Rect {
        x: area.x,
        y: area
            .y
            .saturating_add(top_pad)
            .saturating_add(top_bar_height)
            .saturating_add(middle_h),
        width: area.width,
        height: ai_height,
    };
    // Resolve `Auto` against the pane width — narrow panes stack
    // (Vertical), wide panes go side-by-side (Horizontal). 2026-07-07.
    let resolved_orient = rp.split_orientation.resolve(area.width);
    let (request_rect, response_rect) = match resolved_orient {
        crate::request_pane::SplitOrientation::Auto => unreachable!(),
        crate::request_pane::SplitOrientation::Vertical => {
            // #polish 2026-07-06 — even 50/50 split. Was 55/45
            // biased toward Request; user reported Request looked
            // taller than Response and wanted a centered
            // division. `middle_h / 2` puts the divider on the
            // exact center row; any odd remainder goes to the
            // Response half (matches horizontal split's rounding
            // behavior for consistency).
            let req_h = (middle_h / 2).max(6.min(middle_h));
            let res_h = middle_h.saturating_sub(req_h);
            (
                Rect {
                    x: area.x,
                    y: area
                        .y
                        .saturating_add(top_pad)
                        .saturating_add(top_bar_height),
                    width: area.width,
                    height: req_h,
                },
                Rect {
                    x: area.x,
                    y: area
                        .y
                        .saturating_add(top_pad)
                        .saturating_add(top_bar_height)
                        .saturating_add(req_h),
                    width: area.width,
                    height: res_h,
                },
            )
        }
        crate::request_pane::SplitOrientation::Horizontal => {
            let req_w = area.width / 2;
            let res_w = area.width.saturating_sub(req_w);
            (
                Rect {
                    x: area.x,
                    y: area
                        .y
                        .saturating_add(top_pad)
                        .saturating_add(top_bar_height),
                    width: req_w,
                    height: middle_h,
                },
                Rect {
                    x: area.x.saturating_add(req_w),
                    y: area
                        .y
                        .saturating_add(top_pad)
                        .saturating_add(top_bar_height),
                    width: res_w,
                    height: middle_h,
                },
            )
        }
    };

    // ── Zone 1: Request ─────────────────────────────────────────
    // Fully-connected border — no "Request" title text on the top
    // border since the sub-panels (Method, URL, Send, Clear) label
    // themselves. Split-orientation chip still floats on the right.
    // ── Top bar (full width): Method / URL / Send / Save / Clear.
    // Painted OUTSIDE the Request block so the URL bar spans the
    // whole pane in both split orientations. The split-orientation
    // toggle chip floats on the top-right of the top bar (was on
    // the Request block's border in the earlier layout).
    const METHOD_BOX_WIDTH: u16 = 14;
    const MIN_URL_WIDTH: u16 = 20;
    const METHOD_URL_ROW_H: u16 = 3;
    // 2026-07-05: was `1` — the Method box's left border was
    // painted 1 cell right of the Request block's outer corner,
    // so the vertical rule from the block below didn't line up
    // with anything in the top bar. Zero the pad so the top-bar
    // boxes edge-to-edge match the block below. Right edge
    // (Code box) inherits the same treatment.
    const EDGE_PAD: u16 = 0;
    const SEND_BOX_WIDTH: u16 = 10;
    const SAVE_BOX_WIDTH: u16 = 10;
    const CLEAR_BOX_WIDTH: u16 = 11;
    // 2026-07-21 — was 12 (fit " </> Code "), now 16 so
    // " </> Copy as… " renders in full instead of being
    // truncated to " </> Copy" by the paint_box helper.
    const CODE_BOX_WIDTH: u16 = 16;
    // Env chip — sits between URL and Send. Fixed 14 cells so a
    // short env name (`staging`, `dev`, `prod`) fits with the
    // leading `env: ` label + trailing `▾` chevron.
    const ENV_BOX_WIDTH: u16 = 14;
    // Progressive degradation across three width tiers so the URL bar
    // NEVER disappears entirely (SEV-1 fix 2026-07-07):
    //   Full   (>=91): Method + URL + Env + Send + Save + Clear + Code
    //   Medium (>=44): Method + URL + Send                (drop Env / Save / Clear / Code — palette still runs them)
    //   Small  (>=34): Method + URL only
    //   None   (<34):  nothing (rare — under 34 cells means the pane
    //                  is too narrow for anything meaningful)
    // On any width below Full the missing chips are one palette command
    // away; the mandatory URL bar + Send-in-Medium give mouse users a
    // way to compose + fire a request at 120-col terminals with the
    // default tree_width = 30.
    let full_width_needed = METHOD_BOX_WIDTH
        + MIN_URL_WIDTH
        + ENV_BOX_WIDTH
        + SEND_BOX_WIDTH
        + SAVE_BOX_WIDTH
        + CLEAR_BOX_WIDTH
        + CODE_BOX_WIDTH
        + 2 * EDGE_PAD;
    let medium_width_needed = METHOD_BOX_WIDTH + MIN_URL_WIDTH + SEND_BOX_WIDTH + 2 * EDGE_PAD;
    let small_width_needed = METHOD_BOX_WIDTH + MIN_URL_WIDTH + 2 * EDGE_PAD;
    #[derive(Copy, Clone, PartialEq, Eq)]
    enum TopBarTier {
        Full,
        Medium,
        Small,
        None,
    }
    let tier = if top_bar_rect.height < METHOD_URL_ROW_H {
        TopBarTier::None
    } else if top_bar_rect.width >= full_width_needed {
        TopBarTier::Full
    } else if top_bar_rect.width >= medium_width_needed {
        TopBarTier::Medium
    } else if top_bar_rect.width >= small_width_needed {
        TopBarTier::Small
    } else {
        TopBarTier::None
    };
    let show_sub_panels = tier == TopBarTier::Full;

    let mut method_url_absolute: Vec<(Rect, EditField)> = Vec::new();
    let mut send_button_rect: Option<Rect> = None;
    let mut save_button_rect: Option<Rect> = None;
    let mut clear_button_rect: Option<Rect> = None;
    let mut code_button_rect: Option<Rect> = None;
    let mut env_button_rect: Option<Rect> = None;
    if show_sub_panels {
        // Layout across the top strip:
        //   [pad][Method][URL][Env][Send][Save][Clear][Code][pad]
        let row_y = top_bar_rect.y;
        let method_rect = Rect {
            x: top_bar_rect.x.saturating_add(EDGE_PAD),
            y: row_y,
            width: METHOD_BOX_WIDTH,
            height: METHOD_URL_ROW_H,
        };
        let url_x = method_rect.x.saturating_add(METHOD_BOX_WIDTH);
        let url_width = top_bar_rect
            .width
            .saturating_sub(EDGE_PAD)
            .saturating_sub(METHOD_BOX_WIDTH)
            .saturating_sub(ENV_BOX_WIDTH)
            .saturating_sub(SEND_BOX_WIDTH)
            .saturating_sub(SAVE_BOX_WIDTH)
            .saturating_sub(CLEAR_BOX_WIDTH)
            .saturating_sub(CODE_BOX_WIDTH)
            .saturating_sub(EDGE_PAD);
        let url_rect = Rect {
            x: url_x,
            y: row_y,
            width: url_width,
            height: METHOD_URL_ROW_H,
        };
        let env_rect = Rect {
            x: url_x.saturating_add(url_width),
            y: row_y,
            width: ENV_BOX_WIDTH,
            height: METHOD_URL_ROW_H,
        };
        let send_rect = Rect {
            x: env_rect.x.saturating_add(ENV_BOX_WIDTH),
            y: row_y,
            width: SEND_BOX_WIDTH,
            height: METHOD_URL_ROW_H,
        };
        let save_rect = Rect {
            x: send_rect.x.saturating_add(SEND_BOX_WIDTH),
            y: row_y,
            width: SAVE_BOX_WIDTH,
            height: METHOD_URL_ROW_H,
        };
        let clear_rect = Rect {
            x: save_rect.x.saturating_add(SAVE_BOX_WIDTH),
            y: row_y,
            width: CLEAR_BOX_WIDTH,
            height: METHOD_URL_ROW_H,
        };
        let code_rect = Rect {
            x: clear_rect.x.saturating_add(CLEAR_BOX_WIDTH),
            y: row_y,
            width: CODE_BOX_WIDTH,
            height: METHOD_URL_ROW_H,
        };
        if let Some(mr) = draw_method_box(frame, rp, method_rect, focused, t) {
            method_url_absolute.push((mr, EditField::Method));
            app.rects.request_method_button = Some(mr);
        }
        if let Some(ur) = draw_url_box(
            frame,
            rp,
            url_rect,
            focused,
            &mut caret_abs,
            t,
            &envset,
            &mut var_click_rects,
        ) {
            method_url_absolute.push((ur, EditField::Url));
        }
        env_button_rect = draw_env_box(
            frame,
            env_rect,
            &workspace,
            env_override.as_deref(),
            &rp.request.url,
            t,
        );
        send_button_rect = draw_send_box(frame, rp, send_rect, t);
        save_button_rect = draw_save_box(frame, rp, save_rect, t);
        clear_button_rect = draw_clear_box(frame, clear_rect, t);
        code_button_rect = draw_code_box(frame, code_rect, t);
    } else if matches!(tier, TopBarTier::Medium | TopBarTier::Small) {
        // Compact fallback — Method + URL always render; Send is
        // included in Medium tier. Env / Save / Clear / Code drop off
        // (still available via `:http.*` palette commands).
        let row_y = top_bar_rect.y;
        let method_rect = Rect {
            x: top_bar_rect.x.saturating_add(EDGE_PAD),
            y: row_y,
            width: METHOD_BOX_WIDTH,
            height: METHOD_URL_ROW_H,
        };
        let tail_reserve = if tier == TopBarTier::Medium {
            SEND_BOX_WIDTH
        } else {
            0
        };
        let url_x = method_rect.x.saturating_add(METHOD_BOX_WIDTH);
        let url_width = top_bar_rect
            .width
            .saturating_sub(EDGE_PAD)
            .saturating_sub(METHOD_BOX_WIDTH)
            .saturating_sub(tail_reserve)
            .saturating_sub(EDGE_PAD);
        let url_rect = Rect {
            x: url_x,
            y: row_y,
            width: url_width,
            height: METHOD_URL_ROW_H,
        };
        if let Some(mr) = draw_method_box(frame, rp, method_rect, focused, t) {
            method_url_absolute.push((mr, EditField::Method));
            app.rects.request_method_button = Some(mr);
        }
        if let Some(ur) = draw_url_box(
            frame,
            rp,
            url_rect,
            focused,
            &mut caret_abs,
            t,
            &envset,
            &mut var_click_rects,
        ) {
            method_url_absolute.push((ur, EditField::Url));
        }
        if tier == TopBarTier::Medium {
            let send_rect = Rect {
                x: url_x.saturating_add(url_width),
                y: row_y,
                width: SEND_BOX_WIDTH,
                height: METHOD_URL_ROW_H,
            };
            send_button_rect = draw_send_box(frame, rp, send_rect, t);
        }
    }

    // ── Zone 1: Request (tab strip + tab content). Method/URL now
    // live in the top bar above; the Request block is just the
    // edit form for the currently-selected tab.
    let request_block = crate::ui::design_tokens::bordered_plain("");
    let request_inner = request_block.inner(request_rect);
    frame.render_widget(request_block, request_rect);
    // Split-orientation chip floats on the top-right of the Request
    // block's top border row (NOT the top bar — the top bar's
    // right end now hosts the Code chip and would collide). The
    // Request block's border row is a stable painted row we can
    // safely overwrite the rightmost few cells of.
    app.rects.request_split_toggle =
        paint_split_toggle_chip(frame, rp.split_orientation, request_rect, t);
    // The `⇔` chip that toggles a side-by-side edit split. Placed
    // to the LEFT of the split-orientation chip so both chrome chips
    // hug the right end of the Request block's border row.
    app.rects.request_edit_split_chip = paint_edit_split_chip(
        frame,
        rp.edit_tab_split.is_some(),
        request_rect,
        app.rects.request_split_toggle,
        t,
    );

    let tabs_rect = request_inner;
    let mut edit_tabs_split_local: Vec<(Rect, PaneId, crate::request_pane::EditTab)> = Vec::new();
    // Var-click rects collected inside the primary side's draw_edit
    // (row-index y); translated to screen y in the section below the
    // `if tabs_rect.width > 0` block.
    let mut var_clicks_primary: Vec<(Rect, String)> = Vec::new();

    if tabs_rect.width > 0 && tabs_rect.height > 0 {
        let split_secondary = rp.edit_tab_split;
        // Slice tabs_rect into (left, divider, right) when a split
        // is active. Below the minimum width the split degrades to
        // primary-only so cells don't collide.
        let (left_rect, divider_rect, right_rect) = if let Some(_secondary) = split_secondary {
            const MIN_SIDE: u16 = 24;
            if tabs_rect.width > MIN_SIDE * 2 {
                let ratio = rp.edit_split_ratio.clamp(10, 90) as u32;
                let left_w = ((tabs_rect.width as u32 * ratio) / 100) as u16;
                let left_w = left_w.max(MIN_SIDE).min(tabs_rect.width - MIN_SIDE - 1);
                let left = Rect {
                    x: tabs_rect.x,
                    y: tabs_rect.y,
                    width: left_w,
                    height: tabs_rect.height,
                };
                let divider = Rect {
                    x: tabs_rect.x + left_w,
                    y: tabs_rect.y,
                    width: 1,
                    height: tabs_rect.height,
                };
                let right = Rect {
                    x: tabs_rect.x + left_w + 1,
                    y: tabs_rect.y,
                    width: tabs_rect.width - left_w - 1,
                    height: tabs_rect.height,
                };
                (left, Some(divider), Some(right))
            } else {
                (tabs_rect, None, None)
            }
        } else {
            (tabs_rect, None, None)
        };

        // Primary side (left when split, or whole tabs_rect otherwise).
        let mut edit_rows: Vec<Line> = Vec::new();
        draw_edit(
            rp,
            t,
            &mut edit_rows,
            left_rect,
            &mut caret,
            focused,
            pane_id,
            &mut fields,
            &mut edit_tabs_local,
            show_ws,
            &workspace,
            env_override.as_deref(),
            &mut vars_rows_local,
            &mut params_rows_local,
            &mut auth_rows_local,
            &envset,
            &mut var_clicks_primary,
            None,
        );
        let edit_view: Vec<Line> = edit_rows
            .iter()
            .take(left_rect.height as usize)
            .cloned()
            .collect();
        frame.render_widget(
            Paragraph::new(edit_view).style(Style::default().bg(t.bg_dark)),
            left_rect,
        );
        // Format chip (JSON) sits above the primary side only —
        // the secondary side has its own tab strip + content.
        app.rects.request_format_button = paint_body_format_chip(frame, rp, left_rect, t);
        // Regenerate chip sits IMMEDIATELY LEFT of the format chip
        // (same tab-strip row). 2026-07-09 — one-click reroll of
        // dynamic timestamps + UUIDs so users can fire "another
        // order" without hand-editing.
        app.rects.request_regenerate_button =
            paint_body_regenerate_chip(frame, rp, left_rect, t, app.rects.request_format_button);

        // Divider (bg2 vertical bar between the two sides). Draggable.
        if let Some(div_rect) = divider_rect {
            let divider_line = Line::from(Span::styled(
                "\u{2502}".to_string(),
                Style::default().fg(t.bg3).bg(t.bg_dark),
            ));
            let divider_rows: Vec<Line> =
                (0..div_rect.height).map(|_| divider_line.clone()).collect();
            frame.render_widget(
                Paragraph::new(divider_rows).style(Style::default().bg(t.bg_dark)),
                div_rect,
            );
            app.rects.request_edit_split_divider = Some(div_rect);
        }

        // Secondary side.
        if let (Some(secondary), Some(right)) = (split_secondary, right_rect) {
            let mut edit_rows_r: Vec<Line> = Vec::new();
            let mut fields_r: Vec<(Rect, PaneId, EditField)> = Vec::new();
            let mut vars_rows_r: Vec<(Rect, String, KvTableKind)> = Vec::new();
            let mut params_rows_r: Vec<(Rect, String, KvTableKind)> = Vec::new();
            let mut auth_rows_r: Vec<(Rect, String)> = Vec::new();
            let mut var_clicks_r: Vec<(Rect, String)> = Vec::new();
            let mut caret_r: Option<(u16, u16)> = None;
            draw_edit(
                rp,
                t,
                &mut edit_rows_r,
                right,
                &mut caret_r,
                false, // secondary side does not own the caret
                pane_id,
                &mut fields_r,
                &mut edit_tabs_split_local,
                show_ws,
                &workspace,
                env_override.as_deref(),
                &mut vars_rows_r,
                &mut params_rows_r,
                &mut auth_rows_r,
                &envset,
                &mut var_clicks_r,
                Some(secondary),
            );
            let edit_view_r: Vec<Line> = edit_rows_r
                .iter()
                .take(right.height as usize)
                .cloned()
                .collect();
            frame.render_widget(
                Paragraph::new(edit_view_r).style(Style::default().bg(t.bg_dark)),
                right,
            );
            // Secondary side's rects are relative to `right` — translate
            // y with `right.y` as origin.
            let right_h = right.height as usize;
            let right_origin = right.y;
            for (mut r, pid, f) in fields_r.drain(..) {
                let row_off = r.y as usize;
                if row_off >= right_h {
                    continue;
                }
                r.y = right_origin.saturating_add(row_off as u16);
                app.rects.request_fields.push((r, pid, f));
            }
            for (mut r, key, kind) in vars_rows_r.drain(..) {
                let row_off = r.y as usize;
                if row_off >= right_h {
                    continue;
                }
                r.y = right_origin.saturating_add(row_off as u16);
                app.rects.request_vars_rows.push((r, key, kind));
            }
            for (mut r, key, kind) in params_rows_r.drain(..) {
                let row_off = r.y as usize;
                if row_off >= right_h {
                    continue;
                }
                r.y = right_origin.saturating_add(row_off as u16);
                app.rects.request_params_rows.push((r, key, kind));
            }
            for (mut r, id) in auth_rows_r.drain(..) {
                let row_off = r.y as usize;
                if row_off >= right_h {
                    continue;
                }
                r.y = right_origin.saturating_add(row_off as u16);
                app.rects.request_auth_rows.push((r, id));
            }
            for (mut r, name) in var_clicks_r.drain(..) {
                let row_off = r.y as usize;
                if row_off >= right_h {
                    continue;
                }
                r.y = right_origin.saturating_add(row_off as u16);
                app.rects.request_var_click_rects.push((r, name));
            }
        }
    } else {
        app.rects.request_format_button = None;
        app.rects.request_regenerate_button = None;
    }

    // ── Zone 2: Response ─────────────────────────────────────────
    // Bruno-style status chip on the right side of the Response
    // block's top border: "200 OK · 165ms · 263 B" colored per
    // status class (2xx green / 3xx yellow / 4xx orange / 5xx red).
    // Sending / Streaming / Failed states render their own subtle
    // status text; empty pane shows nothing.
    let response_block = {
        // Fully-connected border — no "Response" title text; the
        // sub-tab strip (Body / Headers / Timeline / Tests) is the
        // label. Status chip still floats on the right.
        let mut block = crate::ui::design_tokens::bordered_plain("");
        if let Some(status_line) = response_status_title(rp, t) {
            block = block.title_top(ratatui::text::Line::from(status_line).right_aligned());
        }
        block
    };
    let response_inner = response_block.inner(response_rect);
    frame.render_widget(response_block, response_rect);
    // Response sub-tab strip — Bruno-style: Body / Headers /
    // Timeline / Tests. Two rows tall: row 0 is the labels + type
    // chip, row 1 is the `─` underline bar under the active tab.
    // The actual response content flows below starting at
    // `content_inner`.
    let content_inner = if response_inner.height >= 3 {
        let mut type_chip: Option<Rect> = None;
        let mut copy_chip: Option<Rect> = None;
        let mut wrap_chip: Option<Rect> = None;
        let mut ai_chip: Option<Rect> = None;
        app.rects.request_response_tabs = paint_response_tab_strip(
            frame,
            rp,
            response_inner,
            t,
            &mut type_chip,
            &mut copy_chip,
            &mut wrap_chip,
            &mut ai_chip,
        );
        app.rects.request_response_type_chip = type_chip;
        app.rects.request_response_copy_chip = copy_chip;
        app.rects.request_response_wrap_chip = wrap_chip;
        app.rects.request_response_ai_prompt_chip = ai_chip;
        Rect {
            x: response_inner.x,
            y: response_inner.y.saturating_add(2),
            width: response_inner.width,
            height: response_inner.height.saturating_sub(2),
        }
    } else {
        app.rects.request_response_tabs.clear();
        response_inner
    };
    let mut response_rows: Vec<Line> = Vec::new();
    if content_inner.width > 0 && content_inner.height > 0 {
        // Filter chip lives at the top of the Response content — visible
        // whenever the filter is active OR focused (so users see the
        // "/" hint even before typing). Empty + unfocused = hidden.
        if !rp.filter.is_empty() || rp.filter_focused {
            let hits = compute_filter_hits(rp);
            response_rows.push(filter_row(&rp.filter, rp.filter_focused, hits, t));
        }
        let wrap_width = if rp.body_wrap {
            Some(content_inner.width.saturating_sub(2).max(20))
        } else {
            None
        };
        draw_response(rp, t, &mut response_rows, wrap_width);
        // `rp.scroll` now applies to the Response content area
        // (below the sub-tab strip). Clamp against content length.
        let h = content_inner.height as usize;
        let max_scroll = response_rows
            .len()
            .saturating_sub(h.min(response_rows.len()));
        rp.scroll = rp.scroll.min(max_scroll);
        let scroll = rp.scroll;
        let response_view: Vec<Line> = response_rows.into_iter().skip(scroll).take(h).collect();
        frame.render_widget(
            Paragraph::new(response_view).style(Style::default().bg(t.bg_dark)),
            content_inner,
        );
    }

    // ── Zone 3: AI ─────────────────────────────────────────
    let ai_block = crate::ui::design_tokens::bordered_plain("AI");
    let ai_inner = ai_block.inner(ai_rect);
    frame.render_widget(ai_block, ai_rect);
    if ai_inner.width > 0 && ai_inner.height > 0 {
        let ai_line = Line::from(vec![
            Span::styled(" ", Style::default().bg(t.bg_dark)),
            Span::styled(
                "click here to ask a custom question".to_string(),
                crate::ui::design_tokens::hint_style(),
            ),
            Span::styled(
                "   \u{00B7} `a` quick debug".to_string(),
                Style::default().fg(t.comment).bg(t.bg_dark),
            ),
        ]);
        frame.render_widget(
            Paragraph::new(vec![ai_line]).style(Style::default().bg(t.bg_dark)),
            ai_inner,
        );
        app.rects.request_ai_section = Some(ai_inner);
    } else {
        app.rects.request_ai_section = None;
    }

    // Register the whole pane area for wheel + fallback routing.
    app.rects.editor_panes.push((area, pane_id));
    // Var click rects were collected in absolute screen coords by
    // draw_url_box (and later body renderers). Move them onto the
    // per-frame rects vec so the mouse handler can pick them up.
    app.rects.request_var_click_rects.extend(var_click_rects);

    // ── Rect adjustment: edit_rows rects were collected with y = row
    // index within `edit_rows` (0-based relative to `tabs_rect`).
    // Translate to screen y = tabs_rect.y + row_index, clipped to
    // tabs_rect.height so a click past the visible content doesn't
    // fire. Uses `tabs_rect` (NOT `request_inner`) because that's
    // the area `draw_edit` was passed — using `request_inner.y`
    // would offset every tab-click by METHOD_URL_ROW_H (3 rows)
    // and route Method-box clicks to the tab strip.
    let edit_h = tabs_rect.height as usize;
    let edit_origin_y = tabs_rect.y;
    for (mut r, pid, f) in fields.drain(..) {
        let row_off = r.y as usize;
        if row_off >= edit_h {
            continue;
        }
        r.y = edit_origin_y.saturating_add(row_off as u16);
        app.rects.request_fields.push((r, pid, f));
    }
    // Method + URL sub-panel rects were built with ABSOLUTE
    // screen coords by `draw_method_box` / `draw_url_box`; they
    // don't go through the row-index → screen-y translation.
    for (rect, field) in method_url_absolute.drain(..) {
        app.rects.request_fields.push((rect, pane_id, field));
    }
    app.rects.request_send_button = send_button_rect;
    app.rects.request_save_button = save_button_rect;
    app.rects.request_clear_button = clear_button_rect;
    app.rects.request_code_button = code_button_rect;
    app.rects.request_env_button = env_button_rect;
    // request_format_button is now set inside draw_edit's Body
    // rendering path (right-aligned chip on the top-right of the
    // body area, visible only when the body is JSON).
    for (mut r, pid, tab) in edit_tabs_local.drain(..) {
        let row_off = r.y as usize;
        if row_off >= edit_h {
            continue;
        }
        r.y = edit_origin_y.saturating_add(row_off as u16);
        app.rects.request_edit_tabs.push((r, pid, tab));
    }
    for (mut r, name) in var_clicks_primary.drain(..) {
        let row_off = r.y as usize;
        if row_off >= edit_h {
            continue;
        }
        r.y = edit_origin_y.saturating_add(row_off as u16);
        app.rects.request_var_click_rects.push((r, name));
    }
    // Secondary tab strip — same y-translation shape but pushed into
    // a distinct rect vec so click routing knows which side to update.
    for (mut r, pid, tab) in edit_tabs_split_local.drain(..) {
        let row_off = r.y as usize;
        if row_off >= edit_h {
            continue;
        }
        r.y = edit_origin_y.saturating_add(row_off as u16);
        app.rects.request_edit_tabs_split.push((r, pid, tab));
    }
    // #polish 2026-07-07 (code-reviewer finding) — primary-side drains
    // used to `.clear()` then push, wiping any rects the secondary
    // side of a split-edit view had pushed earlier in this same
    // `draw()` call (secondary drains sit ~200 lines up). Only clear
    // once per render, at the very top of the panel-rects setup in
    // `ui::mod::draw`, so BOTH sides accumulate here.
    for (mut r, key, kind) in vars_rows_local.drain(..) {
        let row_off = r.y as usize;
        if row_off >= edit_h {
            continue;
        }
        r.y = edit_origin_y.saturating_add(row_off as u16);
        app.rects.request_vars_rows.push((r, key, kind));
    }
    for (mut r, key, kind) in params_rows_local.drain(..) {
        let row_off = r.y as usize;
        if row_off >= edit_h {
            continue;
        }
        r.y = edit_origin_y.saturating_add(row_off as u16);
        app.rects.request_params_rows.push((r, key, kind));
    }
    for (mut r, id) in auth_rows_local.drain(..) {
        let row_off = r.y as usize;
        if row_off >= edit_h {
            continue;
        }
        r.y = edit_origin_y.saturating_add(row_off as u16);
        app.rects.request_auth_rows.push((r, id));
    }

    // Caret — two sources can set it:
    //   * `caret_abs` — URL sub-panel's caret in absolute screen
    //     coords (set by `draw_url_box`).
    //   * `caret` — row-index y from `draw_edit` for Body/Headers/
    //     etc. fields (translated below).
    //
    // URL wins when both are set (matches the pane's default focus
    // = URL). Row-index carets get translated against `tabs_rect`.
    if caret_abs.is_some() {
        return caret_abs;
    }
    caret.map(|(x, y)| {
        let y = (y as usize).min(edit_h.saturating_sub(1)) as u16;
        (x, edit_origin_y.saturating_add(y))
    })
}

// Border color override was removed 2026-07-05 — every
// modal_panel(title) now uses the design-token default border
// (t.fg on t.bg_dark), matching the rest of the app's bordered
// panels instead of a per-pane blue-on-focus override.

/// Compute the right-aligned status title for the Response block —
/// Bruno-style "200 OK · 165ms · 263 B" on green (or matching status
/// color). Returns `None` when there's no interesting state to show
/// (fresh pane / placeholder). Sending / Streaming / non-placeholder
/// Failed states each get their own compact title so the user can
/// see the pane's state without reading the body.
fn response_status_title(
    rp: &crate::request_pane::RequestPane,
    t: theme::Theme,
) -> Option<Vec<Span<'static>>> {
    match &rp.state {
        RunState::Sending => Some(vec![Span::styled(
            " \u{27F3} sending\u{2026} ",
            Style::default()
                .fg(t.yellow)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        )]),
        RunState::Streaming(r) => Some(vec![Span::styled(
            format!(" \u{25B6} streaming \u{00B7} {} events ", r.sse_event_count),
            Style::default()
                .fg(t.cyan)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        )]),
        RunState::Failed(e) if is_not_sent_placeholder(e) => None,
        RunState::Failed(_) => Some(vec![Span::styled(
            " \u{2717} failed ",
            Style::default()
                .fg(t.red)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        )]),
        RunState::Done(r) => {
            let status_color = match r.status {
                200..=299 => t.green,
                300..=399 => t.yellow,
                400..=499 => t.orange,
                500..=599 => t.red,
                _ => t.bg3,
            };
            let sep = |t: theme::Theme| {
                Span::styled(" \u{00B7} ", Style::default().fg(t.comment).bg(t.bg_dark))
            };
            Some(vec![
                Span::styled(
                    format!(" {} {} ", r.status, r.status_text),
                    Style::default()
                        .fg(status_color)
                        .bg(t.bg_dark)
                        .add_modifier(Modifier::BOLD),
                ),
                sep(t),
                Span::styled(
                    format!("{}ms", r.elapsed.as_millis()),
                    Style::default().fg(t.comment).bg(t.bg_dark),
                ),
                sep(t),
                Span::styled(
                    format!("{} ", human_bytes(r.body.len())),
                    Style::default().fg(t.comment).bg(t.bg_dark),
                ),
            ])
        }
    }
}

/// Response sub-tab strip — Bruno-style Body / Headers / Timeline
/// / Tests row with an UNDERLINED active tab and plain-fg inactive
/// tabs (no chip bg). A right-aligned `JSON ▼` chip shows the
/// detected response content type. Returns the click rects for
/// each tab.
#[allow(clippy::too_many_arguments)]
fn paint_response_tab_strip(
    frame: &mut Frame,
    rp: &crate::request_pane::RequestPane,
    response_inner: Rect,
    t: theme::Theme,
    type_chip_out: &mut Option<Rect>,
    copy_chip_out: &mut Option<Rect>,
    wrap_chip_out: &mut Option<Rect>,
    ai_chip_out: &mut Option<Rect>,
) -> Vec<(Rect, crate::request_pane::ResponseTab)> {
    *type_chip_out = None;
    *copy_chip_out = None;
    *wrap_chip_out = None;
    *ai_chip_out = None;
    let mut rects = Vec::new();
    if response_inner.width == 0 || response_inner.height < 2 {
        return rects;
    }
    let active = rp.response_tab;
    let label_rect = Rect {
        x: response_inner.x,
        y: response_inner.y,
        width: response_inner.width,
        height: 1,
    };
    let bar_rect = Rect {
        x: response_inner.x,
        y: response_inner.y.saturating_add(1),
        width: response_inner.width,
        height: 1,
    };
    // Response-header count for the "Headers" tab label — matches
    // Bruno's "Headers 24" affordance. Only shown when there's a
    // Done response with headers; otherwise the label stays bare.
    let header_count: Option<usize> = match &rp.state {
        RunState::Done(r) if !r.headers.is_empty() => Some(r.headers.len()),
        _ => None,
    };
    let mut label_spans: Vec<Span> = Vec::new();
    label_spans.push(Span::styled("  ", Style::default().bg(t.bg_dark)));
    let mut bar_spans: Vec<Span> = Vec::new();
    bar_spans.push(Span::styled("  ", Style::default().bg(t.bg_dark)));
    let mut col: u16 = 2;
    for tab in crate::request_pane::ResponseTab::ALL {
        let base = tab.label();
        // Append " N" to the Headers label when we know the count.
        let label = if matches!(tab, crate::request_pane::ResponseTab::Headers)
            && let Some(n) = header_count
        {
            format!("{base} {n}")
        } else {
            base.to_string()
        };
        let is_cur = active == *tab;
        let label_style = if is_cur {
            Style::default()
                .fg(t.fg)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(t.comment).bg(t.bg_dark)
        };
        let chip_w = label.chars().count() as u16;
        label_spans.push(Span::styled(label.clone(), label_style));
        label_spans.push(Span::styled(
            "  ".to_string(),
            Style::default().bg(t.bg_dark),
        ));
        // Underline bar row — `─` under the active tab, blanks
        // under the inactive tabs. The bar renders on the SECOND
        // row of the tab strip so it's visually detached from the
        // label baseline (matches the mockup's
        // `Response\n────────` look).
        // `━` (U+2501, box-drawings-heavy-horizontal) painted in
        // theme yellow so the active-tab indicator pops without
        // being harsh (matches Bruno's brand-color underline
        // treatment while staying inside our theme palette).
        let bar_glyph = if is_cur { "\u{2501}" } else { " " };
        let bar_style = if is_cur {
            Style::default()
                .fg(t.yellow)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().bg(t.bg_dark)
        };
        bar_spans.push(Span::styled(bar_glyph.repeat(chip_w as usize), bar_style));
        bar_spans.push(Span::styled(
            "  ".to_string(),
            Style::default().bg(t.bg_dark),
        ));
        rects.push((
            Rect {
                x: response_inner.x.saturating_add(col),
                y: response_inner.y,
                width: chip_w,
                height: 1,
            },
            *tab,
        ));
        col += chip_w + 2;
    }
    frame.render_widget(
        Paragraph::new(vec![Line::from(label_spans)]).style(Style::default().bg(t.bg_dark)),
        label_rect,
    );
    frame.render_widget(
        Paragraph::new(vec![Line::from(bar_spans)]).style(Style::default().bg(t.bg_dark)),
        bar_rect,
    );
    // Right-aligned content-type chip on the labels row. Reflects
    // the *effective* format (override if set, else auto-detect).
    // Click routes to `http_response_format_prompt` via
    // `App::rects::request_response_type_chip`.
    // Right-aligned chips, laid out from right to left:
    //   type chip ("JSON ▼") — always shown
    //   copy chip ("copy")   — always shown; toasts on empty body
    //   wrap chip ("wrap")   — always shown; on = cyan, off = dim
    //
    // Each chip is painted with a per-slot right-x that tracks how
    // much space the ones to its right already consumed.
    let type_label = effective_response_type_label(rp);
    let type_text = format!(" {type_label} \u{25BC} ");
    let type_w = type_text.chars().count() as u16;
    let copy_text = " copy ".to_string();
    let copy_w = copy_text.chars().count() as u16;
    let wrap_text = " wrap ".to_string();
    let wrap_w = wrap_text.chars().count() as u16;

    let mut right_edge = label_rect
        .x
        .saturating_add(label_rect.width)
        .saturating_sub(1);
    if label_rect.width >= type_w + 2 {
        let chip_x = right_edge.saturating_sub(type_w);
        let chip_rect = Rect {
            x: chip_x,
            y: label_rect.y,
            width: type_w,
            height: 1,
        };
        *type_chip_out = Some(chip_rect);
        frame.render_widget(
            Paragraph::new(vec![Line::from(vec![Span::styled(
                type_text,
                Style::default()
                    .fg(t.cyan)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD),
            )])])
            .style(Style::default().bg(t.bg_dark)),
            chip_rect,
        );
        right_edge = chip_x.saturating_sub(1);
    }
    if right_edge > label_rect.x + copy_w + 2 {
        let chip_x = right_edge.saturating_sub(copy_w);
        let chip_rect = Rect {
            x: chip_x,
            y: label_rect.y,
            width: copy_w,
            height: 1,
        };
        *copy_chip_out = Some(chip_rect);
        frame.render_widget(
            Paragraph::new(vec![Line::from(vec![Span::styled(
                copy_text,
                Style::default().fg(t.comment).bg(t.bg_dark),
            )])])
            .style(Style::default().bg(t.bg_dark)),
            chip_rect,
        );
        right_edge = chip_x.saturating_sub(1);
    }
    if right_edge > label_rect.x + wrap_w + 2 {
        let chip_x = right_edge.saturating_sub(wrap_w);
        let chip_rect = Rect {
            x: chip_x,
            y: label_rect.y,
            width: wrap_w,
            height: 1,
        };
        *wrap_chip_out = Some(chip_rect);
        let wrap_style = if rp.body_wrap {
            Style::default()
                .fg(t.cyan)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(t.comment).bg(t.bg_dark)
        };
        frame.render_widget(
            Paragraph::new(vec![Line::from(vec![Span::styled(wrap_text, wrap_style)])])
                .style(Style::default().bg(t.bg_dark)),
            chip_rect,
        );
        right_edge = chip_x.saturating_sub(1);
    }
    // `⚡ AI` chip — only when the response looks like a failure.
    // 2xx passes hide it (nothing to ask an AI about). Painted to
    // the LEFT of wrap, styled orange to draw the eye. Click →
    // `http.copy_ai_prompt`.
    if is_response_failure(rp) {
        let ai_text = " \u{26A1} AI ".to_string();
        let ai_w = ai_text.chars().count() as u16;
        if right_edge > label_rect.x + ai_w + 2 {
            let chip_x = right_edge.saturating_sub(ai_w);
            let chip_rect = Rect {
                x: chip_x,
                y: label_rect.y,
                width: ai_w,
                height: 1,
            };
            // Cyan rather than orange — design-critic 2026-07-09
            // flagged that orange collides with the 4xx-status
            // color rendered elsewhere on the same row. The chip
            // is an ACTION, not a status readout.
            frame.render_widget(
                Paragraph::new(vec![Line::from(vec![Span::styled(
                    ai_text,
                    Style::default()
                        .fg(t.cyan)
                        .bg(t.bg_dark)
                        .add_modifier(Modifier::BOLD),
                )])])
                .style(Style::default().bg(t.bg_dark)),
                chip_rect,
            );
            *ai_chip_out = Some(chip_rect);
        }
    }
    rects
}

/// Response state that warrants the `⚡ AI` "explain this failure"
/// chip. Mirrors `ai_prompt::build_prompt`'s failure detection so
/// the chip only appears when there's something the prompt can
/// actually surface.
fn is_response_failure(rp: &crate::request_pane::RequestPane) -> bool {
    use crate::http::schema::SchemaStatus;
    use crate::request_pane::RunState;
    match &rp.state {
        RunState::Done(r) => {
            !(200..300).contains(&r.status)
                || r.schema_result
                    .as_ref()
                    .is_some_and(|s| matches!(s.status, SchemaStatus::Invalid))
        }
        RunState::Failed(_) => true,
        _ => false,
    }
}

/// Effective response-type label — override wins over auto-detect.
fn effective_response_type_label(rp: &crate::request_pane::RequestPane) -> String {
    use crate::request_pane::ResponseBodyFormat;
    match rp.response_body_format {
        ResponseBodyFormat::Auto => detect_response_content_type(rp),
        ResponseBodyFormat::Json => "JSON".to_string(),
        ResponseBodyFormat::Xml => "XML".to_string(),
        ResponseBodyFormat::Html => "HTML".to_string(),
        ResponseBodyFormat::Text => "TEXT".to_string(),
    }
}

/// Detect the response body's content type for the sub-tab strip's
/// right-aligned chip. Prefers the `content-type` header when
/// present, falls back to body-shape sniffing. Returns "—" when
/// there's no response.
fn detect_response_content_type(rp: &crate::request_pane::RequestPane) -> String {
    let r = match &rp.state {
        RunState::Done(r) => r,
        RunState::Streaming(r) => r,
        _ => return "\u{2014}".to_string(),
    };
    for (k, v) in &r.headers {
        if k.eq_ignore_ascii_case("content-type") {
            let vlow = v.to_ascii_lowercase();
            if vlow.contains("json") {
                return "JSON".to_string();
            }
            if vlow.contains("html") {
                return "HTML".to_string();
            }
            if vlow.contains("xml") {
                return "XML".to_string();
            }
            if vlow.contains("javascript") || vlow.contains("ecmascript") {
                return "JS".to_string();
            }
            if vlow.contains("css") {
                return "CSS".to_string();
            }
            // api-round-9 SEV-3 2026-07-11 — detect binary media
            // types so the body renderer can show a placeholder
            // instead of raw byte garbage.
            if vlow.starts_with("image/") {
                return "IMAGE".to_string();
            }
            if vlow.starts_with("video/") {
                return "VIDEO".to_string();
            }
            if vlow.starts_with("audio/") {
                return "AUDIO".to_string();
            }
            if vlow.contains("pdf") {
                return "PDF".to_string();
            }
            if vlow.contains("octet-stream")
                || vlow.contains("zip")
                || vlow.contains("gzip")
                || vlow.contains("tar")
                || vlow.contains("protobuf")
                || vlow.contains("msgpack")
            {
                return "BINARY".to_string();
            }
            if vlow.contains("plain") || vlow.contains("text/") {
                return "TEXT".to_string();
            }
        }
    }
    let head = r.body.trim_start();
    match head.chars().next() {
        Some('{') | Some('[') => "JSON".to_string(),
        Some('<') => "XML".to_string(),
        _ => "TEXT".to_string(),
    }
}

/// Split-orientation toggle chip — floats at the top-right of the
/// Request block's border row. Renders `[▥][▤]` where the active
/// orientation is bold-cyan and the other is dim-comment. Click
/// cycles orientation.
fn paint_split_toggle_chip(
    frame: &mut Frame,
    orient: crate::request_pane::SplitOrientation,
    request_rect: Rect,
    t: theme::Theme,
) -> Option<Rect> {
    // Layout: `[▥ ▤]` (5 chars). The old `[ ▥ ▤ ]` (7 chars)
    // rendered with visibly asymmetric inner gutters — `▥` and
    // `▤` have different left/right sidebearings in most Nerd
    // Fonts, so a symmetric space on each side visually collapses
    // one and inflates the other. Pinning the icons directly to
    // the brackets removes the asymmetry.
    // Chip now shows 3 states (auto / ▥ vertical / ▤ horizontal)
    // since SplitOrientation grew an Auto variant that resolves by
    // width. Auto is the default and cycles first: [A ▥ ▤]. 2026-07-07.
    let chip_w: u16 = 7;
    if request_rect.width < chip_w + 4 || request_rect.height == 0 {
        return None;
    }
    let chip_x = request_rect
        .x
        .saturating_add(request_rect.width)
        .saturating_sub(chip_w)
        .saturating_sub(2);
    let chip_rect = Rect {
        x: chip_x,
        y: request_rect.y,
        width: chip_w,
        height: 1,
    };
    let auto_active = matches!(orient, crate::request_pane::SplitOrientation::Auto);
    let vert_active = matches!(orient, crate::request_pane::SplitOrientation::Vertical);
    let horiz_active = matches!(orient, crate::request_pane::SplitOrientation::Horizontal);
    let active_style = Style::default()
        .fg(t.cyan)
        .bg(t.bg_dark)
        .add_modifier(Modifier::BOLD);
    let inactive_style = Style::default().fg(t.comment).bg(t.bg_dark);
    let bracket = Style::default().fg(t.bg3).bg(t.bg_dark);
    let line = Line::from(vec![
        Span::styled("[", bracket),
        Span::styled(
            "A",
            if auto_active {
                active_style
            } else {
                inactive_style
            },
        ),
        Span::styled(" ", Style::default().bg(t.bg_dark)),
        Span::styled(
            "",
            if vert_active {
                active_style
            } else {
                inactive_style
            },
        ),
        Span::styled(" ", Style::default().bg(t.bg_dark)),
        Span::styled(
            "",
            if horiz_active {
                active_style
            } else {
                inactive_style
            },
        ),
        Span::styled("]", bracket),
    ]);
    frame.render_widget(
        Paragraph::new(vec![line]).style(Style::default().bg(t.bg_dark)),
        chip_rect,
    );
    Some(chip_rect)
}

/// The `⇔` chip that opens (or closes) a side-by-side split of the
/// Request pane's Edit content area. Sits on the Request block's
/// top border row, immediately to the LEFT of the split-orientation
/// `[▥ ▤]` chip. Active (split open) = cyan bold; inactive = comment.
/// 2026-07-07.
fn paint_edit_split_chip(
    frame: &mut Frame,
    split_open: bool,
    request_rect: Rect,
    orient_chip: Option<Rect>,
    t: theme::Theme,
) -> Option<Rect> {
    let chip_w: u16 = 3; // `[⇔]`
    let right_edge_x = match orient_chip {
        Some(r) => r.x,
        None => request_rect
            .x
            .saturating_add(request_rect.width)
            .saturating_sub(2),
    };
    if right_edge_x <= request_rect.x + 4 || request_rect.height == 0 {
        return None;
    }
    let chip_x = right_edge_x.saturating_sub(chip_w).saturating_sub(1);
    let chip_rect = Rect {
        x: chip_x,
        y: request_rect.y,
        width: chip_w,
        height: 1,
    };
    let bracket = Style::default().fg(t.bg3).bg(t.bg_dark);
    let icon_style = if split_open {
        Style::default()
            .fg(t.cyan)
            .bg(t.bg_dark)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(t.comment).bg(t.bg_dark)
    };
    let line = Line::from(vec![
        Span::styled("[", bracket),
        Span::styled("\u{21D4}", icon_style),
        Span::styled("]", bracket),
    ]);
    frame.render_widget(
        Paragraph::new(vec![line]).style(Style::default().bg(t.bg_dark)),
        chip_rect,
    );
    Some(chip_rect)
}

/// Body tab's Format chip — floats at the top-right of `tabs_rect`
/// (same row as the tab strip). Rendered only when the current
/// Edit-tab is Body AND the body is detected as JSON. Reads as
/// `[ { } Format ]` on the panel bg, cyan text so it stands out
/// from the tab strip's chips (which use the row-highlight cyan bg).
/// Returns the absolute-coord click rect for the pane-level
/// mouse handler.
fn paint_body_format_chip(
    frame: &mut Frame,
    rp: &crate::request_pane::RequestPane,
    tabs_rect: Rect,
    t: theme::Theme,
) -> Option<Rect> {
    if rp.edit_tab != crate::request_pane::EditTab::Body {
        return None;
    }
    let body = rp.request.body.as_deref().unwrap_or("");
    if !matches!(detect_body_kind(body), Some("JSON")) {
        return None;
    }
    let chip_text = " { } Format ";
    let chip_w = chip_text.chars().count() as u16;
    if tabs_rect.width < chip_w + 2 || tabs_rect.height == 0 {
        return None;
    }
    // Right-aligned on the tab-strip row (row 0 of tabs_rect).
    let chip_x = tabs_rect
        .x
        .saturating_add(tabs_rect.width)
        .saturating_sub(chip_w)
        .saturating_sub(1); // 1-cell right pad
    let chip_y = tabs_rect.y;
    let chip_rect = Rect {
        x: chip_x,
        y: chip_y,
        width: chip_w,
        height: 1,
    };
    let line = Line::from(vec![Span::styled(
        chip_text.to_string(),
        Style::default()
            .fg(t.cyan)
            .bg(t.bg_dark)
            .add_modifier(Modifier::BOLD),
    )]);
    frame.render_widget(
        Paragraph::new(vec![line]).style(Style::default().bg(t.bg_dark)),
        chip_rect,
    );
    Some(chip_rect)
}

/// `↻ Reroll` chip — paints immediately to the LEFT of the format
/// chip (when present) on the Body-tab strip. Click → runs
/// `http.regenerate_body`, which walks the JSON body and refreshes
/// every ISO 8601 timestamp + lowercase UUID with fresh values.
///
/// Suppressed when the Body isn't JSON (matches the format chip's
/// visibility) or when there's no format chip to anchor against
/// on a too-narrow strip.
/// 2026-07-09.
fn paint_body_regenerate_chip(
    frame: &mut Frame,
    rp: &crate::request_pane::RequestPane,
    tabs_rect: Rect,
    t: theme::Theme,
    format_chip: Option<Rect>,
) -> Option<Rect> {
    if rp.edit_tab != crate::request_pane::EditTab::Body {
        return None;
    }
    let body = rp.request.body.as_deref().unwrap_or("");
    if !matches!(detect_body_kind(body), Some("JSON")) {
        return None;
    }
    let chip_text = " \u{21BB} Regenerate ";
    let chip_w = chip_text.chars().count() as u16;
    // Anchor to the format chip's left edge minus 1 cell of gap.
    // When there IS no format chip (narrow strip), fall back to
    // right-aligning on the tabs_rect.
    let (chip_x, chip_y) = if let Some(fc) = format_chip {
        let x = fc.x.saturating_sub(chip_w).saturating_sub(1);
        // Skip painting if it would collide with the tabs_rect
        // left edge — no room.
        if x < tabs_rect.x + 1 {
            return None;
        }
        (x, fc.y)
    } else {
        let x = tabs_rect
            .x
            .saturating_add(tabs_rect.width)
            .saturating_sub(chip_w)
            .saturating_sub(1);
        if x < tabs_rect.x + 1 {
            return None;
        }
        (x, tabs_rect.y)
    };
    let chip_rect = Rect {
        x: chip_x,
        y: chip_y,
        width: chip_w,
        height: 1,
    };
    let line = Line::from(vec![Span::styled(
        chip_text.to_string(),
        Style::default()
            .fg(t.green)
            .bg(t.bg_dark)
            .add_modifier(Modifier::BOLD),
    )]);
    frame.render_widget(
        Paragraph::new(vec![line]).style(Style::default().bg(t.bg_dark)),
        chip_rect,
    );
    Some(chip_rect)
}

/// Save sub-panel — click writes the current fields back to
/// `source_path`. When `source_path` is None, opens a Save-As
/// prompt. Rendered as a bold blue "⎘ Save" label. Dim when
/// the pane has no URL yet (nothing meaningful to save).
fn draw_save_box(
    frame: &mut Frame,
    rp: &crate::request_pane::RequestPane,
    rect: Rect,
    t: theme::Theme,
) -> Option<Rect> {
    let block = crate::ui::design_tokens::bordered_plain("Save");
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    if inner.width == 0 || inner.height == 0 {
        return None;
    }
    let color = if rp.request.url.trim().is_empty() {
        t.comment
    } else {
        t.blue
    };
    let text = " \u{2398} Save ";
    let text_w = text.chars().count() as u16;
    let mid_pad = inner.width.saturating_sub(text_w) / 2;
    let content = Line::from(vec![
        Span::styled(" ".repeat(mid_pad as usize), Style::default().bg(t.bg_dark)),
        Span::styled(
            text.to_string(),
            Style::default()
                .fg(color)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        ),
    ]);
    frame.render_widget(
        Paragraph::new(vec![content]).style(Style::default().bg(t.bg_dark)),
        inner,
    );
    Some(inner)
}

/// Env sub-panel — modal_panel titled "Env" with the active env
/// name + a ▾ chevron so the box reads as a dropdown affordance.
/// Left-click → env picker (`open_http_env_picker`); right-click
/// opens a small context menu. Cyan when a per-pane override is
/// active, dim when no env is available at all, normal fg otherwise.
fn draw_env_box(
    frame: &mut Frame,
    rect: Rect,
    workspace: &std::path::Path,
    env_override: Option<&str>,
    url: &str,
    t: theme::Theme,
) -> Option<Rect> {
    let block = crate::ui::design_tokens::bordered_plain("Env");
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    if inner.width == 0 || inner.height == 0 {
        return None;
    }
    let envset = crate::http::template::EnvSet::select(workspace, env_override);
    // NOTE: this env_button code path stays on the plain `select` — the
    // env-chip label reflects the *runtime override* / MNML_ENV story
    // (what the user has selected), not the config default. The
    // draw_request_view path uses `select_with_config_default` for
    // *var resolution* colouring so a config-default env still resolves
    // `{{VAR}}` tokens as cyan.
    let env_name = envset.name().map(str::to_string);
    let has_override = env_override.is_some();
    // #24 v2 — detect unresolved `{{VAR}}` refs in the URL to
    // decide whether the chip should carry a warning color.
    // Only checks vars against the currently-loaded EnvSet; if
    // ANY referenced var is missing, the chip turns yellow.
    let has_unresolved = has_unresolved_var(url, &envset);
    let (label, color) = match env_name {
        _ if has_unresolved => (env_name.unwrap_or_else(|| "none".to_string()), t.yellow),
        Some(n) if has_override => (n, t.cyan),
        Some(n) => (n, t.fg),
        None => ("none".to_string(), t.comment),
    };
    // Truncate at 6 chars + ellipsis so a long env name stays
    // within the fixed chip width. Room budget: `NAME ▾ ` (7 cells)
    // inside a 14-wide inner (12 minus border).
    let short = if label.chars().count() > 6 {
        let mut s: String = label.chars().take(5).collect();
        s.push('\u{2026}');
        s
    } else {
        label
    };
    let text = format!(" {short} \u{25BE} ");
    let text_w = text.chars().count() as u16;
    let mid_pad = inner.width.saturating_sub(text_w) / 2;
    let content = Line::from(vec![
        Span::styled(" ".repeat(mid_pad as usize), Style::default().bg(t.bg_dark)),
        Span::styled(
            text,
            Style::default()
                .fg(color)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        ),
    ]);
    frame.render_widget(
        Paragraph::new(vec![content]).style(Style::default().bg(t.bg_dark)),
        inner,
    );
    Some(inner)
}

/// #24 v2 — thin wrapper around `template::unresolved` for the
/// env chip's warning-color check. Returns true when the URL
/// references any `{{VAR}}` that's missing from `envset`.
fn has_unresolved_var(text: &str, envset: &crate::http::template::EnvSet) -> bool {
    !crate::http::template::unresolved(text, envset).is_empty()
}

/// One `{{VAR}}` occurrence in a piece of text — used by the URL /
/// body renderers to break the text into styled spans (var vs plain)
/// and to register click rects for jump-to-definition. Bytes are
/// input-relative; the caller offsets them onto the screen.
#[derive(Debug, Clone)]
struct VarToken {
    /// Byte index of the leading `{`.
    start: usize,
    /// Byte index one past the trailing `}`.
    end: usize,
    /// Trimmed variable name (no `{{`/`}}`, no surrounding spaces).
    name: String,
    /// `true` when the name resolves via the active env or as a built-
    /// in dynamic (`$uuid`, `$timestamp`, …); `false` when the name is
    /// present in `{{…}}` form but missing from the env.
    resolved: bool,
}

/// Walk `text` and return every well-formed `{{name}}` occurrence
/// (in source order). Malformed / unclosed tokens are skipped so the
/// renderer never over-eats real text. Runs `resolve` under the hood
/// so the caller gets the resolved/unresolved bit for free.
fn tokenize_vars(text: &str, envset: &crate::http::template::EnvSet) -> Vec<VarToken> {
    let mut out = Vec::new();
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if i + 1 < bytes.len()
            && bytes[i] == b'{'
            && bytes[i + 1] == b'{'
            && let Some(end_off) = text[i + 2..].find("}}")
        {
            let inner_start = i + 2;
            let inner_end = inner_start + end_off;
            let name = text[inner_start..inner_end].trim().to_string();
            if !name.is_empty() {
                // Match the resolve() gate in http::template — dynamics
                // start with `$` and go through dynamic_var; plain names
                // hit the env lookup.
                let resolved = match name.strip_prefix('$') {
                    Some(dyn_name) => crate::http::template::dynamic_var(dyn_name).is_some(),
                    None => envset.lookup(&name).is_some(),
                };
                out.push(VarToken {
                    start: i,
                    end: inner_end + 2,
                    name,
                    resolved,
                });
            }
            i = inner_end + 2;
            continue;
        }
        let c = text[i..].chars().next().unwrap();
        i += c.len_utf8();
    }
    out
}

/// Split `text` into styled spans, coloring `{{VAR}}` tokens per
/// resolved vs unresolved. Non-var runs use `plain`. Also emits one
/// click rect per token when `emit_click` is `Some((base_x, base_y,
/// out_vec))` — `base_x` should include any left-edge padding the
/// caller already added, `base_y` is the row's screen y, and the
/// pushed rects use character offsets from `text.start()`.
///
/// One-line only — this is used by the URL box + a single Body line.
/// Multi-line body text calls this per-line with the correct base_y.
#[allow(clippy::too_many_arguments)]
fn build_var_spans(
    text: &str,
    envset: &crate::http::template::EnvSet,
    plain: Style,
    resolved_style: Style,
    unresolved_style: Style,
    base_x: u16,
    base_y: u16,
    click_out: Option<&mut Vec<(Rect, String)>>,
) -> Vec<Span<'static>> {
    let tokens = tokenize_vars(text, envset);
    if tokens.is_empty() {
        return vec![Span::styled(text.to_string(), plain)];
    }
    let mut spans: Vec<Span<'static>> = Vec::with_capacity(tokens.len() * 2 + 1);
    let mut cur = 0usize;
    // Character-count as we go so we can position click rects by
    // visible column (bytes ≠ cells for multibyte, but URLs and env
    // names are ASCII in practice — chars() handles the rare non-ASCII
    // case correctly enough for click routing).
    let char_x_at = |slice: &str| -> u16 { slice.chars().count() as u16 };
    let clicks = click_out;
    let (mut push_click_rect, has_click): (Box<dyn FnMut(Rect, String)>, bool) = match clicks {
        Some(v) => (Box::new(move |r, n| v.push((r, n))), true),
        None => (Box::new(|_r, _n| {}), false),
    };
    for tok in &tokens {
        if tok.start > cur {
            let leading = &text[cur..tok.start];
            spans.push(Span::styled(leading.to_string(), plain));
        }
        let token_text = &text[tok.start..tok.end];
        let style = if tok.resolved {
            resolved_style
        } else {
            unresolved_style
        };
        spans.push(Span::styled(token_text.to_string(), style));
        if has_click {
            let before = &text[..tok.start];
            let x = base_x + char_x_at(before);
            let width = char_x_at(token_text);
            push_click_rect(
                Rect {
                    x,
                    y: base_y,
                    width,
                    height: 1,
                },
                tok.name.clone(),
            );
        }
        cur = tok.end;
    }
    if cur < text.len() {
        spans.push(Span::styled(text[cur..].to_string(), plain));
    }
    spans
}

/// Clear sub-panel — modal_panel titled "Clear" with a bold red-ish
/// "✕ Clear" label. Click resets the active Request pane's fields
/// (URL, headers, body, method → GET). Same code path as
/// `+ New request` on the sidebar. No y/n prompt — the action is
/// non-destructive vs. the workspace (source_path is preserved
/// only if it exists), and Recent has one-click restore.
fn draw_clear_box(frame: &mut Frame, rect: Rect, t: theme::Theme) -> Option<Rect> {
    let block = crate::ui::design_tokens::bordered_plain("Clear");
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    if inner.width == 0 || inner.height == 0 {
        return None;
    }
    let text = " \u{2715} Clear ";
    let text_w = text.chars().count() as u16;
    let mid_pad = inner.width.saturating_sub(text_w) / 2;
    let content = Line::from(vec![
        Span::styled(" ".repeat(mid_pad as usize), Style::default().bg(t.bg_dark)),
        Span::styled(
            text.to_string(),
            Style::default()
                .fg(t.orange)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        ),
    ]);
    frame.render_widget(
        Paragraph::new(vec![content]).style(Style::default().bg(t.bg_dark)),
        inner,
    );
    Some(inner)
}

/// Code sub-panel — Bruno-style `</>` "Generate Code" button.
/// Click opens a language picker (curl / Python / JS / Go / wget /
/// HTTPie) and copies the rendered snippet to the clipboard.
fn draw_code_box(frame: &mut Frame, rect: Rect, t: theme::Theme) -> Option<Rect> {
    // 2026-07-21 — box label + inner chip both say "Copy as…"
    // instead of "Code" so the copy intent isn't hidden. User:
    // "i was expecting a copy button". Matches HTTPie Desktop.
    let block = crate::ui::design_tokens::bordered_plain("Copy as…");
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    if inner.width == 0 || inner.height == 0 {
        return None;
    }
    let text = " </> Copy as… ";
    let text_w = text.chars().count() as u16;
    let mid_pad = inner.width.saturating_sub(text_w) / 2;
    let content = Line::from(vec![
        Span::styled(" ".repeat(mid_pad as usize), Style::default().bg(t.bg_dark)),
        Span::styled(
            text.to_string(),
            Style::default()
                .fg(t.purple)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        ),
    ]);
    frame.render_widget(
        Paragraph::new(vec![content]).style(Style::default().bg(t.bg_dark)),
        inner,
    );
    Some(inner)
}

/// Send sub-panel — modal_panel titled "Send" with a bold green
/// "▶ Send" label inside. Click routes to the `http.send` palette
/// command via the pane-level mouse handler (via
/// `App::rects::request_send_button`). Returns the absolute-coord
/// click rect for the whole box.
fn draw_send_box(
    frame: &mut Frame,
    rp: &crate::request_pane::RequestPane,
    rect: Rect,
    t: theme::Theme,
) -> Option<Rect> {
    let block = crate::ui::design_tokens::bordered_plain("Send");
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    if inner.width == 0 || inner.height == 0 {
        return None;
    }
    // Sending → the button flips to "⟳ Abort" (yellow) so users
    // have a mouse-reachable cancel affordance. Click during Sending
    // routes to `http.abort` instead of `http.send`. Other states
    // show ▶ Send with per-state color: cyan while Streaming, dim
    // when URL is empty ("not ready"), green when ready to fire.
    // #polish — `⟳` (U+27F3) needs an extra space; ▶ (U+25B6)
    // renders fine with a single space. Encode the gap per glyph.
    let (glyph, gap, label, color) = match &rp.state {
        crate::request_pane::RunState::Sending => ("\u{27F3}", "  ", "Abort", t.yellow),
        crate::request_pane::RunState::Streaming(_) => ("\u{25B6}", " ", "Send", t.cyan),
        _ if rp.request.url.trim().is_empty() => ("\u{25B6}", " ", "Send", t.comment),
        _ => ("\u{25B6}", " ", "Send", t.green),
    };
    let text = format!(" {glyph}{gap}{label} ");
    let text_w = text.chars().count() as u16;
    let mid_pad = inner.width.saturating_sub(text_w) / 2;
    let content = Line::from(vec![
        Span::styled(" ".repeat(mid_pad as usize), Style::default().bg(t.bg_dark)),
        Span::styled(
            text,
            Style::default()
                .fg(color)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        ),
    ]);
    frame.render_widget(
        Paragraph::new(vec![content]).style(Style::default().bg(t.bg_dark)),
        inner,
    );
    Some(inner)
}

/// Method sub-panel — legend-outline modal_panel titled "Method" with
/// the verb rendered as COLORED TEXT (not a colored bg chip) and a
/// trailing `▼` down-arrow so the box reads as a dropdown affordance.
/// Colors follow `method_color` (GET green, POST orange, PUT blue,
/// PATCH cyan, DELETE red, HEAD yellow, OPTIONS purple). Returns the
/// absolute-coord click rect for the whole Method box (the caller
/// registers it directly into `app.rects.request_fields`, skipping
/// the row-index translation loop that the tab-strip rects go
/// through).
fn draw_method_box(
    frame: &mut Frame,
    rp: &crate::request_pane::RequestPane,
    rect: Rect,
    _focused: bool,
    t: theme::Theme,
) -> Option<Rect> {
    let block = crate::ui::design_tokens::bordered_plain("Method");
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    if inner.width == 0 || inner.height == 0 {
        return None;
    }
    let method = rp.request.method.to_uppercase();
    let m_color = method_color(&method, t);
    // Content row: " [ GET ]   ▼ " — verb rendered as a solid
    // colored CHIP (verb color as bg, bg_dark as text color) so it
    // reads as a button. Dropdown arrow dim-comment on right.
    let chip_text = format!(" {method} ");
    let chip_width = chip_text.chars().count() as u16;
    let mid_pad = inner
        .width
        .saturating_sub(1) // leading pad
        .saturating_sub(chip_width)
        .saturating_sub(2); // arrow + trailing pad
    let content = Line::from(vec![
        Span::styled(" ", Style::default().bg(t.bg_dark)),
        Span::styled(
            chip_text,
            Style::default()
                .fg(t.bg_dark)
                .bg(m_color)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(" ".repeat(mid_pad as usize), Style::default().bg(t.bg_dark)),
        Span::styled("\u{25BC}", Style::default().fg(t.comment).bg(t.bg_dark)),
        Span::styled(" ", Style::default().bg(t.bg_dark)),
    ]);
    frame.render_widget(
        Paragraph::new(vec![content]).style(Style::default().bg(t.bg_dark)),
        inner,
    );
    Some(inner)
}

/// URL sub-panel — legend-outline modal_panel titled "URL" spanning
/// the remainder of the row's width. Renders the URL as editable
/// text; when the URL field is focused, positions the terminal caret
/// at the character offset that corresponds to `url_cursor`. Returns
/// the absolute-coord click rect for the URL box.
#[allow(clippy::too_many_arguments)]
fn draw_url_box(
    frame: &mut Frame,
    rp: &crate::request_pane::RequestPane,
    rect: Rect,
    focused: bool,
    caret: &mut Option<(u16, u16)>,
    t: theme::Theme,
    envset: &crate::http::template::EnvSet,
    var_clicks: &mut Vec<(Rect, String)>,
) -> Option<Rect> {
    let block = crate::ui::design_tokens::bordered_plain("URL");
    let inner = block.inner(rect);
    frame.render_widget(block, rect);
    if inner.width == 0 || inner.height == 0 {
        return None;
    }
    let url_text = rp.request.url.clone();
    // Placeholder shown any time the URL is empty — even when the
    // field has focus. Matches HTML input placeholder semantics
    // (Postman/Bruno/Insomnia all keep the hint visible under the
    // caret until the first keystroke). A new Request pane defaults
    // focus to `EditField::Url`, so gating on `!focused` here would
    // hide the hint entirely.
    let content = if url_text.is_empty() {
        Line::from(vec![
            Span::styled(" ", Style::default().bg(t.bg_dark)),
            Span::styled(
                "Enter request URL".to_string(),
                Style::default()
                    .fg(t.comment)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::ITALIC),
            ),
        ])
    } else {
        let plain = Style::default().fg(t.fg).bg(t.bg_dark);
        let resolved = Style::default().fg(t.cyan).bg(t.bg_dark);
        let unresolved = Style::default()
            .fg(t.red)
            .bg(t.bg_dark)
            .add_modifier(Modifier::BOLD);
        let mut spans = vec![Span::styled(" ", Style::default().bg(t.bg_dark))];
        // Collect var-click rects locally so we can clip any that
        // spill past the URL box's right edge — build_var_spans
        // walks character offsets and doesn't know the visible
        // width. When URL text overflows the box (common on long
        // paths), un-clipped rects land under neighbouring chips
        // (Env / Send) and steal right-clicks. SEV-2 fix 2026-07-07.
        let mut url_var_clicks: Vec<(Rect, String)> = Vec::new();
        spans.extend(build_var_spans(
            &url_text,
            envset,
            plain,
            resolved,
            unresolved,
            inner.x + 1,
            inner.y,
            Some(&mut url_var_clicks),
        ));
        let url_right_edge = inner.x.saturating_add(inner.width);
        for (mut r, name) in url_var_clicks {
            // Drop rects entirely past the box; clip rects that
            // straddle the edge.
            if r.x >= url_right_edge {
                continue;
            }
            let max_w = url_right_edge.saturating_sub(r.x);
            if r.width > max_w {
                r.width = max_w;
            }
            var_clicks.push((r, name));
        }
        Line::from(spans)
    };
    frame.render_widget(
        Paragraph::new(vec![content]).style(Style::default().bg(t.bg_dark)),
        inner,
    );
    if focused && rp.focus == EditField::Url {
        let caret_col = 1u16 + url_chars_before_cursor(&url_text, rp.url_cursor) as u16;
        let cx = inner.x + caret_col.min(inner.width.saturating_sub(1));
        *caret = Some((cx, inner.y));
    }
    Some(inner)
}

#[allow(clippy::too_many_arguments)]
fn draw_edit(
    rp: &crate::request_pane::RequestPane,
    t: theme::Theme,
    rows: &mut Vec<Line<'static>>,
    area: Rect,
    caret: &mut Option<(u16, u16)>,
    focused: bool,
    pane_id: PaneId,
    fields: &mut Vec<(Rect, PaneId, EditField)>,
    tabs: &mut Vec<(Rect, PaneId, crate::request_pane::EditTab)>,
    show_ws: bool,
    workspace: &std::path::Path,
    env_override: Option<&str>,
    vars_rows_local: &mut Vec<(Rect, String, KvTableKind)>,
    params_rows_local: &mut Vec<(Rect, String, KvTableKind)>,
    auth_rows_local: &mut Vec<(Rect, String)>,
    // The env set used to resolve `{{VAR}}` tokens in value cells /
    // body / URL. Computed once at the top of `draw()` so per-frame
    // env reloads are minimized.
    envset: &crate::http::template::EnvSet,
    // Var-token click rects for Params / Headers value cells, in
    // row-index y coords — the caller translates to screen y like it
    // does for `params_rows_local`.
    var_clicks_local: &mut Vec<(Rect, String)>,
    // When `Some`, render this tab instead of `rp.edit_tab` — used by
    // the right side of a side-by-side edit split.
    tab_override: Option<crate::request_pane::EditTab>,
) {
    // Stash a click-target rect for the row at `row_idx_in_rows` covering
    // the full pane width (y stays as the *row index*; `draw` translates
    // it to a screen y after applying scroll).
    // Skip field-click registration for the SECONDARY side of a
    // side-by-side edit split — that side is view-and-click-cells-
    // only in v1, so a whole-row click there shouldn't silently
    // redirect keyboard focus into a buffer that isn't visually
    // focused. Fix 2026-07-07 — was: `let _ = focused;` (unused),
    // so both sides pushed identical rects and the mouse handler
    // couldn't tell them apart.
    let register_field =
        |fields: &mut Vec<(Rect, PaneId, EditField)>, row_y: u16, field: EditField| {
            if !focused {
                return;
            }
            fields.push((
                Rect {
                    x: area.x,
                    y: row_y,
                    width: area.width,
                    height: 1,
                },
                pane_id,
                field,
            ));
        };
    let body_style = Style::default().fg(t.fg).bg(t.bg_dark);
    let plain = |s: String, st: Style| Line::from(Span::styled(s, st));
    let dim = Style::default().fg(t.comment).bg(t.bg_dark);
    // `label_style` + `bar_span` closures were used by the old
    // section-header rows (Body / Headers / Params labels above
    // their content). The redundant labels were removed 2026-07-05
    // since the tab strip already labels the active view. The
    // closures are kept commented out here as a note; if a future
    // sub-section header inside a tab needs the focus-bar treatment
    // it can re-introduce them.
    let _ = t;

    // Method + URL rows are drawn by the top-level `draw()` as two
    // side-by-side bordered sub-panels (Method box + URL box) so
    // each has its own legend outline. draw_edit no longer paints
    // that row — the URL caret + method/url click rects are also
    // registered by the top-level. draw_edit picks up from the tab
    // strip.
    let _ = caret;

    // Tab strip (Body / Headers / Params / Auth / Vars / Source).
    // Bruno-style: 2 rows tall — row 0 = labels (active = fg BOLD,
    // inactive = comment fg, no chip bg), row 1 = `━` bar under
    // the active tab. Matches the Response sub-tab strip so both
    // sides read as the same primitive.
    {
        use crate::request_pane::EditTab;
        let label_y = rows.len() as u16;
        let bar_y = label_y + 1;
        let mut label_spans: Vec<Span> = Vec::new();
        let mut bar_spans: Vec<Span> = Vec::new();
        let mut col: u16 = 2;
        label_spans.push(Span::styled("  ", Style::default().bg(t.bg_dark)));
        bar_spans.push(Span::styled("  ", Style::default().bg(t.bg_dark)));
        let strip_tab = tab_override.unwrap_or(rp.edit_tab);
        for tab in EditTab::ALL {
            let label = tab.label();
            let is_cur = strip_tab == *tab;
            let label_style = if is_cur {
                Style::default()
                    .fg(t.fg)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(t.comment).bg(t.bg_dark)
            };
            let chip_w = label.chars().count() as u16;
            label_spans.push(Span::styled(label.to_string(), label_style));
            // 2-cell gap between labels (breathing room for the
            // underline bar).
            label_spans.push(Span::styled(
                "  ".to_string(),
                Style::default().bg(t.bg_dark),
            ));
            // Underline bar row — `━` under active in theme yellow
            // (matches the Response strip), blank under inactive.
            let bar_glyph = if is_cur { "\u{2501}" } else { " " };
            let bar_style = if is_cur {
                Style::default()
                    .fg(t.yellow)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().bg(t.bg_dark)
            };
            bar_spans.push(Span::styled(bar_glyph.repeat(chip_w as usize), bar_style));
            bar_spans.push(Span::styled(
                "  ".to_string(),
                Style::default().bg(t.bg_dark),
            ));
            tabs.push((
                Rect {
                    x: area.x + col,
                    y: label_y,
                    width: chip_w,
                    height: 1,
                },
                pane_id,
                *tab,
            ));
            col += chip_w + 2;
        }
        rows.push(Line::from(label_spans));
        rows.push(Line::from(bar_spans));
        let _ = bar_y;
    }

    // ── Per-tab content ───────────────────────────────────────────────
    let cur_tab = tab_override.unwrap_or(rp.edit_tab);

    if cur_tab == crate::request_pane::EditTab::Headers {
        // Headers tab — Excel-cell table shared with Params
        // (`render_kv_table`). Rows come from parsing
        // `headers_buffer`; the inline draft appends
        // `Name: value\n` on commit + re-parses.
        let headers: Vec<(String, String)> = rp
            .headers_buffer
            .lines()
            .filter_map(|l| {
                let t = l.trim();
                if t.is_empty() || t.starts_with('#') {
                    return None;
                }
                let (k, v) = crate::request_pane::split_header_line(t)?;
                Some((k.trim().to_string(), v.trim().to_string()))
            })
            .collect();
        render_kv_table(
            rows,
            fields,
            area,
            t,
            dim,
            &headers,
            rp.headers_add.as_ref(),
            rp.kv_edit.as_ref(),
            KvTableKind::Headers,
            None,
            pane_id,
            focused,
            params_rows_local,
            Some(envset),
            Some(var_clicks_local),
        );
    } // end Headers tab

    if cur_tab == crate::request_pane::EditTab::Body {
        // Body — no header/label row. The tab strip above already
        // says "Body"; the body content starts at the first line
        // right below it, matching Bruno/Postman's "the body IS
        // the pane" idiom.
        //
        // Format chip lives at the top-right of the body area for
        // JSON bodies — see the block below where we register
        // `request_format_button`.
        let b_focus = rp.focus == EditField::Body;
        let body = rp.request.body.as_deref().unwrap_or("");
        let detected = detect_body_kind(body);
        if body.is_empty() {
            // Empty body: render a numbered "line 1" so the pane
            // reads as a ready-to-type editor (not a status
            // message). Caret sits at column 4 (after the ` 1 `
            // gutter) when Body has focus so typing lands directly
            // on that line.
            let empty_y = rows.len() as u16;
            rows.push(Line::from(vec![
                Span::styled(" 1 ", Style::default().fg(t.comment).bg(t.bg_dark)),
                Span::styled(String::new(), Style::default().bg(t.bg_dark)),
            ]));
            register_field(fields, empty_y, EditField::Body);
            if b_focus && focused && caret.is_none() {
                *caret = Some((area.x + 3, empty_y));
            }
        } else {
            // JSON body: pre-compute tree-sitter colored spans per
            // line so keys/strings/numbers/keywords are colored the
            // same way as the response view's JSON body. Falls back
            // to plain-fg on non-JSON.
            let json_spans: Vec<Vec<crate::highlight::ColoredSpan>> = if detected == Some("JSON") {
                crate::highlight::highlight_lines(body, "json")
            } else {
                Vec::new()
            };
            // Line-number gutter — mirrors the Response body's
            // treatment so both read as "loaded file" views.
            let total_lines = body.lines().count().max(1);
            let gutter_w = total_lines.to_string().len();
            let gutter = |n: usize, t: theme::Theme| {
                Span::styled(
                    format!(" {:>width$} ", n, width = gutter_w),
                    Style::default().fg(t.comment).bg(t.bg_dark),
                )
            };
            // Track a running byte offset so nth_line_start/end are O(1)
            // per row instead of O(n). Was profiled by the render-review
            // 2026-07-10 — the previous impl walked `body` from byte 0 on
            // every iteration, making Body-tab render O(n²) in a JSON
            // body. Doubles cost on the [⇔] edit-split (two body paints
            // per frame). 2026-07-11 perf fix.
            let body_bytes = body.as_bytes();
            let mut line_start_offset: usize = 0;
            for (i, line) in body.lines().enumerate() {
                let row_y = rows.len() as u16;
                let n = i + 1;
                let body_offset_of_line_start = line_start_offset;
                let body_offset_of_line_end = line_start_offset + line.len();
                // Advance past this line's trailing separator. `str::lines()`
                // strips both `\n` and `\r\n`, but `line.len()` returns the
                // length WITHOUT the separator, so we have to consume both
                // bytes on CRLF or the offset drifts by 1 per line —
                // cursor placement then lands on the wrong row for
                // pasted-from-Windows / Postman bodies. code-reviewer
                // catch, 2026-07-11.
                let sep_len = if body_bytes.get(body_offset_of_line_end).copied() == Some(b'\r')
                    && body_bytes.get(body_offset_of_line_end + 1).copied() == Some(b'\n')
                {
                    2
                } else {
                    1
                };
                line_start_offset = body_offset_of_line_end + sep_len;
                // 2026-06-19 — keyboard hunt SEV-3 v2: when
                // [ui] show_whitespace is on, render `\t` as `→` and
                // leading spaces as `·` (matching the editor view) so
                // a user typing Tab in the multi-line Body field
                // actually sees something happen.
                let rendered = if show_ws {
                    line.replace('\t', "")
                } else {
                    line.to_string()
                };
                // JSON gets colored_line_with_vars (tree-sitter colors
                // for keys/strings/numbers, overridden by var styles
                // for `{{VAR}}` tokens); other content types run
                // build_var_spans on the plain body style. Both paths
                // emit click rects for jump-to-definition.
                let resolved_style = Style::default()
                    .fg(t.cyan)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD);
                let unresolved_style = Style::default()
                    .fg(t.red)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD);
                let gutter_prefix_cols = (gutter_w as u16).saturating_add(2);
                let content_line = if let Some(spans) = json_spans.get(i) {
                    let mut inner = colored_line_with_vars(
                        &rendered,
                        spans,
                        t.grey_fg,
                        t,
                        envset,
                        resolved_style,
                        unresolved_style,
                        area.x.saturating_add(gutter_prefix_cols),
                        row_y,
                        Some(var_clicks_local),
                    );
                    inner.spans.insert(0, gutter(n, t));
                    inner
                } else {
                    let plain_style = Style::default().fg(t.grey_fg).bg(t.bg_dark);
                    let mut inner_spans = vec![gutter(n, t)];
                    inner_spans.extend(build_var_spans(
                        &rendered,
                        envset,
                        plain_style,
                        resolved_style,
                        unresolved_style,
                        area.x.saturating_add(gutter_prefix_cols),
                        row_y,
                        Some(var_clicks_local),
                    ));
                    Line::from(inner_spans)
                };
                rows.push(content_line);
                register_field(fields, row_y, EditField::Body);
                if b_focus
                    && focused
                    && caret.is_none()
                    && rp.body_cursor >= body_offset_of_line_start
                    && rp.body_cursor <= body_offset_of_line_end
                {
                    let col_in_line = body
                        [body_offset_of_line_start..rp.body_cursor.min(body.len())]
                        .chars()
                        .count() as u16;
                    let y = (rows.len() - 1) as u16;
                    // Caret sits after the gutter: " NN " = gutter_w + 2 cols.
                    let prefix_cols = (gutter_w as u16).saturating_add(2);
                    *caret = Some((area.x + prefix_cols + col_in_line, y));
                }
            }
            // Trailing newline ⇒ caret on an empty line at the end.
            if b_focus && focused && caret.is_none() && body.ends_with('\n') {
                let y = rows.len() as u16;
                rows.push(plain(String::new(), body_style));
                let prefix_cols = (gutter_w as u16).saturating_add(2);
                *caret = Some((area.x + prefix_cols, y));
            }
        }
    } // end Body tab

    // 2026-06-19 — mouse hunt SEV-2 #5: Params/Vars/Source content
    // rows didn't register click targets, so right-click anywhere
    // in those tabs got no context menu. Register the next-pushed
    // row as `EditField::Url` so the field-aware right-click works
    // (the URL-titled menu has Paste curl + Send + Copy as curl —
    // exactly what a user on the Source tab would want).
    // Same `focused` gate as `register_field` / `render_kv_table`'s
    // `register` — the secondary side of a split-edit view shouldn't
    // push whole-row field rects that redirect keyboard focus into a
    // buffer that isn't visually focused. Fix 2026-07-07.
    let register_tab_row = |fields: &mut Vec<(Rect, PaneId, EditField)>, row_y: u16| {
        if !focused {
            return;
        }
        fields.push((
            Rect {
                x: area.x,
                y: row_y,
                width: area.width,
                height: 1,
            },
            pane_id,
            EditField::Url,
        ));
    };
    // ── Params tab — inline `+ Add` row + clickable existing
    //     params. Click `+ Add` → start an inline key/value draft
    //     row (Tab cycles fields, Enter commits, Esc cancels).
    //     No section label (the tab strip already labels this view).
    if cur_tab == crate::request_pane::EditTab::Params {
        let url = &rp.request.url;
        let params: Vec<(String, String)> = match url.find('?') {
            Some(i) => url[i + 1..]
                .split('&')
                .filter(|s| !s.is_empty())
                .map(|kv| match kv.split_once('=') {
                    Some((k, v)) => (k.to_string(), v.to_string()),
                    None => (kv.to_string(), String::new()),
                })
                .collect(),
            None => Vec::new(),
        };
        render_kv_table(
            rows,
            fields,
            area,
            t,
            dim,
            &params,
            rp.params_add.as_ref(),
            rp.kv_edit.as_ref(),
            KvTableKind::Params,
            rp.hover_params_key.as_deref(),
            pane_id,
            focused,
            params_rows_local,
            Some(envset),
            Some(var_clicks_local),
        );
    }

    // ── Vars tab: read-only list of active env file's KEY=VALUE rows ──
    // ── Auth tab — Postman-style. Shows current Authorization
    //     header + quick-set rows (None / Bearer / Basic / API key /
    //     Apply saved preset). Each row clickable to dispatch the
    //     matching App method. ───
    if cur_tab == crate::request_pane::EditTab::Auth {
        // Detect current auth state from the Authorization header.
        let current = rp
            .request
            .headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("authorization"))
            .map(|(_, v)| v.clone());
        let summary = match current.as_deref() {
            Some(v) if v.starts_with("Bearer ") => {
                format!("Bearer · {}", v[7..].chars().take(20).collect::<String>())
            }
            Some(v) if v.starts_with("Basic ") => "Basic · (base64 user:pass)".to_string(),
            Some(v) if v.len() > 24 => format!("{}", &v[..22]),
            Some(v) => v.to_string(),
            None => "(no Authorization header — request will be unauthenticated)".to_string(),
        };
        let summary_y = rows.len() as u16;
        rows.push(Line::from(vec![
            Span::styled("    Current:  ".to_string(), dim),
            Span::styled(
                summary,
                Style::default()
                    .fg(if current.is_some() { t.cyan } else { t.comment })
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD),
            ),
        ]));
        register_tab_row(fields, summary_y);
        rows.push(plain(String::new(), body_style));

        // Action rows. Icons match the rest of the app's nerd-font
        // vocabulary — `+` for additive actions, `⟳` for refresh
        // (Nerd Font U+27F3), `×` for destructive. No emoji so the
        // Auth section reads consistently with the rest of the pane.
        // Some glyphs (⟳, ⇓, ×) render tight against the following
        // char in Nerd Font / CoreText combos — the ⟳ especially
        // eats its right sidebearing. Encode each row as `(icon,
        // space, label)` so we can bump the gap on those glyphs
        // without unbalancing the `+` rows.
        let actions: &[(&str, &str, &str, char)] = &[
            ("set_bearer", " ", "Set Bearer token…", '+'),
            ("set_basic", " ", "Set Basic auth (user:pass)…", '+'),
            ("set_api_key", " ", "Set X-Api-Key…", '+'),
            ("apply_preset", "  ", "Apply saved preset…", ''),
            ("save_preset", " ", "Save current as preset…", ''),
            ("clear", " ", "Clear Authorization", '×'),
        ];
        for (id, gap, label, icon) in actions {
            let row_y = rows.len() as u16;
            // Color: `clear` red (destructive), `save_preset` green,
            // others normal fg. Matches the app-wide semantic-color
            // convention.
            let base_color = match *id {
                "clear" => t.red,
                "save_preset" => t.green,
                _ => t.fg,
            };
            // Hover highlight — same treatment as Params / Vars.
            // Hovered row keeps its semantic color but paints on the
            // cyan bg so users know which row will fire. (#11 v13)
            let is_hover = rp.hover_auth_id.as_deref() == Some(*id);
            let row_bg = if is_hover { t.cyan } else { t.bg_dark };
            let text_fg = if is_hover { t.bg_dark } else { base_color };
            rows.push(Line::from(vec![
                Span::styled("  ", Style::default().bg(row_bg)),
                Span::styled(
                    format!("{icon}{gap}{label}"),
                    Style::default()
                        .fg(text_fg)
                        .bg(row_bg)
                        .add_modifier(Modifier::BOLD),
                ),
            ]));
            auth_rows_local.push((
                Rect {
                    x: area.x,
                    y: row_y,
                    width: area.width,
                    height: 1,
                },
                id.to_string(),
            ));
            register_tab_row(fields, row_y);
        }
    }

    if cur_tab == crate::request_pane::EditTab::Vars {
        // Read active env's vars. Runtime override wins first; then
        // .rqst → .mnml order with last-wins on same key. Matches
        // EnvSet::load precedence exactly.
        let env_name = crate::http::template::EnvSet::select(workspace, env_override)
            .name()
            .map(str::to_string)
            .unwrap_or_else(|| "dev".to_string());
        let mut by_key: std::collections::BTreeMap<String, String> =
            std::collections::BTreeMap::new();
        for sub in [".rqst", ".mnml"] {
            let path = workspace
                .join(sub)
                .join("env")
                .join(format!("{env_name}.env"));
            if let Ok(text) = std::fs::read_to_string(&path) {
                for line in text.lines() {
                    let trimmed = line.trim_start();
                    if trimmed.is_empty() || trimmed.starts_with('#') {
                        continue;
                    }
                    if let Some((k, v)) = trimmed.split_once('=') {
                        by_key.insert(k.trim().to_string(), v.trim().to_string());
                    }
                }
            }
        }
        // Header line: env name + hint (v3 supports cell inline edit).
        let name_y = rows.len() as u16;
        rows.push(Line::from(vec![
            Span::styled("    env: ", dim),
            Span::styled(
                format!("{env_name}.env"),
                Style::default()
                    .fg(t.cyan)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("   · click cell to edit · Tab commits · Esc cancels", dim),
        ]));
        register_tab_row(fields, name_y);
        rows.push(plain(String::new(), body_style));

        // #23 v3 — Vars now uses the shared render_kv_table helper
        // (same table shape as Params / Headers), with a Vars-scoped
        // KvEditKind so cell edits commit through
        // `App::commit_vars_kv_edit` (writes back to .env). No
        // draft-add row for Vars in v3 — the `+ Add new variable…`
        // action row below still opens the palette prompt.
        let data: Vec<(String, String)> = by_key.into_iter().collect();
        render_kv_table(
            rows,
            fields,
            area,
            t,
            dim,
            &data,
            None, // no draft/add-row support for Vars in v3
            rp.kv_edit.as_ref(),
            KvTableKind::Vars,
            rp.hover_vars_key.as_deref(),
            pane_id,
            focused,
            vars_rows_local,
            None,
            None,
        );
    }

    // ── Source tab: paste/type raw curl / .http source here, run
    //     `:http.paste_source` (Ctrl+Enter) to parse it into the
    //     structured fields. ──
    if cur_tab == crate::request_pane::EditTab::Source {
        let s_focus = rp.focus == EditField::Source;
        let hint_y = rows.len() as u16;
        rows.push(Line::from(vec![Span::styled(
            "    Source — type / paste curl or .http here · :http.paste_source (Ctrl+Enter)"
                .to_string(),
            dim,
        )]));
        register_tab_row(fields, hint_y);
        rows.push(plain(String::new(), body_style));
        let src = &rp.source_buffer;
        let val_style = Style::default().fg(t.fg).bg(t.bg_dark);
        if src.is_empty() {
            let y = rows.len() as u16;
            rows.push(Line::from(vec![Span::styled(
                "    (empty — paste here, or Ctrl+Shift+V to read clipboard)".to_string(),
                dim,
            )]));
            register_tab_row(fields, y);
            // If focused, render caret at left margin so the user
            // sees where their typing will land.
            if s_focus && focused && caret.is_none() {
                let y = (rows.len() - 1) as u16;
                *caret = Some((area.x + 4, y));
            }
        } else {
            // Running byte offset — same O(n²) → O(n) fix as the Body
            // tab above. CRLF-safe (code-reviewer catch 2026-07-11).
            let src_bytes = src.as_bytes();
            let mut src_line_start_offset: usize = 0;
            for line in src.lines() {
                let y = rows.len() as u16;
                register_tab_row(fields, y);
                rows.push(Line::from(vec![Span::styled(
                    format!("    {line}"),
                    val_style,
                )]));
                let start = src_line_start_offset;
                let end = src_line_start_offset + line.len();
                let sep_len = if src_bytes.get(end).copied() == Some(b'\r')
                    && src_bytes.get(end + 1).copied() == Some(b'\n')
                {
                    2
                } else {
                    1
                };
                src_line_start_offset = end + sep_len;
                if s_focus
                    && focused
                    && caret.is_none()
                    && rp.source_cursor >= start
                    && rp.source_cursor <= end
                {
                    let col = src[start..rp.source_cursor.min(src.len())].chars().count() as u16;
                    let yy = (rows.len() - 1) as u16;
                    *caret = Some((area.x + 4 + col, yy));
                }
            }
            if s_focus && focused && caret.is_none() && src.ends_with('\n') {
                let y = rows.len() as u16;
                rows.push(plain(String::new(), body_style));
                *caret = Some((area.x + 4, y));
            }
        }
    }

    // Sending/Streaming/Done indicator (small). Skip entirely
    // when the pane is in the "not yet fired" placeholder state
    // — a red ✗ on a brand new blank request reads as an error
    // when nothing has actually failed. Real transport errors
    // still render red.
    if !matches!(&rp.state, RunState::Failed(e) if is_not_sent_placeholder(e)) {
        rows.push(plain(String::new(), body_style));
    }
    match &rp.state {
        RunState::Sending => rows.push(plain(
            "  ⟳  sending…".to_string(),
            Style::default().fg(t.yellow).bg(t.bg_dark),
        )),
        RunState::Streaming(r) => rows.push(plain(
            format!("  ▶ streaming · {} events received", r.sse_event_count),
            Style::default().fg(t.cyan).bg(t.bg_dark),
        )),
        RunState::Failed(e) if !is_not_sent_placeholder(e) => rows.push(plain(
            format!("  ✗ last send: {e}"),
            Style::default().fg(t.red).bg(t.bg_dark),
        )),
        RunState::Failed(_) => {}
        // 2026-07-21 — Done state suppressed on the request side:
        // the response pane already shows "{status} · {elapsed}ms
        // · {bytes}" in its own header, so echoing "✓ last: 200
        // (228 ms)" under the request body was pure redundancy.
        // User: "why say last: 200 (228ms) if its already on the
        // response pane?"
        RunState::Done(_) => {}
    }
}

/// True when a `Failed(msg)` state is the "not sent yet" placeholder
/// (blank Request pane, before the user fires anything) rather than
/// a real transport / assertion failure. Used by both the Request and
/// Response sections to skip the red ✗ error style on a fresh pane.
fn is_not_sent_placeholder(msg: &str) -> bool {
    msg.contains("not sent")
}

/// Render a byte count as a 2-3 char human string. 999 → 999 B,
/// 1234 → 1.2 KB, 1_234_567 → 1.2 MB.
fn human_bytes(n: usize) -> String {
    const KB: usize = 1024;
    const MB: usize = 1024 * 1024;
    if n < KB {
        format!("{n} B")
    } else if n < MB {
        format!("{:.1} KB", n as f64 / KB as f64)
    } else {
        format!("{:.1} MB", n as f64 / MB as f64)
    }
}

/// Lightweight content-type sniffing for the Body field label
/// hint. Walks at most the first ~512 bytes — runs every frame
/// on the body's leading prefix, so keep it cheap.
fn detect_body_kind(body: &str) -> Option<&'static str> {
    let head = body.trim_start();
    if head.is_empty() {
        return None;
    }
    let sample: String = head.chars().take(256).collect();
    let first = sample.chars().next()?;
    match first {
        '{' | '[' => Some("JSON"),
        '<' => {
            // XML or HTML — close enough; if it starts with `<?xml`
            // or a tag, call it XML.
            Some("XML")
        }
        _ => {
            // Form-encoded: `key=val&key=val` shape, no quotes/braces.
            if sample.contains('=')
                && sample.contains('&')
                && !sample.contains('{')
                && !sample.contains('[')
            {
                Some("form")
            } else {
                Some("text")
            }
        }
    }
}

fn url_chars_before_cursor(text: &str, byte_cursor: usize) -> usize {
    text[..byte_cursor.min(text.len())].chars().count()
}

// `nth_line_start` / `nth_line_end` removed 2026-07-11 — Body-tab
// and Source-tab renderers now maintain a running byte offset in
// their loops. Was O(n) per call inside an O(n) loop → O(n²) per
// paint.

fn draw_response(
    rp: &crate::request_pane::RequestPane,
    t: theme::Theme,
    rows: &mut Vec<Line<'static>>,
    body_wrap_width: Option<u16>,
) {
    let body_style = Style::default().fg(t.fg).bg(t.bg_dark);
    let plain = |s: String, st: Style| Line::from(Span::styled(s, st));

    // The Response zone no longer echoes the request-line (▶ METHOD
    // URL) at the top — the Request zone above already shows that
    // exact info. Duplicating it read as a "here comes another
    // request" line inside what should be a response-only section.
    // Same reasoning skips the request-headers / request-body echo:
    // that content is authoritative in the Request zone's Headers /
    // Body tabs. Keep the `q_lower` filter binding — the
    // response-header render below still uses it.
    let q_lower = rp.filter.trim().to_ascii_lowercase();

    // ── response ──
    match &rp.state {
        RunState::Sending => {
            // Cyan matches the pane's focus family; the animated
            // spinner sits inside a compact chip so it reads as an
            // in-flight indicator, not a static label.
            rows.push(plain(
                "  ⟳  sending…".to_string(),
                Style::default()
                    .fg(t.cyan)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD),
            ));
        }
        RunState::Streaming(r) => {
            // SSE in-flight — show status chip + accumulated body
            // (events appended as they arrive).
            rows.push(plain(
                format!("  ▶ streaming · {} {}", r.status, r.status_text),
                Style::default()
                    .fg(t.cyan)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD),
            ));
            rows.push(plain(String::new(), body_style));
            for l in r.body.lines() {
                rows.push(plain(l.to_string(), body_style));
            }
        }
        RunState::Failed(e) if is_not_sent_placeholder(e) => {
            // Fresh Request pane — nothing has failed yet. Render
            // as a subtle hint on comment fg, no ✗ glyph, so a
            // blank pane doesn't LOOK like an error state.
            rows.push(plain(
                format!("  {e}"),
                Style::default().fg(t.comment).bg(t.bg_dark),
            ));
        }
        RunState::Failed(e) => {
            rows.push(plain(
                format!("{e}"),
                Style::default()
                    .fg(t.red)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD),
            ));
        }
        RunState::Done(r) => {
            // Response sub-tabs (Body / Headers / Timeline / Tests).
            // The sub-tab strip is painted outside this fn; here we
            // branch on `rp.response_tab` to render only the active
            // tab's content.
            use crate::request_pane::ResponseTab;
            match rp.response_tab {
                ResponseTab::Headers => {
                    // Headers tab: full response-header list, filtered.
                    for (k, v) in &r.headers {
                        if header_matches_filter(k, v, &q_lower) {
                            rows.push(header_row(k, v, t));
                        }
                    }
                    return;
                }
                ResponseTab::Timeline => {
                    // Per-phase timing bars. reqwest::blocking only
                    // exposes two natural boundaries — `send()`
                    // returning (DNS + connect + TLS + request-send
                    // + response-headers all bundled as "wait") and
                    // the body-read loop after ("receive"). Render
                    // as horizontal bars scaled to the max of the
                    // two phases so the ratio is obvious at a glance.
                    let wait_ms = r.timing.wait.as_millis() as u64;
                    let recv_ms = r.timing.receive.as_millis() as u64;
                    let total_ms = r.elapsed.as_millis() as u64;
                    let max = wait_ms.max(recv_ms).max(1);
                    const BAR_W: u64 = 40;
                    let make_bar = |ms: u64, color: ratatui::style::Color| {
                        let filled = (ms * BAR_W / max) as usize;
                        Line::from(vec![
                            Span::styled("  ".to_string(), Style::default().bg(t.bg_dark)),
                            Span::styled(
                                "".repeat(filled),
                                Style::default().fg(color).bg(t.bg_dark),
                            ),
                            Span::styled(
                                "".repeat(BAR_W as usize - filled),
                                Style::default().fg(t.bg3).bg(t.bg_dark),
                            ),
                            Span::styled(
                                format!("  {ms} ms"),
                                Style::default().fg(t.comment).bg(t.bg_dark),
                            ),
                        ])
                    };
                    rows.push(Line::from(vec![
                        Span::styled(
                            "  Wait     ".to_string(),
                            Style::default()
                                .fg(t.comment)
                                .bg(t.bg_dark)
                                .add_modifier(Modifier::BOLD),
                        ),
                        Span::styled(
                            "(connect + TLS + send + headers received)".to_string(),
                            Style::default().fg(t.comment).bg(t.bg_dark),
                        ),
                    ]));
                    rows.push(make_bar(wait_ms, t.blue));
                    rows.push(plain(String::new(), body_style));
                    rows.push(Line::from(vec![
                        Span::styled(
                            "  Receive  ".to_string(),
                            Style::default()
                                .fg(t.comment)
                                .bg(t.bg_dark)
                                .add_modifier(Modifier::BOLD),
                        ),
                        Span::styled(
                            "(body read)".to_string(),
                            Style::default().fg(t.comment).bg(t.bg_dark),
                        ),
                    ]));
                    rows.push(make_bar(recv_ms, t.green));
                    rows.push(plain(String::new(), body_style));
                    rows.push(plain(
                        format!("  Total    {total_ms} ms"),
                        Style::default()
                            .fg(t.fg)
                            .bg(t.bg_dark)
                            .add_modifier(Modifier::BOLD),
                    ));
                    return;
                }
                ResponseTab::Tests => {
                    // Tests tab: assertion results (@assert directives
                    // in the .http file).
                    if r.assertions.is_empty() {
                        rows.push(plain(
                            "  (no assertions in this request)".to_string(),
                            Style::default().fg(t.comment).bg(t.bg_dark),
                        ));
                        return;
                    }
                    for a in &r.assertions {
                        if a.passed {
                            rows.push(plain(
                                format!("{}", a.label),
                                Style::default().fg(t.green).bg(t.bg_dark),
                            ));
                        } else {
                            rows.push(plain(
                                format!("{}", a.label),
                                Style::default()
                                    .fg(t.red)
                                    .bg(t.bg_dark)
                                    .add_modifier(Modifier::BOLD),
                            ));
                        }
                    }
                    return;
                }
                ResponseTab::Body => {}
            }
            // Body tab (default) — the pretty JSON body flows below
            // starting fresh at row 0 (no header echo).
            rows.push(plain(String::new(), body_style));
            // api-round-9 SEV-3 2026-07-11 — detect binary media
            // types and render a placeholder instead of raw bytes.
            let ct_lower = r
                .headers
                .iter()
                .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
                .map(|(_, v)| v.to_ascii_lowercase())
                .unwrap_or_default();
            let is_binary_ct = ct_lower.starts_with("image/")
                || ct_lower.starts_with("video/")
                || ct_lower.starts_with("audio/")
                || ct_lower.contains("octet-stream")
                || ct_lower.contains("pdf")
                || ct_lower.contains("zip")
                || ct_lower.contains("gzip")
                || ct_lower.contains("tar")
                || ct_lower.contains("protobuf")
                || ct_lower.contains("msgpack");
            // api-round-14 SEV-2 2026-07-16 — was
            // `body_bytes.len().max(body.len())` which INFLATED
            // binary/non-UTF8 sizes: lossy UTF-8 decoding replaces
            // each invalid byte with U+FFFD (3 bytes in UTF-8),
            // so `body.len() > body_bytes.len()` for non-UTF8
            // data and `max()` picked the wrong side. Raw bytes
            // are always the correct size when present; fall back
            // to `body.len()` only when no raw copy was captured.
            let size = if !r.body_bytes.is_empty() {
                r.body_bytes.len()
            } else {
                r.body.len()
            };
            if is_binary_ct {
                let kind = if ct_lower.starts_with("image/") {
                    "image"
                } else if ct_lower.starts_with("video/") {
                    "video"
                } else if ct_lower.starts_with("audio/") {
                    "audio"
                } else if ct_lower.contains("pdf") {
                    "pdf"
                } else {
                    "binary"
                };
                rows.push(plain(
                    format!(" [binary {kind} · {size} bytes · Ctrl+S to save the raw body]"),
                    body_style,
                ));
                rows.push(plain(
                    format!(" content-type: {}", ct_lower.trim()),
                    body_style,
                ));
                return;
            }
            // api-round-14 SEV-2 2026-07-16 — "TEXT" format ("plain
            // text (no highlight)") used to still call pretty_body
            // unconditionally, which auto-prettifies JSON etc. from
            // the content-type. Users had no way to view the actual
            // raw response bytes. Now: Text short-circuits pretty
            // and shows the body verbatim.
            use crate::request_pane::ResponseBodyFormat;
            let pretty = if matches!(rp.response_body_format, ResponseBodyFormat::Text) {
                r.body.clone()
            } else {
                pretty_body(&r.body, &r.headers)
            };
            // Pick the syntax-highlighter language. Override wins
            // over auto-detect. XML aliases to HTML (same grammar).
            // Text = no highlight.
            let highlight_lang: Option<&'static str> = match rp.response_body_format {
                ResponseBodyFormat::Json => Some("json"),
                ResponseBodyFormat::Xml | ResponseBodyFormat::Html => Some("html"),
                ResponseBodyFormat::Text => None,
                ResponseBodyFormat::Auto => {
                    let ct = r
                        .headers
                        .iter()
                        .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
                        .map(|(_, v)| v.to_ascii_lowercase())
                        .unwrap_or_default();
                    if ct.contains("json") {
                        Some("json")
                    } else if ct.contains("html") || ct.contains("xml") {
                        Some("html")
                    } else {
                        let b = pretty.trim_start();
                        if b.starts_with('{') || b.starts_with('[') {
                            Some("json")
                        } else if b.starts_with('<') {
                            Some("html")
                        } else {
                            None
                        }
                    }
                }
            };
            // Per-line tree-sitter spans. Empty when no highlighter
            // was picked — body renders in the plain body_style then.
            let json_spans: Vec<Vec<crate::highlight::ColoredSpan>> = match highlight_lang {
                Some(lang) => crate::highlight::highlight_lines(&pretty, lang),
                None => Vec::new(),
            };
            let get_spans = |i: usize| -> &[crate::highlight::ColoredSpan] {
                json_spans.get(i).map(|v| v.as_slice()).unwrap_or(&[])
            };
            // Line-number gutter — like the editor's. Width tracks
            // the total-line-count digits so wide files (1000+ lines)
            // don't crowd the body. Rendered on `bg_dark` in
            // `comment` fg — same subdued treatment as the editor.
            let total_lines = pretty.lines().count().max(1);
            let gutter_w = total_lines.to_string().len();
            let gutter = |n: usize, t: theme::Theme| {
                Span::styled(
                    format!(" {:>width$} ", n, width = gutter_w),
                    Style::default().fg(t.comment).bg(t.bg_dark),
                )
            };
            // Optional word-wrap — soft-wraps each line at the pane
            // width so long JSON strings stay visible. `w` in Response
            // view toggles. Wrapped continuation rows show a blank
            // gutter so the number aligns with the FIRST wrapped chunk.
            let wrap_plain =
                |s: &str, out: &mut Vec<Line<'static>>, style: Style, n: usize, t: theme::Theme| {
                    let blank_gutter =
                        Span::styled(" ".repeat(gutter_w + 2), Style::default().bg(t.bg_dark));
                    match body_wrap_width {
                        Some(w) if s.chars().count() > w as usize => {
                            let chars: Vec<char> = s.chars().collect();
                            for (chunk_i, chunk) in chars.chunks(w as usize).enumerate() {
                                let g = if chunk_i == 0 {
                                    gutter(n, t)
                                } else {
                                    blank_gutter.clone()
                                };
                                let text: String = chunk.iter().collect();
                                out.push(Line::from(vec![g, Span::styled(text, style)]));
                            }
                        }
                        _ => out.push(Line::from(vec![
                            gutter(n, t),
                            Span::styled(s.to_string(), style),
                        ])),
                    }
                };
            let with_gutter =
                |mut line: Line<'static>, n: usize, t: theme::Theme| -> Line<'static> {
                    line.spans.insert(0, gutter(n, t));
                    line
                };
            // Body filter — same query as the header filter. A line
            // shows if it contains the query (case-insensitive) OR
            // its neighbors do (±1 for context). Empty filter shows
            // every line. Original line numbers are preserved in the
            // gutter even when non-matching lines are hidden.
            if q_lower.is_empty() {
                for (i, l) in pretty.lines().enumerate() {
                    let n = i + 1;
                    let spans = get_spans(i);
                    if body_wrap_width.is_none() && !spans.is_empty() {
                        rows.push(with_gutter(colored_line(l, spans, t.fg, t), n, t));
                    } else {
                        wrap_plain(l, rows, body_style, n, t);
                    }
                }
            } else {
                let lines: Vec<&str> = pretty.lines().collect();
                let matches: Vec<bool> = lines
                    .iter()
                    .map(|l| l.to_ascii_lowercase().contains(&q_lower))
                    .collect();
                let hits = matches.iter().filter(|m| **m).count();
                for (i, l) in lines.iter().enumerate() {
                    // Show a matching line + its two neighbors on each
                    // side, so JSON context stays readable.
                    let show = matches[i]
                        || (i > 0 && matches[i - 1])
                        || (i > 1 && matches[i - 2])
                        || (i + 1 < matches.len() && matches[i + 1])
                        || (i + 2 < matches.len() && matches[i + 2]);
                    if !show {
                        continue;
                    }
                    let n = i + 1;
                    // Highlight matching lines with a subtle bg tint
                    // so the match itself stands out from its context.
                    // Skip syntax highlighting for matched lines — the
                    // bg2 tint is the visual signal, and mixing tint +
                    // color is noisy.
                    let style = if matches[i] {
                        Style::default().fg(t.fg).bg(t.bg2)
                    } else {
                        body_style
                    };
                    let spans = get_spans(i);
                    if !matches[i] && body_wrap_width.is_none() && !spans.is_empty() {
                        rows.push(with_gutter(colored_line(l, spans, t.fg, t), n, t));
                    } else {
                        wrap_plain(l, rows, style, n, t);
                    }
                }
                if hits == 0 {
                    rows.push(plain(
                        format!("  (no lines match \"{}\")", rp.filter),
                        Style::default()
                            .fg(t.comment)
                            .bg(t.bg_dark)
                            .add_modifier(Modifier::DIM),
                    ));
                }
            }
            if !r.assertions.is_empty() {
                rows.push(plain(String::new(), body_style));
                for a in &r.assertions {
                    if a.passed {
                        rows.push(plain(
                            format!("{}", a.label),
                            Style::default().fg(t.green).bg(t.bg_dark),
                        ));
                    } else {
                        let line = match &a.detail {
                            Some(d) => format!("{}{d}", a.label),
                            None => format!("{}", a.label),
                        };
                        rows.push(plain(line, Style::default().fg(t.red).bg(t.bg_dark)));
                    }
                }
            }
            if !r.captures.is_empty() {
                rows.push(plain(String::new(), body_style));
                for (name, value) in &r.captures {
                    rows.push(Line::from(vec![
                        Span::styled(
                            format!("{name} = "),
                            Style::default().fg(t.cyan).bg(t.bg_dark),
                        ),
                        Span::styled(
                            value.clone(),
                            Style::default()
                                .fg(t.cyan)
                                .bg(t.bg_dark)
                                .add_modifier(Modifier::BOLD),
                        ),
                    ]));
                }
            }
            if let Some(sr) = &r.schema_result {
                rows.push(plain(String::new(), body_style));
                rows.push(schema_footer_line(sr, &t));
            }
        }
    }
}

fn schema_footer_line(
    sr: &crate::http::schema::SchemaResult,
    t: &crate::ui::theme::Theme,
) -> Line<'static> {
    use crate::http::schema::SchemaStatus;
    let sidecar = sr
        .schema_path
        .as_ref()
        .and_then(|p| p.file_name())
        .and_then(|s| s.to_str())
        .unwrap_or("");
    match &sr.status {
        SchemaStatus::Valid => Line::from(vec![Span::styled(
            format!("  ✓ Schema valid ({sidecar})"),
            Style::default()
                .fg(t.green)
                .bg(t.bg_dark)
                .add_modifier(Modifier::BOLD),
        )]),
        SchemaStatus::Invalid => {
            let n = sr.errors.len();
            let plural = if n == 1 { "error" } else { "errors" };
            Line::from(vec![Span::styled(
                format!("  ✗ Schema: {n} {plural} ({sidecar}) — :http.show_schema_errors"),
                Style::default()
                    .fg(t.red)
                    .bg(t.bg_dark)
                    .add_modifier(Modifier::BOLD),
            )])
        }
        SchemaStatus::NoSidecar => Line::from(vec![]),
        SchemaStatus::ReadError(e) => Line::from(vec![Span::styled(
            format!("  ⚠ Schema read error ({sidecar}): {e}"),
            Style::default().fg(t.yellow).bg(t.bg_dark),
        )]),
        SchemaStatus::SchemaParseError(e) => Line::from(vec![Span::styled(
            format!("  ⚠ Schema parse error ({sidecar}): {e}"),
            Style::default().fg(t.yellow).bg(t.bg_dark),
        )]),
        SchemaStatus::NotJson => Line::from(vec![Span::styled(
            format!("  ⚠ Body isn't JSON — schema ({sidecar}) skipped"),
            Style::default().fg(t.yellow).bg(t.bg_dark),
        )]),
    }
}

/// Pretty-print a body if it looks like JSON; otherwise return it as-is.
fn pretty_body(body: &str, headers: &[(String, String)]) -> String {
    let is_json = headers
        .iter()
        .any(|(k, v)| k.eq_ignore_ascii_case("content-type") && v.contains("json"))
        || {
            let b = body.trim_start();
            b.starts_with('{') || b.starts_with('[')
        };
    if is_json
        && let Ok(v) = serde_json::from_str::<serde_json::Value>(body)
        && let Ok(p) = serde_json::to_string_pretty(&v)
    {
        return p;
    }
    body.to_string()
}