paperboy 0.1.2

A Rust TUI API tester
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
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, Borders, Clear, List, ListItem, ListState, Paragraph, WidgetRef, Wrap,
};

use crate::collection::{Collection, WsRow};
use crate::environment::ValueSource;
use crate::hurl::RunStatus;
use crate::i18n::{Language, Strings};
use crate::request;
use crate::tree;

use super::app::*;
use super::editor::*;
use super::git_save::*;
use super::new_request::*;
use super::remote::*;
use super::selection;
use super::theme::*;
use super::wrapcache::{PanelWrap, TextPos};
use std::sync::Arc;

/// Marks a collection/environment title as loaded from git — shown before the
/// name whenever `Collection::git_origin` / `env_git_origin` is set.
pub(crate) const GIT_ICON: &str = "\u{2387}";
/// Joins a collection tab to its linked Global Environment's sub-tab in the
/// tab bar (see `draw_tabs`).
pub(crate) const LINK_ICON: &str = "\u{1F517}";
/// Flags a substituted `{{ VAR }}` in the Request viewer whose Global
/// Environment value is being shadowed by the collection's linked
/// Environment (see `TuiApp::shadowed_env_keys`). Deliberately a plain ASCII
/// glyph rather than a Unicode symbol like ⚠ — several terminals render
/// that one with emoji-style double-cell width even without a variation
/// selector, which visually overlaps the very next character.
pub(crate) const SHADOW_ICON: &str = "!";
/// Marks a subfolder row in the request list tree, and (in the request
/// editor's form) hints that a File-kind field's Value opens a file picker
/// on Enter.
pub(crate) const FOLDER_ICON: &str = "\u{1F4C1}";
/// Chevrons on a Workspace collection file row: expanded (requests inlined)
/// vs collapsed.
const COLLECTION_OPEN_ICON: &str = "\u{25BE}"; //const COLLECTION_CLOSED_ICON: &str = "\u{25B8}"; //
/// A rendered row of the request list, unifying the ordinary title-folder
/// tree ([`tree::Row`]) and the Workspace file-tree ([`WsRow`]) so
/// [`draw_collection_left`] can lay both out with one loop. `Entry.indent`
/// nudges a Workspace request under its collection's file row.
enum LeftRow {
    Up,
    Folder(String),
    Collection { name: String, open: bool },
    Entry { idx: usize, indent: bool },
}

impl LeftRow {
    /// The list rows for tab `col`: the Workspace file-tree when it's bound to
    /// a folder, otherwise the title-folder tree.
    fn build(col: &Collection) -> Vec<LeftRow> {
        if col.is_workspace() {
            col.ws_rows()
                .into_iter()
                .map(|r| match r {
                    WsRow::Up => LeftRow::Up,
                    WsRow::Folder(name) => LeftRow::Folder(name),
                    WsRow::Collection { name, open, .. } => LeftRow::Collection { name, open },
                    WsRow::Request(idx) => LeftRow::Entry { idx, indent: true },
                })
                .collect()
        } else {
            col.rows()
                .into_iter()
                .map(|r| match r {
                    tree::Row::Up => LeftRow::Up,
                    tree::Row::Folder(name) => LeftRow::Folder(name),
                    tree::Row::Entry(idx) => LeftRow::Entry { idx, indent: false },
                })
                .collect()
        }
    }

    /// The entry index if this is a request row (for URL scrolling/substitution).
    fn entry_idx(&self) -> Option<usize> {
        match self {
            LeftRow::Entry { idx, .. } => Some(*idx),
            _ => None,
        }
    }
}

pub(crate) fn panel(title: String, focused: bool, th: &Theme) -> Block<'static> {
    let border = if focused { th.accent } else { th.dim };
    Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(border))
        .title(Span::styled(
            title,
            Style::default().fg(th.text).add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(th.panel))
}

pub(crate) fn centered_rect(width: u16, height: u16, area: Rect) -> Rect {
    let w = width.min(area.width);
    let h = height.min(area.height);
    let x = area.x + (area.width - w) / 2;
    let y = area.y + (area.height - h) / 2;
    Rect::new(x, y, w, h)
}

pub(crate) fn draw(f: &mut Frame, app: &mut TuiApp) {
    let s = Strings::for_language(&app.language);
    let th = theme(&app.language);

    app.refresh_json(app.active_tab);
    app.maybe_auto_open_workspace_picker();

    f.render_widget(Block::default().style(Style::default().bg(th.bg)), f.area());

    let rows = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(3),
        Constraint::Length(3),
        Constraint::Min(3),
        Constraint::Length(1),
    ])
    .split(f.area());

    draw_menu(f, rows[0], app, &s, &th);
    draw_topbar(f, rows[1], app, &s, &th);
    draw_tabs(f, rows[2], app, &s, &th);
    draw_body(f, rows[3], app, &s, &th);
    draw_footer(f, rows[4], &s, &th, app.can_copy());

    // Painted after the panels themselves so it reflects this frame's
    // content (the Main/Response caches used to compute it are refreshed by
    // `draw_collection_main`/`draw_response` inside `draw_body` above).
    paint_selection_highlight(f, app, &th);

    if app.overlay.is_some() {
        draw_overlay(f, app, &s, &th);
    } else {
        app.prompt_editor_area = Rect::default();
    }
}

/// Paint every active text selection region — the active one
/// (`text_selection`) and any additional Alt+Click+Drag regions in
/// `extra_selections` — with a flat, explicit highlight colour (see
/// `Theme::select_bg`/`select_fg`) rather than `Modifier::REVERSED`, so it
/// reads as unambiguously the app's own highlight instead of looking like a
/// terminal's own native (usually plain reverse-video) selection. Each
/// region is confined to its own panel's cached text area/rows, so a
/// highlight can never bleed into a neighbouring panel or the rest of the
/// terminal row.
fn paint_selection_highlight(f: &mut Frame, app: &TuiApp, th: &Theme) {
    if app.text_selection.is_none() && app.extra_selections.is_empty() {
        return;
    }
    let buf = f.buffer_mut();
    let style = Style::default().bg(th.select_bg).fg(th.select_fg);
    for sel in app
        .extra_selections
        .iter()
        .copied()
        .chain(app.text_selection)
    {
        let (area, scroll, wrap) = match sel.pane {
            Pane::Main => (app.main_text_area, app.main_scroll, app.main_wrap.as_ref()),
            Pane::Response => (app.resp_text_area, app.resp_scroll, app.resp_wrap.as_ref()),
            _ => continue,
        };
        let Some(wrap) = wrap else { continue };
        let cells = selection::highlight_cells(sel.anchor, sel.cursor, wrap, area, scroll);
        for (row, from, to) in cells {
            for col in from..to {
                if let Some(cell) = buf.cell_mut((col, row)) {
                    cell.set_style(style);
                }
            }
        }
    }
}

pub(crate) fn draw_menu(f: &mut Frame, area: Rect, app: &TuiApp, s: &Strings, th: &Theme) {
    let base = Style::default().fg(th.accent).add_modifier(Modifier::BOLD);
    let mut spans = vec![Span::raw(" ")];
    spans.extend(mnemonic_spans(s.file_menu_label, base));
    spans.push(Span::raw("   "));
    spans.extend(mnemonic_spans(s.options_menu_label, base));
    if let Some(st) = &app.status {
        spans.push(Span::raw("     "));
        let c = if st.is_ok() { th.ok } else { th.err };
        spans.push(Span::styled(st.text(s), Style::default().fg(c)));
    }
    f.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::default().bg(th.panel)),
        area,
    );
}

pub(crate) fn draw_topbar(f: &mut Frame, area: Rect, app: &TuiApp, s: &Strings, th: &Theme) {
    let lang = match app.language {
        Language::English => s.lang_english,
        Language::French => s.lang_french,
        Language::Danish => s.lang_danish,
    };
    let mut spans = vec![
        Span::styled(
            s.app_heading,
            Style::default().fg(th.accent).add_modifier(Modifier::BOLD),
        ),
        Span::raw("  "),
        Span::styled(format!("[{lang}]"), Style::default().fg(th.dim)),
        Span::raw("   "),
        Span::styled(s.base_url, Style::default().fg(th.text)),
        Span::raw(" "),
        Span::styled(
            app.vars.base_url.clone(),
            Style::default().fg(th.text).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("  (b {})", s.hint_edit_base_url),
            Style::default().fg(th.dim),
        ),
    ];
    // Surface the last runner error (transport failure / failed assert / parse
    // error) here on the status bar so it is never silently swallowed.
    let error = { app.response.lock().unwrap().error.clone() };
    if !error.is_empty() {
        spans.push(Span::styled(
            format!("   {} {error}", s.req_error_prefix),
            Style::default().fg(th.err).add_modifier(Modifier::BOLD),
        ));
    }
    f.render_widget(
        Paragraph::new(Line::from(spans)).block(panel(String::new(), false, th)),
        area,
    );
}

/// Icon prefix shown before a tab's name (in both the tab bar and the
/// Requests-list panel title): the ⎇ git-branch icon if the tab (or, for a
/// Workspace, the folder itself) was loaded from git, the folder icon if
/// it's bound to a Workspace — a git-downloaded Workspace tab shows both,
/// in that order.
fn tab_icons(col: &crate::collection::Collection) -> String {
    let mut icons = String::new();
    if col.git_origin.is_some() || col.workspace_downloaded_from_git {
        icons.push_str(GIT_ICON);
        icons.push(' ');
    }
    if col.workspace_root.is_some() {
        icons.push_str(FOLDER_ICON);
        icons.push(' ');
    }
    icons
}

pub(crate) fn draw_tabs(f: &mut Frame, area: Rect, app: &TuiApp, s: &Strings, th: &Theme) {
    let focused = app.focus == Pane::Tabs;
    let mut spans: Vec<Span> = Vec::new();
    let mk = |label: String, active: bool| -> Span {
        if active {
            Span::styled(
                format!(" {label} "),
                Style::default()
                    .bg(th.accent)
                    .fg(th.bg)
                    .add_modifier(Modifier::BOLD),
            )
        } else {
            Span::styled(format!(" {label} "), Style::default().fg(th.dim))
        }
    };
    for (i, col) in app.collections.iter().enumerate() {
        if i > 0 {
            spans.push(Span::raw(""));
        }
        // The tab's own name is persistent (renameable with F2) and never
        // changes when the user picks a different collection within a
        // Workspace — only the Requests-list panel title below reflects
        // that (see `draw_collection_left`).
        let name = if i == 0 {
            s.tab_request.to_string()
        } else {
            format!("{}{}", tab_icons(col), col.name)
        };
        spans.push(mk(name, app.active_tab == i));
    }
    f.render_widget(
        Paragraph::new(Line::from(spans)).block(panel(s.tabs_heading.to_string(), focused, th)),
        area,
    );
}

pub(crate) fn draw_body(f: &mut Frame, area: Rect, app: &mut TuiApp, s: &Strings, th: &Theme) {
    let cols =
        Layout::horizontal([Constraint::Length(app.list_width), Constraint::Min(10)]).split(area);
    let ci = app.active_tab;
    draw_collection_left(f, cols[0], app, ci, s, th);
    let right = Layout::vertical([Constraint::Min(4), Constraint::Percentage(app.response_pct)])
        .split(cols[1]);
    draw_collection_main(f, right[0], app, ci, s, th);
    draw_response(f, right[1], app, ci, s, th);
}

