vorto 0.14.0

A Vim-flavored modal terminal editor with batteries included: tree-sitter, LSP, fuzzy pickers, vim-surround, multi-cursor, and optional Copilot.
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
//! Owns the bottom-line prompt (`:cmd`, `/search`, fuzzy pickers,
//! rename input) and translates key events into outcomes the App
//! reacts to.

use std::path::{Path, PathBuf};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::bookmark::Bookmark;
use crate::buffer_ref::BufferRef;
use crate::finder::{ExplorerMode, ExplorerState, Finder, FuzzyKind, IgnoreOpts};
use crate::lsp::{CodeAction, Location};

mod completion;
mod line_input;

pub use completion::{CommandPrompt, CompletionKind};
pub use line_input::LineInput;
pub(crate) use line_input::apply_line_key;

/// Active prompt state. Mirrors the four ways the user can interact
/// with the bottom-line input: `:` command line, `/` (or `?`) search,
/// fuzzy pickers, and rename.
pub enum Prompt {
    None,
    Command(CommandPrompt),
    Search {
        forward: bool,
        query: LineInput,
    },
    Fuzzy(Finder),
    /// `<space>r` — text input for the new identifier. The cursor and
    /// URI captured at open-time aren't stored here: the LSP rename
    /// request is built against the live cursor at submit, which
    /// matches what the user sees (the cursor is locked while the
    /// prompt is up because Normal-mode input is suspended).
    Rename(LineInput),
    /// `<space>a` — popup menu of LSP code actions, anchored just under
    /// the buffer cursor. Up/Down navigate, Enter submits, Esc cancels.
    /// Filtering is intentionally omitted: action lists are short and
    /// users want to read titles, not type query strings.
    CodeActionMenu {
        actions: Vec<CodeAction>,
        selected: usize,
    },
    /// `K` — read-only popup showing `textDocument/hover` content
    /// anchored at the cursor. j/k/Up/Down/PageUp/PageDown scroll the
    /// content; any other key (including Enter and Esc) closes it.
    Hover {
        content: String,
        scroll: usize,
    },
    /// `:lsp` — read-only, screen-centered modal listing every
    /// configured LSP server and whether it's currently running.
    /// Same key model as [`Self::Hover`]: scroll keys page the
    /// content, any other key dismisses.
    LspStatus {
        content: String,
        scroll: usize,
    },
    /// Copilot device-flow signin: screen-centered modal showing the
    /// user code and verification URL. The clipboard already holds
    /// `code` (the open path sets that up); the modal exists so the
    /// info doesn't scroll away in the toast queue while the user is
    /// in the browser. Any key dismisses; signin_confirm continues to
    /// run in the background.
    CopilotSignin {
        code: String,
        url: String,
    },
    /// `<space>e` — tree file explorer. Owns the full node list, the
    /// expand state, and the live fuzzy query. Submit on a file
    /// produces `OpenRelativeFile`; submit on a dir toggles its
    /// expand state in-place and stays open.
    Explorer(ExplorerState),
    /// `:grammar` — interactive list of tree-sitter grammars with their
    /// install status. Unlike the read-only modals above, this one
    /// drives actions: `j`/`k` move the selection, Enter installs the
    /// selected grammar (asynchronously — the row flips to
    /// [`GrammarState::Installing`] and the worker reports back via
    /// [`crate::event::AppEvent::GrammarInstalled`]), and `d` removes an
    /// installed one. The modal stays open across installs so the user
    /// can queue several.
    ///
    /// `/` opens a live filter — printable keys flow into `query` and the
    /// list narrows to grammars whose name contains it (case-insensitive,
    /// order preserved). Enter leaves the filter input *and* installs the
    /// highlighted grammar (the type-narrow-Enter flow); Esc just leaves
    /// the input. Either way the query stays in effect — a further Esc
    /// clears it, and one more closes the modal. While `filtering`, letter
    /// keys type into the query rather than triggering `j/k/i/d/x`; arrows
    /// and Ctrl-N/P still move the cursor either way.
    GrammarList {
        rows: Vec<GrammarRow>,
        /// Index into the *visible* (filtered) rows — see
        /// [`grammar_visible_indices`] — not into `rows` directly.
        selected: usize,
        /// Live filter text. Empty shows every row.
        query: String,
        /// `/` filter input is live; printable keys edit `query`.
        filtering: bool,
    },
    /// Shown at file-open time when the active language has an install
    /// recipe (built-in or `[grammars.*]`) but its parser/queries aren't
    /// fully installed yet — offered in place of the old "highlight
    /// failed" error toast. `y` installs (async), `n`/Esc dismisses; the
    /// arrow keys (or `h`/`l`/Tab) move between the Yes/No buttons and
    /// Enter confirms the highlighted one. We only ask once per grammar
    /// per session (see [`App::asked_grammars`]).
    GrammarInstallConfirm {
        /// Recipe/grammar name to install on accept.
        grammar: String,
        /// Language name, for the prompt message.
        language: String,
        /// Highlighted button: `true` = Yes (install), `false` = No.
        /// Toggled by the arrow keys; Enter acts on it. Opens on Yes so a
        /// bare Enter still accepts, matching the old behavior.
        accept: bool,
    },
    /// Raised by the autoreload watcher when the active buffer's backing
    /// file changed on disk (mtime/len drift from the load/save
    /// baseline). `y` reloads (taking an undo snapshot first, so the
    /// reload is recoverable with `u`); `n`/Esc dismisses and the App
    /// acks the current disk state so it won't re-prompt until the file
    /// changes *again*. Same Yes/No button model as
    /// [`Self::GrammarInstallConfirm`]. `dirty` tags whether the buffer
    /// had unsaved edits when the change was detected, so the message can
    /// warn that reloading replaces them (undo restores).
    FileReloadConfirm {
        /// Backing file path, for the prompt message.
        path: PathBuf,
        /// Whether the buffer had unsaved edits at detection time.
        dirty: bool,
        /// Highlighted button: `true` = Yes (reload), `false` = No.
        accept: bool,
    },
    /// `:agent` with no configured default — pick which AI agent to
    /// launch. A plain selection list: `j`/`k` (or arrows / Ctrl-N/P)
    /// move, Enter launches the highlighted agent (and persists it as the
    /// default), Esc cancels. No filter — the catalog is short.
    AgentPicker {
        /// Agent names, in catalog order.
        agents: Vec<String>,
        selected: usize,
    },
    /// `:theme` — filterable theme picker with **live preview**. Modeled
    /// on [`Self::GrammarList`]'s filter/navigation, but every selection
    /// change emits [`PromptOutcome::PreviewTheme`] so the App swaps the
    /// active theme as the cursor moves; Enter
    /// ([`PromptOutcome::SelectTheme`]) commits + persists, Esc cancels
    /// (the App reverts to the theme that was active when the picker
    /// opened). `/` toggles the live filter, same as the grammar modal.
    ThemePicker {
        /// Theme names (bundled ∪ user), sorted; `ansi` included.
        themes: Vec<String>,
        /// Index into the *visible* (filtered) projection — see
        /// [`theme_visible_indices`].
        selected: usize,
        /// Live filter text. Empty shows every theme.
        query: String,
        /// `/` filter input is live; printable keys edit `query`.
        filtering: bool,
    },
}

