shoka 0.14.1

A repository workspace manager — jj-aware, TUI-first successor to ghq / rhq.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
//! `shoka tui` — Phase 2 dashboard skeleton.
//!
//! A ratatui app over the shelf. Each row is a repo with its slug,
//! tags, and resolved clone path. Navigation is j/k (or arrow keys),
//! `/` opens a filter input that nucleo scores in real time, Enter
//! exits the TUI and emits the chosen repo's path via the same
//! `SHOKA_CD_OUT` sidechannel contract `shoka cd` uses — the shell
//! wrapper that already services `cd` picks up TUI's output without
//! changes.
//!
//! Layout (3 rows):
//!
//! 1. Header — counts + active filter prefix.
//! 2. Table — slug / branch / ↑↓ / ✓ / PR / CI / path / tags,
//!    current selection highlighted. Status columns read the
//!    cached `git_status` + `gh` snapshots off `cache.toml`;
//!    entries that haven't been refreshed yet render `?` (git) /
//!    `-` (gh) so users can tell "unchecked" or "no data" apart
//!    from a definite zero.
//! 3. Footer — mode-specific key hints, or the live filter input.
//!
//! What's intentionally **not** here yet:
//!
//! - **Multi-select / bulk ops.** The TUI is currently a fancy `cd`
//!   picker. Bulk `exec --tag X -- ...` would be a natural extension.
//! - **OSC 7 cwd hint.** Phase 3 polish.

use std::io;
use std::path::PathBuf;

use anyhow::{Context, Result};
use crossterm::event::{
    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind,
};
use crossterm::execute;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use nucleo::Matcher;
use nucleo::pattern::{CaseMatching, Normalization, Pattern};
use ratatui::Frame;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::Line;
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Row, Table, TableState, Wrap};
use ratatui::{Terminal, prelude::Backend};
use teravars::Engine;

use crate::actions::{ActionKind, ActionOutcome, run_action};
use crate::cache::Cache;
use crate::cli::TuiArgs;

/// Catppuccin Mocha palette, kept as `Color::Rgb` so the dashboard
/// reads the same on every true-color terminal — falling back to
/// indexed colors would lose the soft pastel feel that's the whole
/// point of the theme. The roles below match the upstream palette
/// names so a future refresh can swap in Frappé / Macchiato /
/// Latte by retargeting these constants only.
mod theme {
    use ratatui::style::Color;

    // Background ramp (deepest → lightest).
    pub const MANTLE: Color = Color::Rgb(0x18, 0x18, 0x25);
    pub const BASE: Color = Color::Rgb(0x1e, 0x1e, 0x2e);
    pub const SURFACE0: Color = Color::Rgb(0x31, 0x32, 0x44);
    pub const SURFACE1: Color = Color::Rgb(0x45, 0x47, 0x5a);
    pub const OVERLAY: Color = Color::Rgb(0x6c, 0x70, 0x86);

    // Text ramp.
    pub const SUBTEXT: Color = Color::Rgb(0xba, 0xc2, 0xde);
    pub const TEXT: Color = Color::Rgb(0xcd, 0xd6, 0xf4);

    // Accents. Picked from Catppuccin's named roles so the meaning
    // (success / warning / etc.) is portable across the file.
    pub const LAVENDER: Color = Color::Rgb(0xb4, 0xbe, 0xfe);
    pub const SKY: Color = Color::Rgb(0x89, 0xdc, 0xeb);
    pub const TEAL: Color = Color::Rgb(0x94, 0xe2, 0xd5);
    pub const GREEN: Color = Color::Rgb(0xa6, 0xe3, 0xa1);
    pub const YELLOW: Color = Color::Rgb(0xf9, 0xe2, 0xaf);
    pub const PEACH: Color = Color::Rgb(0xfa, 0xb3, 0x87);
    pub const RED: Color = Color::Rgb(0xf3, 0x8b, 0xa8);
    pub const MAUVE: Color = Color::Rgb(0xcb, 0xa6, 0xf7);
    pub const PINK: Color = Color::Rgb(0xf5, 0xc2, 0xe7);
}
use crate::commands::ShokaContext;
use crate::commands::cd::emit_path;
use crate::config::{ResolvedConfig, ShokaConfig};
use crate::gh::{CiStatus, GhSnapshot};
use crate::git_status::GitStatusSnapshot;
use crate::state::{Repo, Shelf};

pub async fn run(ctx: &ShokaContext, args: TuiArgs) -> Result<()> {
    let cfg = ShokaConfig::load(&ctx.paths)?;
    let resolved = cfg.resolve(ctx.profile_override.as_deref())?;
    let shelf = Shelf::load(&ctx.paths)?;

    if shelf.is_empty() {
        // Print rather than crash into ratatui's alternate-screen
        // setup — an empty shelf would render a blank dashboard with
        // no useful affordance.
        anyhow::bail!(
            "shelf is empty — nothing to dashboard. `shoka clone <url>` \
             or `shoka import <dir>` first"
        );
    }

    // Cache load is best-effort: a missing / corrupt cache still
    // lets the dashboard open (rows just render with `?` in the
    // status columns). The user can recover via `shoka cache clear`
    // + a refresh — the alternative (refusing to open the TUI)
    // would block them from doing it from inside shoka itself.
    let cache = match Cache::load(&ctx.paths) {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!(target: "shoka", "tui: cache load failed, falling back to no-status mode ({e:#})");
            Cache::default()
        }
    };

    let rows = build_rows(&shelf, &resolved, &cache, &args.tags)?;
    if rows.is_empty() {
        anyhow::bail!(
            "no repos matched the tag filter ({} on the shelf total)",
            shelf.len()
        );
    }

    let mut app = App::new(rows);
    let selection = run_app(&mut app)?;

    // After the alternate screen tears down, emit the path so the
    // shell wrapper can `cd`. None = user quit without picking.
    if let Some(idx) = selection {
        emit_path(&app.rows[idx].path)?;
    }
    Ok(())
}

/// Pre-resolved row data the table renders. Building these once
/// up-front lets the per-frame render stay allocation-light.
#[derive(Debug, Clone)]
struct DashRow {
    slug: String,
    path: PathBuf,
    /// `slug` + " " + path-as-string, cached so the per-keystroke
    /// nucleo scorer in [`App::refilter`] has a single haystack to
    /// score against. Path is included because the dashboard now
    /// renders multiple checkouts of the same remote (different
    /// `path`s for the same triple), and a slug-only filter would
    /// be useless for picking among them.
    search_key: String,
    /// Display string — `tags.join(", ")` cached so we don't
    /// re-join per frame.
    tags_display: String,
    /// Cached git status snapshot from `cache.toml`. `None` when
    /// the entry hasn't been refreshed yet — the TUI renders that
    /// distinctly from "snapshot says clean" so users can tell
    /// "unchecked" apart from "no changes".
    status: Option<GitStatusSnapshot>,
    /// Cached gh snapshot — open PR count + most-recent CI
    /// conclusion. `None` for non-github hosts, missing tokens, or
    /// API errors; TUI renders `-` in the PR/CI cells for that
    /// case so users can distinguish "no data" from "zero PRs".
    gh: Option<GhSnapshot>,
}

fn build_rows(
    shelf: &Shelf,
    resolved: &ResolvedConfig,
    cache: &Cache,
    tag_filter: &[String],
) -> Result<Vec<DashRow>> {
    let mut engine = Engine::new();
    let mut out = Vec::with_capacity(shelf.len());
    for repo in &shelf.repos {
        if !tag_filter.is_empty() && !has_all_tags(repo, tag_filter) {
            continue;
        }
        let path = resolved
            .clone_path_for(repo, &mut engine)
            .with_context(|| format!("resolving clone path for {}", repo.slug()))?;
        // Split lookup: `git_status` is per-checkout so it needs the
        // path-aware identity (multi-clone rows must each carry
        // their own branch / dirty / ahead-behind), while `gh` is
        // remote-derived — open PR count + CI status are the same
        // upstream value regardless of which local copy asks, so
        // sharing across triple siblings is correct and saves API
        // budget. Resolves the TODO from #57.
        let status = cache
            .find(&repo.host, &repo.owner, &repo.name, repo.path.as_deref())
            .and_then(|c| c.git_status.clone());
        let gh = cache
            .find_gh_by_triple(&repo.host, &repo.owner, &repo.name)
            .cloned();
        let slug = repo.slug();
        let search_key = format!("{slug} {}", path.display());
        out.push(DashRow {
            slug,
            path,
            search_key,
            tags_display: repo.tags.join(", "),
            status,
            gh,
        });
    }
    Ok(out)
}

fn has_all_tags(repo: &Repo, wanted: &[String]) -> bool {
    wanted.iter().all(|w| repo.tags.iter().any(|t| t == w))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    Normal,
    Filter,
}

struct App {
    rows: Vec<DashRow>,
    /// Filter query (the live input). Empty in normal mode.
    filter: String,
    /// Indices into `rows`, sorted by nucleo score (highest first).
    /// Recomputed from scratch whenever `filter` changes.
    matches: Vec<usize>,
    /// Position within `matches` of the currently-highlighted row.
    /// 0 when `matches` is empty (and the selection is just "none").
    cursor: usize,
    mode: Mode,
    /// `?` help popup overlay state. Orthogonal to [`Mode`] so the
    /// popup can be opened (or closed) from either Normal or Filter
    /// without leaking modal state between the two. Toggled by `?`
    /// or F1 and dismissed by `Esc`, `q`, or `?` again.
    show_help: bool,
    /// Issue / PR Telescope-style picker overlay. `Some` when an
    /// `i` / `p` keystroke fetched a list (or hit an error worth
    /// displaying); `None` otherwise. Intercepts all input while
    /// active, mirroring `show_help`. See [`Picker`] for the
    /// per-item state.
    picker: Option<Picker>,
    /// Fetch / push action result overlay. `Some` after `f` / `P`
    /// finishes (or fails). Any keystroke dismisses it. Intercepts
    /// input ahead of normal navigation so a stray `j` doesn't move
    /// the cursor while the user is still reading the result.
    action_popup: Option<ActionPopup>,
    /// Transient status banner shown in the footer after `y` / `o`
    /// (and other light, non-popup actions). Cleared on the next
    /// non-status-producing keystroke so the user always sees the
    /// outcome of their most recent action without it sticking
    /// around as visual noise.
    status_message: Option<String>,
    table_state: TableState,
    matcher: Matcher,
}