pub(crate) fn draw_collection_left(
    f: &mut Frame,
    area: Rect,
    app: &TuiApp,
    ci: usize,
    s: &Strings,
    th: &Theme,
) {
    // Use the same split percentage as the right column so the divider between
    // the list and Environment panels lines up with the Main/Response divider
    // (and stays aligned when the response pane is resized with +/-).
    let panes = Layout::vertical([Constraint::Min(3), Constraint::Percentage(app.response_pct)])
        .split(area);

    // Entry list. For an ordinary tab this is the title-folder tree
    // (`col.rows()`); for a Workspace tab it's the real filesystem file-tree
    // with the open collection's requests inlined (`col.ws_rows()`). Both are
    // unified into `LeftRow` so a single loop lays them out — either way
    // deeply nested content stays a flat, scannable list.
    let focused = app.focus == Pane::List;
    let col = &app.collections[ci];
    let view_rows = LeftRow::build(col);
    let sel = col.list_cursor.min(view_rows.len().saturating_sub(1));
    // Classify every `{{ VAR }}` the requests reference so the list URLs can be
    // substituted and colour-coded by whether their value is loaded.
    let env = app.effective_env(ci);
    let smap = crate::request::subst_map(col, env.as_ref());
    // Columns available for the URL text (after the border, highlight symbol,
    // user-added marker and the fixed method column). Recorded so h-scrolling
    // can be clamped to stop once the URL's end is visible (no blank overscroll).
    let url_w = panes[0].width.saturating_sub(2 + 2 + 2 + 5);
    app.list_scroll_w.set(url_w);
    // Scroll is measured against the SUBSTITUTED display length (what's shown).
    // Folder/Up/collection rows have no scrollable URL text.
    let sel_len = view_rows
        .get(sel)
        .and_then(LeftRow::entry_idx)
        .and_then(|idx| col.entries.get(idx))
        .map(|e| crate::request::subst_display(&e.url, &smap).chars().count())
        .unwrap_or(0);
    let max_scroll = sel_len.saturating_sub((url_w as usize).saturating_sub(1));
    let hscroll = (app.list_hscroll as usize).min(max_scroll);
    let items: Vec<ListItem> = view_rows
        .iter()
        .enumerate()
        .map(|(i, row)| match row {
            LeftRow::Up => ListItem::new(Line::from(Span::styled(
                s.list_up_row.to_string(),
                Style::default().fg(th.dim),
            ))),
            LeftRow::Folder(name) => ListItem::new(Line::from(Span::styled(
                format!("{FOLDER_ICON} {name}/"),
                Style::default().fg(th.accent).add_modifier(Modifier::BOLD),
            ))),
            LeftRow::Collection { name, open } => {
                let chevron = if *open {
                    COLLECTION_OPEN_ICON
                } else {
                    COLLECTION_CLOSED_ICON
                };
                ListItem::new(Line::from(Span::styled(
                    format!("{chevron} {name}"),
                    Style::default().fg(th.text).add_modifier(Modifier::BOLD),
                )))
            }
            LeftRow::Entry { idx, indent } => {
                let e = &col.entries[*idx];
                // A plus marks a request the user added by hand (in a real
                // collection); a pencil marks one edited away from its loaded
                // state — matching the environment-panel convention.
                let (marker, marker_fg) = if e.user_added {
                    ("\u{271a} ", th.ok)
                } else if e.modified {
                    ("\u{270e} ", th.accent)
                } else {
                    ("  ", th.text)
                };
                // Workspace request rows are indented one level so they read
                // as children of their collection's file row.
                let mut spans = Vec::new();
                if *indent {
                    spans.push(Span::raw("  "));
                }
                spans.push(Span::styled(marker, Style::default().fg(marker_fg)));
                spans.push(Span::styled(
                    format!("{:<5}", e.method),
                    Style::default()
                        .fg(method_color(&e.method))
                        .add_modifier(Modifier::BOLD),
                ));
                // Pass/fail from the most recent "Run All" (Alt+F5); a
                // dotted marker while a run is still in progress; blank
                // until a batch run has actually covered this entry.
                spans.push(match e.last_run {
                    RunStatus::Passed => Span::styled("\u{2713} ", Style::default().fg(th.ok)),
                    RunStatus::Failed => Span::styled("\u{2717} ", Style::default().fg(th.err)),
                    RunStatus::Running => {
                        Span::styled("\u{2026} ", Style::default().fg(th.pending))
                    }
                    RunStatus::NotRun => Span::raw("  "),
                });
                // The URL, with `{{ VAR }}` substituted + colour-coded by status.
                let mut seen = SubstSeen::default();
                let url_spans = highlight_spans(&e.url, &smap, th, &mut seen, None, None);
                // Horizontally scroll only the selected row so its full (possibly
                // long) URL can be read with ← / →; other rows show from the start.
                // Arrow hints appear on whichever side still has hidden text so
                // it's clear more can be scrolled into view in that direction.
                if i == sel {
                    let avail = url_w as usize;
                    let show_left = hscroll > 0;
                    let content_w_before_right = avail.saturating_sub(show_left as usize);
                    let remaining = sel_len.saturating_sub(hscroll);
                    let show_right = remaining > content_w_before_right;
                    let content_w = content_w_before_right.saturating_sub(show_right as usize);
                    if show_left {
                        spans.push(Span::styled("\u{2039}", Style::default().fg(th.dim))); // ‹ = scrolled
                    }
                    spans.extend(take_display(skip_display(url_spans, hscroll), content_w));
                    if show_right {
                        spans.push(Span::styled("\u{203a}", Style::default().fg(th.dim))); // › = more to the right
                    }
                } else {
                    spans.extend(url_spans);
                }
                ListItem::new(Line::from(spans))
            }
        })
        .collect();
    // A Workspace-bound tab with no collection chosen yet would otherwise
    // just show a blank list — a friendly hint (and `w`'s reminder) is much
    // less confusing than empty panels with no obvious next step.
    let items: Vec<ListItem> =
        if items.is_empty() && col.workspace_root.is_some() && col.path.is_none() {
            vec![ListItem::new(Line::styled(
                s.workspace_empty_state.to_string(),
                Style::default().fg(th.dim),
            ))]
        } else {
            items
        };
    let mut title = if ci == 0 {
        s.tab_request.to_string()
    } else {
        // Unlike the tab bar (which always shows the tab's own, renameable
        // name), a Workspace-bound tab shows whichever collection file is
        // currently loaded here — this is the one name that's expected to
        // change every time the user picks a different collection within
        // the Workspace, without touching the tab's own name.
        let display_name = if col.workspace_root.is_some() {
            col.path
                .as_deref()
                .map(|p| collection_name_from_path(&p.to_string_lossy(), &col.name))
                .unwrap_or_else(|| col.name.clone())
        } else {
            col.name.clone()
        };
        format!("{}{}", tab_icons(col), display_name)
    };
    if col.is_workspace() {
        if !col.workspace_browse.is_empty() {
            title = format!("{title}{}", col.workspace_browse.join(""));
        }
    } else if !col.folder.is_empty() {
        title = format!("{title}{}", col.folder.join(""));
    }
    // A collection linked to a Global Environment shows that environment's
    // name (green, joined by a link icon) in this panel's title bar, so
    // it's visible at a glance which environment its requests will
    // substitute from — the trailing "(v)" hints at the key that opens its
    // full entries popup (works from any pane).
    let mut title_spans = vec![Span::styled(
        title.clone(),
        Style::default().fg(th.text).add_modifier(Modifier::BOLD),
    )];
    let mut title_len = title.chars().count();
    if let Some(env) = col
        .linked_env_id
        .and_then(|id| app.global_envs.iter().find(|e| e.id == id))
    {
        let link_part = format!(" {LINK_ICON} ");
        let env_suffix = " (v)";
        title_len +=
            link_part.chars().count() + env.name.chars().count() + env_suffix.chars().count();
        title_spans.push(Span::styled(link_part, Style::default().fg(th.dim)));
        title_spans.push(Span::styled(
            env.name.clone(),
            Style::default().fg(th.ok).add_modifier(Modifier::BOLD),
        ));
        title_spans.push(Span::styled(env_suffix, Style::default().fg(th.dim)));
    }
    // A brief "w to browse" reminder right in the title bar, next to the
    // folder icon — new users are much more likely to notice it here than
    // in the busier bottom-border hint line below. Only shown when it
    // actually fits without the title overflowing the panel.
    if col.workspace_root.is_some() {
        let workspace_title_hint = format!(" · w {}", s.foot_workspace);
        if title_len + workspace_title_hint.chars().count() < panes[0].width as usize {
            title_spans.push(Span::styled(
                workspace_title_hint,
                Style::default().fg(th.dim),
            ));
        }
    }
    // Run/Run All hints live on this panel's bottom border (rather than the
    // global footer, which was getting overcrowded) since they act on
    // whichever collection is shown here regardless of which pane has focus.
    let run_key = if app.enhanced_keys { "^Enter/F5" } else { "F5" };
    let mut run_hint = format!("{run_key} {} · Alt+F5 {}", s.foot_run, s.foot_run_all);
    // Append the "p" link/unlink-environment hint too, but only when the
    // panel is wide enough to actually show it without the bottom border
    // text overflowing/wrapping onto the panel itself.
    let link_hint = format!(" · p {}", s.foot_env_link);
    if (run_hint.chars().count() + link_hint.chars().count()) < panes[0].width as usize {
        run_hint.push_str(&link_hint);
    }
    // Same treatment for the Workspace-browse hint, shown only on tabs
    // actually bound to a Workspace folder.
    if col.workspace_root.is_some() {
        let workspace_hint = format!(" · w {}", s.foot_workspace);
        if (run_hint.chars().count() + workspace_hint.chars().count()) < panes[0].width as usize {
            run_hint.push_str(&workspace_hint);
        }
    }
    let border = if focused { th.accent } else { th.dim };
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(border))
        .title(Line::from(title_spans))
        .style(Style::default().bg(th.panel))
        .title_bottom(Line::styled(run_hint, Style::default().fg(th.dim)));
    let list = List::new(items)
        .block(block)
        .highlight_style(
            Style::default()
                .bg(th.accent)
                .fg(th.bg)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("");
    let mut st = ListState::default();
    if !view_rows.is_empty() {
        st.select(Some(sel));
    }
    f.render_stateful_widget(list, panes[0], &mut st);

    // Environment panel
    draw_env_panel(f, panes[1], app, s, th);
}

pub(crate) fn draw_env_panel(f: &mut Frame, area: Rect, app: &TuiApp, s: &Strings, th: &Theme) {
    let focused = app.focus == Pane::GlobalEnv;
    // The activate/deactivate hint lives on this panel's bottom border (same
    // convention as the Requests list's Run/Run All hint) since it acts on
    // whichever row is selected here, regardless of which pane has focus.
    let activate_hint = format!("a {}", s.foot_env_activate);
    let block = panel(s.env_heading.to_string(), focused, th)
        .title_bottom(Line::styled(activate_hint, Style::default().fg(th.dim)));
    if app.global_envs.is_empty() {
        let p = Paragraph::new(vec![
            Line::styled(s.env_no_envs.to_string(), Style::default().fg(th.dim)),
            Line::styled(
                format!("{} \u{2192} {}", s.file_menu, s.load_environment),
                Style::default().fg(th.dim),
            ),
        ])
        .block(block)
        .wrap(Wrap { trim: false });
        f.render_widget(p, area);
        return;
    }
    let sel = app
        .global_env_idx
        .min(app.global_envs.len().saturating_sub(1));
    // Columns available for the name text (after the border, highlight
    // symbol and the active-marker column); used to clamp scrolling.
    let text_w = area.width.saturating_sub(2 + 2 + 2);
    app.global_env_scroll_w.set(text_w);
    let sel_len = app
        .global_envs
        .get(sel)
        .map(|e| e.name.chars().count())
        .unwrap_or(0);
    let max_scroll = sel_len.saturating_sub((text_w as usize).saturating_sub(1));
    let hscroll = (app.global_env_hscroll as usize).min(max_scroll);
    let items: Vec<ListItem> = app
        .global_envs
        .iter()
        .enumerate()
        .map(|(i, env)| {
            let is_active = app.active_env_id == Some(env.id);
            // Active: green name + a checkmark marker; git origin shows the
            // same ⎇ icon convention used elsewhere.
            let (marker, marker_fg) = if is_active {
                ("\u{2713} ", th.ok)
            } else {
                ("  ", th.dim)
            };
            let name_color = if is_active { th.ok } else { th.text };
            let selected = i == sel;
            let mark_fg = if selected { th.bg } else { marker_fg };
            let git_prefix = if env.git_origin.is_some() {
                format!("{GIT_ICON} ")
            } else {
                String::new()
            };
            let mut spans = vec![Span::styled(marker, Style::default().fg(mark_fg))];
            let full = format!("{git_prefix}{}", env.name);
            if selected {
                // Same truncate-with-arrow-hints convention as the Requests
                // list / entries popup: scroll the whole name so a very long
                // one can still be read end-to-end.
                let avail = text_w as usize;
                let show_left = hscroll > 0;
                let content_w_before_right = avail.saturating_sub(show_left as usize);
                let remaining = sel_len.saturating_sub(hscroll);
                let show_right = remaining > content_w_before_right;
                let content_w = content_w_before_right.saturating_sub(show_right as usize);
                let visible: String = full.chars().skip(hscroll).take(content_w).collect();
                let mut text = String::new();
                if show_left {
                    text.push('\u{2039}');
                }
                text.push_str(&visible);
                if show_right {
                    text.push('\u{203a}');
                }
                let fg = if selected { th.bg } else { name_color };
                spans.push(Span::styled(text, Style::default().fg(fg)));
            } else {
                spans.push(Span::styled(full, Style::default().fg(name_color)));
            }
            ListItem::new(Line::from(spans))
        })
        .collect();
    let list = List::new(items)
        .block(block)
        .highlight_style(Style::default().bg(th.accent).add_modifier(Modifier::BOLD))
        .highlight_symbol("");
    let mut st = ListState::default();
    st.select(Some(sel));
    f.render_stateful_widget(list, area, &mut st);
}