/// One grammar entry in the `:grammar` modal.
#[derive(Clone)]
pub struct GrammarRow {
    /// Grammar name — the `.so` stem and the `grammar install <name>`
    /// handle.
    pub name: String,
    pub state: GrammarState,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum GrammarState {
    /// Library present on disk.
    Installed,
    /// No library yet — Enter installs it.
    Missing,
    /// Install worker is in flight.
    Installing,
}

/// Indices into `rows` that match `query`, case-insensitive substring,
/// order preserved (the list stays alphabetically sorted while it
/// narrows). An empty query matches every row. Shared by the renderer
/// and the key handler so the visible projection can't drift between
/// what's drawn and what `selected` acts on.
pub(crate) fn grammar_visible_indices(rows: &[GrammarRow], query: &str) -> Vec<usize> {
    if query.is_empty() {
        return (0..rows.len()).collect();
    }
    let needle = query.to_lowercase();
    rows.iter()
        .enumerate()
        .filter(|(_, r)| r.name.to_lowercase().contains(&needle))
        .map(|(i, _)| i)
        .collect()
}

/// Indices into `themes` matching `query` (case-insensitive substring,
/// order preserved). Empty query matches everything. The theme-picker
/// twin of [`grammar_visible_indices`]; shared by the renderer and key
/// handler so the visible projection can't drift.
pub(crate) fn theme_visible_indices(themes: &[String], query: &str) -> Vec<usize> {
    if query.is_empty() {
        return (0..themes.len()).collect();
    }
    let needle = query.to_lowercase();
    themes
        .iter()
        .enumerate()
        .filter(|(_, name)| name.to_lowercase().contains(&needle))
        .map(|(i, _)| i)
        .collect()
}

/// Flip the row at `idx` to [`GrammarState::Installing`] and yield its
/// name to install, if it was [`Missing`](GrammarState::Missing). An
/// already-installed or in-flight row is a no-op (returns `None`).
/// Shared by the modal's Enter and `i`.
fn grammar_install_at(rows: &mut [GrammarRow], idx: usize) -> Option<String> {
    let row = rows.get_mut(idx)?;
    (row.state == GrammarState::Missing).then(|| {
        row.state = GrammarState::Installing;
        row.name.clone()
    })
}

/// Flip the row at `idx` back to [`Missing`](GrammarState::Missing) and
/// yield its name to remove, if it was
/// [`Installed`](GrammarState::Installed). No-op otherwise.
fn grammar_remove_at(rows: &mut [GrammarRow], idx: usize) -> Option<String> {
    let row = rows.get_mut(idx)?;
    (row.state == GrammarState::Installed).then(|| {
        row.state = GrammarState::Missing;
        row.name.clone()
    })
}

impl Prompt {
    pub fn is_open(&self) -> bool {
        !matches!(self, Prompt::None)
    }
}

/// What a key event produced. `Nothing` means "input absorbed, prompt
/// stays open"; everything else closes the prompt and asks the caller
/// to act.
pub enum PromptOutcome {
    Nothing,
    /// User pressed Esc / Ctrl-C — prompt closed, no action.
    Cancelled,
    /// `:cmd` submitted. Caller parses and dispatches.
    RunCommand(String),
    /// `/` or `?` submitted.
    Search {
        forward: bool,
        query: String,
    },
    /// Fuzzy file picker submission. The path is relative to
    /// `startup_cwd` — re-anchored by the caller.
    OpenRelativeFile(String),
    /// Fuzzy line picker submission. 0-based row in the active buffer.
    GotoLine(usize),
    /// Fuzzy references picker submission.
    JumpToLocation(Location),
    /// Fuzzy buffer picker submission. The caller maps the
    /// [`BufferRef`] back to an actual buffer load (`Scratch` →
    /// fresh empty buffer, `File(path)` → `open_path`).
    OpenBuffer(BufferRef),
    /// Rename submitted with the new identifier.
    SubmitRename(String),
    /// Code action picker selection. The caller either applies the
    /// embedded `WorkspaceEdit` or sends a `codeAction/resolve` round
    /// trip first when `edit` is `None`.
    SelectCodeAction(CodeAction),
    /// Explorer rename/move — a file or directory was relocated on
    /// disk from `old` to `new` (both absolute). The caller rewrites
    /// any open or sleeping buffer whose path falls under `old` so the
    /// next save lands at the new location instead of recreating the
    /// source. The explorer prompt stays open.
    PathMoved {
        old: PathBuf,
        new: PathBuf,
    },
    /// `:grammar` modal — Enter on a missing grammar. The caller spawns
    /// the install worker; the modal stays open with the row already
    /// flipped to [`GrammarState::Installing`].
    InstallGrammar(String),
    /// `:grammar` modal — `d` on an installed grammar. The caller
    /// deletes the library; the modal stays open with the row flipped
    /// back to [`GrammarState::Missing`].
    RemoveGrammar(String),
    /// `:agent` picker — Enter on the highlighted agent. The caller
    /// launches it and persists it as the default (first time only).
    SelectAgent(String),
    /// `:theme` picker — the highlighted theme changed (navigation or a
    /// filter edit). The caller swaps the active theme for live preview
    /// *without* persisting; the picker stays open.
    PreviewTheme(String),
    /// `:theme` picker — Enter committed the highlighted theme. The
    /// caller keeps it active and writes `theme = "..."` to the config.
    SelectTheme(String),
    /// `<space>mm` picker — Enter on a mark. The caller switches to the
    /// mark's buffer and parks the cursor on its line; the picker closes.
    GotoBookmark(Bookmark),
    /// `<space>mm` picker — `d` on a mark. The caller drops it from the
    /// store (and persists); the picker stays open with the row already
    /// removed from its in-memory list.
    RemoveBookmark(BufferRef),
    /// Autoreload confirm — `y`/Enter accepted. The caller re-reads the
    /// active buffer from disk (same path as `:reload`).
    ReloadFile,
    /// Autoreload confirm — `n`/Esc declined. The caller acks the current
    /// on-disk state so the watcher won't re-prompt until the file
    /// changes again.
    DeclineReloadFile,
}

/// Interaction mode for the `Fuzzy(Bookmarks)` picker, mirroring the
/// file explorer: [`Selection`](Self::Selection) is the default where
/// `j`/`k`/`d`/Enter act on the highlighted row, and `/` switches to
/// [`Filter`](Self::Filter) where printable keys narrow the list. This
/// is what makes the bookmark picker behave like `<space>e` rather than
/// a type-to-filter fuzzy finder.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum BookmarkPickMode {
    Selection,
    Filter,
}

pub struct PromptController {
    pub state: Prompt,
    /// Side-channel for `Fuzzy(Locations)` pickers — `locations[idx]`
    /// matches the picker's `items[idx]`. Cleared on submit or cancel.
    locations: Vec<Location>,
    /// Side-channel for `Fuzzy(Buffers)` pickers — `buffer_paths[idx]`
    /// is the buffer to open when the user submits the matching item.
    /// Cleared on submit or cancel.
    buffer_paths: Vec<BufferRef>,
    /// Side-channel for `Fuzzy(Bookmarks)` pickers — `bookmark_marks[idx]`
    /// is the jump target / delete subject for the matching item. Cleared
    /// on submit or cancel.
    bookmark_marks: Vec<Bookmark>,
    /// Current mode of the bookmark picker (Selection vs Filter). Reset to
    /// Selection each time the picker opens.
    bookmark_mode: BookmarkPickMode,
}

impl PromptController {
    pub fn new() -> Self {
        Self {
            state: Prompt::None,
            locations: Vec::new(),
            buffer_paths: Vec::new(),
            bookmark_marks: Vec::new(),
            bookmark_mode: BookmarkPickMode::Selection,
        }
    }

    pub fn is_open(&self) -> bool {
        self.state.is_open()
    }

    /// Side-channel `Location`s that mirror the active `Locations` picker.
    /// Returns `&[]` for any other prompt state. The UI uses this to read
    /// `locations[idx]` for preview rendering.
    pub fn locations(&self) -> &[Location] {
        &self.locations
    }

    pub fn open_command(&mut self) {
        self.state = Prompt::Command(CommandPrompt::new());
    }

    pub fn open_search(&mut self, forward: bool) {
        self.state = Prompt::Search {
            forward,
            query: LineInput::new(),
        };
    }

    pub fn open_files(
        &mut self,
        startup_cwd: &Path,
        ignore: IgnoreOpts,
        hidden_patterns: &[String],
        max_items: usize,
    ) {
        self.state = Prompt::Fuzzy(Finder::files(
            startup_cwd,
            ignore,
            hidden_patterns,
            max_items,
        ));
    }

    /// `<space>e` — tree file explorer. All dirs start collapsed; the
    /// user expands by pressing Enter / Right on a dir row. Typing
    /// into the query box fuzzy-filters files and auto-expands their
    /// ancestor dirs so matches stay reachable.
    pub fn open_explorer(
        &mut self,
        startup_cwd: &Path,
        ignore: IgnoreOpts,
        hidden_patterns: Vec<String>,
        max_items: usize,
        compact: bool,
    ) {
        self.state = Prompt::Explorer(ExplorerState::new(
            startup_cwd,
            ignore,
            hidden_patterns,
            max_items,
            compact,
        ));
    }

    pub fn open_lines(&mut self, lines: &[String]) {
        self.state = Prompt::Fuzzy(Finder::lines(lines));
    }

    pub fn open_locations(&mut self, items: Vec<String>, locations: Vec<Location>) {
        self.locations = locations;
        self.state = Prompt::Fuzzy(Finder::locations(items));
    }

    /// Open the jump-history picker. Same `Location` side-channel as
    /// [`Self::open_locations`]; submit fires `JumpToLocation`.
    pub fn open_jumps(&mut self, items: Vec<String>, locations: Vec<Location>) {
        self.locations = locations;
        self.state = Prompt::Fuzzy(Finder::jumps(items));
    }