/// Result of an `f` / `P` keystroke. Holds the captured stdout +
/// stderr so the popup can show what git/jj said without the user
/// having to drop back to a shell. `outcome` is `None` for the
/// no-VCS-detected branch (where the action never ran).
#[derive(Debug, Clone)]
struct ActionPopup {
    kind: ActionKind,
    repo_label: String,
    outcome: Option<ActionOutcome>,
    /// Error message when [`outcome`] is `None`. Empty otherwise.
    error: String,
}

/// What the picker is showing — drives the title + the fetcher
/// chosen by `open_picker`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PickerKind {
    Issues,
    Prs,
}

impl PickerKind {
    fn title(self) -> &'static str {
        match self {
            PickerKind::Issues => "Issues",
            PickerKind::Prs => "Pull Requests",
        }
    }
}

/// Picker overlay state. Either showing live data ([`Self::loaded`])
/// or a single-line failure message ([`Self::error`]) — both render
/// in the same popup so the user always sees *something* explaining
/// why they pressed the key.
struct Picker {
    kind: PickerKind,
    /// Display label for the repo the picker was opened on, e.g.
    /// `github.com/yukimemi/shoka`. Shown in the popup title so
    /// the user can tell which row they triggered against.
    repo_label: String,
    /// Items fetched from gh. Empty when `error` is `Some` or when
    /// the repo legitimately has no open issues / PRs.
    items: Vec<crate::gh::PickerItem>,
    /// Precomputed [`crate::gh::PickerItem::search_key`] per item.
    /// Built once at construction so the hot path in [`refilter`]
    /// (one nucleo scoring round per item per keystroke) doesn't
    /// reallocate a `String` for every entry every time the user
    /// types a character.
    search_keys: Vec<String>,
    /// Live filter query.
    filter: String,
    /// Indices into `items`, score-sorted (highest first).
    matches: Vec<usize>,
    /// Position within `matches` of the highlighted row.
    cursor: usize,
    /// When `Some`, the popup renders just the message (no list,
    /// no filter). Drives the "no token" / "non-github host" /
    /// "fetch errored" branches.
    error: Option<String>,
    matcher: Matcher,
}

impl Picker {
    fn loaded(kind: PickerKind, repo_label: String, items: Vec<crate::gh::PickerItem>) -> Self {
        let matches = (0..items.len()).collect();
        let search_keys = items.iter().map(|i| i.search_key()).collect();
        Self {
            kind,
            repo_label,
            items,
            search_keys,
            filter: String::new(),
            matches,
            cursor: 0,
            error: None,
            matcher: Matcher::default(),
        }
    }

    fn error(kind: PickerKind, repo_label: String, msg: impl Into<String>) -> Self {
        Self {
            kind,
            repo_label,
            items: Vec::new(),
            search_keys: Vec::new(),
            filter: String::new(),
            matches: Vec::new(),
            cursor: 0,
            error: Some(msg.into()),
            matcher: Matcher::default(),
        }
    }

    /// Re-rank items against the current filter. Empty filter =
    /// identity order (as returned by the gh API, which is
    /// most-recently-updated first); a non-empty filter scores each
    /// item's precomputed `search_keys` entry via nucleo and keeps
    /// positive-score matches sorted descending.
    fn refilter(&mut self) {
        if self.filter.is_empty() {
            self.matches = (0..self.items.len()).collect();
        } else {
            let pattern = Pattern::parse(&self.filter, CaseMatching::Smart, Normalization::Smart);
            let mut scored: Vec<(usize, u32)> = Vec::new();
            let mut buf: Vec<char> = Vec::new();
            for (idx, key) in self.search_keys.iter().enumerate() {
                buf.clear();
                let haystack = nucleo::Utf32Str::new(key, &mut buf);
                if let Some(score) = pattern.score(haystack, &mut self.matcher) {
                    scored.push((idx, score));
                }
            }
            scored.sort_by_key(|&(_, score)| std::cmp::Reverse(score));
            self.matches = scored.into_iter().map(|(idx, _)| idx).collect();
        }
        self.cursor = 0;
    }

    fn move_down(&mut self) {
        if self.matches.is_empty() {
            return;
        }
        self.cursor = (self.cursor + 1).min(self.matches.len() - 1);
    }

    fn move_up(&mut self) {
        self.cursor = self.cursor.saturating_sub(1);
    }

    /// The currently-highlighted item, if any. `None` when the
    /// list is empty (no matches, no fetched items, or error mode).
    fn selected(&self) -> Option<&crate::gh::PickerItem> {
        let idx = *self.matches.get(self.cursor)?;
        self.items.get(idx)
    }
}

impl App {
    fn new(rows: Vec<DashRow>) -> Self {
        let matches = (0..rows.len()).collect();
        let mut table_state = TableState::default();
        table_state.select(if rows.is_empty() { None } else { Some(0) });
        Self {
            rows,
            filter: String::new(),
            matches,
            cursor: 0,
            mode: Mode::Normal,
            show_help: false,
            picker: None,
            action_popup: None,
            status_message: None,
            table_state,
            matcher: Matcher::default(),
        }
    }

    /// Recompute `matches` against `filter`. Empty filter = identity
    /// (everything in shelf order); otherwise nucleo scores each
    /// row's `search_key` (slug + path) and we keep the matches
    /// sorted by score descending. Path is in the haystack so that
    /// multiple path-pinned checkouts of the same remote can be
    /// distinguished by typing part of the dir name. Cursor pins to
    /// the top so the highlighted row is always visible after a
    /// refilter.
    fn refilter(&mut self) {
        if self.filter.is_empty() {
            self.matches = (0..self.rows.len()).collect();
        } else {
            let pattern = Pattern::parse(&self.filter, CaseMatching::Smart, Normalization::Smart);
            let mut scored: Vec<(usize, u32)> = Vec::new();
            let mut buf: Vec<char> = Vec::new();
            for (idx, row) in self.rows.iter().enumerate() {
                buf.clear();
                let haystack = nucleo::Utf32Str::new(&row.search_key, &mut buf);
                if let Some(score) = pattern.score(haystack, &mut self.matcher) {
                    scored.push((idx, score));
                }
            }
            // Sort by score descending — Reverse so `sort_by_key`
            // gives the natural "best match first" ordering.
            scored.sort_by_key(|&(_, score)| std::cmp::Reverse(score));
            self.matches = scored.into_iter().map(|(idx, _)| idx).collect();
        }
        self.cursor = 0;
        self.table_state.select(if self.matches.is_empty() {
            None
        } else {
            Some(0)
        });
    }

    fn move_down(&mut self) {
        if self.matches.is_empty() {
            return;
        }
        self.cursor = (self.cursor + 1).min(self.matches.len() - 1);
        self.table_state.select(Some(self.cursor));
    }

    fn move_up(&mut self) {
        self.cursor = self.cursor.saturating_sub(1);
        if !self.matches.is_empty() {
            self.table_state.select(Some(self.cursor));
        }
    }

    fn selected_row(&self) -> Option<usize> {
        self.matches.get(self.cursor).copied()
    }
}

/// RAII guard: enabling raw mode + alt-screen in `new`, tearing
/// them down in `drop`. Using a guard rather than an explicit
/// cleanup block at the end of `run_app` means a panic anywhere
/// inside the TUI still restores the terminal — without the guard,
/// the user would be stranded in raw mode with their input
/// invisible until they hit `reset`.
struct TerminalGuard;

impl TerminalGuard {
    fn new() -> Result<Self> {
        enable_raw_mode().context("enabling terminal raw mode")?;
        execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)
            .context("entering alt screen")?;
        Ok(Self)
    }
}

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        // Best-effort cleanup — there's nothing we can do if any of
        // these fail (no panic-in-drop), and the user is going to
        // get their terminal back one way or another. Print cursor
        // show explicitly: LeaveAlternateScreen restores the main
        // buffer but the cursor visibility flag persists, and we
        // hid it via TableState rendering.
        let _ = disable_raw_mode();
        let _ = execute!(
            io::stdout(),
            LeaveAlternateScreen,
            DisableMouseCapture,
            crossterm::cursor::Show
        );
    }
}

/// Main loop. Returns `Ok(Some(idx))` when the user pressed Enter on
/// a row, `Ok(None)` when they quit (q / Esc / Ctrl-C). The
/// [`TerminalGuard`] takes care of teardown — including on panic.
fn run_app(app: &mut App) -> Result<Option<usize>> {
    let _guard = TerminalGuard::new()?;
    let backend = CrosstermBackend::new(io::stdout());
    let mut terminal = Terminal::new(backend).context("constructing ratatui terminal")?;
    event_loop(&mut terminal, app)
}