/// The popup listing one [`crate::environment::Environment`]'s vars (opened
/// via Enter on a Global Environments list row, or 'v' on a linked
/// collection's Tabs entry) — same rendering as the old inline Environment
/// panel: a status dot per variable (orange=loading, cyan=literal,
/// green=loaded, red=failed), a marker column (➕ user-added, ✎ modified),
/// and horizontal-scrolling of the selected row's `key = value` text with
/// ‹/› arrow hints when there's more text in that direction.
pub(crate) fn draw_env_popup(
    f: &mut Frame,
    app: &TuiApp,
    popup: &EnvPopupState,
    s: &Strings,
    th: &Theme,
) {
    let Some(env) = app.global_envs.iter().find(|e| e.id == popup.env_id) else {
        return;
    };
    let area = centered_rect(78, 20.min(f.area().height.saturating_sub(2)), f.area());
    f.render_widget(Clear, area);
    let title = if env.git_origin.is_some() {
        format!("{}{GIT_ICON} {}", s.env_heading, env.name)
    } else {
        format!("{}{}", s.env_heading, env.name)
    };
    if env.vars.is_empty() {
        let block = panel(title, true, th);
        let p = Paragraph::new(Line::styled(
            s.env_no_env.to_string(),
            Style::default().fg(th.dim),
        ))
        .block(block)
        .wrap(Wrap { trim: false });
        f.render_widget(p, area);
        return;
    }
    let sel = popup.idx.min(env.vars.len().saturating_sub(1));
    // Columns available for the `key = value` text (after the border,
    // highlight symbol, marker and status dot); used to clamp scrolling.
    let text_w = area.width.saturating_sub(2 + 2 + 2 + 2);
    popup.scroll_w.set(text_w);
    let sel_len = env
        .vars
        .get(sel)
        .map(|v| v.key.chars().count() + 3 + v.display_value().chars().count())
        .unwrap_or(0);
    let max_scroll = sel_len.saturating_sub((text_w as usize).saturating_sub(1));
    let hscroll = (popup.hscroll as usize).min(max_scroll);
    let items: Vec<ListItem> = env
        .vars
        .iter()
        .enumerate()
        .map(|(i, v)| {
            // Status dot, colour-matched to the request substitution
            // scheme: orange = loading, cyan = literal, green = loaded
            // from a source (env/1Password/SSM), red = failed to resolve.
            let dot = if v.loading {
                th.pending
            } else if v.resolved {
                match v.source {
                    ValueSource::Literal => th.subst,
                    _ => th.ok,
                }
            } else {
                th.err
            };
            let val_color = if v.resolved { th.text } else { th.pending };
            let shown = if v.loading {
                s.env_loading.to_string()
            } else {
                v.display_value()
            };
            // Marker column (left of the status dot): a plus marks a
            // hand-added variable; otherwise a pencil marks a value the
            // user has edited away from its loaded value.
            let (marker, marker_fg) = if v.user_added {
                ("\u{271a} ", th.ok)
            } else if v.modified {
                ("\u{270e} ", th.accent)
            } else {
                ("  ", th.dim)
            };
            // The selected row is highlighted with a background only (see
            // `highlight_style` below), so text spans get a legible dark
            // foreground here while the STATUS DOT keeps its own colour —
            // that colour must stay visible even when the row is selected.
            let selected = i == sel;
            let mark_fg = if selected { th.bg } else { marker_fg };
            let mut spans = vec![
                Span::styled(marker, Style::default().fg(mark_fg)),
                Span::styled("", Style::default().fg(dot)),
            ];
            if selected {
                // The selected row scrolls its whole `key = value` so long
                // entries can be read end-to-end (rendered as one span in
                // the highlight foreground). Arrow hints appear on
                // whichever side still has hidden text.
                let combined = format!("{} = {}", v.key, shown);
                let avail = text_w as usize;
                let show_left = hscroll > 0;
                let content_w_before_right = avail.saturating_sub(show_left as usize);
                let remaining = sel_len.saturating_sub(hscroll);
                let show_right = remaining > content_w_before_right;
                let content_w = content_w_before_right.saturating_sub(show_right as usize);
                let visible: String = combined.chars().skip(hscroll).take(content_w).collect();
                let mut text = String::new();
                if show_left {
                    text.push('\u{2039}');
                }
                text.push_str(&visible);
                if show_right {
                    text.push('\u{203a}');
                }
                spans.push(Span::styled(text, Style::default().fg(th.bg)));
            } else {
                spans.push(Span::styled(v.key.clone(), Style::default().fg(th.text)));
                spans.push(Span::styled(" = ", Style::default().fg(th.dim)));
                spans.push(Span::styled(shown, Style::default().fg(val_color)));
            }
            ListItem::new(Line::from(spans))
        })
        .collect();
    let list = List::new(items)
        .block(panel(title, true, th))
        // Background + bold only (no fg): patching fg would overwrite the
        // status dot's colour, which must remain visible when selected.
        .highlight_style(Style::default().bg(th.accent).add_modifier(Modifier::BOLD))
        .highlight_symbol("");
    let mut st = ListState::default();
    st.select(Some(sel));
    f.render_stateful_widget(list, area, &mut st);
}

/// The colour for a substitution of the given [`SubstKind`].
fn subst_color(kind: crate::request::SubstKind, th: &Theme) -> Color {
    use crate::request::SubstKind;
    match kind {
        SubstKind::Literal => th.subst,   // cyan
        SubstKind::Loaded => th.ok,       // green
        SubstKind::Pending => th.pending, // orange
        SubstKind::Failed => th.err,      // red
    }
}

/// Tracks which [`SubstKind`]s were actually rendered while highlighting a
/// request's text, so the status legend can show only the dots that are
/// relevant to it instead of all four unconditionally.
#[derive(Default)]
struct SubstSeen {
    loaded: bool,
    literal: bool,
    pending: bool,
    failed: bool,
    /// At least one rendered substitution's Global Environment value is
    /// being shadowed by the collection's linked Environment.
    shadowed: bool,
}

impl SubstSeen {
    fn mark(&mut self, kind: crate::request::SubstKind) {
        use crate::request::SubstKind;
        match kind {
            SubstKind::Loaded => self.loaded = true,
            SubstKind::Literal => self.literal = true,
            SubstKind::Pending => self.pending = true,
            SubstKind::Failed => self.failed = true,
        }
    }

    fn any(&self) -> bool {
        self.loaded || self.literal || self.pending || self.failed
    }
}

/// Split one line of raw request text into styled spans, colour-coding each
/// *known* `{{ VAR }}` by its resolution status: a resolved value is substituted
/// (green = loaded from a source, cyan = literal); an unavailable one keeps the
/// `{{ VAR }}` placeholder (orange = loading, red = failed / not initialised).
/// Unknown placeholders are kept in the default colour. Marks `seen` with the
/// status of every known variable that was rendered. `shadowed`, when given,
/// flags variable names whose value from the active Global Environment is
/// being overridden by the collection's linked Environment (see
/// `TuiApp::shadowed_env_keys`) — such substitutions get a trailing warning
/// icon so the collision isn't silently invisible to the user. When
/// `icon_cols` is given, the character offset (within this call's returned
/// spans, i.e. relative to the start of `text`) of every such warning icon
/// is appended to it — used to strip the icon back out of copied/selected
/// text later (see `TuiApp::main_shadow_icon_positions`), since it's a
/// purely visual annotation that would otherwise corrupt a pasted request.
fn highlight_spans(
    text: &str,
    vars: &std::collections::HashMap<String, crate::request::SubstInfo>,
    th: &Theme,
    seen: &mut SubstSeen,
    shadowed: Option<&std::collections::HashSet<String>>,
    mut icon_cols: Option<&mut Vec<usize>>,
) -> Vec<Span<'static>> {
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut cur_len: usize = 0;
    let mut rest = text;
    while let Some(open) = rest.find("{{") {
        let Some(close_rel) = rest[open + 2..].find("}}") else {
            break;
        };
        let close = open + 2 + close_rel; // index of the closing "}}"
        let end = close + 2; // just past "}}"
        let inner = rest[open + 2..close].trim();
        if open > 0 {
            let piece = rest[..open].to_string();
            cur_len += piece.chars().count();
            spans.push(Span::styled(piece, Style::default().fg(th.text)));
        }
        match vars.get(inner) {
            Some(info) => {
                seen.mark(info.kind);
                let color = subst_color(info.kind, th);
                match &info.shown {
                    // Resolved: show the value in its status colour, with a
                    // warning icon immediately before it (no gap) when this
                    // key is shadowing/shadowed — placed on the left so it
                    // never gets crowded out by whatever character follows
                    // the substitution (e.g. a URL path separator).
                    Some(val) => {
                        if shadowed.is_some_and(|s| s.contains(inner)) {
                            if let Some(cols) = icon_cols.as_deref_mut() {
                                cols.push(cur_len);
                            }
                            cur_len += SHADOW_ICON.chars().count();
                            spans.push(Span::styled(SHADOW_ICON, Style::default().fg(th.pending)));
                            seen.shadowed = true;
                        }
                        cur_len += val.chars().count();
                        spans.push(Span::styled(val.clone(), Style::default().fg(color)));
                    }
                    // Unavailable: keep `{{ VAR }}` in its status colour.
                    None => {
                        let piece = rest[open..end].to_string();
                        cur_len += piece.chars().count();
                        spans.push(Span::styled(piece, Style::default().fg(color)));
                    }
                }
            }
            None => {
                let piece = rest[open..end].to_string();
                cur_len += piece.chars().count();
                spans.push(Span::styled(piece, Style::default().fg(th.text)));
            }
        }
        rest = &rest[end..];
    }
    if !rest.is_empty() {
        spans.push(Span::styled(rest.to_string(), Style::default().fg(th.text)));
    }
    spans
}