    /// `<space>d` / `<space>D` — diagnostics picker. Same `Location`
    /// side-channel as references; only the picker kind (and therefore
    /// the title / formatting) differs.
    pub fn open_diagnostics(
        &mut self,
        items: Vec<String>,
        locations: Vec<Location>,
        workspace: bool,
    ) {
        self.locations = locations;
        self.state = Prompt::Fuzzy(Finder::diagnostics(items, workspace));
    }

    /// `<space>/` — workspace-wide content picker. One candidate per
    /// file; on each keystroke, the Finder scans every line of every
    /// file and exposes the matched line numbers via
    /// `MatchItem::line_hits`. Submit jumps to the file's best-scoring
    /// match.
    ///
    /// `locations[i]` is the *base* `Location` for `items[i]`: same
    /// URI, line 0. Submit clones it and overrides the line with
    /// `selection.line_hits[0]`.
    pub fn open_workspace_search(
        &mut self,
        items: Vec<String>,
        file_lines: Vec<Vec<String>>,
        locations: Vec<Location>,
    ) {
        self.locations = locations;
        self.state = Prompt::Fuzzy(Finder::workspace_search(items, file_lines));
    }

    /// Open a fuzzy buffer picker. `items` are the display strings;
    /// `refs` are the matching [`BufferRef`]s in parallel order —
    /// the controller stores them and produces an `OpenBuffer(…)`
    /// outcome on submit.
    pub fn open_buffers(&mut self, items: Vec<String>, refs: Vec<BufferRef>) {
        self.buffer_paths = refs;
        self.state = Prompt::Fuzzy(Finder::buffers(items));
    }

    /// `<space>g` — git changed-files picker. `items` are paths relative
    /// to the workspace root when under it, absolute otherwise; submit
    /// produces `OpenRelativeFile` exactly like the file picker (which
    /// resolves both forms), so there's no side-channel to stash.
    pub fn open_git_changed(&mut self, items: Vec<String>) {
        self.state = Prompt::Fuzzy(Finder::git_changed(items));
    }

    /// Read-only view of the buffer-picker side-channel, mirroring
    /// [`Self::locations`]. The UI uses this for preview rendering.
    pub fn buffer_paths(&self) -> &[BufferRef] {
        &self.buffer_paths
    }

    /// Read-only view of the bookmark-picker side-channel. The UI reads
    /// `bookmark_marks()[idx]` to render the preview for the selected
    /// mark.
    pub fn bookmark_marks(&self) -> &[Bookmark] {
        &self.bookmark_marks
    }

    pub fn open_rename(&mut self) {
        self.state = Prompt::Rename(LineInput::new());
    }

    /// Open the cursor-anchored code-actions popup. `actions` is consumed
    /// — we own them while the menu is up so submit can hand a fully-
    /// owned `CodeAction` to the caller without an extra clone.
    pub fn open_code_actions(&mut self, actions: Vec<CodeAction>) {
        self.state = Prompt::CodeActionMenu {
            actions,
            selected: 0,
        };
    }

    /// Open a hover popup with the given content. Cursor position is
    /// captured by the renderer at draw time, so `App` doesn't need to
    /// store it.
    pub fn open_hover(&mut self, content: String) {
        self.state = Prompt::Hover { content, scroll: 0 };
    }

    /// Open the `:lsp` status modal with pre-formatted content.
    pub fn open_lsp_status(&mut self, content: String) {
        self.state = Prompt::LspStatus { content, scroll: 0 };
    }

    /// Open the `:grammar` modal with the given rows. Selection starts
    /// at the top.
    pub fn open_grammar_list(&mut self, rows: Vec<GrammarRow>) {
        self.state = Prompt::GrammarList {
            rows,
            selected: 0,
            query: String::new(),
            filtering: false,
        };
    }

    /// Update a grammar row's state in place when the modal is open and
    /// still showing this grammar. No-op otherwise (the user may have
    /// closed the modal before the install worker reported back). Called
    /// from the `GrammarInstalled` handler.
    pub fn grammar_set_state(&mut self, name: &str, state: GrammarState) {
        if let Prompt::GrammarList { rows, .. } = &mut self.state
            && let Some(row) = rows.iter_mut().find(|r| r.name == name)
        {
            row.state = state;
        }
    }

    /// Open the open-time "install this grammar?" confirmation modal.
    pub fn open_grammar_install_prompt(&mut self, grammar: String, language: String) {
        self.state = Prompt::GrammarInstallConfirm {
            grammar,
            language,
            accept: true,
        };
    }

    /// Open the autoreload "file changed on disk — reload?" confirmation.
    /// Opens on Yes so a bare Enter reloads. `dirty` drives the
    /// unsaved-edits warning in the message.
    pub fn open_file_reload_prompt(&mut self, path: PathBuf, dirty: bool) {
        self.state = Prompt::FileReloadConfirm {
            path,
            dirty,
            accept: true,
        };
    }

    /// Open the Copilot signin modal. Any prior modal is replaced.
    pub fn open_copilot_signin(&mut self, code: String, url: String) {
        self.state = Prompt::CopilotSignin { code, url };
    }

    /// Open the `:agent` picker with `agents` (catalog order). Selection
    /// starts at the top.
    pub fn open_agent_picker(&mut self, agents: Vec<String>) {
        self.state = Prompt::AgentPicker {
            agents,
            selected: 0,
        };
    }

    /// Open the `:theme` picker. `selected` starts on the currently
    /// active theme (`current`) when it's in the list, so the cursor
    /// lands on what's already applied and arrowing away previews
    /// alternatives.
    pub fn open_theme_picker(&mut self, themes: Vec<String>, current: &str) {
        let selected = themes.iter().position(|t| t == current).unwrap_or(0);
        self.state = Prompt::ThemePicker {
            themes,
            selected,
            query: String::new(),
            filtering: false,
        };
    }

    /// Open the `<space>mm` bookmark picker as a [`FuzzyKind::Bookmarks`]
    /// finder. `items[i]` is the `path:line` display string for
    /// `marks[i]` (the jump target / delete subject) — the two stay
    /// parallel, including across `Ctrl-d` deletes.
    pub fn open_bookmarks(&mut self, items: Vec<String>, marks: Vec<Bookmark>) {
        self.bookmark_marks = marks;
        self.bookmark_mode = BookmarkPickMode::Selection;
        self.state = Prompt::Fuzzy(Finder::bookmarks(items));
    }

    /// The bookmark picker's current mode — the renderer uses it to show
    /// the query line only while filtering and to label the footer.
    pub fn bookmark_mode(&self) -> BookmarkPickMode {
        self.bookmark_mode
    }

    /// Key handling for the `Fuzzy(Bookmarks)` picker, modeled on the file
    /// explorer: Selection mode is the default (navigate + `d` delete +
    /// Enter jump), `/` switches to Filter mode (printable keys narrow the
    /// fuzzy match set), and Esc peels Filter → Selection → close.
    fn handle_bookmark_key(&mut self, key: KeyEvent) -> PromptOutcome {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        if ctrl && key.code == KeyCode::Char('c') {
            self.close();
            return PromptOutcome::Cancelled;
        }
        match self.bookmark_mode {
            BookmarkPickMode::Selection => match key.code {
                KeyCode::Esc => {
                    self.close();
                    PromptOutcome::Cancelled
                }
                KeyCode::Enter => self.submit(),
                KeyCode::Char('j') | KeyCode::Down => {
                    self.finder_next();
                    PromptOutcome::Nothing
                }
                KeyCode::Char('k') | KeyCode::Up => {
                    self.finder_prev();
                    PromptOutcome::Nothing
                }
                KeyCode::Char('n') if ctrl => {
                    self.finder_next();
                    PromptOutcome::Nothing
                }
                KeyCode::Char('p') if ctrl => {
                    self.finder_prev();
                    PromptOutcome::Nothing
                }
                KeyCode::Char('/') => {
                    self.bookmark_mode = BookmarkPickMode::Filter;
                    PromptOutcome::Nothing
                }
                KeyCode::Char('d') | KeyCode::Char('x') => self.delete_selected_bookmark(),
                _ => PromptOutcome::Nothing,
            },
            BookmarkPickMode::Filter => match key.code {
                // Esc leaves the filter input but keeps the picker open
                // (and the query in effect); a second Esc — now in
                // Selection — closes.
                KeyCode::Esc => {
                    self.bookmark_mode = BookmarkPickMode::Selection;
                    PromptOutcome::Nothing
                }
                KeyCode::Enter => self.submit(),
                KeyCode::Up => {
                    self.finder_prev();
                    PromptOutcome::Nothing
                }
                KeyCode::Down => {
                    self.finder_next();
                    PromptOutcome::Nothing
                }
                KeyCode::Char('n') if ctrl => {
                    self.finder_next();
                    PromptOutcome::Nothing
                }
                KeyCode::Char('p') if ctrl => {
                    self.finder_prev();
                    PromptOutcome::Nothing
                }
                // Everything else edits the fuzzy query.
                _ => {
                    if let Prompt::Fuzzy(finder) = &mut self.state {
                        finder.apply_line_key(key);
                    }
                    PromptOutcome::Nothing
                }
            },
        }
    }