fn event_loop<B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> Result<Option<usize>> {
    loop {
        // ratatui's `Backend::Error` is not always `std::error::Error +
        // Send + Sync` (depends on the backend), so anyhow's
        // `.context` blanket impl doesn't apply. Convert manually.
        terminal
            .draw(|f| ui(f, app))
            .map_err(|e| anyhow::anyhow!("drawing frame: {e}"))?;

        // Block on `read()` rather than polling: there's no
        // animation or background work to drive, and Ctrl-C arrives
        // as a `KeyEvent` under crossterm's raw mode (not a signal),
        // so we're never stranded waiting. The polled variant
        // burned CPU + wall-time for no UX gain.
        let evt = event::read().context("reading event")?;
        let Event::Key(key) = evt else { continue };
        if key.kind == KeyEventKind::Release {
            // Windows fires Press + Release; we only act on Press so
            // a single physical keystroke doesn't double-fire.
            continue;
        }

        // Action popup intercepts everything — it's the latest
        // modal and the user is reading the captured git/jj output.
        // Any keystroke (other than Ctrl-C, which always quits)
        // dismisses it, matching the "press any key to continue"
        // convention.
        if app.action_popup.is_some() {
            if key.code == KeyCode::Char('c')
                && key
                    .modifiers
                    .contains(crossterm::event::KeyModifiers::CONTROL)
            {
                return Ok(None);
            }
            app.action_popup = None;
            continue;
        }

        // Picker overlay intercepts input first — it's the most
        // recently opened modal, so dismissal there takes priority
        // over the help popup or normal navigation.
        if app.picker.is_some() {
            // Ctrl-C escape hatch (same reasoning as the help popup).
            if key.code == KeyCode::Char('c')
                && key
                    .modifiers
                    .contains(crossterm::event::KeyModifiers::CONTROL)
            {
                return Ok(None);
            }
            handle_picker_key(app, key);
            continue;
        }

        // Help popup intercepts everything except its own dismissal
        // keys + Ctrl-C. Keep this check outside `match app.mode` so
        // the popup can be opened from Filter mode too — but only
        // Normal-mode keys (specifically `?` / F1) open it; while in
        // Filter, `?` is still a literal character to type.
        if app.show_help {
            // Ctrl-C is the "I want out, no matter what" key. Honour
            // it even with the popup open — making the user dismiss
            // the popup first before they can quit is a UX trap
            // (especially if a stuck render somehow strands the
            // popup), and Ctrl-C is the only key reliably reachable
            // when other dismissals don't.
            if key.code == KeyCode::Char('c')
                && key
                    .modifiers
                    .contains(crossterm::event::KeyModifiers::CONTROL)
            {
                return Ok(None);
            }
            match key.code {
                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('?') | KeyCode::F(1) => {
                    app.show_help = false;
                }
                _ => {}
            }
            continue;
        }

        match app.mode {
            Mode::Normal => {
                // Any keystroke in normal mode wipes the last
                // status banner (y / o being the only setters
                // today). y / o set it again inside their handlers
                // below, so repeating either keeps the message
                // visible until a *different* key arrives.
                app.status_message = None;
                match key.code {
                    KeyCode::Char('q') | KeyCode::Esc => return Ok(None),
                    KeyCode::Char('c')
                        if key
                            .modifiers
                            .contains(crossterm::event::KeyModifiers::CONTROL) =>
                    {
                        return Ok(None);
                    }
                    KeyCode::Char('?') | KeyCode::F(1) => {
                        app.show_help = true;
                    }
                    KeyCode::Char('i') => open_picker(app, PickerKind::Issues),
                    KeyCode::Char('p') => open_picker(app, PickerKind::Prs),
                    KeyCode::Char('f') => run_action_for_selected(app, ActionKind::Fetch),
                    KeyCode::Char('P') => run_action_for_selected(app, ActionKind::Push),
                    KeyCode::Char('y') => yank_selected_slug(app),
                    KeyCode::Char('o') => open_selected_repo_home(app),
                    KeyCode::Char('j') | KeyCode::Down => app.move_down(),
                    KeyCode::Char('k') | KeyCode::Up => app.move_up(),
                    KeyCode::Char('g') => {
                        app.cursor = 0;
                        if !app.matches.is_empty() {
                            app.table_state.select(Some(0));
                        }
                    }
                    KeyCode::Char('G') if !app.matches.is_empty() => {
                        app.cursor = app.matches.len() - 1;
                        app.table_state.select(Some(app.cursor));
                    }
                    KeyCode::Char('/') => {
                        app.mode = Mode::Filter;
                    }
                    KeyCode::Enter => {
                        return Ok(app.selected_row());
                    }
                    _ => {}
                }
            }
            Mode::Filter => match key.code {
                KeyCode::Esc => {
                    app.filter.clear();
                    app.refilter();
                    app.mode = Mode::Normal;
                }
                KeyCode::Enter => {
                    // Accept the filter and drop back to normal mode.
                    // Cursor is already at the top match.
                    app.mode = Mode::Normal;
                }
                KeyCode::Backspace => {
                    app.filter.pop();
                    app.refilter();
                }
                KeyCode::Char(c) => {
                    app.filter.push(c);
                    app.refilter();
                }
                _ => {}
            },
        }
    }
}

fn ui(f: &mut Frame, app: &mut App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // header
            Constraint::Min(0),    // table
            Constraint::Length(1), // footer
        ])
        .split(f.area());

    render_header(f, chunks[0], app);
    render_table(f, chunks[1], app);
    render_footer(f, chunks[2], app);

    // Help popup is drawn over the dashboard; the picker is drawn
    // *over the help popup* — both use `Clear` to wipe their rect
    // first, so the lower layers don't bleed through. Order matters:
    // we draw picker last so it visually wins when both flags are
    // set (shouldn't happen via UI flow, but defensive).
    if app.show_help {
        render_help(f, f.area());
    }
    if let Some(picker) = &app.picker {
        render_picker(f, f.area(), picker);
    }
    if let Some(popup) = &app.action_popup {
        render_action_popup(f, f.area(), popup);
    }
}

fn render_header(f: &mut Frame, area: Rect, app: &App) {
    use ratatui::text::Span;

    let total = app.rows.len();
    let shown = app.matches.len();

    // ✦ marker + bold "shoka" + version pulled from cargo so the
    // banner stays in lockstep with the release the user is running.
    let mut spans = vec![
        Span::styled("", Style::default().fg(theme::MAUVE)),
        Span::styled(
            "shoka",
            Style::default()
                .fg(theme::LAVENDER)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" v{}", env!("CARGO_PKG_VERSION")),
            Style::default().fg(theme::OVERLAY),
        ),
        Span::styled("  📚 ", Style::default().fg(theme::PEACH)),
        Span::styled(
            shown.to_string(),
            Style::default()
                .fg(theme::GREEN)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" / {total} repo(s)"),
            Style::default().fg(theme::SUBTEXT),
        ),
    ];
    if !app.filter.is_empty() {
        spans.push(Span::styled(
            "  ◇ /",
            Style::default()
                .fg(theme::PEACH)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled(
            &app.filter,
            Style::default()
                .fg(theme::YELLOW)
                .add_modifier(Modifier::BOLD),
        ));
    }

    f.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::default().bg(theme::MANTLE)),
        area,
    );
}

fn render_table(f: &mut Frame, area: Rect, app: &mut App) {
    use ratatui::text::Span;
    use ratatui::widgets::Cell;

    let header_row = Row::new(vec![
        Cell::from("  repo "),
        Cell::from(" branch "),
        Cell::from(" ↑↓ "),
        Cell::from(""),
        Cell::from(" PR "),
        Cell::from(" CI "),
        Cell::from(" path "),
        Cell::from(" tags "),
    ])
    .style(
        Style::default()
            .add_modifier(Modifier::BOLD)
            .fg(theme::PINK)
            .bg(theme::SURFACE0),
    )
    .height(1);

    let rows: Vec<Row> = app
        .matches
        .iter()
        .enumerate()
        .map(|(visible_idx, &row_idx)| {
            let row = &app.rows[row_idx];
            let (branch, ahead_behind, dirty) = status_cells(row.status.as_ref());
            let (pr, ci) = gh_cells(row.gh.as_ref());

            // Alternating row tint — subtle stripe that makes
            // long shelves easier to scan without competing with
            // the selection highlight (which gets full LAVENDER).
            let row_bg = if visible_idx % 2 == 0 {
                theme::BASE
            } else {
                theme::MANTLE
            };
            let base_style = Style::default().fg(theme::TEXT).bg(row_bg);

            // The selection highlight (LAVENDER bg) bleeds into
            // its cells via `row_highlight_style`, so cell-level
            // styling is the *unselected* look — the highlight
            // overrides only `bg` and `fg`, leaving span colors
            // for non-current rows intact.
            Row::new(vec![
                Cell::from(Line::from(vec![
                    Span::raw(" "),
                    Span::styled(&row.slug, Style::default().fg(theme::TEXT)),
                ])),
                Cell::from(Span::styled(branch, Style::default().fg(theme::SKY))),
                Cell::from(style_ahead_behind(&ahead_behind)),
                Cell::from(style_dirty(&dirty)),
                Cell::from(style_pr(&pr)),
                Cell::from(style_ci(&ci)),
                Cell::from(Span::styled(
                    row.path.to_string_lossy(),
                    Style::default().fg(theme::OVERLAY),
                )),
                Cell::from(Span::styled(
                    &row.tags_display,
                    Style::default().fg(theme::TEAL),
                )),
            ])
            .style(base_style)
        })
        .collect();

    let widths = [
        Constraint::Percentage(28), // repo
        Constraint::Length(14),     // branch
        Constraint::Length(8),      // ↑N ↓N
        Constraint::Length(2),      // dirty glyph
        Constraint::Length(4),      // PR count (e.g. "99+")
        Constraint::Length(2),      // CI glyph
        Constraint::Min(20),        // path
        Constraint::Length(14),     // tags
    ];
    let table = Table::new(rows, widths)
        .header(header_row)
        .row_highlight_style(
            Style::default()
                .bg(theme::LAVENDER)
                .fg(theme::MANTLE)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("")
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(theme::OVERLAY))
                .style(Style::default().bg(theme::BASE)),
        );

    // Pass the real `TableState` by `&mut` so the scroll offset
    // ratatui computes (for keeping the highlighted row visible as
    // the cursor moves off-screen) actually persists across frames.
    // Cloning here would discard those mutations and break long-
    // shelf scrolling.
    f.render_stateful_widget(table, area, &mut app.table_state);
}