/// Drop the first `skip` displayed characters from a run of spans (used to apply
/// horizontal scrolling to the coloured, substituted collection-list URL).
fn skip_display(spans: Vec<Span<'static>>, mut skip: usize) -> Vec<Span<'static>> {
    if skip == 0 {
        return spans;
    }
    let mut out: Vec<Span<'static>> = Vec::new();
    for sp in spans {
        let len = sp.content.chars().count();
        if skip >= len {
            skip -= len;
            continue;
        }
        if skip > 0 {
            let kept: String = sp.content.chars().skip(skip).collect();
            out.push(Span::styled(kept, sp.style));
            skip = 0;
        } else {
            out.push(sp);
        }
    }
    out
}

/// Keep only the first `take` displayed characters from a run of spans,
/// dropping everything after. Used together with [`skip_display`] to reserve
/// a column for a "more text this way" arrow hint when a horizontally
/// scrolled line is still truncated on the right.
fn take_display(spans: Vec<Span<'static>>, mut take: usize) -> Vec<Span<'static>> {
    let mut out: Vec<Span<'static>> = Vec::new();
    for sp in spans {
        if take == 0 {
            break;
        }
        let len = sp.content.chars().count();
        if len <= take {
            take -= len;
            out.push(sp);
        } else {
            let kept: String = sp.content.chars().take(take).collect();
            out.push(Span::styled(kept, sp.style));
            take = 0;
        }
    }
    out
}

/// Hard-wrap a single (possibly styled) line to `width` display columns,
/// splitting spans across the wrap boundary without altering their styling.
/// Used for the Request JSON / Response bodies so a very long, unbroken line
/// (a long token, minified JSON, etc.) remains fully readable — scrollable
/// into view line-by-line — instead of being cut off at the panel's edge.
pub(crate) fn wrap_line(line: Line<'static>, width: usize) -> Vec<Line<'static>> {
    if width == 0 {
        return vec![line];
    }
    let mut out: Vec<Line<'static>> = Vec::new();
    let mut cur: Vec<Span<'static>> = Vec::new();
    let mut cur_w = 0usize;
    for span in line.spans {
        let mut remaining: &str = span.content.as_ref();
        loop {
            if remaining.is_empty() {
                break;
            }
            let avail = width - cur_w;
            if avail == 0 {
                out.push(Line::from(std::mem::take(&mut cur)));
                cur_w = 0;
                continue;
            }
            let take: String = remaining.chars().take(avail).collect();
            cur_w += take.chars().count();
            remaining = &remaining[take.len()..];
            cur.push(Span::styled(take, span.style));
        }
    }
    out.push(Line::from(cur));
    out
}

/// Wrap only a bounded window of a single (unstyled) line — skip
/// `skip_rows` whole wrapped rows, then wrap at most `max_rows` more,
/// without ever touching or allocating the rest of the line. Unlike
/// [`wrap_line`], whose cost is proportional to the *entire* line, this
/// keeps cost proportional to `(skip_rows + max_rows) * width` — critical
/// for panels holding one enormous raw line (e.g. a large base64 blob or
/// minified JSON body pasted with no newlines), where re-wrapping the
/// whole line on every redraw would grind the app to a halt regardless of
/// how few rows are actually on screen.
pub(crate) fn wrap_line_window(
    text: &str,
    width: usize,
    skip_rows: usize,
    max_rows: usize,
) -> Vec<Line<'static>> {
    if max_rows == 0 {
        return Vec::new();
    }
    if width == 0 {
        return if skip_rows == 0 {
            vec![Line::raw(text.to_string())]
        } else {
            Vec::new()
        };
    }
    let skip_chars = skip_rows.saturating_mul(width);
    let take_chars = max_rows.saturating_mul(width);
    let windowed: String = text.chars().skip(skip_chars).take(take_chars).collect();
    if windowed.is_empty() {
        return Vec::new();
    }
    wrap_line(Line::raw(windowed), width)
}

/// Word-wrap `text` to `width` columns, never splitting a word across lines
/// unless the word alone is longer than `width` (in which case it's
/// hard-broken so it doesn't just overflow the box). Unlike `wrap_line`
/// (used for raw Request/Response body text, where character-exact
/// wrapping is correct), Help popup descriptions are prose, so wrapping on
/// word boundaries reads far more naturally.
pub(crate) fn word_wrap(text: &str, width: usize) -> Vec<String> {
    if width == 0 {
        return vec![text.to_string()];
    }
    let mut lines = Vec::new();
    let mut cur = String::new();
    for word in text.split_whitespace() {
        if word.chars().count() > width {
            if !cur.is_empty() {
                lines.push(std::mem::take(&mut cur));
            }
            let mut rest = word;
            while rest.chars().count() > width {
                let take: String = rest.chars().take(width).collect();
                let take_len = take.len();
                lines.push(take);
                rest = &rest[take_len..];
            }
            cur = rest.to_string();
            continue;
        }
        let candidate_len = if cur.is_empty() {
            word.chars().count()
        } else {
            cur.chars().count() + 1 + word.chars().count()
        };
        if candidate_len > width {
            lines.push(std::mem::take(&mut cur));
        }
        if !cur.is_empty() {
            cur.push(' ');
        }
        cur.push_str(word);
    }
    if !cur.is_empty() || lines.is_empty() {
        lines.push(cur);
    }
    lines
}

/// A section-heading line for the Help popup: the title flanked by thin
/// grey horizontal rules filling the rest of `width`, e.g.
/// "── Navigation ─────────────────────". Used instead of a bold heading
/// line + a following blank line, so each titled section costs one line
/// instead of two while still reading as clearly divided from the section
/// above/below it.
pub(crate) fn help_section_divider(title: &str, width: usize, th: &Theme) -> Line<'static> {
    const LEFT_RULE: usize = 2;
    let title_w = Span::raw(title.to_string()).width();
    let right_rule = width.saturating_sub(LEFT_RULE + 2 + title_w).max(2);
    Line::from(vec![
        Span::styled("".repeat(LEFT_RULE), Style::default().fg(th.dim)),
        Span::raw(" "),
        Span::styled(
            title.to_string(),
            Style::default().fg(th.text).add_modifier(Modifier::BOLD),
        ),
        Span::raw(" "),
        Span::styled("".repeat(right_rule), Style::default().fg(th.dim)),
    ])
}

/// Build one Help popup shortcut entry: the shortcut left-padded to the
/// fixed key column (or left as-is if it's itself longer than the column),
/// followed by its description word-wrapped to fit `width`. Any wrapped
/// continuation line is indented so it lines up under the description
/// column instead of wrapping back to column 0.
pub(crate) fn help_entry_lines(shortcut: &str, desc: &str, width: usize) -> Vec<Line<'static>> {
    const KEY_COL: usize = 17;
    let indent = shortcut.chars().count().max(KEY_COL) + 1;
    let desc_width = width.saturating_sub(indent).max(1);
    let wrapped = word_wrap(desc, desc_width);
    let mut out = Vec::with_capacity(wrapped.len().max(1));
    for (i, chunk) in wrapped.iter().enumerate() {
        if i == 0 {
            out.push(Line::raw(format!("{shortcut:<KEY_COL$} {chunk}")));
        } else {
            out.push(Line::raw(format!("{:indent$}{chunk}", "")));
        }
    }
    out
}

/// Builds one Help "Glossary" tab entry: a coloured icon + bolded label
/// (e.g. "● loaded"), followed by its wrapped description — the glossary
/// counterpart to `help_entry_lines`, styled so the icon/label colour
/// matches exactly what's shown inline next to a substituted variable.
pub(crate) fn glossary_entry_lines(
    icon: &str,
    color: Color,
    label: &str,
    desc: &str,
    width: usize,
) -> Vec<Line<'static>> {
    const KEY_COL: usize = 17;
    let header = format!("{icon} {label}");
    // Use *display* width (columns), not `.chars().count()`: a couple of
    // glossary icons (folder, link) are double-width emoji, so counting
    // chars would under-measure the header by one column for those rows.
    // That one-column error used to throw off the description's own
    // word-wrap budget on its first line only (continuation lines are
    // padded with plain ASCII spaces, so they were never affected) — the
    // visible symptom was the first line starting one column further right
    // than the wrapped lines beneath it, which could shove the last word
    // (often the "—" separator) onto its own orphaned continuation line.
    let header_w = Span::raw(header.clone()).width();
    let indent = header_w.max(KEY_COL) + 1;
    let desc_width = width.saturating_sub(indent).max(1);
    let wrapped = word_wrap(desc, desc_width);
    // Total spaces after the header needed to reach the description's start
    // column (`indent`) — replaces the old `format!("{:<pad_width$}")` (which
    // pads by char count) + a separate literal space, so wide-icon rows are
    // padded by exactly as many columns as narrow-icon ones are.
    let pad = " ".repeat(indent.saturating_sub(header_w));
    let mut out = Vec::with_capacity(wrapped.len().max(1));
    for (i, chunk) in wrapped.iter().enumerate() {
        if i == 0 {
            out.push(Line::from(vec![
                Span::styled(
                    header.clone(),
                    Style::default().fg(color).add_modifier(Modifier::BOLD),
                ),
                Span::raw(pad.clone()),
                Span::raw(chunk.clone()),
            ]));
        } else {
            out.push(Line::raw(format!("{:indent$}{chunk}", "")));
        }
    }
    out
}

/// Number of wrapped rows a line of `char_len` characters produces at
/// `width` display columns, matching `wrap_line`'s own boundary math exactly
/// (one row minimum, even for an empty line). Used by
/// `wrapcache::PanelWrap` to size the total scrollable extent and locate a
/// scroll position — never to build the actual wrapped `Line`s.
pub(crate) fn wrapped_row_count(char_len: usize, width: usize) -> usize {
    if width == 0 || char_len == 0 {
        1
    } else {
        char_len.div_ceil(width)
    }
}