    fn finder_next(&mut self) {
        if let Prompt::Fuzzy(finder) = &mut self.state {
            finder.next();
        }
    }

    fn finder_prev(&mut self) {
        if let Prompt::Fuzzy(finder) = &mut self.state {
            finder.prev();
        }
    }

    /// Remove the highlighted mark from the bookmark picker (Selection
    /// mode `d`): drop it from the finder's item list and the parallel
    /// side-channel, then ask the caller to drop it from the store. The
    /// picker stays open.
    fn delete_selected_bookmark(&mut self) -> PromptOutcome {
        let idx = match &self.state {
            Prompt::Fuzzy(finder) => finder.selection().map(|s| s.idx),
            _ => None,
        };
        let Some(idx) = idx else {
            return PromptOutcome::Nothing;
        };
        let Some(target) = self.bookmark_marks.get(idx).map(|m| m.target.clone()) else {
            return PromptOutcome::Nothing;
        };
        if let Prompt::Fuzzy(finder) = &mut self.state {
            finder.remove_item(idx);
        }
        self.bookmark_marks.remove(idx);
        PromptOutcome::RemoveBookmark(target)
    }

    pub fn handle_key(&mut self, key: KeyEvent, root: &Path) -> PromptOutcome {
        let ctrl_c =
            key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c');

        // Bookmark picker: an Explorer-style Selection/Filter widget
        // built on the fuzzy finder (so it keeps the preview pane). Owns
        // all of its keys — `j`/`k`/`d`/Enter in Selection, `/` to filter
        // — so it never reaches the generic close/submit path below.
        if matches!(&self.state, Prompt::Fuzzy(f) if f.kind == FuzzyKind::Bookmarks) {
            return self.handle_bookmark_key(key);
        }

        // Explorer steals Esc/Enter ahead of the generic close/submit
        // path so its sub-modes can carry their own meaning: Esc may
        // pop back to selection (from filter / pending input) rather
        // than closing the prompt, and Enter routes to file ops when a
        // pending mode is up.
        if let Prompt::Explorer(state) = &mut self.state {
            if key.code == KeyCode::Esc || ctrl_c {
                if matches!(state.mode, ExplorerMode::Selection) {
                    self.close();
                    return PromptOutcome::Cancelled;
                }
                state.cancel_pending();
                return PromptOutcome::Nothing;
            }
            if key.code == KeyCode::Enter {
                return self.handle_explorer_enter();
            }
            // `y` confirms a pending delete; the explorer's apply_key
            // treats anything else (besides Enter/Esc above) as a
            // cancel.
            if matches!(state.mode, ExplorerMode::PendingDelete)
                && matches!(key.code, KeyCode::Char('y') | KeyCode::Char('Y'))
            {
                return self.run_explorer_delete();
            }
            state.apply_key(key);
            return PromptOutcome::Nothing;
        }

        // `:grammar` modal owns Enter (install) and `d` (remove) ahead
        // of the generic submit/close path, since Enter must *not* close
        // the modal — the user queues an install and keeps browsing. It
        // also owns `/` (filter) and, while filtering, every printable
        // key (they edit the query rather than firing j/k/i/d/x).
        if let Prompt::GrammarList {
            rows,
            selected,
            query,
            filtering,
        } = &mut self.state
        {
            let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

            // Ctrl-C always closes; Esc peels back one layer at a time —
            // out of filter input, then a non-empty filter, then the modal.
            if ctrl_c {
                self.close();
                return PromptOutcome::Cancelled;
            }
            if key.code == KeyCode::Esc {
                if *filtering {
                    *filtering = false;
                } else if !query.is_empty() {
                    query.clear();
                    *selected = 0;
                } else {
                    self.close();
                    return PromptOutcome::Cancelled;
                }
                return PromptOutcome::Nothing;
            }

            // `selected` indexes the visible (filtered) projection.
            let visible = grammar_visible_indices(rows, query);
            let last = visible.len().saturating_sub(1);

            // Navigation that works in both modes: arrows + Ctrl-N/P never
            // collide with query text.
            match key.code {
                KeyCode::Up => {
                    *selected = selected.saturating_sub(1);
                    return PromptOutcome::Nothing;
                }
                KeyCode::Down => {
                    *selected = (*selected + 1).min(last);
                    return PromptOutcome::Nothing;
                }
                KeyCode::Char('p') if ctrl => {
                    *selected = selected.saturating_sub(1);
                    return PromptOutcome::Nothing;
                }
                KeyCode::Char('n') if ctrl => {
                    *selected = (*selected + 1).min(last);
                    return PromptOutcome::Nothing;
                }
                _ => {}
            }

            if *filtering {
                // Filter input: printable keys (no Ctrl) edit the query;
                // each edit resets the cursor to the top match. Enter
                // leaves the input (the query stays in effect) *and*
                // installs the highlighted grammar if it's missing — the
                // type-narrow-Enter flow installs in one keystroke. Letter
                // actions (i/d/x) aren't available while typing.
                match key.code {
                    KeyCode::Enter => {
                        *filtering = false;
                        if let Some(&idx) = visible.get(*selected)
                            && let Some(name) = grammar_install_at(rows, idx)
                        {
                            return PromptOutcome::InstallGrammar(name);
                        }
                    }
                    KeyCode::Backspace => {
                        query.pop();
                        *selected = 0;
                    }
                    KeyCode::Char(c) if !ctrl => {
                        query.push(c);
                        *selected = 0;
                    }
                    _ => {}
                }
                return PromptOutcome::Nothing;
            }

            // Selection mode: vim motions + single-key actions.
            match key.code {
                KeyCode::Char('k') => *selected = selected.saturating_sub(1),
                KeyCode::Char('j') => *selected = (*selected + 1).min(last),
                KeyCode::Char('/') => *filtering = true,
                KeyCode::Enter | KeyCode::Char('i') => {
                    if let Some(&idx) = visible.get(*selected)
                        && let Some(name) = grammar_install_at(rows, idx)
                    {
                        return PromptOutcome::InstallGrammar(name);
                    }
                }
                KeyCode::Char('d') | KeyCode::Char('x') => {
                    if let Some(&idx) = visible.get(*selected)
                        && let Some(name) = grammar_remove_at(rows, idx)
                    {
                        return PromptOutcome::RemoveGrammar(name);
                    }
                }
                _ => {}
            }
            return PromptOutcome::Nothing;
        }

        // `:theme` picker. Like the grammar modal it owns `/` (filter)
        // and, while filtering, the printable keys — but every selection
        // change emits `PreviewTheme` so the App swaps the active theme as
        // the cursor moves. Enter commits (`SelectTheme`); Esc peels back
        // filter input → non-empty query → the modal (reverting handled by
        // the App on `Cancelled`).
        if let Prompt::ThemePicker {
            themes,
            selected,
            query,
            filtering,
        } = &mut self.state
        {
            let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

            if ctrl_c {
                self.close();
                return PromptOutcome::Cancelled;
            }

            if key.code == KeyCode::Esc {
                if *filtering {
                    *filtering = false;
                    return PromptOutcome::Nothing;
                } else if !query.is_empty() {
                    query.clear();
                    *selected = 0;
                    // fall through to re-preview the new top match
                } else {
                    self.close();
                    return PromptOutcome::Cancelled;
                }
            } else {
                let visible = theme_visible_indices(themes, query);
                let last = visible.len().saturating_sub(1);
                match key.code {
                    // Navigation works in both modes (never types).
                    KeyCode::Up => *selected = selected.saturating_sub(1),
                    KeyCode::Down => *selected = (*selected + 1).min(last),
                    KeyCode::Char('p') if ctrl => *selected = selected.saturating_sub(1),
                    KeyCode::Char('n') if ctrl => *selected = (*selected + 1).min(last),
                    // Enter commits in either mode.
                    KeyCode::Enter => {
                        let name = visible.get(*selected).and_then(|&i| themes.get(i)).cloned();
                        self.close();
                        return name
                            .map(PromptOutcome::SelectTheme)
                            .unwrap_or(PromptOutcome::Cancelled);
                    }
                    // While filtering, printable keys edit the query.
                    _ if *filtering => match key.code {
                        KeyCode::Backspace => {
                            query.pop();
                            *selected = 0;
                        }
                        KeyCode::Char(c) if !ctrl => {
                            query.push(c);
                            *selected = 0;
                        }
                        _ => return PromptOutcome::Nothing,
                    },
                    // Selection-mode vim motions + `/` to filter.
                    KeyCode::Char('k') => *selected = selected.saturating_sub(1),
                    KeyCode::Char('j') => *selected = (*selected + 1).min(last),
                    KeyCode::Char('/') => {
                        *filtering = true;
                        return PromptOutcome::Nothing;
                    }
                    _ => return PromptOutcome::Nothing,
                }
            }

            // Any path that moved the selection (or cleared the filter)
            // previews whatever is now highlighted.
            let visible = theme_visible_indices(themes, query);
            let name = visible.get(*selected).and_then(|&i| themes.get(i)).cloned();
            return name
                .map(PromptOutcome::PreviewTheme)
                .unwrap_or(PromptOutcome::Nothing);
        }

        // Open-time "install this grammar?" confirmation. `y` installs,
        // `n`/Esc/Ctrl-C decline; the arrow keys (or `h`/`l`/Tab) move
        // between the Yes/No buttons and Enter acts on the highlighted
        // one. Stray keys are ignored so the dialog stays put. The App
        // already recorded the grammar in `asked_grammars`, so dismissing
        // won't re-prompt this session.
        if let Prompt::GrammarInstallConfirm {
            grammar, accept, ..
        } = &mut self.state
        {
            // Arrow / Tab navigation toggles the highlighted button and
            // keeps the dialog open.
            match key.code {
                KeyCode::Left
                | KeyCode::Right
                | KeyCode::Up
                | KeyCode::Down
                | KeyCode::Char('h')
                | KeyCode::Char('l')
                | KeyCode::Tab
                | KeyCode::BackTab => {
                    *accept = !*accept;
                    return PromptOutcome::Nothing;
                }
                _ => {}
            }

            // Decision keys. Copy the choice out before `close()` so the
            // mutable borrow of `state` is released.
            let decision = if ctrl_c || key.code == KeyCode::Esc {
                Some(false)
            } else {
                match key.code {
                    KeyCode::Char('y') | KeyCode::Char('Y') => Some(true),
                    KeyCode::Char('n') | KeyCode::Char('N') => Some(false),
                    KeyCode::Enter => Some(*accept),
                    _ => None,
                }
            };
            let Some(install) = decision else {
                return PromptOutcome::Nothing;
            };
            let grammar = grammar.clone();
            self.close();
            return if install {
                PromptOutcome::InstallGrammar(grammar)
            } else {
                PromptOutcome::Cancelled
            };
        }

        // Autoreload confirm — same Yes/No model as the grammar prompt.
        // Declining returns `DeclineReloadFile` (not `Cancelled`) so the
        // App can ack the current disk state and stop re-prompting.
        if let Prompt::FileReloadConfirm { accept, .. } = &mut self.state {
            match key.code {
                KeyCode::Left
                | KeyCode::Right
                | KeyCode::Up
                | KeyCode::Down
                | KeyCode::Char('h')
                | KeyCode::Char('l')
                | KeyCode::Tab
                | KeyCode::BackTab => {
                    *accept = !*accept;
                    return PromptOutcome::Nothing;
                }
                _ => {}
            }
            let decision = if ctrl_c || key.code == KeyCode::Esc {
                Some(false)
            } else {
                match key.code {
                    KeyCode::Char('y') | KeyCode::Char('Y') => Some(true),
                    KeyCode::Char('n') | KeyCode::Char('N') => Some(false),
                    KeyCode::Enter => Some(*accept),
                    _ => None,
                }
            };
            let Some(reload) = decision else {
                return PromptOutcome::Nothing;
            };
            self.close();
            return if reload {
                PromptOutcome::ReloadFile
            } else {
                PromptOutcome::DeclineReloadFile
            };
        }

        if key.code == KeyCode::Esc || ctrl_c {
            self.close();
            return PromptOutcome::Cancelled;
        }
        if key.code == KeyCode::Enter {
            return self.submit();
        }

        match &mut self.state {
            Prompt::None => PromptOutcome::Nothing,
            Prompt::Command(cp) => {
                match key.code {
                    KeyCode::Tab => cp.tab(1, root),
                    KeyCode::BackTab => cp.tab(-1, root),
                    _ => {
                        cp.completion = None;
                        apply_line_key(&mut cp.input, key);
                    }
                }
                PromptOutcome::Nothing
            }
            Prompt::Rename(input) => {
                apply_line_key(input, key);
                PromptOutcome::Nothing
            }
            Prompt::Search { query, .. } => {
                apply_line_key(query, key);
                PromptOutcome::Nothing
            }
            Prompt::Fuzzy(finder) => {
                let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                match key.code {
                    KeyCode::Up => finder.prev(),
                    KeyCode::Down => finder.next(),
                    KeyCode::Char('n') if ctrl => finder.next(),
                    KeyCode::Char('p') if ctrl => finder.prev(),
                    _ => finder.apply_line_key(key),
                }
                PromptOutcome::Nothing
            }
            Prompt::CodeActionMenu { actions, selected } => {
                let last = actions.len().saturating_sub(1);
                match key.code {
                    KeyCode::Up => *selected = selected.saturating_sub(1),
                    KeyCode::Char('k') => *selected = selected.saturating_sub(1),
                    KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                        *selected = selected.saturating_sub(1)
                    }
                    KeyCode::Down => *selected = (*selected + 1).min(last),
                    KeyCode::Char('j') => *selected = (*selected + 1).min(last),
                    KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                        *selected = (*selected + 1).min(last)
                    }
                    _ => {}
                }
                PromptOutcome::Nothing
            }
            Prompt::AgentPicker { agents, selected } => {
                // Selection list like CodeActionMenu: navigate here, Enter
                // submits via `submit()` (intercepted at the top of
                // `handle_key`), Esc closes generically.
                let last = agents.len().saturating_sub(1);
                let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                match key.code {
                    KeyCode::Up | KeyCode::Char('k') => *selected = selected.saturating_sub(1),
                    KeyCode::Char('p') if ctrl => *selected = selected.saturating_sub(1),
                    KeyCode::Down | KeyCode::Char('j') => *selected = (*selected + 1).min(last),
                    KeyCode::Char('n') if ctrl => *selected = (*selected + 1).min(last),
                    _ => {}
                }
                PromptOutcome::Nothing
            }
            Prompt::Explorer(_)
            | Prompt::GrammarList { .. }
            | Prompt::GrammarInstallConfirm { .. }
            | Prompt::FileReloadConfirm { .. }
            | Prompt::ThemePicker { .. } => {
                // All fully handled by their early intercepts above (they
                // own Esc/Enter and per-key dispatch). Reaching this arm
                // means the early branch didn't match — which shouldn't
                // happen — but stay defensive.
                PromptOutcome::Nothing
            }
            Prompt::Hover { scroll, .. } | Prompt::LspStatus { scroll, .. } => {
                // Read-only popup. Esc/Ctrl-C/Enter are intercepted by
                // the top of `handle_key`, so here we only see scroll
                // keys and "anything else" (which we treat as dismiss).
                match key.code {
                    KeyCode::Up | KeyCode::Char('k') => {
                        *scroll = scroll.saturating_sub(1);
                    }
                    KeyCode::Down | KeyCode::Char('j') => {
                        *scroll = scroll.saturating_add(1);
                    }
                    KeyCode::PageUp => {
                        *scroll = scroll.saturating_sub(5);
                    }
                    KeyCode::PageDown => {
                        *scroll = scroll.saturating_add(5);
                    }
                    _ => {
                        self.close();
                        return PromptOutcome::Cancelled;
                    }
                }
                PromptOutcome::Nothing
            }
            Prompt::CopilotSignin { .. } => {
                // No scrollable body — any non-Esc/Ctrl-C/Enter key
                // dismisses too. Esc/Ctrl-C handled at the top.
                self.close();
                PromptOutcome::Cancelled
            }
        }
    }

    /// Enter handler for the Explorer prompt. The meaning depends on
    /// the current mode:
    ///   * `Selection` / `Filter` — on a dir, toggle expand; on a file,
    ///     close the prompt and signal `OpenRelativeFile`.
    ///   * `PendingCreate` / `PendingRename` / `PendingMove` — run the
    ///     filesystem op against the input buffer.
    ///   * `PendingDelete` — Enter on the confirmation is treated as
    ///     "yes" (matching the shell convention for default-yes when
    ///     the user explicitly pressed `d` already; we still default
    ///     the chord to N for any other key).
    fn handle_explorer_enter(&mut self) -> PromptOutcome {
        let Prompt::Explorer(state) = &mut self.state else {
            return PromptOutcome::Nothing;
        };
        match state.mode {
            ExplorerMode::Selection | ExplorerMode::Filter => {
                let Some(node) = state.selection() else {
                    return PromptOutcome::Nothing;
                };
                if node.is_dir {
                    state.toggle_selected();
                    state.refilter();
                    return PromptOutcome::Nothing;
                }
                let rel = node.rel_path.clone();
                self.close();
                PromptOutcome::OpenRelativeFile(rel)
            }
            ExplorerMode::PendingCreate => self.run_explorer_create(),
            ExplorerMode::PendingRename => self.run_explorer_rename(),
            ExplorerMode::PendingMove => self.run_explorer_move(),
            ExplorerMode::PendingDelete => self.run_explorer_delete(),
        }
    }

    fn run_explorer_create(&mut self) -> PromptOutcome {
        let Prompt::Explorer(state) = &mut self.state else {
            return PromptOutcome::Nothing;
        };
        let Some(input) = state.action.as_ref() else {
            return PromptOutcome::Nothing;
        };
        let raw = input.text.clone();
        match state.perform_create(&raw) {
            Ok(_) => {
                state.cancel_pending();
                PromptOutcome::Nothing
            }
            Err(msg) => {
                state.error = Some(msg);
                PromptOutcome::Nothing
            }
        }
    }

    fn run_explorer_rename(&mut self) -> PromptOutcome {
        let Prompt::Explorer(state) = &mut self.state else {
            return PromptOutcome::Nothing;
        };
        let Some(node) = state.selection() else {
            return PromptOutcome::Nothing;
        };
        let old_rel = node.rel_path.clone();
        let Some(input) = state.action.as_ref() else {
            return PromptOutcome::Nothing;
        };
        let new_name = input.text.clone();
        match state.perform_rename(&old_rel, &new_name) {
            Ok(new_rel) => {
                let old_abs = state.root.join(&old_rel);
                let new_abs = state.root.join(&new_rel);
                state.cancel_pending();
                PromptOutcome::PathMoved {
                    old: old_abs,
                    new: new_abs,
                }
            }
            Err(msg) => {
                state.error = Some(msg);
                PromptOutcome::Nothing
            }
        }
    }

    fn run_explorer_move(&mut self) -> PromptOutcome {
        let Prompt::Explorer(state) = &mut self.state else {
            return PromptOutcome::Nothing;
        };
        let Some(node) = state.selection() else {
            return PromptOutcome::Nothing;
        };
        let old_rel = node.rel_path.clone();
        let Some(input) = state.action.as_ref() else {
            return PromptOutcome::Nothing;
        };
        let new_rel = input.text.clone();
        match state.perform_move(&old_rel, &new_rel) {
            Ok(new_rel) => {
                let old_abs = state.root.join(&old_rel);
                let new_abs = state.root.join(&new_rel);
                state.cancel_pending();
                PromptOutcome::PathMoved {
                    old: old_abs,
                    new: new_abs,
                }
            }
            Err(msg) => {
                state.error = Some(msg);
                PromptOutcome::Nothing
            }
        }
    }

    fn run_explorer_delete(&mut self) -> PromptOutcome {
        let Prompt::Explorer(state) = &mut self.state else {
            return PromptOutcome::Nothing;
        };
        let Some(node) = state.selection() else {
            return PromptOutcome::Nothing;
        };
        let rel = node.rel_path.clone();
        match state.perform_delete(&rel) {
            Ok(()) => {
                state.cancel_pending();
                PromptOutcome::Nothing
            }
            Err(msg) => {
                state.error = Some(msg);
                PromptOutcome::Nothing
            }
        }
    }

    fn close(&mut self) {
        self.state = Prompt::None;
        self.locations.clear();
        self.buffer_paths.clear();
        self.bookmark_marks.clear();
    }

    fn submit(&mut self) -> PromptOutcome {
        let prompt = std::mem::replace(&mut self.state, Prompt::None);
        match prompt {
            Prompt::None => PromptOutcome::Nothing,
            Prompt::Command(cp) => PromptOutcome::RunCommand(cp.input.as_str().trim().to_string()),
            Prompt::Search { forward, query } => PromptOutcome::Search {
                forward,
                query: query.into_string(),
            },
            Prompt::Rename(new_name) => PromptOutcome::SubmitRename(new_name.into_string()),
            Prompt::Fuzzy(finder) => self.submit_fuzzy(finder),
            // Explorer's and the grammar modal's submits are short-
            // circuited inside `handle_key` (their early intercepts own
            // Enter), so these branches are only reached through a
            // future caller that bypasses the key path — no-op.
            Prompt::Explorer(_)
            | Prompt::GrammarList { .. }
            | Prompt::GrammarInstallConfirm { .. }
            | Prompt::FileReloadConfirm { .. }
            | Prompt::ThemePicker { .. } => PromptOutcome::Nothing,
            Prompt::CodeActionMenu {
                mut actions,
                selected,
            } => {
                if selected < actions.len() {
                    PromptOutcome::SelectCodeAction(actions.swap_remove(selected))
                } else {
                    PromptOutcome::Nothing
                }
            }
            Prompt::AgentPicker { agents, selected } => agents
                .into_iter()
                .nth(selected)
                .map(PromptOutcome::SelectAgent)
                .unwrap_or(PromptOutcome::Nothing),
            // Read-only popups — Enter just dismisses them.
            Prompt::Hover { .. } | Prompt::LspStatus { .. } | Prompt::CopilotSignin { .. } => {
                PromptOutcome::Cancelled
            }
        }
    }

    fn submit_fuzzy(&mut self, finder: Finder) -> PromptOutcome {
        let Some(sel) = finder.selection() else {
            self.locations.clear();
            return PromptOutcome::Nothing;
        };
        match finder.kind {
            FuzzyKind::Files { .. } | FuzzyKind::GitChangedFiles => {
                PromptOutcome::OpenRelativeFile(finder.items[sel.idx].clone())
            }
            FuzzyKind::Lines => PromptOutcome::GotoLine(sel.idx),
            FuzzyKind::Locations | FuzzyKind::Jumps | FuzzyKind::Diagnostics { .. } => {
                let loc = self.locations.get(sel.idx).cloned();
                self.locations.clear();
                match loc {
                    Some(loc) => PromptOutcome::JumpToLocation(loc),
                    None => PromptOutcome::Nothing,
                }
            }
            FuzzyKind::WorkspaceSearch => {
                // Workspace search: `locations[idx]` is the file's base
                // (line 0, char 0); the actual jump target lives on the
                // match item — the matched row, and the column where
                // the substring starts, so the cursor lands on the hit.
                let target_line = sel.line_hits.first().copied().unwrap_or(0) as u32;
                let target_col = sel.match_col;
                let loc = self.locations.get(sel.idx).cloned().map(|mut l| {
                    l.range.start.line = target_line;
                    l.range.start.character = target_col;
                    l.range.end.line = target_line;
                    l.range.end.character = target_col;
                    l
                });
                self.locations.clear();
                match loc {
                    Some(loc) => PromptOutcome::JumpToLocation(loc),
                    None => PromptOutcome::Nothing,
                }
            }
            FuzzyKind::Buffers => {
                let r = self.buffer_paths.get(sel.idx).cloned();
                self.buffer_paths.clear();
                match r {
                    Some(r) => PromptOutcome::OpenBuffer(r),
                    None => PromptOutcome::Nothing,
                }
            }
            FuzzyKind::Bookmarks => {
                let mark = self.bookmark_marks.get(sel.idx).cloned();
                self.bookmark_marks.clear();
                match mark {
                    Some(mark) => PromptOutcome::GotoBookmark(mark),
                    None => PromptOutcome::Nothing,
                }
            }
        }
    }
}