/// Style the ahead/behind cell by its shape. `=` (in sync) reads
/// dim green so it doesn't compete with the actually-interesting
/// rows; `↑N` (ahead, pushable) is bright green; `↓N` (behind,
/// needs pull) is yellow; mixed `↑N ↓M` is mauve (action-required
/// but ambiguous direction). Unknown / no-upstream falls back to
/// overlay so it visibly recedes.
fn style_ahead_behind(s: &str) -> ratatui::text::Span<'static> {
    use ratatui::text::Span;
    let color = if s == "=" {
        theme::OVERLAY
    } else if s.starts_with('') && s.contains('') {
        theme::MAUVE
    } else if s.starts_with('') {
        theme::GREEN
    } else if s.starts_with('') {
        theme::YELLOW
    } else {
        theme::OVERLAY
    };
    Span::styled(s.to_string(), Style::default().fg(color))
}

/// Dirty glyph: clean `✓` reads dim green, dirty `●` pops peach so
/// the user's eye immediately catches "this row has uncommitted
/// changes" without parsing text. `?` (never refreshed) stays
/// overlay-grey for the same don't-distract reason as `=` in
/// ahead/behind.
fn style_dirty(s: &str) -> ratatui::text::Span<'static> {
    use ratatui::text::Span;
    let color = match s {
        "" => theme::GREEN,
        "" => theme::PEACH,
        _ => theme::OVERLAY,
    };
    Span::styled(s.to_string(), Style::default().fg(color))
}

/// PR cell: any non-zero, non-dash count is pink+bold so a busy
/// mono-repo visibly stands out. Zero / `-` reads overlay so it
/// recedes — the dashboard's job is to highlight *what to act on*.
fn style_pr(s: &str) -> ratatui::text::Span<'static> {
    use ratatui::text::Span;
    let style = if s == "0" || s == "-" {
        Style::default().fg(theme::OVERLAY)
    } else {
        Style::default()
            .fg(theme::PINK)
            .add_modifier(Modifier::BOLD)
    };
    Span::styled(s.to_string(), style)
}

/// CI glyph: green check / red cross / yellow pending / overlay
/// skipped — the standard traffic-light reading. `!` (unknown
/// conclusion) reads red since "we don't know if this passed" is
/// closer to "broken" than to "fine".
fn style_ci(s: &str) -> ratatui::text::Span<'static> {
    use ratatui::text::Span;
    let color = match s {
        "" => theme::GREEN,
        "" | "!" => theme::RED,
        "" => theme::YELLOW,
        "" => theme::OVERLAY,
        _ => theme::OVERLAY,
    };
    Span::styled(s.to_string(), Style::default().fg(color))
}

/// Format the two gh cells (open PR count + CI glyph). `(-, -)`
/// when the snapshot is `None` (non-github host, missing token, or
/// API error); otherwise PR count is clamped to "99+" so the
/// 4-char column doesn't blow out on a busy mono-repo, and CI is
/// reduced to a single glyph for at-a-glance scanning.
fn gh_cells(snap: Option<&GhSnapshot>) -> (String, String) {
    let Some(snap) = snap else {
        return ("-".into(), "-".into());
    };
    let pr = match snap.open_pr_count {
        Some(n) if n >= 100 => "99+".into(),
        Some(n) => n.to_string(),
        None => "-".into(),
    };
    let ci = match snap.ci_status {
        Some(CiStatus::Success) => "".into(),
        Some(CiStatus::Failure) => "".into(),
        Some(CiStatus::Pending) => "".into(),
        Some(CiStatus::Skipped) => "".into(),
        Some(CiStatus::Other) => "!".into(),
        None => "-".into(),
    };
    (pr, ci)
}

/// Format the three status cells the dashboard renders for one row.
/// Returns `(branch, ahead_behind, dirty)`. When `status` is `None`
/// (entry hasn't been refreshed yet), all three show a faint `?`
/// rather than blank — users can tell "unchecked" from "clean".
fn status_cells(status: Option<&GitStatusSnapshot>) -> (String, String, String) {
    let Some(s) = status else {
        return ("?".into(), "?".into(), "?".into());
    };
    let branch = s.branch.clone().unwrap_or_else(|| "-".into());
    let ahead_behind = match (s.ahead, s.behind) {
        (Some(0), Some(0)) => "=".to_string(),
        (Some(a), Some(b)) if a > 0 && b > 0 => format!("{a}{b}"),
        (Some(a), Some(0)) if a > 0 => format!("{a}"),
        (Some(0), Some(b)) if b > 0 => format!("{b}"),
        // Either side unknown — no upstream ref to compare against.
        _ => "-".into(),
    };
    let dirty = if s.dirty { "".into() } else { "".into() };
    (branch, ahead_behind, dirty)
}

fn render_footer(f: &mut Frame, area: Rect, app: &App) {
    use ratatui::text::Span;

    // A status message (set by y / o) preempts the mode hint so the
    // user immediately sees what their last action did. Styled
    // brighter than the hint (teal vs subtext) so it reads as a
    // fresh result, not a permanent legend.
    if let Some(msg) = &app.status_message {
        let line = Line::from(vec![
            Span::styled(
                "",
                Style::default()
                    .fg(theme::TEAL)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                msg,
                Style::default()
                    .fg(theme::TEAL)
                    .add_modifier(Modifier::BOLD),
            ),
        ]);
        f.render_widget(
            Paragraph::new(line).style(Style::default().bg(theme::MANTLE)),
            area,
        );
        return;
    }

    let line = match app.mode {
        Mode::Normal => Line::from(footer_pills(&[
            ("j/k", "move"),
            ("/", "filter"),
            ("", "cd"),
            ("i", "iss"),
            ("p", "PR"),
            ("f", "fetch"),
            ("P", "push"),
            ("y", "yank"),
            ("o", "open"),
            ("?", "help"),
            ("q", "quit"),
        ])),
        Mode::Filter => Line::from(footer_pills(&[
            ("type", "filter"),
            ("", "del"),
            ("", "accept"),
            ("esc", "clear"),
        ])),
    };
    f.render_widget(
        Paragraph::new(line).style(Style::default().bg(theme::MANTLE)),
        area,
    );
}

/// Build the styled spans for the footer's keybind pills. Each
/// `(key, label)` pair renders as `[key]label` with the key bracketed
/// in mauve+bold and the label dim subtext. A space separator before
/// every pill keeps the gap consistent (a trailing one before the
/// first pill is fine — it doubles as the left-edge padding the
/// terminal would otherwise eat).
///
/// Labels are `&'static str` so the per-frame render path skips
/// the per-pill `String` allocation that an owned label would
/// require; the bracketed key still allocates (one `String` per
/// pill per frame) but that's bounded by the small pill count and
/// keeps the API ergonomic.
fn footer_pills(pairs: &[(&'static str, &'static str)]) -> Vec<ratatui::text::Span<'static>> {
    use ratatui::text::Span;
    let mut out: Vec<Span<'static>> = Vec::with_capacity(pairs.len() * 4);
    for (key, label) in pairs {
        out.push(Span::raw(" "));
        out.push(Span::styled(
            format!("[{key}]"),
            Style::default()
                .fg(theme::MAUVE)
                .add_modifier(Modifier::BOLD),
        ));
        out.push(Span::styled(*label, Style::default().fg(theme::SUBTEXT)));
    }
    out
}

/// Render the help popup. Centered in the terminal, sized to fit
/// the keybind table comfortably without flexing per frame. Clears
/// its rect first so the underlying table doesn't bleed through.
///
/// Kept colocated with the dashboard widgets so the legend stays in
/// lockstep with what `event_loop` actually handles — if a key is
/// added or renamed there, this list is the one place to update
/// alongside it.
fn render_help(f: &mut Frame, area: Rect) {
    use ratatui::text::Span;

    let popup = centered_rect(62, 78, area);

    // Sectioned layout so related keys cluster visually instead of
    // dissolving into a flat 15-row list. Sections render with a
    // mauve header line; entries inside line up by widest-key
    // padding *within each section* so each block is locally tidy.
    let sections: [(&str, &[(&str, &str)]); 4] = [
        (
            "Navigation",
            &[
                ("j / ↓", "move down"),
                ("k / ↑", "move up"),
                ("g", "jump to top"),
                ("G", "jump to bottom"),
                ("/", "filter — type to narrow, esc to clear"),
                ("Enter", "select (emit path for the shell wrapper to cd)"),
            ],
        ),
        (
            "Pickers & Browser",
            &[
                ("i", "open Issues for this repo in a fuzzy picker"),
                ("p", "open Pull Requests for this repo in a fuzzy picker"),
                ("o", "open repo home in browser"),
                ("y", "yank slug to clipboard"),
            ],
        ),
        (
            "Repo actions",
            &[
                ("f", "fetch (jj git fetch / git fetch)"),
                ("P", "push (jj git push / git push)"),
            ],
        ),
        (
            "Quit",
            &[
                ("? / F1", "toggle this help"),
                ("q / Esc", "quit"),
                ("Ctrl-C", "quit"),
            ],
        ),
    ];

    // `chars().count()` rather than `.len()`: the latter is byte
    // length, which for entries like `j / ↓` overcounts by two bytes
    // per arrow (UTF-8 encoding of `↓` is 3 bytes vs. 1 char). That
    // would push every other row out of alignment in the popup.
    let mut body: Vec<Line> = Vec::new();
    for (i, (heading, entries)) in sections.iter().enumerate() {
        if i > 0 {
            body.push(Line::from(""));
        }
        body.push(Line::from(Span::styled(
            format!("{heading}"),
            Style::default()
                .fg(theme::MAUVE)
                .add_modifier(Modifier::BOLD),
        )));
        let key_width = entries
            .iter()
            .map(|(k, _)| k.chars().count())
            .max()
            .unwrap_or(6);
        for (key, desc) in entries.iter() {
            body.push(Line::from(vec![
                Span::styled(
                    format!("    {key:>w$}  ", w = key_width),
                    Style::default()
                        .fg(theme::YELLOW)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(*desc, Style::default().fg(theme::SUBTEXT)),
            ]));
        }
    }

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme::MAUVE))
        .title(Span::styled(
            " 📚 shoka — keybinds ",
            Style::default()
                .fg(theme::LAVENDER)
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::BASE));

    let para = Paragraph::new(body).block(block);

    f.render_widget(Clear, popup);
    f.render_widget(para, popup);
}