pub(crate) fn draw_collection_main(
    f: &mut Frame,
    area: Rect,
    app: &mut TuiApp,
    ci: usize,
    s: &Strings,
    th: &Theme,
) {
    let focused = app.focus == Pane::Main;
    let hurl_view = app.default_request_view == request::RequestView::Hurl;
    let title = if hurl_view {
        s.entry_request_hurl
    } else {
        s.entry_request_json
    };
    let block = panel(title.to_string(), focused, th);
    let inner = block.inner(area);
    f.render_widget(block, area);

    if app.collections[ci].entries.is_empty() {
        app.main_max_scroll = 0;
        app.main_scroll = 0;
        app.main_text_area = Rect::default();
        app.main_wrap = None;
        app.main_shadow_icon_positions.clear();
        app.main_scrollbar_area = Rect::default();
        f.render_widget(
            Paragraph::new(Line::styled(
                s.no_requests_hint.to_string(),
                Style::default().fg(th.dim),
            )),
            inner,
        );
        return;
    }

    let col = &app.collections[ci];
    let idx = col.selected_entry.min(col.entries.len() - 1);
    let entry = &col.entries[idx];
    let method = entry.method.clone();
    let url = entry.url.clone();
    let captures = entry.captures.clone();
    let asserts = entry.asserts.clone();
    // The Hurl view always renders (it's actual Hurl syntax, not JSON, so the
    // "invalid JSON" check below is meaningless for it and skipped entirely).
    let (buf, valid) = if hurl_view {
        (entry.to_hurl(), true)
    } else {
        let buf = col.request_json_buf.clone();
        let valid = serde_json::from_str::<serde_json::Value>(&buf).is_ok();
        (buf, valid)
    };
    // How each `{{ VAR }}` should be shown/coloured in the preview (secrets masked).
    let env = app.effective_env(ci);
    let dvars = crate::request::subst_map(&app.collections[ci], env.as_ref());
    // Keys where the linked Environment's value shadows the active Global
    // Environment's — flagged with a warning icon below.
    let shadowed = app.shadowed_env_keys(ci);
    // `col`/`entry` borrows end here — everything needed is cloned above.

    let mut seen = SubstSeen::default();
    // Top region: method/url (with substitutions) + run hint, then [Captures]/[Asserts].
    let mut top_lines: Vec<Line> = Vec::new();
    let mut first: Vec<Span> = vec![Span::styled(
        format!("{method} "),
        Style::default()
            .fg(method_color(&method))
            .add_modifier(Modifier::BOLD),
    )];
    first.extend(highlight_spans(
        &url,
        &dvars,
        th,
        &mut seen,
        Some(&shadowed),
        None,
    ));
    first.push(Span::styled(
        format!(
            "   [ {}{} ]",
            s.run_entry.trim(),
            if app.enhanced_keys {
                "^Enter / F5"
            } else {
                "F5"
            }
        ),
        Style::default().fg(th.accent),
    ));
    top_lines.push(Line::from(first));
    // Build the (highlighted) JSON body; this also flags whether anything was
    // substituted so we can show the legend. Also records, per body line,
    // the character offset of every shadow-warning icon inserted into it
    // (`shadow_positions`) — purely a visual annotation, so it's stripped
    // back out of copied/selected text later (see
    // `TuiApp::main_shadow_icon_positions`) rather than corrupting a pasted
    // request with a stray "!".
    let mut shadow_positions: std::collections::HashSet<TextPos> = std::collections::HashSet::new();
    let body_lines: Vec<Line> = buf
        .lines()
        .enumerate()
        .map(|(li, l)| {
            let mut cols = Vec::new();
            let spans = highlight_spans(l, &dvars, th, &mut seen, Some(&shadowed), Some(&mut cols));
            for c in cols {
                shadow_positions.insert(TextPos::new(li, c));
            }
            Line::from(spans)
        })
        .collect();
    // The plain text `body_lines` actually renders — i.e. `buf` with every
    // resolved `{{ VAR }}` already substituted in, exactly like the user
    // sees on screen — rather than `buf` itself, which still has the raw
    // `{{ VAR }}` moustache syntax. This (not `buf`) is what backs the
    // panel's scroll geometry, mouse-selection extraction, and the
    // whole-panel copy fallback, so a copied/selected value always matches
    // what's visually shown instead of the underlying template.
    let mut display_text: String = body_lines
        .iter()
        .map(|line| {
            line.spans
                .iter()
                .map(|sp| sp.content.as_ref())
                .collect::<String>()
        })
        .collect::<Vec<_>>()
        .join("\n");
    // `buf.lines()` (used to build `body_lines` above) drops a trailing
    // newline just like `str::lines()` always does, so restore it here —
    // otherwise a whole-panel copy of Hurl text would silently lose the
    // trailing newline the raw buffer actually had.
    if buf.ends_with('\n') {
        display_text.push('\n');
    }
    top_lines.push(if valid {
        Line::styled(
            format!("Enter {}", s.json_enter_to_edit),
            Style::default().fg(th.dim),
        )
    } else {
        Line::styled(s.json_invalid.to_string(), Style::default().fg(th.err))
    });
    if seen.any() {
        let segments = [
            (seen.loaded, s.subst_hint_loaded, th.ok),
            (seen.literal, s.subst_hint_literal, th.subst),
            (seen.pending, s.subst_hint_loading, th.pending),
            (seen.failed, s.subst_hint_missing, th.err),
        ];
        let mut spans: Vec<Span<'static>> = Vec::new();
        for (present, word, color) in segments {
            if !present {
                continue;
            }
            if !spans.is_empty() {
                spans.push(Span::raw(" "));
            }
            spans.push(Span::styled(
                format!("\u{25cf} {word}"),
                Style::default().fg(color),
            ));
        }
        // Rendered with the same "!" icon used inline (not the "●" dot) so
        // the legend visually matches the marker the user actually sees
        // next to shadowed substitutions.
        if seen.shadowed {
            if !spans.is_empty() {
                spans.push(Span::raw(" "));
            }
            spans.push(Span::styled(
                format!("{SHADOW_ICON} {}", s.subst_hint_shadowed),
                Style::default().fg(th.pending),
            ));
        }
        top_lines.push(Line::from(spans));
    }
    if !captures.is_empty() {
        top_lines.push(Line::styled(
            "[Captures]",
            Style::default().fg(th.accent).add_modifier(Modifier::BOLD),
        ));
        for (name, expr) in &captures {
            top_lines.push(Line::from(vec![
                Span::raw("  "),
                Span::styled(name.clone(), Style::default().fg(th.text)),
                Span::styled("", Style::default().fg(th.dim)),
                Span::styled(expr.clone(), Style::default().fg(th.dim)),
            ]));
        }
    }
    if !asserts.is_empty() {
        top_lines.push(Line::styled(
            "[Asserts]",
            Style::default().fg(th.accent).add_modifier(Modifier::BOLD),
        ));
        for a in &asserts {
            top_lines.push(Line::from(vec![
                Span::raw("  "),
                Span::styled(a.clone(), Style::default().fg(th.dim)),
            ]));
        }
    }

    // Push a dim line to visually separate the Request meta-information from
    // the raw request itself
    top_lines.push(Line::from(vec![Span::styled(
        "".repeat(area.width as usize),
        Style::default().fg(th.dim),
    )]));

    // Keep at least 3 rows for the JSON body when the panel is tall enough.
    let cap = inner.height.saturating_sub(3).max(2);
    let top_h = (top_lines.len() as u16).clamp(2, cap);
    let split = Layout::vertical([Constraint::Length(top_h), Constraint::Min(1)]).split(inner);
    f.render_widget(Paragraph::new(top_lines), split[0]);

    // Clamp scrolling so the user can't scroll past the last line into blank space.
    let text_area = split[1];
    let width = text_area.width as usize;
    // Request bodies (JSON or Hurl text) are realistically small, so
    // rebuilding this cache fresh every frame (rather than reusing it across
    // frames the way the Response panel does) is cheap and sidesteps having
    // to separately invalidate it when `dvars`/highlighting-relevant state
    // changes instead of just the buffer text itself.
    let wrap = PanelWrap::build(Arc::from(display_text.as_str()), width);
    let total_lines = wrap.total_rows().min(u16::MAX as u32) as u16;
    let max_scroll = total_lines.saturating_sub(text_area.height);
    app.main_max_scroll = max_scroll;
    app.main_scroll = app.main_scroll.min(max_scroll);
    let scroll = app.main_scroll;

    // Only the visible window's raw lines are re-highlighted/wrapped — this
    // keeps dragging a selection or scrolling responsive even for a large body.
    let start = wrap.row_col_to_textpos(scroll as u32, 0);
    let row_in_start_line = start.col.checked_div(width).unwrap_or(0);
    let height = text_area.height as usize;
    let mut visible_wrapped: Vec<Line<'static>> = Vec::with_capacity(height);
    'outer: for (idx, line) in body_lines.iter().enumerate().skip(start.line) {
        let skip = if idx == start.line {
            row_in_start_line
        } else {
            0
        };
        for row in wrap_line(line.clone(), width).into_iter().skip(skip) {
            visible_wrapped.push(row);
            if visible_wrapped.len() >= height {
                break 'outer;
            }
        }
    }

    // Overlay a scrollbar on the panel's right border (not stealing an inner
    // text column) whenever the body has more wrapped rows than fit, so it's
    // visually obvious there's more to see and roughly where in the body the
    // visible window currently sits.
    if max_scroll > 0 {
        let bar_area = Rect {
            x: area.x + area.width - 1,
            y: text_area.y,
            width: 1,
            height: text_area.height,
        };
        draw_scrollbar(
            f,
            bar_area,
            total_lines as usize,
            height,
            scroll as usize,
            th,
        );
        app.main_scrollbar_area = bar_area;
    } else {
        app.main_scrollbar_area = Rect::default();
    }

    // Cache the wrap/geometry so mouse selection can map coordinates back to
    // real, copyable text — scoped to this panel's own Rect only.
    app.main_text_area = text_area;
    app.main_wrap = Some(wrap);
    app.main_shadow_icon_positions = shadow_positions;

    f.render_widget(
        Paragraph::new(visible_wrapped).style(Style::default().fg(th.text)),
        text_area,
    );
}

pub(crate) fn draw_response(
    f: &mut Frame,
    area: Rect,
    app: &mut TuiApp,
    ci: usize,
    s: &Strings,
    th: &Theme,
) {
    let focused = app.focus == Pane::Response;
    let block = panel(s.response_heading.to_string(), focused, th);
    let inner = block.inner(area);
    f.render_widget(block, area);

    // The in-flight spinner is still driven by the single shared "live"
    // response slot (no per-entry concept of "currently sending"), but once
    // a request has finished, the actual status/body/asserts shown always
    // come from the *selected entry's own* last response — not whichever
    // entry happened to finish last — so switching entries after a batch
    // "Run All" shows the right result for each one.
    let loading = app.response.lock().unwrap().loading;
    let entry = app
        .collections
        .get(ci)
        .and_then(|col| col.entries.get(col.selected_entry));
    let (status, status_text, body, error, asserts) =
        match entry.and_then(|e| e.last_response.as_ref()) {
            Some(r) => (
                r.status,
                r.status_text.clone(),
                r.body.clone(),
                r.error.clone(),
                r.assert_results.clone(),
            ),
            None => (0, String::new(), Arc::from(""), String::new(), Vec::new()),
        };

    if loading {
        app.resp_max_scroll = 0;
        app.resp_text_area = Rect::default();
        app.resp_wrap = None;
        app.resp_scrollbar_area = Rect::default();
        f.render_widget(
            Paragraph::new(Line::styled(
                format!("{}", s.sending),
                Style::default().fg(th.accent),
            )),
            inner,
        );
        return;
    }
    if !error.is_empty() {
        app.resp_max_scroll = 0;
        app.resp_text_area = Rect::default();
        app.resp_wrap = None;
        app.resp_scrollbar_area = Rect::default();
        f.render_widget(
            Paragraph::new(format!("{} {error}", s.req_error_prefix))
                .style(Style::default().fg(th.err))
                .wrap(Wrap { trim: false }),
            inner,
        );
        return;
    }
    if status == 0 {
        app.resp_max_scroll = 0;
        app.resp_text_area = Rect::default();
        app.resp_wrap = None;
        app.resp_scrollbar_area = Rect::default();
        f.render_widget(
            Paragraph::new(Line::styled(
                s.no_response_yet.to_string(),
                Style::default().fg(th.dim),
            )),
            inner,
        );
        return;
    }

    let color = match status {
        200..=299 => th.ok,
        400..=599 => th.err,
        _ => Color::Gray,
    };

    // Status line, with an [Asserts] pass/fail badge supplemental to the status.
    let mut status_spans = vec![
        Span::styled(format!("{} ", s.status_label), Style::default().fg(th.text)),
        Span::styled(
            format!("{status} {status_text}"),
            Style::default().fg(color).add_modifier(Modifier::BOLD),
        ),
    ];
    let passed = asserts.iter().filter(|a| a.passed).count();
    let total = asserts.len();
    if total > 0 {
        let all_ok = passed == total;
        let badge = if all_ok { th.ok } else { th.err };
        let mark = if all_ok { "\u{2713}" } else { "\u{2717}" };
        status_spans.push(Span::raw("   "));
        status_spans.push(Span::styled(
            format!("[Asserts] {mark} {passed}/{total}"),
            Style::default().fg(badge).add_modifier(Modifier::BOLD),
        ));
    }

    // One line per assert (✓/✗ with the expression and, on failure, the actual).
    let assert_lines: Vec<Line> = asserts
        .iter()
        .map(|a| {
            let (mark, c) = if a.passed {
                ("\u{2713}", th.ok)
            } else {
                ("\u{2717}", th.err)
            };
            let mut spans = vec![
                Span::styled(format!("  {mark} "), Style::default().fg(c)),
                Span::styled(a.expr.clone(), Style::default().fg(th.text)),
            ];
            if !a.detail.is_empty() {
                spans.push(Span::styled(
                    format!("  {}", a.detail),
                    Style::default().fg(th.dim),
                ));
            }
            Line::from(spans)
        })
        .collect();

    // Layout: status (1) · asserts (capped, keeping ≥1 body row) · body (rest).
    let assert_h = (assert_lines.len() as u16).min(inner.height.saturating_sub(2));
    let rows = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(assert_h),
        Constraint::Min(1),
    ])
    .split(inner);

    f.render_widget(Paragraph::new(Line::from(status_spans)), rows[0]);
    if assert_h > 0 {
        f.render_widget(Paragraph::new(assert_lines), rows[1]);
    }

    // Wrap long lines to the body width and clamp scrolling so the user can't
    // scroll past the last line into blank space. The wrap/line structure is
    // cached (`PanelWrap::rebuild_if_needed`) and reused across frames as
    // long as `body`'s identity and the panel width haven't changed, and even
    // a rebuild only wraps the rows actually on screen — this is what keeps
    // dragging a selection or scrolling responsive regardless of how large
    // an "obscenely large" response body is.
    let body_area = rows[2];
    let width = body_area.width as usize;
    PanelWrap::rebuild_if_needed(&mut app.resp_wrap, &body, width);
    let wrap = app.resp_wrap.as_ref().expect("just rebuilt above");
    let total_lines = wrap.total_rows().min(u16::MAX as u32) as u16;
    let max_scroll = total_lines.saturating_sub(body_area.height);
    app.resp_max_scroll = max_scroll;
    app.resp_scroll = app.resp_scroll.min(max_scroll);

    let visible_wrapped = wrap.visible_window(app.resp_scroll, body_area.height);

    // Overlay a scrollbar on the panel's right border (not stealing an inner
    // text column, and safely outside `resp_text_area` so it can never be
    // clicked into as part of a text selection) whenever the body has more
    // wrapped rows than fit.
    if max_scroll > 0 {
        let bar_area = Rect {
            x: area.x + area.width - 1,
            y: body_area.y,
            width: 1,
            height: body_area.height,
        };
        draw_scrollbar(
            f,
            bar_area,
            total_lines as usize,
            body_area.height as usize,
            app.resp_scroll as usize,
            th,
        );
        app.resp_scrollbar_area = bar_area;
    } else {
        app.resp_scrollbar_area = Rect::default();
    }

    // Cache the geometry so mouse selection can map coordinates back to real,
    // copyable text — scoped to this panel's own Rect only.
    app.resp_text_area = body_area;

    f.render_widget(
        Paragraph::new(visible_wrapped).style(Style::default().fg(th.text)),
        body_area,
    );
}