impl Default for PromptController {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn rows() -> Vec<GrammarRow> {
        ["bash", "python", "rust", "toml", "typescript"]
            .into_iter()
            .map(|name| GrammarRow {
                name: name.to_string(),
                state: GrammarState::Missing,
            })
            .collect()
    }

    fn key(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
    }

    fn code(c: KeyCode) -> KeyEvent {
        KeyEvent::new(c, KeyModifiers::NONE)
    }

    fn press(pc: &mut PromptController, key: KeyEvent) -> PromptOutcome {
        pc.handle_key(key, Path::new(""))
    }

    fn names(rows: &[GrammarRow], query: &str) -> Vec<String> {
        grammar_visible_indices(rows, query)
            .into_iter()
            .map(|i| rows[i].name.clone())
            .collect()
    }

    #[test]
    fn visible_indices_empty_query_keeps_order() {
        let rows = rows();
        assert_eq!(
            names(&rows, ""),
            ["bash", "python", "rust", "toml", "typescript"]
        );
    }

    #[test]
    fn visible_indices_substring_case_insensitive() {
        let rows = rows();
        // Matches anywhere in the name, not just a prefix.
        assert_eq!(names(&rows, "t"), ["python", "rust", "toml", "typescript"]);
        assert_eq!(names(&rows, "PY"), ["python"]);
        assert_eq!(names(&rows, "script"), ["typescript"]);
        assert!(names(&rows, "zzz").is_empty());
    }