/// Build a centered popup rect taking `pct_x` × `pct_y` of `area`.
/// Standard `Layout` split — two vertical splits then two horizontal
/// splits — so the popup is genuinely centered on any terminal
/// size, not just the dev's.
///
/// Percentages are clamped to `[0, 100]` so a caller-bug like
/// `pct_x = 120` doesn't underflow `100 - pct_x` and panic in
/// debug builds. The current call site is hard-coded to safe
/// values, but defensive clamping makes the helper reusable
/// without surprising the next caller.
fn centered_rect(pct_x: u16, pct_y: u16, area: Rect) -> Rect {
    let pct_x = pct_x.min(100);
    let pct_y = pct_y.min(100);
    let vert = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - pct_y) / 2),
            Constraint::Percentage(pct_y),
            Constraint::Percentage((100 - pct_y) / 2),
        ])
        .split(area);
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - pct_x) / 2),
            Constraint::Percentage(pct_x),
            Constraint::Percentage((100 - pct_x) / 2),
        ])
        .split(vert[1])[1]
}

/// Resolve the current row → octocrab client → list_open_issues /
/// list_open_prs (synchronous: `block_on` inside `block_in_place`,
/// safe under the multi-threaded tokio runtime shoka's `main` uses).
/// All failure modes (no selected row, non-github host, missing
/// token, gh client build error, API error) collapse to a single
/// `Picker::error(...)` so the user always gets a popup that
/// explains what happened instead of a silently-stuck keystroke.
///
/// Blocking the runtime here makes the UI freeze briefly during the
/// fetch — acceptable for a v1 picker, since the call is bounded by
/// `per_page(100)` plus normal network RTT. A future polish PR can
/// move this to a background tokio task + spinner without
/// restructuring callers.
fn open_picker(app: &mut App, kind: PickerKind) {
    let Some(row_idx) = app.selected_row() else {
        return;
    };
    let row = &app.rows[row_idx];

    // Slug is `<host>/<owner>/<name>`. Anything else means a malformed
    // shelf entry — short-circuit with a message rather than panic.
    let parts: Vec<&str> = row.slug.splitn(3, '/').collect();
    let &[host, owner, name] = parts.as_slice() else {
        app.picker = Some(Picker::error(
            kind,
            row.slug.clone(),
            format!("can't parse slug `{}`", row.slug),
        ));
        return;
    };
    let repo_label = format!("{host}/{owner}/{name}");

    if host != "github.com" {
        app.picker = Some(Picker::error(
            kind,
            repo_label,
            format!(
                "{} are only available on github.com (this repo is on `{host}`)",
                kind.title()
            ),
        ));
        return;
    }

    // Resolve token + build client + fetch, all under one block_on
    // so we don't fragment the runtime stack. block_in_place lets
    // the multi-threaded scheduler reuse this worker thread while
    // we block, rather than stalling other tasks.
    let fetched = tokio::task::block_in_place(|| {
        tokio::runtime::Handle::current().block_on(async move {
            let Some(token) = crate::gh::resolve_token().await else {
                return Err(anyhow::anyhow!(
                    "no GITHUB_TOKEN — set the env var or run `gh auth login`"
                ));
            };
            let client = crate::gh::build_client(&token)
                .map_err(|e| anyhow::anyhow!("gh client init failed: {e:#}"))?;
            match kind {
                PickerKind::Issues => crate::gh::list_open_issues(&client, owner, name).await,
                PickerKind::Prs => crate::gh::list_open_prs(&client, owner, name).await,
            }
        })
    });

    let picker = match fetched {
        Ok(items) => Picker::loaded(kind, repo_label, items),
        Err(e) => Picker::error(kind, repo_label, format!("{e:#}")),
    };
    app.picker = Some(picker);
}

/// Dispatch a keystroke while the picker overlay is open. Mutates
/// `app.picker` (close on Esc/q, refilter on typing, move cursor,
/// hand off to `open::that` on Enter).
fn handle_picker_key(app: &mut App, key: crossterm::event::KeyEvent) {
    let Some(picker) = app.picker.as_mut() else {
        return;
    };
    match key.code {
        KeyCode::Esc | KeyCode::Char('q') => {
            app.picker = None;
        }
        KeyCode::Char('j') | KeyCode::Down => picker.move_down(),
        KeyCode::Char('k') | KeyCode::Up => picker.move_up(),
        KeyCode::Enter => {
            if let Some(item) = picker.selected() {
                let url = item.html_url.clone();
                // `open::that` blocks until the OS handler launches
                // (xdg-open / open / start), but those are fast and
                // detach immediately, so the UI freeze is sub-100ms.
                if let Err(e) = open::that(&url) {
                    tracing::warn!(
                        target: "shoka",
                        "failed to open {url} in browser: {e:#}"
                    );
                }
            }
            app.picker = None;
        }
        KeyCode::Backspace => {
            picker.filter.pop();
            picker.refilter();
        }
        KeyCode::Char(c) => {
            picker.filter.push(c);
            picker.refilter();
        }
        _ => {}
    }
}

/// Run a fetch or push on the currently-selected row. Like
/// `open_picker`, this blocks on tokio under `block_in_place` so the
/// existing sync TUI loop doesn't need restructuring. The captured
/// stdout / stderr land in an `ActionPopup` the next frame draws —
/// the UI freeze during the action is the cost of v1 simplicity,
/// matched to the freeze pickers already accept.
fn run_action_for_selected(app: &mut App, kind: ActionKind) {
    let Some(row_idx) = app.selected_row() else {
        return;
    };
    let row = &app.rows[row_idx];
    let repo_label = row.slug.clone();
    let path = row.path.clone();

    let result = tokio::task::block_in_place(|| {
        tokio::runtime::Handle::current().block_on(run_action(&path, kind))
    });

    app.action_popup = Some(match result {
        Ok(outcome) => ActionPopup {
            kind,
            repo_label,
            outcome: Some(outcome),
            error: String::new(),
        },
        Err(e) => ActionPopup {
            kind,
            repo_label,
            outcome: None,
            error: format!("{e:#}"),
        },
    });
}

/// Copy the selected row's slug (e.g. `github.com/owner/name`) to
/// the system clipboard. Failures surface as a status banner rather
/// than a popup — yanking is meant to be invisible-on-success, and
/// a wall of red on a missing clipboard daemon would just be noise.
fn yank_selected_slug(app: &mut App) {
    let Some(row_idx) = app.selected_row() else {
        return;
    };
    let slug = app.rows[row_idx].slug.clone();
    match arboard::Clipboard::new().and_then(|mut cb| cb.set_text(slug.clone())) {
        Ok(()) => {
            app.status_message = Some(format!("yanked: {slug}"));
        }
        Err(e) => {
            app.status_message = Some(format!("yank failed: {e}"));
        }
    }
}

/// Open the selected row's repo home page in the user's default
/// browser. `host/owner/name` slugs translate directly to
/// `https://host/owner/name`, which is what every real host
/// (github.com, gitlab.com, codeberg.org…) serves. The synthetic
/// `local/...` host that `shoka import` mints for repos without a
/// remote has no web home, so short-circuit with a status note
/// rather than launch an inevitably-404 browser tab.
fn open_selected_repo_home(app: &mut App) {
    let Some(row_idx) = app.selected_row() else {
        return;
    };
    let slug = app.rows[row_idx].slug.clone();
    if slug.starts_with("local/") {
        app.status_message = Some("no repo home: local-only repo".into());
        return;
    }
    let url = format!("https://{slug}");
    match open::that(&url) {
        Ok(()) => {
            app.status_message = Some(format!("opened: {url}"));
        }
        Err(e) => {
            app.status_message = Some(format!("open failed: {e}"));
        }
    }
}