pub(crate) fn draw_footer(f: &mut Frame, area: Rect, s: &Strings, th: &Theme, can_copy: bool) {
    // Run/Run All (F5 / Alt+F5) now live on the Collections panel's bottom
    // border (see draw_collection_left), and the base-URL row above already
    // shows its own "b" hint — kept out of here to leave room for the rest.
    let mut hint = vec![
        format!("Tab {}", s.foot_focus),
        format!("↑↓ {}", s.foot_move),
        format!("Enter {}", s.foot_edit),
        format!("n {}", s.foot_new),
        format!("r {}", s.foot_reload_var),
        format!("f {}", s.foot_file),
        format!("s {}", s.foot_options),
        format!("[ / ], ^←/→ {}", s.help_prev_next_tab),
        format!("F2 {}", s.foot_rename),
        format!("x {}", s.foot_close),
    ];
    // Only shown while `y` would actually do something — the rest of the
    // footer is a fixed set of always-available shortcuts, but `y` copies
    // either the active selection or, with none, the whole Request JSON /
    // Response panel that currently has focus (see `TuiApp::can_copy`).
    if can_copy {
        hint.push(format!("y {}", s.foot_copy_selection));
    }
    hint.push(format!("? {}", s.foot_help));
    hint.push(format!("q {}", s.foot_quit));
    let hint = hint.join(" · ");
    f.render_widget(
        Paragraph::new(Line::styled(hint, Style::default().fg(th.dim)))
            .style(Style::default().bg(th.panel)),
        area,
    );
}