    #[test]
    fn slash_enters_filter_and_chars_edit_query() {
        let mut pc = PromptController::new();
        pc.open_grammar_list(rows());

        press(&mut pc, key('/'));
        let Prompt::GrammarList {
            query, filtering, ..
        } = &pc.state
        else {
            panic!("expected grammar list");
        };
        assert!(*filtering);
        assert!(query.is_empty());

        for c in "ty".chars() {
            press(&mut pc, key(c));
        }
        let Prompt::GrammarList {
            query,
            filtering,
            selected,
            rows,
        } = &pc.state
        else {
            panic!("expected grammar list");
        };
        assert!(*filtering);
        assert_eq!(query, "ty");
        // Only typescript matches "ty"; selection resets to the top match.
        assert_eq!(*selected, 0);
        assert_eq!(names(rows, query), ["typescript"]);
    }

    #[test]
    fn esc_peels_filter_then_query_then_closes() {
        let mut pc = PromptController::new();
        pc.open_grammar_list(rows());
        press(&mut pc, key('/'));
        press(&mut pc, key('r'));

        // First Esc leaves the input but keeps the query in effect.
        assert!(matches!(
            press(&mut pc, code(KeyCode::Esc)),
            PromptOutcome::Nothing
        ));
        let Prompt::GrammarList {
            query, filtering, ..
        } = &pc.state
        else {
            panic!("expected grammar list");
        };
        assert!(!*filtering);
        assert_eq!(query, "r");

        // Second Esc clears the query (list reopens to full).
        assert!(matches!(
            press(&mut pc, code(KeyCode::Esc)),
            PromptOutcome::Nothing
        ));
        let Prompt::GrammarList { query, .. } = &pc.state else {
            panic!("expected grammar list");
        };
        assert!(query.is_empty());

        // Third Esc closes the modal.
        assert!(matches!(
            press(&mut pc, code(KeyCode::Esc)),
            PromptOutcome::Cancelled
        ));
        assert!(matches!(pc.state, Prompt::None));
    }