/// Render the action result popup. Two modes — error (no VCS
/// detected, spawn failed) shows a red banner + dismiss hint;
/// outcome (subprocess ran) shows the command, exit status, and
/// captured stdout/stderr. Either mode is dismissed by any key.
fn render_action_popup(f: &mut Frame, area: Rect, popup: &ActionPopup) {
    let rect = centered_rect(80, 60, area);
    f.render_widget(Clear, rect);

    let title = format!("{}{} ", popup.kind.label(), popup.repo_label);
    let border_color = match &popup.outcome {
        Some(o) if o.success => theme::GREEN,
        Some(_) => theme::RED,
        None => theme::RED,
    };
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(border_color))
        .title(ratatui::text::Span::styled(
            title,
            Style::default()
                .fg(theme::LAVENDER)
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::BASE));
    let inner = block.inner(rect);
    f.render_widget(block, rect);

    let mut lines: Vec<Line> = Vec::new();
    if let Some(outcome) = &popup.outcome {
        let status = if outcome.success {
            "✓ success"
        } else {
            "✗ failed"
        };
        let status_color = if outcome.success {
            theme::GREEN
        } else {
            theme::RED
        };
        lines.push(Line::from(vec![
            ratatui::text::Span::styled(
                format!("  {} ", outcome.vcs.label()),
                Style::default()
                    .fg(theme::MAUVE)
                    .add_modifier(Modifier::BOLD),
            ),
            ratatui::text::Span::styled(
                format!("$ {}", outcome.command),
                Style::default().fg(theme::TEXT),
            ),
        ]));
        lines.push(Line::from(ratatui::text::Span::styled(
            format!("  {status}"),
            Style::default()
                .fg(status_color)
                .add_modifier(Modifier::BOLD),
        )));
        lines.push(Line::from(""));
        if !outcome.stdout.trim().is_empty() {
            lines.push(Line::from(ratatui::text::Span::styled(
                "  stdout:",
                Style::default().fg(theme::SKY).add_modifier(Modifier::BOLD),
            )));
            for line in outcome.stdout.lines() {
                lines.push(Line::from(ratatui::text::Span::styled(
                    format!("    {line}"),
                    Style::default().fg(theme::SUBTEXT),
                )));
            }
        }
        if !outcome.stderr.trim().is_empty() {
            if !outcome.stdout.trim().is_empty() {
                lines.push(Line::from(""));
            }
            lines.push(Line::from(ratatui::text::Span::styled(
                "  stderr:",
                Style::default()
                    .fg(theme::PINK)
                    .add_modifier(Modifier::BOLD),
            )));
            for line in outcome.stderr.lines() {
                lines.push(Line::from(ratatui::text::Span::styled(
                    format!("    {line}"),
                    Style::default().fg(theme::SUBTEXT),
                )));
            }
        }
        if outcome.stdout.trim().is_empty() && outcome.stderr.trim().is_empty() {
            lines.push(Line::from(ratatui::text::Span::styled(
                "  (no output)",
                Style::default().fg(theme::OVERLAY),
            )));
        }
    } else {
        lines.push(Line::from(""));
        lines.push(Line::from(ratatui::text::Span::styled(
            format!("{}", popup.error),
            Style::default().fg(theme::RED),
        )));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(ratatui::text::Span::styled(
        "  press any key to close",
        Style::default().fg(theme::OVERLAY),
    )));

    // Wrap long lines instead of truncating them at the popup edge —
    // git / jj can emit very long URLs, error messages, and progress
    // strings that would otherwise be silently clipped (no horizontal
    // scrollbar exists in ratatui). `trim: false` keeps leading indent
    // so the `    stdout:` / `    stderr:` indent stays readable.
    f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}