pub(crate) fn draw_overlay(f: &mut Frame, app: &mut TuiApp, s: &Strings, th: &Theme) {
    match app.overlay.as_ref().unwrap() {
        Overlay::FileMenu(sel) => {
            let items = file_menu_items(s);
            draw_menu_popup(f, s.file_menu, &items, *sel, th);
        }
        Overlay::FileLoadMenu(sel) => {
            let items = file_load_items(s);
            draw_menu_popup(f, s.file_load_menu, &items, *sel, th);
        }
        Overlay::FileSaveMenu(sel) => {
            let items = file_save_items(s);
            draw_menu_popup(f, s.file_save_menu, &items, *sel, th);
        }
        Overlay::FileLoadSource(kind, sel) => {
            let items = file_load_source_items(s);
            let title = format!("{} {}", s.file_load_menu, kind.name(s));
            draw_menu_popup(f, &title, &items, *sel, th);
        }
        Overlay::FileSaveDest(kind, sel) => {
            let items = file_save_dest_items(*kind, s);
            let title = format!("{} {}", s.file_save_menu, kind.name(s));
            draw_menu_popup(f, &title, &items, *sel, th);
        }
        Overlay::Options(sel) => {
            let items = [s.language_label, s.preferences_menu, s.clear_all];
            draw_menu_popup(f, s.options_menu, &items, *sel, th);
        }
        Overlay::Preferences(sel) => {
            let mark = |b: bool| if b { "[x]" } else { "[ ]" };
            let exit_item = format!("{} {}", mark(app.confirm_on_exit), s.confirm_on_exit);
            let clear_item = format!("{} {}", mark(app.confirm_on_clear), s.confirm_on_clear);
            let view_label = match app.default_request_view {
                request::RequestView::Json => "JSON",
                request::RequestView::Hurl => "Hurl",
            };
            let view_item = format!("{}: {view_label}", s.default_request_view_label);
            let always_save_item = format!(
                "{} {}",
                mark(app.always_save_when_prompted),
                s.always_save_when_prompted
            );
            let items = [
                exit_item.as_str(),
                clear_item.as_str(),
                view_item.as_str(),
                always_save_item.as_str(),
            ];
            draw_menu_popup(f, s.preferences_menu, &items, *sel, th);
        }
        Overlay::Confirm { action, sel } => {
            let question: String = match action {
                ConfirmAction::Exit => {
                    let mut q = s.confirm_exit_q.to_string();
                    // Fold the secret-loss warning into the exit popup (rather
                    // than a second popup) when there are unsaved secret edits.
                    if app.has_unsaved_secret_changes() {
                        q.push(' ');
                        q.push_str(s.confirm_exit_secrets);
                    }
                    q
                }
                ConfirmAction::Clear => s.confirm_clear_q.to_string(),
                // Scoped to the entity being saved: the collection warning counts
                // only requests, the environment warning only variables.
                ConfirmAction::Save(FileAction::SaveEnv) => s.confirm_save_env_q.replace(
                    "{e}",
                    &app.current_env_id()
                        .map(|id| app.changed_env_count(id))
                        .unwrap_or(0)
                        .to_string(),
                ),
                ConfirmAction::Save(_) => s.confirm_save_collection_q.replace(
                    "{r}",
                    &app.changed_request_count(app.active_tab).to_string(),
                ),
                ConfirmAction::Overwrite(_) => {
                    let name = app
                        .pending_save_path
                        .as_ref()
                        .map(|p| {
                            p.file_name()
                                .map(|n| n.to_string_lossy().into_owned())
                                .unwrap_or_else(|| p.to_string_lossy().into_owned())
                        })
                        .unwrap_or_default();
                    s.confirm_overwrite_q.replace("{f}", &name)
                }
                ConfirmAction::DeleteEnv(_) => s.env_delete_confirm.to_string(),
            };
            draw_confirm_popup(f, &question, &[s.confirm_yes, s.confirm_no], *sel, th);
        }
        Overlay::LanguageMenu(sel) => {
            let items = [s.lang_english, s.lang_french, s.lang_danish];
            draw_menu_popup(f, s.language_label, &items, *sel, th);
        }
        Overlay::RequestViewMenu(sel) => {
            let items = [s.view_json_label, s.view_hurl_label];
            draw_menu_popup(f, s.default_request_view_label, &items, *sel, th);
        }
        Overlay::Help(tab) => {
            // Widen the popup on spacious terminals so long descriptions
            // need to wrap less often (`centered_rect` clamps this further
            // to whatever's actually available on narrow terminals).
            let box_w = f.area().width.saturating_sub(6).clamp(64, 100);
            let inner_w = (box_w as usize).saturating_sub(2); // minus the left/right border

            let tab_bar = |active: usize| {
                Line::from(vec![
                    Span::styled(
                        format!(" {} ", s.help_tab_shortcuts),
                        if active == 0 {
                            Style::default()
                                .bg(th.accent)
                                .fg(th.bg)
                                .add_modifier(Modifier::BOLD)
                        } else {
                            Style::default().fg(th.dim)
                        },
                    ),
                    Span::raw(" "),
                    Span::styled(
                        format!(" {} ", s.help_tab_glossary),
                        if active == 1 {
                            Style::default()
                                .bg(th.accent)
                                .fg(th.bg)
                                .add_modifier(Modifier::BOLD)
                        } else {
                            Style::default().fg(th.dim)
                        },
                    ),
                    Span::raw("   "),
                    Span::styled(s.help_tab_switch_hint, Style::default().fg(th.dim)),
                ])
            };

            let shortcuts_body = || {
                // Grouped into short, titled sections (mirroring the
                // Glossary tab's two-heading layout) instead of one long
                // flat list — new users found the un-grouped list hard to
                // scan for the shortcut they needed.
                let groups: [(&str, &[(&str, &str)]); 7] = [
                    (
                        s.help_group_navigation,
                        &[
                            ("Tab / Shift+Tab", s.help_focus),
                            ("↑ ↓  / j k", s.help_move),
                            ("^\u{2191} ^\u{2193}", s.help_page_response),
                            ("\u{2192}  / h l", s.help_switch_tabs),
                        ],
                    ),
                    (
                        s.help_group_tabs,
                        &[
                            ("[ / ], PgUp/PgDn, ^\u{2190}/\u{2192}", s.help_prev_next_tab),
                            ("F2 / x", s.help_rename_close),
                            ("^W / u", s.help_tab_manage),
                            ("^Shift+\u{2190} \u{2192}", s.help_tab_reorder),
                        ],
                    ),
                    (
                        s.help_group_requests,
                        &[
                            ("Enter", s.help_select),
                            (
                                if app.enhanced_keys {
                                    "^Enter, F5"
                                } else {
                                    "F5"
                                },
                                s.help_run,
                            ),
                            ("Alt+F5", s.help_run_all),
                            ("n", s.help_new),
                            ("Shift+H", s.help_raw_mode),
                            ("Shift+J", s.help_raw_json),
                            ("b", s.help_base_url),
                            ("u (List pane)", s.help_restore_request),
                        ],
                    ),
                    (
                        s.help_group_menus,
                        &[
                            ("f / s", s.help_menus),
                            ("\u{2190} / \u{2192} (File menu)", s.help_menu_submenu_nav),
                            ("w", s.help_workspace_browse),
                            ("\u{2192} / Enter (Workspace)", s.help_workspace_open),
                            ("^r (File browser)", s.help_browser_reset),
                        ],
                    ),
                    (
                        s.help_group_environments,
                        &[
                            ("r (Env popup)", s.help_reload_var),
                            ("F2 (Env panel)", s.help_env_rename),
                            ("a", s.help_env_activate),
                            ("x", s.help_env_delete),
                            ("p (List pane)", s.help_env_link),
                            ("v", s.help_env_view_linked),
                        ],
                    ),
                    (
                        s.help_group_editing,
                        &[
                            ("", s.help_row_toggle_delete),
                            ("y", s.help_copy_selection),
                            ("Alt+Click+Drag", s.help_multi_select),
                            ("F2", s.help_save_editor),
                        ],
                    ),
                    (
                        s.help_group_panels,
                        &[
                            ("+ / -", s.help_resize),
                            ("< / >", s.help_resize_width),
                            ("Esc", s.help_cancel),
                            ("q, ^C", s.help_quit),
                        ],
                    ),
                ];
                let mut body = Vec::new();
                for (i, (heading, entries)) in groups.iter().enumerate() {
                    if i > 0 {
                        body.push(Line::raw(""));
                    }
                    body.push(help_section_divider(heading, inner_w, th));
                    for &(shortcut, desc) in entries.iter() {
                        body.extend(help_entry_lines(shortcut, desc, inner_w));
                    }
                }
                body
            };

            let glossary_body = || {
                let mut body = vec![help_section_divider(s.glossary_heading, inner_w, th)];
                let entries: [(&str, Color, &str, &str); 5] = [
                    (
                        "\u{25cf}",
                        th.subst,
                        s.glossary_label_literal,
                        s.glossary_desc_literal,
                    ),
                    (
                        "\u{25cf}",
                        th.ok,
                        s.glossary_label_loaded,
                        s.glossary_desc_loaded,
                    ),
                    (
                        "\u{25cf}",
                        th.pending,
                        s.glossary_label_pending,
                        s.glossary_desc_pending,
                    ),
                    (
                        "\u{25cf}",
                        th.err,
                        s.glossary_label_failed,
                        s.glossary_desc_failed,
                    ),
                    (
                        SHADOW_ICON,
                        th.pending,
                        s.glossary_label_shadowed,
                        s.glossary_desc_shadowed,
                    ),
                ];
                for (icon, color, label, desc) in entries {
                    body.extend(glossary_entry_lines(icon, color, label, desc, inner_w));
                }
                // A second group covers every other icon shown around the
                // app (list rows, tab bar, form editor) so this one tab is
                // a complete legend rather than just the substitution dots.
                body.push(Line::raw(""));
                body.push(help_section_divider(s.glossary_heading_icons, inner_w, th));
                let icon_entries: [(&str, Color, &str, &str); 9] = [
                    (
                        "\u{270e}",
                        th.accent,
                        s.glossary_label_modified,
                        s.glossary_desc_modified,
                    ),
                    (
                        "\u{271a}",
                        th.ok,
                        s.glossary_label_added,
                        s.glossary_desc_added,
                    ),
                    (
                        "\u{2713}",
                        th.ok,
                        s.glossary_label_passed,
                        s.glossary_desc_passed,
                    ),
                    (
                        "\u{2717}",
                        th.err,
                        s.glossary_label_run_failed,
                        s.glossary_desc_run_failed,
                    ),
                    (
                        "\u{2026}",
                        th.pending,
                        s.glossary_label_running,
                        s.glossary_desc_running,
                    ),
                    (GIT_ICON, th.text, s.glossary_label_git, s.glossary_desc_git),
                    (
                        LINK_ICON,
                        th.dim,
                        s.glossary_label_linked,
                        s.glossary_desc_linked,
                    ),
                    (
                        FOLDER_ICON,
                        th.accent,
                        s.glossary_label_folder,
                        s.glossary_desc_folder,
                    ),
                    (
                        "\u{2039}\u{203a}",
                        th.dim,
                        s.glossary_label_scroll_hint,
                        s.glossary_desc_scroll_hint,
                    ),
                ];
                for (icon, color, label, desc) in icon_entries {
                    body.extend(glossary_entry_lines(icon, color, label, desc, inner_w));
                }
                body
            };

            let mut lines = vec![
                Line::styled(
                    s.help_heading,
                    Style::default().fg(th.accent).add_modifier(Modifier::BOLD),
                ),
                tab_bar(*tab),
            ];
            lines.extend(if *tab == 0 {
                shortcuts_body()
            } else {
                glossary_body()
            });

            // Both tabs share one fixed height (the taller of the two,
            // measured with the *other* tab's body too) so switching tabs
            // doesn't resize the popup out from under the user — a stable
            // box makes the tab strip read as one steady window rather than
            // a jarring resize on every switch. `centered_rect` further caps
            // this to the terminal's own height on small terminals, in which
            // case the body is scrolled (Up/Down) with a scrollbar on the
            // right border rather than clipping off the bottom silently.
            let other_len = 2 + if *tab == 0 {
                glossary_body().len()
            } else {
                shortcuts_body().len()
            };
            let content_len = lines.len().max(other_len);
            let box_h = content_len as u16 + 2;
            let area = centered_rect(box_w, box_h, f.area());
            f.render_widget(Clear, area);
            let title = format!(
                "{}{}",
                s.help_title,
                if *tab == 0 {
                    s.help_tab_shortcuts
                } else {
                    s.help_tab_glossary
                }
            );
            let visible_rows = area.height.saturating_sub(2) as usize;
            let max_scroll = content_len.saturating_sub(visible_rows) as u16;
            if app.help_scroll > max_scroll {
                app.help_scroll = max_scroll;
            }
            let scroll = app.help_scroll;
            f.render_widget(
                Paragraph::new(lines)
                    .block(panel(title, true, th))
                    .wrap(Wrap { trim: false })
                    .scroll((scroll, 0)),
                area,
            );
            if max_scroll > 0 {
                let bar_area = Rect {
                    x: area.x + area.width - 1,
                    y: area.y + 1,
                    width: 1,
                    height: visible_rows as u16,
                };
                draw_scrollbar(f, bar_area, content_len, visible_rows, scroll as usize, th);
            }
        }
        Overlay::Prompt {
            kind,
            editor,
            title,
            mask,
            reset_to,
            secret_intact,
            secret_checkbox,
        } => {
            let ml = editor.multiline;
            // Grow the box by one line to fit the "still secret?" checkbox row.
            let h = if ml {
                14
            } else if secret_checkbox.is_some() {
                5
            } else {
                3
            };
            let w = if ml {
                (f.area().width * 8 / 10).max(30)
            } else {
                64
            };
            let area = centered_rect(w, h, f.area());
            f.render_widget(Clear, area);
            let mut hint = if matches!(kind, PromptKind::Raw(_)) {
                format!("{title}  ({})", s.raw_mode_hint)
            } else if matches!(kind, PromptKind::RawJson(_)) {
                format!("{title}  ({})", s.raw_json_hint)
            } else if ml {
                format!("{title}  ({})", s.prompt_save_hint_ml)
            } else {
                format!("{title}  ({})", s.prompt_save_hint_sl)
            };
            // Offer a reset only when the field has been changed from its
            // originally-loaded value.
            if reset_to
                .as_deref()
                .is_some_and(|orig| orig != editor.text())
            {
                hint.push_str(&format!("  ·  {}", s.prompt_reset_hint));
            }
            if secret_checkbox.is_some() {
                hint.push_str(&format!("  ·  {}", s.env_still_secret_hint));
            }
            let block = panel(hint, true, th);
            let inner = block.inner(area);
            f.render_widget(block, area);
            // Reserve the last inner row for the checkbox when applicable.
            let (editor_area, checkbox_area) = if let Some(checked) = secret_checkbox {
                let rows =
                    Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(inner);
                (rows[0], Some((rows[1], checked)))
            } else {
                (inner, None)
            };
            if *mask && *secret_intact {
                // Draw the untouched secret as a fixed-width mask so its length
                // is not leaked (the value itself is never shown).
                f.render_widget(
                    Paragraph::new(crate::environment::SECRET_MASK)
                        .style(Style::default().fg(th.text)),
                    editor_area,
                );
                let cx = editor_area.x + crate::environment::SECRET_MASK.chars().count() as u16;
                f.set_cursor_position(ratatui::layout::Position::new(
                    cx.min(editor_area.right().saturating_sub(1)),
                    editor_area.y,
                ));
            } else {
                render_editor(f, editor_area, editor, *mask, th);
                // Show the dimmed save-extension ghost (".hurl"/".vars") after the
                // filename when it hasn't been typed yet, so Tab/Right can complete
                // it. Only for single-line, unmasked file prompts that still fit.
                let ghost = kind.save_ghost();
                if !ml && !*mask && !ghost.is_empty() {
                    let text = editor.text();
                    let len = text.chars().count() as u16;
                    if !text.ends_with(ghost) && len < editor_area.width {
                        let gx = editor_area.x + len;
                        let avail = editor_area.right().saturating_sub(gx);
                        if avail > 0 {
                            let shown: String = ghost.chars().take(avail as usize).collect();
                            f.render_widget(
                                Paragraph::new(shown).style(Style::default().fg(th.dim)),
                                Rect::new(gx, editor_area.y, avail, 1),
                            );
                        }
                    }
                }
            }
            // Only Raw Mode's / Raw JSON Mode's editor supports mouse
            // click-drag text selection (see `TuiApp::on_mouse`); recording
            // this Rect for every other prompt kind would be harmless but
            // meaningless, so it's scoped to the two cases that actually
            // hit-test against it.
            app.prompt_editor_area = if matches!(kind, PromptKind::Raw(_) | PromptKind::RawJson(_))
            {
                editor_area
            } else {
                Rect::default()
            };
            if let Some((area, checked)) = checkbox_area {
                let mark = if *checked { "[x]" } else { "[ ]" };
                let fg = if *checked { th.pending } else { th.ok };
                f.render_widget(
                    Paragraph::new(format!("{mark} {}", s.env_still_secret))
                        .style(Style::default().fg(fg)),
                    area,
                );
            }
        }
        Overlay::Browser(_action, ex) => {
            let w = (f.area().width * 7 / 10).max(50);
            let h = (f.area().height * 7 / 10).max(10);
            let area = centered_rect(w, h, f.area());
            f.render_widget(Clear, area);
            ex.widget().render_ref(area, f.buffer_mut());
        }
        Overlay::NewRequest(form) => draw_new_request(f, form, s, th, app.enhanced_keys),
        Overlay::EnvVarForm(form) => draw_env_var_form(f, form, s, th),
        Overlay::RemoteGit(w) => draw_remote_wizard(f, w, s, th),
        Overlay::GitSave(w) => draw_git_save_wizard(f, w, s, th),
        Overlay::EnvPopup(popup) => draw_env_popup(f, app, popup, s, th),
        Overlay::EnvLinkPicker(picker) => draw_env_link_picker(f, app, picker, s, th),
        Overlay::EnvCollision(collision) => draw_env_collision(f, collision, s, th),
        Overlay::WorkspacePicker(picker) => draw_workspace_picker(f, picker, s, th),
        Overlay::CloseGitWorkspace { path, sel, .. } => {
            let question = s
                .close_git_workspace_q
                .replace("{p}", &path.to_string_lossy());
            let choices = [
                s.close_git_workspace_keep,
                s.close_git_workspace_delete,
                s.close_git_workspace_cancel,
            ];
            draw_confirm_popup(f, &question, &choices, *sel, th);
        }
        Overlay::WorkspaceReloadConfirm { reload, sel, .. } => {
            let ref_label = if reload.origin.ref_kind == crate::git_remote::RefKind::Branch {
                s.git_branches
            } else {
                s.git_tags
            };
            let question = s
                .workspace_reload_confirm_q
                .replace("{name}", &reload.tab_name)
                .replace(
                    "{ref}",
                    &format!("[{ref_label}] {}", reload.origin.ref_name),
                )
                .replace("{url}", &reload.origin.repo_url);
            draw_confirm_popup(f, &question, &[s.confirm_yes, s.confirm_no], *sel, th);
        }
        Overlay::WorkspaceReloadLoading { idx } => {
            let name = app
                .collections
                .get(*idx)
                .map(|c| c.name.as_str())
                .unwrap_or("");
            let text = format!("{} ({name})", s.workspace_reload_loading);
            let w = (text.chars().count() as u16 + 4).max(30);
            let area = centered_rect(w, 5, f.area());
            f.render_widget(Clear, area);
            let block = Block::default().borders(Borders::ALL);
            f.render_widget(
                Paragraph::new(text)
                    .block(block)
                    .wrap(Wrap { trim: true })
                    .alignment(ratatui::layout::Alignment::Center),
                area,
            );
        }
        Overlay::WorkspaceStorageChoice { sel, .. } => {
            let choices = [s.git_workspace_storage_temp, s.git_workspace_storage_choose];
            draw_confirm_popup(f, s.git_workspace_storage_q, &choices, *sel, th);
        }
        Overlay::WorkspaceGitSaveUnsaved { sel, .. } => {
            let choices = [
                s.git_save_ws_unsaved_save,
                s.git_save_ws_unsaved_ignore,
                s.git_save_ws_unsaved_cancel,
            ];
            draw_confirm_popup(f, s.git_save_ws_unsaved_q, &choices, *sel, th);
        }
        Overlay::WorkspaceSwitchUnsaved { sel, .. } => {
            let choices = [
                s.ws_switch_unsaved_save,
                s.ws_switch_unsaved_discard,
                s.ws_switch_unsaved_cancel,
            ];
            draw_confirm_popup(f, s.ws_switch_unsaved_q, &choices, *sel, th);
        }
    }
}