    #[test]
    fn enter_in_filter_installs_and_leaves_input() {
        let mut pc = PromptController::new();
        pc.open_grammar_list(rows());
        press(&mut pc, key('/'));
        press(&mut pc, key('t'));
        press(&mut pc, key('o')); // "to" → only "toml"

        // Enter installs the highlighted match and leaves the filter
        // input, keeping the query in effect.
        match press(&mut pc, code(KeyCode::Enter)) {
            PromptOutcome::InstallGrammar(name) => assert_eq!(name, "toml"),
            _ => panic!("expected InstallGrammar(toml)"),
        }
        let Prompt::GrammarList {
            rows,
            query,
            filtering,
            ..
        } = &pc.state
        else {
            panic!("expected grammar list still open");
        };
        assert!(!*filtering);
        assert_eq!(query, "to");
        let toml = rows.iter().find(|r| r.name == "toml").unwrap();
        assert!(matches!(toml.state, GrammarState::Installing));
    }

    #[test]
    fn enter_in_selection_mode_installs() {
        let mut pc = PromptController::new();
        pc.open_grammar_list(rows());
        // No filter — Enter on the first row installs it.
        match press(&mut pc, code(KeyCode::Enter)) {
            PromptOutcome::InstallGrammar(name) => assert_eq!(name, "bash"),
            _ => panic!("expected InstallGrammar(bash)"),
        }
    }

    #[test]
    fn confirm_opens_on_yes_and_bare_enter_installs() {
        let mut pc = PromptController::new();
        pc.open_grammar_install_prompt("rust".into(), "Rust".into());
        match press(&mut pc, code(KeyCode::Enter)) {
            PromptOutcome::InstallGrammar(name) => assert_eq!(name, "rust"),
            _ => panic!("expected InstallGrammar(rust)"),
        }
        assert!(matches!(pc.state, Prompt::None));
    }

    #[test]
    fn confirm_arrow_toggles_then_enter_declines() {
        let mut pc = PromptController::new();
        pc.open_grammar_install_prompt("rust".into(), "Rust".into());
        // Move to the No button; the dialog stays open.
        assert!(matches!(
            press(&mut pc, code(KeyCode::Right)),
            PromptOutcome::Nothing
        ));
        let Prompt::GrammarInstallConfirm { accept, .. } = &pc.state else {
            panic!("expected confirm dialog");
        };
        assert!(!*accept);
        // Enter now acts on the highlighted "No".
        assert!(matches!(
            press(&mut pc, code(KeyCode::Enter)),
            PromptOutcome::Cancelled
        ));
        assert!(matches!(pc.state, Prompt::None));
    }

    #[test]
    fn confirm_y_and_n_pick_directly() {
        let mut pc = PromptController::new();
        pc.open_grammar_install_prompt("rust".into(), "Rust".into());
        // `n` declines even though Yes is highlighted.
        assert!(matches!(press(&mut pc, key('n')), PromptOutcome::Cancelled));

        let mut pc = PromptController::new();
        pc.open_grammar_install_prompt("rust".into(), "Rust".into());
        // Highlight No, then `y` still installs.
        press(&mut pc, code(KeyCode::Left));
        match press(&mut pc, key('y')) {
            PromptOutcome::InstallGrammar(name) => assert_eq!(name, "rust"),
            _ => panic!("expected InstallGrammar(rust)"),
        }
    }

    #[test]
    fn confirm_stray_key_keeps_dialog_open() {
        let mut pc = PromptController::new();
        pc.open_grammar_install_prompt("rust".into(), "Rust".into());
        assert!(matches!(press(&mut pc, key('q')), PromptOutcome::Nothing));
        assert!(matches!(pc.state, Prompt::GrammarInstallConfirm { .. }));
    }

    #[test]
    fn file_reload_opens_on_yes_and_bare_enter_reloads() {
        let mut pc = PromptController::new();
        pc.open_file_reload_prompt(PathBuf::from("/tmp/x.rs"), false);
        assert!(matches!(
            press(&mut pc, code(KeyCode::Enter)),
            PromptOutcome::ReloadFile
        ));
        assert!(matches!(pc.state, Prompt::None));
    }

    #[test]
    fn file_reload_decline_returns_decline_outcome() {
        // Esc and `n` both decline with the dedicated outcome (not the
        // generic `Cancelled`) so the App can ack the disk state.
        let mut pc = PromptController::new();
        pc.open_file_reload_prompt(PathBuf::from("/tmp/x.rs"), true);
        assert!(matches!(
            press(&mut pc, key('n')),
            PromptOutcome::DeclineReloadFile
        ));

        let mut pc = PromptController::new();
        pc.open_file_reload_prompt(PathBuf::from("/tmp/x.rs"), true);
        assert!(matches!(
            press(&mut pc, code(KeyCode::Esc)),
            PromptOutcome::DeclineReloadFile
        ));
    }

    #[test]
    fn file_reload_arrow_toggles_then_enter_declines() {
        let mut pc = PromptController::new();
        pc.open_file_reload_prompt(PathBuf::from("/tmp/x.rs"), false);
        assert!(matches!(
            press(&mut pc, code(KeyCode::Right)),
            PromptOutcome::Nothing
        ));
        let Prompt::FileReloadConfirm { accept, .. } = &pc.state else {
            panic!("expected file-reload dialog");
        };
        assert!(!*accept);
        assert!(matches!(
            press(&mut pc, code(KeyCode::Enter)),
            PromptOutcome::DeclineReloadFile
        ));
    }