/// Render the picker overlay. Always centered, always full-bleed
/// over the dashboard. Three modes — error (single line + dismiss
/// hint), empty list (no items match the current filter), populated
/// list (filter line + scrollable items).
fn render_picker(f: &mut Frame, area: Rect, picker: &Picker) {
    let popup = centered_rect(80, 80, area);
    f.render_widget(Clear, popup);

    let title_glyph = match picker.kind {
        PickerKind::Issues => "🐛",
        PickerKind::Prs => "🔀",
    };
    let title = format!(
        " {title_glyph}  {}{} ",
        picker.kind.title(),
        picker.repo_label
    );
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme::MAUVE))
        .title(ratatui::text::Span::styled(
            title,
            Style::default()
                .fg(theme::LAVENDER)
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::BASE));
    let inner = block.inner(popup);
    f.render_widget(block, popup);

    // Single-line error mode: render the message and a dismiss hint,
    // skip the list entirely. Keeps the visual weight matched to
    // what the user can act on.
    if let Some(err) = &picker.error {
        let body = vec![
            Line::from(""),
            Line::from(ratatui::text::Span::styled(
                format!("{err}"),
                Style::default().fg(theme::RED),
            )),
            Line::from(""),
            Line::from(ratatui::text::Span::styled(
                "  esc / q to close",
                Style::default().fg(theme::OVERLAY),
            )),
        ];
        f.render_widget(Paragraph::new(body), inner);
        return;
    }

    // Layout: filter row (1 line) + list (rest minus 1) + footer (1).
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),
            Constraint::Min(0),
            Constraint::Length(1),
        ])
        .split(inner);

    // Filter row — cursor `_` glyph indicates this is a live input.
    let filter_line = Line::from(vec![
        ratatui::text::Span::styled(
            "  / ",
            Style::default()
                .fg(theme::PEACH)
                .add_modifier(Modifier::BOLD),
        ),
        ratatui::text::Span::styled(&picker.filter, Style::default().fg(theme::YELLOW)),
        ratatui::text::Span::styled(
            "",
            Style::default()
                .fg(theme::PEACH)
                .add_modifier(Modifier::BOLD),
        ),
    ]);
    f.render_widget(Paragraph::new(filter_line), chunks[0]);

    // List — show `cursor` highlight + truncate items past visible area.
    // We don't paginate; if a repo has 100+ items the user just narrows
    // with the filter (that's the whole point of the popup).
    let visible_h = chunks[1].height as usize;
    let total = picker.matches.len();
    let scroll_top = picker.cursor.saturating_sub(visible_h.saturating_sub(1));

    let mut lines: Vec<Line> = Vec::with_capacity(total.min(visible_h));
    for (visual_idx, &item_idx) in picker
        .matches
        .iter()
        .enumerate()
        .skip(scroll_top)
        .take(visible_h)
    {
        use ratatui::text::Span;
        let item = &picker.items[item_idx];
        let is_cursor = visual_idx == picker.cursor;
        let prefix = if is_cursor { "" } else { "   " };

        let mut spans: Vec<Span> = vec![
            Span::styled(
                prefix,
                Style::default()
                    .fg(theme::PEACH)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("#{:<5}  ", item.number),
                Style::default().fg(theme::MAUVE),
            ),
            Span::styled(&item.title, Style::default().fg(theme::TEXT)),
        ];
        if !item.labels.is_empty() {
            spans.push(Span::styled(
                format!("  [{}]", item.labels.join(",")),
                Style::default().fg(theme::TEAL),
            ));
        }

        let line_style = if is_cursor {
            Style::default()
                .bg(theme::SURFACE1)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };
        lines.push(Line::from(spans).style(line_style));
    }
    if lines.is_empty() {
        lines.push(Line::from(ratatui::text::Span::styled(
            "  (no matches)",
            Style::default().fg(theme::OVERLAY),
        )));
    }
    f.render_widget(Paragraph::new(lines), chunks[1]);

    // Footer — pill-style hints matching the main dashboard footer.
    f.render_widget(
        Paragraph::new(Line::from(footer_pills(&[
            ("j/k", "move"),
            ("type", "filter"),
            ("", "open"),
            ("esc", "close"),
        ]))),
        chunks[2],
    );
}

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

    fn rows(slugs: &[&str]) -> Vec<DashRow> {
        slugs
            .iter()
            .map(|s| {
                let path = PathBuf::from("/tmp");
                let search_key = format!("{s} {}", path.display());
                DashRow {
                    slug: (*s).into(),
                    path,
                    search_key,
                    tags_display: String::new(),
                    status: None,
                    gh: None,
                }
            })
            .collect()
    }

    /// `rows()` variant that lets a test pin per-row `path` strings,
    /// so we can verify the filter scores against `slug + path`.
    fn rows_with_paths(items: &[(&str, &str)]) -> Vec<DashRow> {
        items
            .iter()
            .map(|(slug, path)| {
                let path = PathBuf::from(path);
                let search_key = format!("{slug} {}", path.display());
                DashRow {
                    slug: (*slug).into(),
                    path,
                    search_key,
                    tags_display: String::new(),
                    status: None,
                    gh: None,
                }
            })
            .collect()
    }

    #[test]
    fn build_rows_splits_status_per_path_but_shares_gh_by_triple() {
        // Regression guard for the split-lookup contract introduced
        // by #57: per-checkout `git_status` must come from the
        // path-pinned cache entry (different value per row), while
        // `gh` is remote-derived and shared across siblings (the
        // first populated snapshot wins, even if it lives on a
        // different sibling than the row being rendered).
        use crate::cache::Cache;
        use crate::config::ShokaConfig;
        use crate::gh::{CiStatus, GhSnapshot};
        use crate::git_status::GitStatusSnapshot;
        use crate::state::{Repo, Shelf};

        let path_a = PathBuf::from("/home/u/a/shoka");
        let path_b = PathBuf::from("/home/u/b/shoka");

        // Shelf: two checkouts of the same remote at different
        // paths. Identical (host, owner, name) — only the path
        // distinguishes them.
        let mut shelf = Shelf::default();
        shelf
            .add(Repo::new("github.com", "yukimemi", "shoka").with_path(path_a.clone()))
            .unwrap();
        shelf
            .add(Repo::new("github.com", "yukimemi", "shoka").with_path(path_b.clone()))
            .unwrap();

        // Cache: two path-pinned rows. Different `git_status`
        // snapshots per row (so we can detect cross-contamination)
        // and `gh` populated only on row B (so we can prove the
        // lookup walked past row A's `None`).
        let status_a = GitStatusSnapshot {
            branch: Some("feat/a".into()),
            dirty: false,
            ahead: Some(1),
            behind: Some(0),
        };
        let status_b = GitStatusSnapshot {
            branch: Some("feat/b".into()),
            dirty: true,
            ahead: Some(0),
            behind: Some(2),
        };
        let shared_gh = GhSnapshot {
            open_pr_count: Some(7),
            ci_status: Some(CiStatus::Success),
        };

        let mut cache = Cache::default();
        let row_a = cache.upsert(&shelf.repos[0]);
        row_a.git_status = Some(status_a.clone());
        row_a.gh = None;
        let row_b = cache.upsert(&shelf.repos[1]);
        row_b.git_status = Some(status_b.clone());
        row_b.gh = Some(shared_gh.clone());

        // `clone_path_for` early-returns `repo.path` for pinned
        // entries before consulting routes, so the root only needs
        // to satisfy `resolve()`'s "must be set" guard — it never
        // surfaces in the output rows for this test's path-pinned
        // shelf.
        let mut cfg = ShokaConfig::default();
        cfg.global.root = Some("/unused-for-pinned-rows".into());
        let resolved = cfg.resolve(None).expect("resolve");
        let rows = build_rows(&shelf, &resolved, &cache, &[]).expect("build rows");
        assert_eq!(rows.len(), 2);

        // Per-path `git_status`: each row sees its own snapshot
        // (not a cross-row leak). This is the bug PR #59 left open
        // and #57 explicitly resolves.
        assert_eq!(rows[0].status.as_ref(), Some(&status_a));
        assert_eq!(rows[1].status.as_ref(), Some(&status_b));

        // Triple-shared `gh`: both rows see the same snapshot —
        // and crucially row A sees row B's populated value (not
        // row A's own `None`), proving `find_gh_by_triple` walked
        // past the unpopulated sibling.
        assert_eq!(rows[0].gh.as_ref(), Some(&shared_gh));
        assert_eq!(rows[1].gh.as_ref(), Some(&shared_gh));
    }

    #[test]
    fn gh_cells_renders_dashes_when_snapshot_missing() {
        let (pr, ci) = gh_cells(None);
        assert_eq!(pr, "-");
        assert_eq!(ci, "-");
    }

    #[test]
    fn gh_cells_renders_count_and_status_glyph() {
        let snap = GhSnapshot {
            open_pr_count: Some(5),
            ci_status: Some(CiStatus::Success),
        };
        let (pr, ci) = gh_cells(Some(&snap));
        assert_eq!(pr, "5");
        assert_eq!(ci, "");
    }

    #[test]
    fn gh_cells_clamps_pr_count_at_99_plus() {
        let snap = GhSnapshot {
            open_pr_count: Some(150),
            ci_status: None,
        };
        let (pr, _) = gh_cells(Some(&snap));
        assert_eq!(pr, "99+");
    }

    #[test]
    fn gh_cells_distinguishes_zero_from_none() {
        // Zero PRs is a definite "no PRs"; None is "didn't check".
        // The cell strings must differ so the user can tell.
        let zero = GhSnapshot {
            open_pr_count: Some(0),
            ci_status: None,
        };
        let (pr_zero, _) = gh_cells(Some(&zero));
        let (pr_none, _) = gh_cells(None);
        assert_eq!(pr_zero, "0");
        assert_eq!(pr_none, "-");
        assert_ne!(pr_zero, pr_none);
    }

    #[test]
    fn gh_cells_renders_each_ci_status() {
        for (status, expected) in [
            (CiStatus::Success, ""),
            (CiStatus::Failure, ""),
            (CiStatus::Pending, ""),
            (CiStatus::Skipped, ""),
            (CiStatus::Other, "!"),
        ] {
            let snap = GhSnapshot {
                open_pr_count: None,
                ci_status: Some(status),
            };
            let (_, ci) = gh_cells(Some(&snap));
            assert_eq!(ci, expected, "ci glyph for {status:?}");
        }
    }

    fn snap(
        branch: &str,
        ahead: Option<usize>,
        behind: Option<usize>,
        dirty: bool,
    ) -> GitStatusSnapshot {
        GitStatusSnapshot {
            branch: Some(branch.into()),
            dirty,
            ahead,
            behind,
        }
    }

    #[test]
    fn status_cells_renders_unknown_for_missing_snapshot() {
        let (b, ab, d) = status_cells(None);
        assert_eq!(b, "?");
        assert_eq!(ab, "?");
        assert_eq!(d, "?");
    }

    #[test]
    fn status_cells_renders_clean_branch_with_equal_marker() {
        let s = snap("main", Some(0), Some(0), false);
        let (b, ab, d) = status_cells(Some(&s));
        assert_eq!(b, "main");
        assert_eq!(ab, "=");
        assert_eq!(d, "");
    }

    #[test]
    fn status_cells_renders_ahead_only_and_behind_only() {
        let (_, ab_ahead, _) = status_cells(Some(&snap("x", Some(3), Some(0), false)));
        assert_eq!(ab_ahead, "↑3");
        let (_, ab_behind, _) = status_cells(Some(&snap("x", Some(0), Some(2), false)));
        assert_eq!(ab_behind, "↓2");
    }

    #[test]
    fn status_cells_renders_diverged_with_both_arrows() {
        let (_, ab, _) = status_cells(Some(&snap("x", Some(2), Some(5), false)));
        assert_eq!(ab, "↑2 ↓5");
    }

    #[test]
    fn status_cells_renders_dash_when_upstream_unknown() {
        // No upstream ref → both ahead/behind are None → dash.
        let (_, ab, _) = status_cells(Some(&snap("x", None, None, false)));
        assert_eq!(ab, "-");
    }

    #[test]
    fn status_cells_renders_dirty_glyph() {
        let (_, _, d) = status_cells(Some(&snap("x", Some(0), Some(0), true)));
        assert_eq!(d, "");
    }

    #[test]
    fn refilter_empty_query_keeps_shelf_order() {
        let mut app = App::new(rows(&["alpha", "beta", "gamma"]));
        app.refilter();
        assert_eq!(app.matches, vec![0, 1, 2]);
    }

    #[test]
    fn refilter_narrows_to_matches() {
        let mut app = App::new(rows(&["alpha", "beta", "gamma", "alphabeta"]));
        app.filter = "alpha".into();
        app.refilter();
        // `alpha` and `alphabeta` should match; `beta` / `gamma` not.
        // Order is nucleo's call (score-descending); both should be
        // first or second.
        let matched_slugs: Vec<&str> = app
            .matches
            .iter()
            .map(|&i| app.rows[i].slug.as_str())
            .collect();
        assert!(
            matched_slugs.contains(&"alpha"),
            "missing alpha: {matched_slugs:?}"
        );
        assert!(
            matched_slugs.contains(&"alphabeta"),
            "missing alphabeta: {matched_slugs:?}"
        );
        assert!(
            !matched_slugs.contains(&"beta"),
            "beta shouldn't match: {matched_slugs:?}"
        );
        assert!(
            !matched_slugs.contains(&"gamma"),
            "gamma shouldn't match: {matched_slugs:?}"
        );
    }

    #[test]
    fn refilter_no_matches_leaves_empty() {
        let mut app = App::new(rows(&["alpha", "beta"]));
        app.filter = "zzzzz".into();
        app.refilter();
        assert!(app.matches.is_empty());
        assert_eq!(app.cursor, 0);
        assert!(app.table_state.selected().is_none());
    }

    #[test]
    fn refilter_matches_against_path_for_multi_clone_disambiguation() {
        // Two rows with the same slug but different on-disk paths.
        // Filtering by a substring that only appears in one path
        // must narrow to that row — that's how the user picks
        // between multiple checkouts of the same remote.
        let mut app = App::new(rows_with_paths(&[
            (
                "github.com/yukimemi/admintask",
                "/home/u/src/DeviceManagement",
            ),
            (
                "github.com/yukimemi/admintask",
                "/home/u/old/admintask-backup",
            ),
            ("github.com/yukimemi/shoka", "/home/u/src/shoka"),
        ]));
        app.filter = "backup".into();
        app.refilter();
        assert_eq!(
            app.matches.len(),
            1,
            "exactly one row should match `backup`: {:?}",
            app.matches
                .iter()
                .map(|&i| &app.rows[i].path)
                .collect::<Vec<_>>()
        );
        assert_eq!(
            app.rows[app.matches[0]].path.to_string_lossy(),
            "/home/u/old/admintask-backup"
        );
    }

    #[test]
    fn refilter_resets_cursor_to_top() {
        let mut app = App::new(rows(&["a", "b", "c", "d"]));
        app.cursor = 3;
        app.refilter();
        assert_eq!(app.cursor, 0);
    }

    #[test]
    fn navigation_clamps_at_edges() {
        let mut app = App::new(rows(&["a", "b", "c"]));
        // Up at top stays at top (saturating_sub).
        app.move_up();
        assert_eq!(app.cursor, 0);
        // Down moves until the last row.
        app.move_down();
        app.move_down();
        app.move_down(); // would be 3, clamped to 2
        assert_eq!(app.cursor, 2);
    }

    #[test]
    fn navigation_on_empty_match_list_is_noop() {
        let mut app = App::new(rows(&[]));
        app.move_down();
        app.move_up();
        assert_eq!(app.cursor, 0);
        assert!(app.selected_row().is_none());
    }

    #[test]
    fn selected_row_returns_underlying_shelf_index() {
        // The TUI tracks cursor against `matches`, but the result
        // needs to be a shelf-relative index so the path emission
        // hits the right repo even when the filter reorders rows.
        let mut app = App::new(rows(&["zzz", "aaa"]));
        app.filter = "aaa".into();
        app.refilter();
        // After filtering only "aaa" remains, mapping to shelf idx 1.
        assert_eq!(app.selected_row(), Some(1));
    }

    fn picker_items(items: &[(u64, &str, &[&str])]) -> Vec<crate::gh::PickerItem> {
        items
            .iter()
            .map(|(n, t, ls)| crate::gh::PickerItem {
                number: *n,
                title: (*t).into(),
                html_url: format!("https://github.com/x/y/issues/{n}"),
                labels: ls.iter().map(|s| (*s).into()).collect(),
            })
            .collect()
    }

    #[test]
    fn picker_refilter_empty_query_keeps_identity_order() {
        let mut p = Picker::loaded(
            PickerKind::Issues,
            "x/y/z".into(),
            picker_items(&[(1, "alpha", &[]), (2, "beta", &[]), (3, "gamma", &[])]),
        );
        p.refilter();
        assert_eq!(p.matches, vec![0, 1, 2]);
    }

    #[test]
    fn picker_refilter_narrows_against_title_and_labels() {
        let mut p = Picker::loaded(
            PickerKind::Issues,
            "x/y/z".into(),
            picker_items(&[
                (1, "broken thing", &["bug"]),
                (2, "happy path", &["enhancement"]),
                (3, "another bug-fix", &[]),
            ]),
        );
        p.filter = "bug".into();
        p.refilter();
        // Items 1 and 3 should match (1 via label, 3 via title);
        // item 2 should not. Order is nucleo's call (score desc).
        let matched: Vec<u64> = p.matches.iter().map(|&i| p.items[i].number).collect();
        assert!(
            matched.contains(&1) && matched.contains(&3),
            "expected items 1 + 3 to match, got: {matched:?}"
        );
        assert!(
            !matched.contains(&2),
            "item 2 should not match `bug`, got: {matched:?}"
        );
    }

    #[test]
    fn picker_error_renders_with_no_items() {
        // Error-mode picker has an empty items list and a non-None
        // error field. `selected()` returns None — render_picker
        // takes the error branch and never reaches the list code.
        let p = Picker::error(PickerKind::Prs, "github.com/x/y".into(), "no GITHUB_TOKEN");
        assert!(p.items.is_empty());
        assert_eq!(p.error.as_deref(), Some("no GITHUB_TOKEN"));
        assert!(p.selected().is_none());
    }

    #[test]
    fn picker_search_key_includes_number_title_and_labels() {
        // The key is what nucleo scores against, so it has to mention
        // every searchable surface. A regression here would silently
        // make label / number queries miss.
        let item = crate::gh::PickerItem {
            number: 42,
            title: "fix the thing".into(),
            html_url: "https://github.com/x/y/issues/42".into(),
            labels: vec!["bug".into(), "p1".into()],
        };
        let key = item.search_key();
        assert!(key.contains("42"), "number missing: {key}");
        assert!(key.contains("fix the thing"), "title missing: {key}");
        assert!(key.contains("bug"), "label missing: {key}");
        assert!(key.contains("p1"), "label missing: {key}");
    }

    /// Helper: construct an `App` whose first row carries the given
    /// slug, so `open_picker`'s row-resolution path runs against a
    /// known input. The non-slug fields don't matter for the early-
    /// return branches we're testing.
    fn app_with_single_slug(slug: &str) -> App {
        App::new(rows(&[slug]))
    }

    fn key(code: KeyCode) -> crossterm::event::KeyEvent {
        crossterm::event::KeyEvent::new(code, crossterm::event::KeyModifiers::NONE)
    }

    #[test]
    fn open_picker_short_circuits_on_malformed_slug() {
        // A slug missing the host/owner/name shape should land us in
        // the error popup with a message that includes the bad slug,
        // not the live-fetch path (which would need network).
        let mut app = app_with_single_slug("no-slashes-here");
        open_picker(&mut app, PickerKind::Issues);
        let picker = app.picker.as_ref().expect("error picker installed");
        let err = picker.error.as_ref().expect("error message set");
        assert!(
            err.contains("no-slashes-here"),
            "malformed-slug error should mention the slug, got: {err}"
        );
    }

    #[test]
    fn open_picker_short_circuits_on_non_github_host() {
        // `host = local` (from `shoka import` for a local-only repo)
        // and `host = gitlab.com` / etc. should all hit the same
        // "github only" branch before any network call. Pointing at
        // a clearly-distinct host keeps the assertion robust against
        // future tweaks to the message text.
        let mut app = app_with_single_slug("gitlab.com/some/proj");
        open_picker(&mut app, PickerKind::Prs);
        let picker = app.picker.as_ref().expect("error picker installed");
        let err = picker.error.as_ref().expect("error message set");
        assert!(
            err.contains("github.com") && err.contains("gitlab.com"),
            "non-github error should mention both the requirement and the actual host, got: {err}"
        );
        assert!(
            err.contains(PickerKind::Prs.title()),
            "error should name the kind so the user knows what they tried to open, got: {err}"
        );
    }

    #[test]
    fn handle_picker_key_esc_closes_picker() {
        let mut app = App::new(rows(&[]));
        app.picker = Some(Picker::loaded(
            PickerKind::Issues,
            "github.com/x/y".into(),
            picker_items(&[(1, "alpha", &[])]),
        ));
        handle_picker_key(&mut app, key(KeyCode::Esc));
        assert!(app.picker.is_none(), "Esc should close the picker");
    }

    #[test]
    fn handle_picker_key_q_closes_picker() {
        let mut app = App::new(rows(&[]));
        app.picker = Some(Picker::loaded(
            PickerKind::Issues,
            "github.com/x/y".into(),
            picker_items(&[(1, "alpha", &[])]),
        ));
        handle_picker_key(&mut app, key(KeyCode::Char('q')));
        assert!(app.picker.is_none(), "q should close the picker");
    }

    #[test]
    fn handle_picker_key_enter_on_empty_items_closes_without_browser_launch() {
        // Enter with no `selected()` skips the `open::that` call
        // entirely (no subprocess fired) and still closes the popup.
        // Tests run in CI where launching a browser would be
        // useless at best and flaky at worst, so the empty-list path
        // is the right hook to assert "Enter does close" without
        // collateral effects.
        let mut app = App::new(rows(&[]));
        app.picker = Some(Picker::loaded(
            PickerKind::Issues,
            "github.com/x/y".into(),
            vec![],
        ));
        handle_picker_key(&mut app, key(KeyCode::Enter));
        assert!(
            app.picker.is_none(),
            "Enter should close the picker even with nothing to open"
        );
    }

    #[test]
    fn handle_picker_key_char_appends_to_filter_and_refilters() {
        let mut app = App::new(rows(&[]));
        app.picker = Some(Picker::loaded(
            PickerKind::Issues,
            "github.com/x/y".into(),
            picker_items(&[(1, "alpha", &[]), (2, "zeta", &[])]),
        ));
        handle_picker_key(&mut app, key(KeyCode::Char('a')));
        let picker = app.picker.as_ref().unwrap();
        assert_eq!(picker.filter, "a");
        // Both items contain `a` (`alpha` literally, `zeta` ends with
        // it), so matches is non-empty — the real assertion is just
        // that typing went through and refilter ran. Stronger orderings
        // belong in the dedicated refilter tests above.
        assert!(!picker.matches.is_empty());
    }

    #[test]
    fn handle_picker_key_backspace_pops_and_refilters() {
        let mut app = App::new(rows(&[]));
        let mut p = Picker::loaded(
            PickerKind::Issues,
            "github.com/x/y".into(),
            picker_items(&[(1, "alpha", &[])]),
        );
        p.filter = "ab".into();
        p.refilter();
        app.picker = Some(p);
        handle_picker_key(&mut app, key(KeyCode::Backspace));
        let picker = app.picker.as_ref().unwrap();
        assert_eq!(picker.filter, "a");
    }

    #[test]
    fn run_action_for_selected_noop_when_no_selection() {
        // Empty shelf → `selected_row()` is `None`, the action
        // function early-returns without spawning a subprocess
        // (which would be wrong: there's no row to act on) and
        // crucially without installing a popup. The dashboard stays
        // exactly as it was.
        let mut app = App::new(rows(&[]));
        run_action_for_selected(&mut app, ActionKind::Fetch);
        assert!(
            app.action_popup.is_none(),
            "no row selected → no popup should be set"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn run_action_for_selected_records_error_when_no_vcs() {
        // Real path that has neither `.jj/` nor `.git/`. `run_action`
        // returns `Err`, which `run_action_for_selected` should fold
        // into a popup with `outcome: None` + a non-empty error
        // message — never panic, never silently swallow.
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().to_path_buf();
        let search_key = format!("local/test/repo {}", path.display());
        let row = DashRow {
            slug: "local/test/repo".into(),
            path,
            search_key,
            tags_display: String::new(),
            status: None,
            gh: None,
        };
        let mut app = App::new(vec![row]);
        run_action_for_selected(&mut app, ActionKind::Fetch);
        let popup = app.action_popup.as_ref().expect("popup installed");
        assert!(
            popup.outcome.is_none(),
            "no-VCS branch should leave `outcome` None to drive the error styling"
        );
        assert!(
            !popup.error.is_empty(),
            "error message must be populated so the user sees why the action failed"
        );
        assert_eq!(popup.kind, ActionKind::Fetch);
        assert_eq!(popup.repo_label, "local/test/repo");
    }

    #[test]
    fn yank_selected_slug_noop_when_no_selection() {
        // Empty shelf → no row, so the clipboard is never touched and
        // no status banner is set. Important because arboard's
        // `Clipboard::new()` can fail on headless CI runners, and we
        // don't want a stray `y` keystroke (e.g. while debugging an
        // empty shelf) to surface a confusing error message.
        let mut app = App::new(rows(&[]));
        yank_selected_slug(&mut app);
        assert!(
            app.status_message.is_none(),
            "no row selected → no status message should be set"
        );
    }

    #[test]
    fn open_selected_repo_home_short_circuits_on_local_host() {
        // `host = local` is the synthetic slug shoka mints for
        // jj-only / no-remote repos via `shoka import`. There's no
        // web home for these, so the open helper must surface a
        // status note instead of spawning a browser to
        // `https://local/...` (which would 404 — annoying, not
        // dangerous, but pointless).
        let mut app = app_with_single_slug("local/scratch/notes");
        open_selected_repo_home(&mut app);
        let msg = app
            .status_message
            .as_ref()
            .expect("status banner installed");
        assert!(
            msg.contains("local-only"),
            "local-host status banner should mention the cause, got: {msg}"
        );
    }

    #[test]
    fn open_selected_repo_home_noop_when_no_selection() {
        // Empty shelf → no row, so neither the browser nor the
        // status banner should fire. Defensive: a stray `o` on an
        // empty dashboard shouldn't open a `https:///` tab.
        let mut app = App::new(rows(&[]));
        open_selected_repo_home(&mut app);
        assert!(
            app.status_message.is_none(),
            "no row selected → no status message should be set"
        );
    }
}