/// The "add environment variable" popup: a two-column `Key | Value` table with
/// one editable row. The focused cell shows a cursor and a subtle background.
pub(crate) fn draw_env_var_form(f: &mut Frame, form: &EnvVarForm, s: &Strings, th: &Theme) {
    let area = centered_rect(70, 7, f.area());
    f.render_widget(Clear, area);
    let block = panel(s.env_add_var_title.to_string(), true, th);
    let inner = block.inner(area);
    f.render_widget(block, area);

    let rows = Layout::vertical([
        Constraint::Length(1), // column headers
        Constraint::Length(1), // input cells
        Constraint::Min(0),    // spacer
        Constraint::Length(1), // key hint
    ])
    .split(inner);
    let split = |r: Rect| {
        Layout::horizontal([Constraint::Percentage(40), Constraint::Percentage(60)])
            .spacing(2)
            .split(r)
    };
    let head = split(rows[0]);
    let cells = split(rows[1]);
    let lbl = |t: &str| {
        Paragraph::new(Span::styled(
            t.to_string(),
            Style::default().fg(th.dim).add_modifier(Modifier::BOLD),
        ))
    };
    f.render_widget(lbl(s.hdr_key), head[0]);
    f.render_widget(lbl(s.hdr_value), head[1]);
    render_line_field(f, cells[0], &form.key, !form.on_value, false, th);
    render_line_field(f, cells[1], &form.value, form.on_value, false, th);

    let hint = format!("Tab {} · {}", s.env_var_switch, s.prompt_save_hint_sl);
    f.render_widget(
        Paragraph::new(Span::styled(hint, Style::default().fg(th.dim))),
        rows[3],
    );
}

/// Picker (opened with 'p' in the Requests/List pane) to link/unlink a Global
/// Environment to the current collection: "(none)" plus every Global
/// Environment name, with the currently-linked one marked.
pub(crate) fn draw_env_link_picker(
    f: &mut Frame,
    app: &TuiApp,
    picker: &EnvLinkPicker,
    s: &Strings,
    th: &Theme,
) {
    let linked = app.collections.get(picker.ci).and_then(|c| c.linked_env_id);
    let mut labels: Vec<String> = vec![s.env_link_none.to_string()];
    labels.extend(app.global_envs.iter().map(|e| {
        if Some(e.id) == linked {
            format!("\u{2713} {}", e.name)
        } else {
            e.name.clone()
        }
    }));
    let items: Vec<&str> = labels.iter().map(|s| s.as_str()).collect();
    draw_menu_popup(f, s.env_link_picker_title, &items, picker.sel, th);
}

/// The 4-choice popup shown when loading an environment whose name collides
/// with one already in the Global Environments list.
pub(crate) fn draw_env_collision(f: &mut Frame, collision: &EnvCollision, s: &Strings, th: &Theme) {
    let items = [
        s.env_collision_replace,
        s.env_collision_keep_both,
        s.env_collision_abort,
        s.env_collision_rename,
    ];
    draw_menu_popup(f, s.env_collision_title, &items, collision.sel, th);
}

/// The recursive file-tree popup used both to auto-prompt (when a Workspace
/// tab has no collection chosen yet) and on-demand (global `w` key) to pick
/// which `.hurl`/`.json` file inside a Workspace folder to load. Directory
/// rows are unselectable visual grouping (bold, folder icon); file rows are
/// the only ones `nav()`/Enter act on.
pub(crate) fn draw_workspace_picker(
    f: &mut Frame,
    picker: &WorkspacePickerState,
    s: &Strings,
    th: &Theme,
) {
    let w = (f.area().width * 7 / 10).max(50);
    let h = (f.area().height * 7 / 10).max(10);
    let area = centered_rect(w, h, f.area());
    f.render_widget(Clear, area);
    let filter_label = if picker.filter_hurl_json {
        s.workspace_filter_on
    } else {
        s.workspace_filter_off
    };
    let title = format!(
        "{}{} [{filter_label}]",
        s.workspace_picker_title,
        picker.root.display()
    );
    let block = panel(title, true, th);
    let inner = block.inner(area);
    f.render_widget(block, area);
    let rows = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(inner);
    if picker.entries.is_empty() {
        f.render_widget(
            Paragraph::new(s.workspace_no_files).style(Style::default().fg(th.dim)),
            rows[0],
        );
        return;
    }
    let items: Vec<ListItem> = picker
        .entries
        .iter()
        .map(|e| {
            let indent = "  ".repeat(e.depth);
            if e.is_dir {
                ListItem::new(Line::styled(
                    format!("{indent}{FOLDER_ICON} {}/", e.display_name),
                    Style::default().fg(th.accent).add_modifier(Modifier::BOLD),
                ))
            } else {
                ListItem::new(Line::styled(
                    format!("{indent}{}", e.display_name),
                    Style::default().fg(th.text),
                ))
            }
        })
        .collect();
    let list = List::new(items)
        .highlight_style(
            Style::default()
                .bg(th.accent)
                .fg(th.bg)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("");
    let mut st = ListState::default();
    st.select(Some(picker.selected));
    f.render_stateful_widget(list, rows[0], &mut st);
    let hint = Paragraph::new(Line::styled(
        if picker.adding_request {
            s.workspace_picker_hint_add
        } else {
            s.workspace_picker_hint
        },
        Style::default().fg(th.dim),
    ));
    f.render_widget(hint, rows[1]);
}

/// Renders a menu label written with the "(X)" mnemonic convention (see
/// `app::menu_mnemonic`, which parses the very same strings for key
/// matching) as plain text with the mnemonic letter underlined and the
/// surrounding parens dropped — e.g. `"En(v)ironment…"` renders as
/// "Environment…" with the "v" underlined. Replaces the old bracketed look
/// (which several users found visually distracting) without touching the
/// underlying i18n strings or the key-matching logic, which both keep
/// working against the original "(X)" text. Labels with no such marker
/// (e.g. Preferences toggle rows) render unchanged.
pub(crate) fn mnemonic_spans(label: &str, style: Style) -> Vec<Span<'static>> {
    // Only a mnemonic marker when exactly one char sits between the
    // parens — matches `app::menu_mnemonic`'s own check.
    if let Some(open) = label.find('(')
        && let Some(close) = label[open + 1..]
            .find(')')
            .map(|r| open + 1 + r)
            .filter(|&close| close == open + 2)
    {
        let before = label[..open].to_string();
        let letter = label[open + 1..close].to_string();
        let after = label[close + 1..].to_string();
        let mut spans = Vec::with_capacity(3);
        if !before.is_empty() {
            spans.push(Span::styled(before, style));
        }
        spans.push(Span::styled(
            letter,
            style.add_modifier(Modifier::UNDERLINED),
        ));
        if !after.is_empty() {
            spans.push(Span::styled(after, style));
        }
        return spans;
    }
    vec![Span::styled(label.to_string(), style)]
}

pub(crate) fn draw_menu_popup(f: &mut Frame, title: &str, items: &[&str], sel: usize, th: &Theme) {
    let width = items
        .iter()
        .map(|i| i.len())
        .max()
        .unwrap_or(10)
        .max(title.len()) as u16
        + 6;
    let height = items.len() as u16 + 2;
    let area = centered_rect(width, height, f.area());
    f.render_widget(Clear, area);
    let list_items: Vec<ListItem> = items
        .iter()
        .map(|i| ListItem::new(Line::from(mnemonic_spans(i, Style::default().fg(th.text)))))
        .collect();
    let list = List::new(list_items)
        .block(panel(title.to_string(), true, th))
        .highlight_style(
            Style::default()
                .bg(th.accent)
                .fg(th.bg)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("");
    let mut st = ListState::default();
    st.select(Some(sel));
    f.render_stateful_widget(list, area, &mut st);
}

/// A small confirmation popup with 2+ choices, laid out in a row and
/// selected with Left/Right/Up/Down/Enter. `sel` is the highlighted index.
/// `question` may contain embedded `\n`s for explicit line breaks (e.g. to
/// put a long path on its own line) — each is wrapped independently.
pub(crate) fn draw_confirm_popup(
    f: &mut Frame,
    question: &str,
    choices: &[&str],
    sel: usize,
    th: &Theme,
) {
    let choices_len: usize = choices.iter().map(|c| c.len() + 3).sum();
    let q_lines: Vec<&str> = question.split('\n').collect();
    let max_line_len = q_lines.iter().map(|l| l.chars().count()).max().unwrap_or(0);
    let width = max_line_len.max(choices_len + 4).clamp(24, 76) as u16 + 4;
    let width = width.min(f.area().width.max(1));
    // Grow the popup vertically so the whole (possibly long) question fits: the
    // Save confirmation is much longer than the Exit/Clear ones. Estimate the
    // wrapped line count for the inner text width (matches `Wrap`'s word
    // breaks), for each explicit line of `question` in turn.
    let text_w = width.saturating_sub(2).max(1) as usize;
    let mut lines = 0usize;
    for q_line in &q_lines {
        let mut line_wraps = 1usize;
        let mut col = 0usize;
        for word in q_line.split_whitespace() {
            let wlen = word.chars().count();
            if col == 0 {
                col = wlen;
            } else if col + 1 + wlen <= text_w {
                col += 1 + wlen;
            } else {
                line_wraps += 1;
                col = wlen;
            }
        }
        lines += line_wraps;
    }
    // question lines + a blank spacer + the choices row + the two borders.
    let height = (lines as u16).saturating_add(4);
    let area = centered_rect(width, height, f.area());
    f.render_widget(Clear, area);
    let block = panel("".to_string(), true, th);
    let inner = block.inner(area);
    f.render_widget(block, area);
    let rows = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(inner);
    f.render_widget(
        Paragraph::new(question)
            .style(Style::default().fg(th.text))
            .wrap(Wrap { trim: true }),
        rows[0],
    );
    let hl = Style::default()
        .bg(th.accent)
        .fg(th.bg)
        .add_modifier(Modifier::BOLD);
    let normal = Style::default().fg(th.text);
    let mut spans = Vec::with_capacity(choices.len() * 2);
    for (i, choice) in choices.iter().enumerate() {
        if i > 0 {
            spans.push(Span::raw("   "));
        }
        spans.push(Span::styled(
            format!(" {choice} "),
            if sel == i { hl } else { normal },
        ));
    }
    f.render_widget(
        Paragraph::new(Line::from(spans)).alignment(ratatui::layout::Alignment::Center),
        rows[1],
    );
}