    #[test]
    fn file_reload_stray_key_keeps_dialog_open() {
        let mut pc = PromptController::new();
        pc.open_file_reload_prompt(PathBuf::from("/tmp/x.rs"), false);
        assert!(matches!(press(&mut pc, key('q')), PromptOutcome::Nothing));
        assert!(matches!(pc.state, Prompt::FileReloadConfirm { .. }));
    }

    #[test]
    fn letter_keys_type_into_query_not_install() {
        let mut pc = PromptController::new();
        pc.open_grammar_list(rows());
        press(&mut pc, key('/'));
        // `i` is an install shortcut in selection mode, but here it must
        // be query text — no install fires.
        let outcome = press(&mut pc, key('i'));
        assert!(matches!(outcome, PromptOutcome::Nothing));
        let Prompt::GrammarList { query, .. } = &pc.state else {
            panic!("expected grammar list");
        };
        assert_eq!(query, "i");
    }
}

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

    fn themes() -> Vec<String> {
        ["ansi", "catppuccin-mocha", "gruvbox-dark"]
            .into_iter()
            .map(str::to_string)
            .collect()
    }

    fn key(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
    }
    fn code(c: KeyCode) -> KeyEvent {
        KeyEvent::new(c, KeyModifiers::NONE)
    }
    fn press(pc: &mut PromptController, k: KeyEvent) -> PromptOutcome {
        pc.handle_key(k, Path::new(""))
    }

    #[test]
    fn opens_on_current_theme() {
        let mut pc = PromptController::new();
        pc.open_theme_picker(themes(), "catppuccin-mocha");
        let Prompt::ThemePicker { selected, .. } = &pc.state else {
            panic!("expected theme picker");
        };
        assert_eq!(*selected, 1);
    }

    #[test]
    fn navigation_previews_the_new_selection() {
        let mut pc = PromptController::new();
        pc.open_theme_picker(themes(), "ansi"); // selected = 0
        match press(&mut pc, key('j')) {
            PromptOutcome::PreviewTheme(name) => assert_eq!(name, "catppuccin-mocha"),
            _ => panic!("expected PreviewTheme(catppuccin-mocha)"),
        }
        // Ctrl-N moves down too.
        let ctrl_n = KeyEvent::new(KeyCode::Char('n'), KeyModifiers::CONTROL);
        match press(&mut pc, ctrl_n) {
            PromptOutcome::PreviewTheme(name) => assert_eq!(name, "gruvbox-dark"),
            _ => panic!("expected PreviewTheme(gruvbox-dark)"),
        }
        // Clamps at the end.
        match press(&mut pc, key('j')) {
            PromptOutcome::PreviewTheme(name) => assert_eq!(name, "gruvbox-dark"),
            _ => panic!("expected PreviewTheme(gruvbox-dark) at tail"),
        }
    }

    #[test]
    fn enter_commits_and_closes() {
        let mut pc = PromptController::new();
        pc.open_theme_picker(themes(), "ansi");
        press(&mut pc, key('j')); // → catppuccin-mocha
        match press(&mut pc, code(KeyCode::Enter)) {
            PromptOutcome::SelectTheme(name) => assert_eq!(name, "catppuccin-mocha"),
            _ => panic!("expected SelectTheme"),
        }
        assert!(matches!(pc.state, Prompt::None));
    }

    #[test]
    fn esc_cancels() {
        let mut pc = PromptController::new();
        pc.open_theme_picker(themes(), "ansi");
        assert!(matches!(
            press(&mut pc, code(KeyCode::Esc)),
            PromptOutcome::Cancelled
        ));
        assert!(matches!(pc.state, Prompt::None));
    }

    #[test]
    fn filter_narrows_and_previews_top_match() {
        let mut pc = PromptController::new();
        pc.open_theme_picker(themes(), "ansi");
        press(&mut pc, key('/'));
        // Typing "gru" narrows to gruvbox-dark and previews it.
        press(&mut pc, key('g'));
        press(&mut pc, key('r'));
        match press(&mut pc, key('u')) {
            PromptOutcome::PreviewTheme(name) => assert_eq!(name, "gruvbox-dark"),
            _ => panic!("expected PreviewTheme(gruvbox-dark) while filtering"),
        }
        // Enter from the filter commits the highlighted match.
        match press(&mut pc, code(KeyCode::Enter)) {
            PromptOutcome::SelectTheme(name) => assert_eq!(name, "gruvbox-dark"),
            _ => panic!("expected SelectTheme(gruvbox-dark)"),
        }
    }

    #[test]
    fn esc_peels_filter_then_query_then_closes() {
        let mut pc = PromptController::new();
        pc.open_theme_picker(themes(), "ansi");
        press(&mut pc, key('/'));
        press(&mut pc, key('c'));
        // First Esc leaves the input, query stays.
        assert!(matches!(
            press(&mut pc, code(KeyCode::Esc)),
            PromptOutcome::Nothing
        ));
        // Second Esc clears the query — previews the new top match.
        assert!(matches!(
            press(&mut pc, code(KeyCode::Esc)),
            PromptOutcome::PreviewTheme(_)
        ));
        // Third Esc closes.
        assert!(matches!(
            press(&mut pc, code(KeyCode::Esc)),
            PromptOutcome::Cancelled
        ));
        assert!(matches!(pc.state, Prompt::None));
    }
}

#[cfg(test)]
mod bookmark_picker_tests {
    use super::*;
    use crate::buffer_ref::BufferRef;

    fn fixture() -> (Vec<Bookmark>, Vec<String>) {
        let marks = vec![
            Bookmark {
                target: BufferRef::File("src/a.rs".into()),
                line: 0,
            },
            Bookmark {
                target: BufferRef::File("src/b.rs".into()),
                line: 9,
            },
            Bookmark {
                target: BufferRef::Scratch(2),
                line: 3,
            },
        ];
        let labels = vec![
            "src/a.rs:1".into(),
            "src/b.rs:10".into(),
            "[scratch 2]:4".into(),
        ];
        (marks, labels)
    }

    fn key(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
    }
    fn code(c: KeyCode) -> KeyEvent {
        KeyEvent::new(c, KeyModifiers::NONE)
    }
    fn press(pc: &mut PromptController, k: KeyEvent) -> PromptOutcome {
        pc.handle_key(k, Path::new(""))
    }

    #[test]
    fn selection_j_then_enter_jumps_highlighted_mark() {
        let mut pc = PromptController::new();
        let (m, l) = fixture();
        pc.open_bookmarks(l, m);
        // Selection mode is the default — `j` moves the cursor.
        press(&mut pc, key('j')); // → row 1
        match press(&mut pc, code(KeyCode::Enter)) {
            PromptOutcome::GotoBookmark(b) => {
                assert_eq!(b.target, BufferRef::File("src/b.rs".into()));
                assert_eq!(b.line, 9);
            }
            _ => panic!("expected GotoBookmark"),
        }
        assert!(matches!(pc.state, Prompt::None));
    }

    #[test]
    fn d_removes_mark_and_stays_open() {
        let mut pc = PromptController::new();
        let (m, l) = fixture();
        pc.open_bookmarks(l, m);
        // Selection-mode `d` deletes (no Ctrl), explorer-style.
        match press(&mut pc, key('d')) {
            PromptOutcome::RemoveBookmark(t) => {
                assert_eq!(t, BufferRef::File("src/a.rs".into()))
            }
            _ => panic!("expected RemoveBookmark"),
        }
        // Picker stays open (still a fuzzy finder) and the side-channel
        // shrank in lockstep with the finder's items.
        assert!(matches!(pc.state, Prompt::Fuzzy(_)));
        assert_eq!(pc.bookmark_marks.len(), 2);
        assert_eq!(
            pc.bookmark_marks[0].target,
            BufferRef::File("src/b.rs".into())
        );
    }

    #[test]
    fn slash_filters_then_enter_jumps_the_match() {
        let mut pc = PromptController::new();
        let (m, l) = fixture();
        pc.open_bookmarks(l, m);
        // `/` enters Filter mode; only "[scratch 2]:4" matches "scratch".
        press(&mut pc, key('/'));
        for c in "scratch".chars() {
            press(&mut pc, key(c));
        }
        match press(&mut pc, code(KeyCode::Enter)) {
            PromptOutcome::GotoBookmark(b) => assert_eq!(b.target, BufferRef::Scratch(2)),
            _ => panic!("expected GotoBookmark(scratch)"),
        }
    }
}