zdbview 0.6.0

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

use anyhow::Result;
use crossterm::event::{
    self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
    MouseEventKind,
};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, Borders, Cell, Clear, List, ListItem, ListState, Paragraph, Row, Table, TableState,
};
use ratatui::{DefaultTerminal, Frame};

use std::path::PathBuf;

use crate::formats::{self, Decoded, FormatKind};
use crate::hexedit::{self, HexEdit};
use crate::mru::{self, Entry};
use crate::overlay::{HelpCtx, Overlays};
use crate::rkyv_inspect::RkyvStore;
use crate::sqlite::{RowsView, Sort, SqliteStore};
use crate::store::{Kind, Store};
use crate::theme::{Theme, ThemeName};

/// How many rows per SQLite page.
const PAGE: i64 = 500;
/// Minimum length for an extracted rkyv string run.
const MIN_STRING: usize = 4;
/// Idle wake-up interval: how often the loop redraws with no input pending, so a
/// toast dismisses itself on time (iftoprs's `event::poll` tick).
const TICK: std::time::Duration = std::time::Duration::from_millis(250);

/// Which pane has keyboard focus.
#[derive(PartialEq, Eq, Clone, Copy)]
enum Focus {
    Left,
    Right,
}

/// Modal input state layered over Normal browsing.
enum Mode {
    Normal,
    /// Editing a SQLite cell in place; buffer holds the pending value.
    EditCell(String),
    /// A raw SQL command line (`:`); buffer holds the statement.
    Command(String),
    /// A `/` search prompt; buffer holds the pattern being typed.
    Search(String),
    /// Adding a new rkyv record; buffer holds the key being typed.
    AddRecord(String),
    /// Renaming a rkyv record's key; buffer holds the new key.
    RenameRecord(String),
    /// Confirm a destructive action (delete row).
    ConfirmDelete,
}

/// The views for a rkyv/binary file. `Records` is only available when the
/// archive was recognized and decoded to key/value.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum RkyvView {
    Records,
    Info,
    Strings,
    Hex,
}

/// Where the cursor was when `/` was pressed. An incremental search always looks
/// from here, so the match moves with the pattern instead of walking forward one
/// hop per keystroke, and Esc puts things back.
#[derive(Debug, Clone, Copy)]
struct SearchOrigin {
    table_idx: usize,
    page_offset: i64,
    row_idx: usize,
    record_idx: usize,
    string_idx: usize,
    hex_row: usize,
}

/// Why the app loop ended: the user quit, or asked for the file picker again.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Outcome {
    Quit,
    /// `o` — back to the picker to open another file.
    Reopen,
}

/// Top-level screen. Overlaid modals (`Mode`) and the help overlay sit on top.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Screen {
    Main,
    /// Full-screen detail of one row/record with a scrollable value pane.
    Detail,
    /// Hex editor over one record's value bytes.
    HexEdit,
    /// Live write monitor over every store zdbview knows about.
    Top,
    /// SQLite schema (CREATE statements) view.
    Schema,
}

/// How the value pane renders raw bytes.
#[derive(PartialEq, Eq, Clone, Copy)]
enum ValueRender {
    Auto,
    Hex,
    Text,
    /// Disassemble the value as a fusevm::Chunk (requires the `disasm` feature).
    Disasm,
}

impl ValueRender {
    fn label(self) -> &'static str {
        match self {
            ValueRender::Auto => "auto",
            ValueRender::Hex => "hex",
            ValueRender::Text => "text",
            ValueRender::Disasm => "disasm",
        }
    }
    fn next(self) -> Self {
        match self {
            ValueRender::Auto => ValueRender::Hex,
            ValueRender::Hex => ValueRender::Text,
            ValueRender::Text => ValueRender::Disasm,
            ValueRender::Disasm => ValueRender::Auto,
        }
    }
}

pub struct App {
    store: Store,
    focus: Focus,
    mode: Mode,
    status: String,
    quit: bool,

    // SQLite state
    table_idx: usize,
    rows: Option<RowsView>,
    page_offset: i64,
    row_idx: usize,
    col_idx: usize,

    // rkyv state
    rkyv_view: RkyvView,
    strings: Vec<crate::rkyv_inspect::StringHit>,
    string_idx: usize,
    hex_row: usize,
    /// Decoded key/value records when the archive was recognized.
    decoded: Option<Decoded>,
    record_idx: usize,

    /// True after a lone `g`, awaiting the second `g` of a `gg` motion.
    pending_g: bool,
    /// Active search pattern (empty = no search); `n`/`N` cycle its matches.
    search: String,

    // Screens / overlays
    screen: Screen,
    value_render: ValueRender,
    /// Cached bytes shown in the Detail value pane.
    detail_value: Vec<u8>,
    detail_scroll: usize,
    schema_scroll: usize,
    /// SQLite schema objects `(type, name, sql)`, loaded lazily.
    schema: Vec<(String, String, String)>,

    // Mouse hit-testing: the on-screen rect and scroll offset of each clickable
    // list/grid, captured during render so a click maps to the right index.
    click_left: Rect,
    click_right: Rect,
    click_records: Rect,
    off_left: usize,
    off_right: usize,
    off_records: usize,
    /// Byte offset of the text cursor within the active input modal's buffer.
    input_cursor: usize,
    /// The open hex editor, while `screen` is `Screen::HexEdit`.
    hex: Option<HexEdit>,
    /// Rect the hex editor last rendered into, for click hit-testing.
    hex_area: Rect,
    /// The write monitor, while `screen` is `Screen::Top`.
    top: Option<crate::monitor::Monitor>,
    /// Set by `o`: leave the app loop and show the file picker again.
    reopen: bool,
    /// A file the monitor asked to open, taking precedence over the picker.
    open_next: Option<PathBuf>,
    /// Position `/` started from, while a search prompt is open.
    search_origin: Option<SearchOrigin>,
    /// Active `/` filter: only matching rows/records/strings are listed. Empty
    /// when nothing is filtered.
    filter: String,
    /// The extracted string list hit its bounds, so it is not exhaustive.
    strings_truncated: bool,
    /// Bytes the string scan covered (the whole file unless it was bounded).
    strings_scanned: usize,
    /// A decode running on another thread, for an archive too big to validate
    /// while the user waits.
    decoding: Option<std::sync::mpsc::Receiver<Option<Decoded>>>,
    /// Rows of the focused scrollable region in the last frame. Paging moves by
    /// this much, so PageUp/PageDown match what is actually on screen instead of
    /// a fixed guess.
    page_rows: usize,
    /// Active row-grid ordering, or `None` for the table's natural `rowid`
    /// order. Reset when another table is selected.
    sort: Option<Sort>,

    /// Themed overlays (help / scheme chooser / palette editor / toast),
    /// shared with the recent-files picker.
    ov: Overlays,
}

impl App {
    /// Open `store` with an already-resolved scheme. The picker hands its own
    /// scheme over this way, so opening a file cannot re-read prefs and land on a
    /// different one.
    pub fn with_theme(store: Store, theme: Theme) -> Self {
        let mut app = App {
            store,
            focus: Focus::Left,
            mode: Mode::Normal,
            status: String::new(),
            quit: false,
            table_idx: 0,
            rows: None,
            page_offset: 0,
            row_idx: 0,
            col_idx: 0,
            rkyv_view: RkyvView::Info,
            strings: Vec::new(),
            string_idx: 0,
            hex_row: 0,
            decoded: None,
            record_idx: 0,
            pending_g: false,
            search: String::new(),
            screen: Screen::Main,
            value_render: ValueRender::Auto,
            detail_value: Vec::new(),
            detail_scroll: 0,
            schema_scroll: 0,
            schema: Vec::new(),
            click_left: Rect::ZERO,
            click_right: Rect::ZERO,
            click_records: Rect::ZERO,
            off_left: 0,
            off_right: 0,
            off_records: 0,
            input_cursor: 0,
            sort: None,
            hex: None,
            hex_area: Rect::ZERO,
            top: None,
            reopen: false,
            open_next: None,
            search_origin: None,
            filter: String::new(),
            strings_truncated: false,
            strings_scanned: 0,
            decoding: None,
            page_rows: 10,
            ov: Overlays::new(theme),
        };
        app.init();
        app
    }

    /// Leave the open file and ask for the picker again (`o`, or `Esc` on the
    /// first level).
    fn back_to_files(&mut self) {
        self.reopen = true;
        self.quit = true;
    }

    /// A file the write monitor asked to open next, if any.
    pub fn open_next(&mut self) -> Option<PathBuf> {
        self.open_next.take()
    }

    /// The scheme currently in use, to carry back to the picker.
    pub fn theme(&self) -> Theme {
        self.ov.theme
    }

    /// Which key sections the help overlay lists for what is on screen.
    fn help_ctx(&self) -> HelpCtx {
        if self.screen == Screen::HexEdit {
            return HelpCtx::HexEdit;
        }
        if self.screen == Screen::Top {
            return HelpCtx::Top;
        }
        match &self.store {
            Store::Sqlite(_) => HelpCtx::Sqlite,
            Store::Rkyv(_) => HelpCtx::Rkyv,
        }
    }

    /// Report an action's result: a transient toast over the UI plus the same
    /// text in the status bar, so it stays readable after the toast fades.
    fn notify(&mut self, msg: impl Into<String>) {
        let msg = msg.into();
        self.ov.toast(msg.clone());
        self.status = msg;
    }

    fn init(&mut self) {
        match &self.store {
            Store::Sqlite(s) => {
                if !s.tables.is_empty() {
                    self.load_table();
                }
                self.status = "j/k ←/→ move · Tab focus · / filter · ^f/^b page · e edit · a add · d delete · : SQL · s sort · c scheme · o/Esc files · h help · q quit".into();
            }
            Store::Rkyv(r) => {
                let s = r.strings(MIN_STRING);
                self.strings_truncated = s.truncated;
                self.strings_scanned = s.scanned;
                self.strings = s.hits;
                // Validating a large archive is slow — 25s for a 382MB shard —
                // so it runs on a thread and the structural view opens at once.
                // The Records view appears when the decode lands.
                if r.bytes.len() > DECODE_INLINE_MAX {
                    self.decoding = Some(spawn_decode(r.bytes.clone()));
                    self.rkyv_view = RkyvView::Info;
                    self.status = format!(
                        "decoding {} in the background · 1 Info · 2 Strings · 3 Hex · o/Esc files · q quit",
                        human_size(r.bytes.len() as u64)
                    );
                    return;
                }
                self.decoded = formats::try_decode(&r.bytes);
                if let Some(d) = &self.decoded {
                    self.rkyv_view = RkyvView::Records;
                    self.status = format!(
                        "{} · {} records · Enter detail · a add e hex-edit r rename d delete · / filter · 0/1/2/3 views · c scheme · o/Esc files · h help · q quit",
                        d.format,
                        d.records.len()
                    );
                } else {
                    self.status = "1 Info · 2 Strings · 3 Hex · j/k scroll · / filter · c scheme · o/Esc files · h help · q quit  (rkyv: unrecognized)".into();
                }
            }
        }
    }

    pub fn run(&mut self, terminal: &mut DefaultTerminal) -> Result<Outcome> {
        while !self.quit {
            self.poll_decode();
            if let Some(w) = self.top.as_mut() {
                w.tick();
            }
            terminal.draw(|f| self.render(f))?;
            if !event::poll(TICK)? {
                self.ov.expire_toast();
                continue;
            }
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => self.on_key(key),
                Event::Mouse(m) => self.on_mouse(m),
                _ => {}
            }
            self.ov.expire_toast();
        }
        Ok(if self.reopen {
            Outcome::Reopen
        } else {
            Outcome::Quit
        })
    }

    // ----- key handling -----------------------------------------------------

    fn on_key(&mut self, key: KeyEvent) {
        let code = key.code;

        // An open overlay owns the key.
        if self.ov.active() {
            self.ov.on_key(code);
            return;
        }

        // Modal input first. Snapshot the buffer into a local so no borrow of
        // `self.mode` is held across the `&mut self` dispatch call.
        enum Modal {
            Edit(String),
            Cmd(String),
            Search(String),
            Add(String),
            Rename(String),
            Confirm,
            None,
        }
        let modal = match &self.mode {
            Mode::EditCell(buf) => Modal::Edit(buf.clone()),
            Mode::Command(buf) => Modal::Cmd(buf.clone()),
            Mode::Search(buf) => Modal::Search(buf.clone()),
            Mode::AddRecord(buf) => Modal::Add(buf.clone()),
            Mode::RenameRecord(buf) => Modal::Rename(buf.clone()),
            Mode::ConfirmDelete => Modal::Confirm,
            Mode::Normal => Modal::None,
        };
        match modal {
            Modal::Edit(buf) => {
                return self.key_input(key, buf, Mode::EditCell, App::commit_edit_cell)
            }
            Modal::Cmd(buf) => return self.key_input(key, buf, Mode::Command, App::commit_command),
            Modal::Search(buf) => {
                // The arrows (and paging) move through the filtered list while the
                // prompt stays open — the pattern only takes Left/Right for its
                // own cursor.
                match code {
                    KeyCode::Up => {
                        self.move_selection(-1);
                        return;
                    }
                    KeyCode::Down => {
                        self.move_selection(1);
                        return;
                    }
                    KeyCode::PageUp => {
                        let step = self.page_step() as isize;
                        self.move_selection(-step);
                        return;
                    }
                    KeyCode::PageDown => {
                        let step = self.page_step() as isize;
                        self.move_selection(step);
                        return;
                    }
                    _ => {}
                }
                return self.key_input(key, buf, Mode::Search, App::commit_search);
            }
            Modal::Add(buf) => {
                return self.key_input(key, buf, Mode::AddRecord, App::commit_add_record)
            }
            Modal::Rename(buf) => {
                return self.key_input(key, buf, Mode::RenameRecord, App::commit_rename_record)
            }
            Modal::Confirm => return self.key_confirm_delete(code),
            Modal::None => {}
        }

        // The overlay openers (`h`/`?` help, `c` chooser, `C` editor) work from
        // every screen, exactly as on the recent-files picker — except inside the
        // hex editor, where those keys are motions and data.
        if self.screen != Screen::HexEdit && self.ov.on_key(code) {
            return;
        }

        // `w` opens the write monitor from any screen but the hex editor (where
        // every letter is data) and the monitor itself, where it closes.
        if code == KeyCode::Char('w')
            && self.screen != Screen::HexEdit
            && self.screen != Screen::Top
        {
            self.open_top();
            return;
        }

        // `o` goes back to the file picker from any screen but the hex editor,
        // where it inserts a byte.
        if code == KeyCode::Char('o') && self.screen != Screen::HexEdit {
            self.back_to_files();
            return;
        }

        match self.screen {
            // The hex editor is modal: it owns every key, including `h` and `c`,
            // because those are its own motions and data.
            Screen::HexEdit => return self.key_hex(key),
            Screen::Top => return self.key_top(code),
            Screen::Detail => return self.key_detail(code),
            Screen::Schema => return self.key_schema(code),
            Screen::Main => {}
        }

        match &self.store {
            Store::Sqlite(_) => self.key_sqlite(key),
            Store::Rkyv(_) => self.key_rkyv(key),
        }
    }

    // ----- mouse (ported from iftoprs `handle_mouse`) -----------------------

    fn on_mouse(&mut self, m: MouseEvent) {
        // An open overlay owns the event (wheel drives it, a click confirms).
        if self.ov.on_mouse(m) {
            return;
        }
        // In the hex editor the wheel scrolls the dump and a click places the
        // cursor on the byte under it.
        if self.screen == Screen::HexEdit {
            let area = self.hex_area;
            if let Some(ed) = self.hex.as_mut() {
                ed.on_mouse(m, area);
            }
            return;
        }
        // Scroll wheel reuses the existing up/down navigation for the active
        // screen/view (rows, records, hex, strings, detail, schema).
        match m.kind {
            MouseEventKind::ScrollDown => self.scroll_select(true),
            MouseEventKind::ScrollUp => self.scroll_select(false),
            MouseEventKind::Down(MouseButton::Left) => self.click_at(m.column, m.row, false),
            MouseEventKind::Down(MouseButton::Right) => self.click_at(m.column, m.row, true),
            _ => {}
        }
    }

    fn scroll_select(&mut self, down: bool) {
        if !matches!(self.mode, Mode::Normal) {
            return;
        }
        let code = if down { KeyCode::Down } else { KeyCode::Up };
        self.on_key(KeyEvent::new(code, KeyModifiers::empty()));
    }

    /// Left/right click at `(col,row)`: select the item under the cursor. Right
    /// click additionally opens the detail screen for it (like iftoprs's
    /// right-click-shows-details). The clickable rects and their scroll offsets
    /// are captured during render, so the mapping is correct even when scrolled.
    fn click_at(&mut self, col: u16, row: u16, right: bool) {
        if !matches!(self.mode, Mode::Normal) || self.screen != Screen::Main {
            return;
        }
        match &self.store {
            Store::Sqlite(_) => {
                if hit(self.click_left, col, row) {
                    self.focus = Focus::Left;
                    let idx = self.off_left + row.saturating_sub(self.click_left.y + 1) as usize;
                    self.select_table(idx);
                } else if hit(self.click_right, col, row) {
                    self.focus = Focus::Right;
                    // +2 for the top border and the header row.
                    let idx = self.off_right + row.saturating_sub(self.click_right.y + 2) as usize;
                    let n = self.rows.as_ref().map(|r| r.rows.len()).unwrap_or(0);
                    if idx < n {
                        self.row_idx = idx;
                        if right {
                            self.enter_detail();
                        }
                    }
                }
            }
            Store::Rkyv(_) => {
                if self.rkyv_view == RkyvView::Records && hit(self.click_records, col, row) {
                    let idx =
                        self.off_records + row.saturating_sub(self.click_records.y + 1) as usize;
                    let n = self.decoded.as_ref().map(|d| d.records.len()).unwrap_or(0);
                    if idx < n {
                        self.record_idx = idx;
                        if right {
                            self.enter_detail();
                        }
                    }
                }
            }
        }
    }

    // ----- Detail / Schema / export / clipboard screens ---------------------

    fn key_detail(&mut self, code: KeyCode) {
        let max_scroll = self.detail_value.len() / 16;
        match code {
            KeyCode::Char('q') => self.quit = true,
            KeyCode::Esc | KeyCode::Enter => {
                self.screen = Screen::Main;
                self.detail_scroll = 0;
            }
            KeyCode::Char('v') => self.value_render = self.value_render.next(),
            KeyCode::Char('y') => self.copy_detail_value(),
            KeyCode::Down | KeyCode::Char('j') => {
                if self.detail_scroll < max_scroll {
                    self.detail_scroll += 1;
                }
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.detail_scroll = self.detail_scroll.saturating_sub(1)
            }
            KeyCode::Char('g') => self.detail_scroll = 0,
            KeyCode::Char('G') => self.detail_scroll = max_scroll,
            KeyCode::PageDown => {
                self.detail_scroll = (self.detail_scroll + self.page_step()).min(max_scroll)
            }
            KeyCode::PageUp => {
                self.detail_scroll = self.detail_scroll.saturating_sub(self.page_step())
            }
            _ => {}
        }
    }

    fn key_schema(&mut self, code: KeyCode) {
        match code {
            KeyCode::Char('q') => self.quit = true,
            KeyCode::Esc | KeyCode::Char('S') => {
                self.screen = Screen::Main;
                self.schema_scroll = 0;
            }
            KeyCode::Down | KeyCode::Char('j') => self.schema_scroll += 1,
            KeyCode::Up | KeyCode::Char('k') => {
                self.schema_scroll = self.schema_scroll.saturating_sub(1)
            }
            KeyCode::Char('g') => self.schema_scroll = 0,
            KeyCode::PageDown => self.schema_scroll += self.page_step(),
            KeyCode::PageUp => {
                self.schema_scroll = self.schema_scroll.saturating_sub(self.page_step())
            }
            _ => {}
        }
    }

    /// Enter the detail screen for the current SQLite row or rkyv record.
    fn enter_detail(&mut self) {
        self.detail_scroll = 0;
        match &self.store {
            Store::Sqlite(_) => {
                let bytes = match (self.current_table(), self.current_rowid()) {
                    (Some(t), Some(rid)) => {
                        let col = self
                            .rows
                            .as_ref()
                            .and_then(|r| r.columns.get(self.col_idx).cloned())
                            .unwrap_or_default();
                        self.sqlite()
                            .and_then(|s| s.cell_bytes(&t, rid, &col).ok())
                            .unwrap_or_default()
                    }
                    _ => self
                        .rows
                        .as_ref()
                        .and_then(|r| r.rows.get(self.row_idx))
                        .and_then(|row| row.get(self.col_idx))
                        .map(|s| s.clone().into_bytes())
                        .unwrap_or_default(),
                };
                self.detail_value = bytes;
                self.screen = Screen::Detail;
            }
            Store::Rkyv(_) => {
                if let Some(rec) = self
                    .decoded
                    .as_ref()
                    .and_then(|d| d.records.get(self.record_idx))
                {
                    self.detail_value = rec.value.clone();
                    self.screen = Screen::Detail;
                }
            }
        }
    }

    fn open_schema(&mut self) {
        if let Some(s) = self.sqlite() {
            self.schema = s.schema().unwrap_or_default();
            self.schema_scroll = 0;
            self.screen = Screen::Schema;
        }
    }

    fn copy_detail_value(&mut self) {
        let text = match self.value_render {
            ValueRender::Text | ValueRender::Auto if looks_textual(&self.detail_value) => {
                String::from_utf8_lossy(&self.detail_value).into_owned()
            }
            _ => hex_string(&self.detail_value),
        };
        let ok = crate::clipboard::copy(&text);
        self.notify(if ok {
            format!("copied {} bytes to clipboard", self.detail_value.len())
        } else {
            "clipboard unavailable (no tty)".into()
        });
    }

    /// Export the current view to a file in the working directory.
    fn export_current(&mut self) {
        match &self.store {
            Store::Sqlite(_) => self.export_sqlite(),
            Store::Rkyv(_) => self.export_rkyv(),
        }
    }

    fn export_sqlite(&mut self) {
        let table = match self.current_table() {
            Some(t) => t,
            None => return,
        };
        let total = self.rows.as_ref().map(|r| r.total).unwrap_or(0);
        let view = match self.sqlite().unwrap().rows(
            &table,
            total.max(1),
            0,
            self.sort.as_ref(),
            &self.filter,
        ) {
            Ok(v) => v,
            Err(e) => {
                self.notify(format!("export failed: {}", e));
                return;
            }
        };
        let csv = crate::export::rows_to_csv(&view.columns, &view.rows);
        let path = format!("{}.csv", sanitize(&table));
        match std::fs::write(&path, csv) {
            Ok(()) => self.status = format!("exported {} rows → {}", view.rows.len(), path),
            Err(e) => self.status = format!("write failed: {}", e),
        }
    }

    fn export_rkyv(&mut self) {
        let d = match &self.decoded {
            Some(d) => d,
            None => {
                self.notify("nothing to export (unrecognized archive)");
                return;
            }
        };
        let recs: Vec<crate::export::RecordExport> = d
            .records
            .iter()
            .map(|r| crate::export::RecordExport {
                key: &r.key,
                fields: &r.fields,
                value: &r.value,
            })
            .collect();
        let json = crate::export::records_to_json(&recs);
        let base = match &self.store {
            Store::Rkyv(r) => r
                .path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("records")
                .to_string(),
            _ => "records".into(),
        };
        let path = format!("{}.records.json", sanitize(&base));
        match std::fs::write(&path, json) {
            Ok(()) => self.status = format!("exported {} records → {}", d.records.len(), path),
            Err(e) => self.status = format!("write failed: {}", e),
        }
    }

    fn key_sqlite(&mut self, key: KeyEvent) {
        let code = key.code;
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

        // Ctrl-f / Ctrl-b page forward / back (vim page motions).
        if ctrl {
            match code {
                KeyCode::Char('f') => self.page_sqlite(true),
                KeyCode::Char('b') => self.page_sqlite(false),
                _ => {}
            }
            return;
        }

        // `gg` motion: a lone `g` arms, the next `g` fires. Any other key
        // disarms.
        if code == KeyCode::Char('g') {
            if self.pending_g {
                self.pending_g = false;
                self.goto_top();
            } else {
                self.pending_g = true;
            }
            return;
        }
        self.pending_g = false;

        match code {
            KeyCode::Char('G') => self.goto_bottom(),
            KeyCode::Char('/') => self.open_modal(Mode::Search(String::new())),
            KeyCode::Char('n') => self.search_next(true),
            KeyCode::Char('N') => self.search_next(false),
            KeyCode::Char('q') => self.quit = true,
            // First level: Esc backs out to the file list, as it does from any
            // nested screen; `q` is the one that quits.
            KeyCode::Esc => self.back_to_files(),
            KeyCode::Tab => {
                self.focus = if self.focus == Focus::Left {
                    Focus::Right
                } else {
                    Focus::Left
                };
            }
            KeyCode::Up | KeyCode::Char('k') => match self.focus {
                Focus::Left => {
                    let visible = self.visible_tables();
                    if let Some(i) = Self::step_visible(&visible, self.table_idx, -1) {
                        self.select_table(i);
                    }
                }
                Focus::Right => self.row_idx = self.row_idx.saturating_sub(1),
            },
            KeyCode::Down | KeyCode::Char('j') => match self.focus {
                Focus::Left => {
                    let visible = self.visible_tables();
                    if let Some(i) = Self::step_visible(&visible, self.table_idx, 1) {
                        self.select_table(i);
                    }
                }
                Focus::Right => {
                    if let Some(r) = &self.rows {
                        if self.row_idx + 1 < r.rows.len() {
                            self.row_idx += 1;
                        }
                    }
                }
            },
            // Columns move with the arrows only: `h` is the help overlay (as in
            // iftoprs) and `l` is left free so the pair stays consistent.
            KeyCode::Left => {
                if self.focus == Focus::Right {
                    self.col_idx = self.col_idx.saturating_sub(1);
                }
            }
            KeyCode::Right => {
                if self.focus == Focus::Right {
                    if let Some(r) = &self.rows {
                        if self.col_idx + 1 < r.columns.len() {
                            self.col_idx += 1;
                        }
                    }
                }
            }
            KeyCode::Enter => match self.focus {
                Focus::Left => self.focus = Focus::Right,
                Focus::Right => self.enter_detail(),
            },
            KeyCode::PageDown => self.page_sqlite(true),
            KeyCode::PageUp => self.page_sqlite(false),
            KeyCode::Char('e') => self.begin_edit_cell(),
            KeyCode::Char('a') => self.insert_row(),
            KeyCode::Char('d') => {
                if self.focus == Focus::Right && self.current_rowid().is_some() {
                    self.mode = Mode::ConfirmDelete;
                }
            }
            KeyCode::Char('S') => self.open_schema(),
            // Sorting: `s` toggles the cursor column (asc → desc → off), and
            // `<`/`>` walk the sort across columns keeping the direction.
            KeyCode::Char('s') => self.sort_by_current_column(),
            KeyCode::Char('<') => self.sort_shift_column(false),
            KeyCode::Char('>') => self.sort_shift_column(true),
            KeyCode::Char('x') => self.export_current(),
            KeyCode::Char('y') => self.copy_sqlite_cell(),
            KeyCode::Char(':') => self.open_modal(Mode::Command(String::new())),
            _ => {}
        }
    }

    fn copy_rkyv_key(&mut self) {
        let key = self
            .decoded
            .as_ref()
            .and_then(|d| d.records.get(self.record_idx))
            .map(|r| r.key.clone());
        if let Some(k) = key {
            let ok = crate::clipboard::copy(&k);
            self.status = if ok {
                "copied key to clipboard".into()
            } else {
                "clipboard unavailable (no tty)".into()
            };
        }
    }

    fn copy_sqlite_cell(&mut self) {
        let cell = self
            .rows
            .as_ref()
            .and_then(|r| r.rows.get(self.row_idx))
            .and_then(|row| row.get(self.col_idx))
            .cloned()
            .unwrap_or_default();
        let ok = crate::clipboard::copy(&cell);
        self.notify(if ok {
            "copied cell to clipboard"
        } else {
            "clipboard unavailable (no tty)"
        });
    }

    fn key_rkyv(&mut self, key: KeyEvent) {
        let code = key.code;
        if code == KeyCode::Char('g') {
            if self.pending_g {
                self.pending_g = false;
                self.rkyv_goto_top();
            } else {
                self.pending_g = true;
            }
            return;
        }
        self.pending_g = false;

        match code {
            KeyCode::Char('G') => self.rkyv_goto_bottom(),
            KeyCode::Char('/') => self.open_modal(Mode::Search(String::new())),
            KeyCode::Char('n') => self.search_next(true),
            KeyCode::Char('N') => self.search_next(false),
            KeyCode::Char('q') => self.quit = true,
            // First level: Esc backs out to the file list, as it does from any
            // nested screen; `q` is the one that quits.
            KeyCode::Esc => self.back_to_files(),
            KeyCode::Char('0') => {
                if self.decoded.is_some() {
                    self.rkyv_view = RkyvView::Records;
                } else if self.decoding.is_some() {
                    self.notify("still decoding — Records will open when it lands");
                }
            }
            KeyCode::Char('1') => self.rkyv_view = RkyvView::Info,
            KeyCode::Char('2') => self.rkyv_view = RkyvView::Strings,
            KeyCode::Char('3') => self.rkyv_view = RkyvView::Hex,
            KeyCode::Up | KeyCode::Char('k') => self.move_rkyv(-1),
            KeyCode::Down | KeyCode::Char('j') => self.move_rkyv(1),
            KeyCode::PageDown => self.page_rkyv(true),
            KeyCode::PageUp => self.page_rkyv(false),
            KeyCode::Enter => {
                if self.rkyv_view == RkyvView::Records {
                    self.enter_detail();
                }
            }
            KeyCode::Char('d') => {
                if self.rkyv_view == RkyvView::Records && self.has_current_record() {
                    self.mode = Mode::ConfirmDelete;
                }
            }
            KeyCode::Char('a') => {
                if self.rkyv_view == RkyvView::Records && self.decoded.is_some() {
                    self.open_modal(Mode::AddRecord(String::new()));
                }
            }
            KeyCode::Char('e') => {
                if self.rkyv_view == RkyvView::Records && self.has_current_record() {
                    self.open_hex_editor();
                }
            }
            KeyCode::Char('r') => {
                let renamable = matches!(
                    self.decoded.as_ref().map(|d| d.kind),
                    Some(
                        FormatKind::Script
                            | FormatKind::Stryke
                            | FormatKind::Autoload
                            | FormatKind::Elisp
                    )
                );
                if self.rkyv_view == RkyvView::Records && self.has_current_record() && renamable {
                    let key = self
                        .decoded
                        .as_ref()
                        .and_then(|d| d.records.get(self.record_idx))
                        .map(|r| r.key.clone())
                        .unwrap_or_default();
                    self.open_modal(Mode::RenameRecord(key));
                }
            }
            KeyCode::Char('x') => self.export_current(),
            KeyCode::Char('y') => self.copy_rkyv_key(),
            _ => {}
        }
    }

    /// Cursor-aware text-input handler shared by every input modal. The cursor
    /// model (UTF-8-safe left/right/word-nav/home/end/kill) is ported from
    /// iftoprs's `FilterState`. `mk` rebuilds the mode from the edited buffer,
    /// `commit` runs on Enter.
    fn key_input(
        &mut self,
        key: KeyEvent,
        mut buf: String,
        mk: fn(String) -> Mode,
        commit: fn(&mut App, &str),
    ) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let mut cur = self.input_cursor.min(buf.len());
        match key.code {
            KeyCode::Esc => {
                self.mode = Mode::Normal;
                // A cancelled `/` drops the filter and puts the cursor back.
                if let Some(o) = self.search_origin.take() {
                    self.set_filter(String::new());
                    self.restore_position(o);
                    self.status.clear();
                }
                return;
            }
            KeyCode::Enter => {
                self.mode = Mode::Normal;
                // Enter keeps the filter the typing already applied.
                if self.search_origin.take().is_some() {
                    return;
                }
                commit(self, &buf);
                return;
            }
            KeyCode::Left => cur = input_left(&buf, cur),
            KeyCode::Right => cur = input_right(&buf, cur),
            KeyCode::Home => cur = 0,
            KeyCode::End => cur = buf.len(),
            KeyCode::Char('a') if ctrl => cur = 0,
            KeyCode::Char('e') if ctrl => cur = buf.len(),
            KeyCode::Char('b') if ctrl => cur = input_left(&buf, cur),
            KeyCode::Char('f') if ctrl => cur = input_right(&buf, cur),
            KeyCode::Char('w') if ctrl => cur = input_delete_word(&mut buf, cur),
            KeyCode::Char('u') if ctrl => {
                buf.drain(..cur);
                cur = 0;
            }
            KeyCode::Char('k') if ctrl => buf.truncate(cur),
            KeyCode::Backspace => {
                if cur > 0 {
                    let p = input_left(&buf, cur);
                    buf.drain(p..cur);
                    cur = p;
                }
            }
            KeyCode::Delete => {
                if cur < buf.len() {
                    let n = input_right(&buf, cur);
                    buf.drain(cur..n);
                }
            }
            KeyCode::Char(c) => {
                buf.insert(cur, c);
                cur += c.len_utf8();
            }
            _ => {}
        }
        self.input_cursor = cur;
        self.mode = mk(buf);
        // A `/` prompt filters the list as it is typed.
        if let Mode::Search(pattern) = &self.mode {
            let pattern = pattern.clone();
            self.filter_preview(&pattern);
        }
    }

    fn snapshot_position(&self) -> SearchOrigin {
        SearchOrigin {
            table_idx: self.table_idx,
            page_offset: self.page_offset,
            row_idx: self.row_idx,
            record_idx: self.record_idx,
            string_idx: self.string_idx,
            hex_row: self.hex_row,
        }
    }

    fn restore_position(&mut self, o: SearchOrigin) {
        self.table_idx = o.table_idx;
        self.record_idx = o.record_idx;
        self.string_idx = o.string_idx;
        self.hex_row = o.hex_row;
        self.row_idx = o.row_idx;
        // Only reload when the page actually moved: a query per keystroke would
        // make typing feel heavy on a large table.
        if self.page_offset != o.page_offset {
            self.page_offset = o.page_offset;
            self.load_table();
            self.row_idx = o.row_idx;
        }
    }

    /// Apply `pattern` as the list filter, on every keystroke. Only matching
    /// rows/records/strings stay listed — the same model as iftoprs's `/`, rather
    /// than hopping between matches.
    ///
    /// For SQLite the filter is a `WHERE` over every column, so it covers the
    /// whole table and not just the loaded page.
    fn filter_preview(&mut self, pattern: &str) {
        self.set_filter(pattern.to_string());
    }

    /// Set the active filter and rebuild whatever the current view lists.
    fn set_filter(&mut self, pattern: String) {
        if self.filter == pattern {
            return;
        }
        self.filter = pattern;
        match &self.store {
            Store::Sqlite(_) => {
                // With the table list focused, follow the filter onto a listed
                // table; otherwise the grid keeps showing a hidden one.
                if self.focus == Focus::Left {
                    let visible = self.visible_tables();
                    if !visible.contains(&self.table_idx) {
                        if let Some(&first) = visible.first() {
                            self.table_idx = first;
                        }
                    }
                }
                // The row grid is filtered in SQL, so the page restarts.
                self.page_offset = 0;
                self.row_idx = 0;
                self.load_table();
            }
            Store::Rkyv(_) => {
                // Keep the selection on a listed row.
                self.record_idx = self.first_visible_record().unwrap_or(0);
                self.string_idx = self.first_visible_string().unwrap_or(0);
            }
        }
        self.status = if self.filter.is_empty() {
            String::new()
        } else {
            let n = self.visible_count();
            format!(
                "/{}  ({} match{})",
                self.filter,
                n,
                if n == 1 { "" } else { "es" }
            )
        };
    }

    /// Does `hay` pass the active filter? An empty filter passes everything.
    fn passes(&self, hay: &str) -> bool {
        self.filter.is_empty() || hay.to_lowercase().contains(&self.filter.to_lowercase())
    }

    /// Indices of the records the filter leaves listed.
    fn visible_records(&self) -> Vec<usize> {
        match &self.decoded {
            Some(d) => d
                .records
                .iter()
                .enumerate()
                .filter(|(_, r)| self.passes(&r.key))
                .map(|(i, _)| i)
                .collect(),
            None => Vec::new(),
        }
    }

    /// Indices of the extracted strings the filter leaves listed.
    fn visible_strings(&self) -> Vec<usize> {
        self.strings
            .iter()
            .enumerate()
            .filter(|(_, s)| self.passes(&s.text))
            .map(|(i, _)| i)
            .collect()
    }

    /// Table names the filter leaves listed (the left pane).
    fn visible_tables(&self) -> Vec<usize> {
        let tables = self.sqlite().map(|s| s.tables.clone()).unwrap_or_default();
        tables
            .iter()
            .enumerate()
            .filter(|(_, t)| self.passes(t))
            .map(|(i, _)| i)
            .collect()
    }

    fn first_visible_record(&self) -> Option<usize> {
        self.visible_records().first().copied()
    }

    fn first_visible_string(&self) -> Option<usize> {
        self.visible_strings().first().copied()
    }

    /// How many rows the current view lists under the filter, for the status line.
    fn visible_count(&self) -> usize {
        match &self.store {
            Store::Sqlite(_) => match self.focus {
                Focus::Left => self.visible_tables().len(),
                Focus::Right => self.rows.as_ref().map(|r| r.total as usize).unwrap_or(0),
            },
            Store::Rkyv(_) => match self.rkyv_view {
                RkyvView::Records => self.visible_records().len(),
                RkyvView::Strings => self.visible_strings().len(),
                _ => 0,
            },
        }
    }

    /// Open a text-input modal, placing the cursor at the end of its buffer.
    fn open_modal(&mut self, mode: Mode) {
        if matches!(mode, Mode::Search(_)) {
            self.search_origin = Some(self.snapshot_position());
        }
        self.input_cursor = match &mode {
            Mode::EditCell(s)
            | Mode::Command(s)
            | Mode::Search(s)
            | Mode::AddRecord(s)
            | Mode::RenameRecord(s) => s.len(),
            _ => 0,
        };
        self.mode = mode;
    }

    fn commit_command(&mut self, sql: &str) {
        self.run_sql(sql);
    }

    fn commit_search(&mut self, pattern: &str) {
        self.search = pattern.to_string();
        self.search_next(true);
    }

    fn key_confirm_delete(&mut self, code: KeyCode) {
        match code {
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                match &self.store {
                    Store::Sqlite(_) => self.delete_current_row(),
                    Store::Rkyv(_) => self.delete_current_record(),
                }
                self.mode = Mode::Normal;
            }
            _ => self.mode = Mode::Normal,
        }
    }

    // ----- rkyv record CRUD -------------------------------------------------

    fn has_current_record(&self) -> bool {
        self.decoded
            .as_ref()
            .is_some_and(|d| self.record_idx < d.records.len())
    }

    /// (kind, shard bytes) for the current rkyv archive, if decoded.
    fn rkyv_kind_bytes(&self) -> Option<(FormatKind, Vec<u8>)> {
        let kind = self.decoded.as_ref().map(|d| d.kind)?;
        match &self.store {
            Store::Rkyv(r) => Some((kind, r.bytes.clone())),
            _ => None,
        }
    }

    /// (display key, del_key, kind, shard bytes) for the selected record.
    fn rkyv_ctx(&self) -> Option<(String, String, FormatKind, Vec<u8>)> {
        let (key, del_key, kind) = self.decoded.as_ref().and_then(|d| {
            d.records
                .get(self.record_idx)
                .map(|r| (r.key.clone(), r.del_key.clone(), d.kind))
        })?;
        match &self.store {
            Store::Rkyv(r) => Some((key, del_key, kind, r.bytes.clone())),
            _ => None,
        }
    }

    /// Apply a shard edit: write the new bytes back atomically and reload.
    fn rkyv_apply(&mut self, result: Result<Vec<u8>, String>, ok_msg: String) {
        let new_bytes = match result {
            Ok(b) => b,
            Err(e) => {
                self.notify(format!("failed: {}", e));
                return;
            }
        };
        let path = match &self.store {
            Store::Rkyv(r) => r.path.clone(),
            _ => return,
        };
        let tmp = path.with_extension("zdbview.tmp");
        let write = std::fs::write(&tmp, &new_bytes).and_then(|_| std::fs::rename(&tmp, &path));
        if let Err(e) = write {
            let _ = std::fs::remove_file(&tmp);
            self.notify(format!("write failed: {}", e));
            return;
        }
        if let Store::Rkyv(r) = &mut self.store {
            r.bytes = new_bytes;
        }
        self.reload_rkyv();
        self.notify(ok_msg);
    }

    /// Delete the selected rkyv record and write the shard back.
    fn delete_current_record(&mut self) {
        let (key, del_key, kind, bytes) = match self.rkyv_ctx() {
            Some(v) => v,
            None => return,
        };
        self.rkyv_apply(
            crate::formats::delete_record(&bytes, kind, &del_key),
            format!("deleted: {}", key),
        );
    }

    fn commit_add_record(&mut self, key: &str) {
        if key.is_empty() {
            self.notify("add cancelled: empty key");
            return;
        }
        let (kind, bytes) = match self.rkyv_kind_bytes() {
            Some(v) => v,
            None => return,
        };
        self.rkyv_apply(
            crate::formats::add_record(&bytes, kind, key, Vec::new()),
            format!("added: {}", key),
        );
    }

    /// Open the hex editor on the selected record's value, pre-filled with its
    /// current bytes (ported editor; see `crate::hexedit`).
    fn open_hex_editor(&mut self) {
        let (key, value) = match self
            .decoded
            .as_ref()
            .and_then(|d| d.records.get(self.record_idx))
        {
            Some(rec) => (rec.key.clone(), rec.value.clone()),
            None => return,
        };
        self.hex = Some(HexEdit::new(key, value));
        self.screen = Screen::HexEdit;
    }

    fn key_hex(&mut self, key: KeyEvent) {
        let action = match self.hex.as_mut() {
            Some(ed) => ed.on_key(key),
            None => {
                self.screen = Screen::Main;
                return;
            }
        };
        match action {
            hexedit::Action::None => {}
            hexedit::Action::Save => self.commit_hex_value(),
            hexedit::Action::Close => {
                self.hex = None;
                self.screen = Screen::Main;
            }
        }
    }

    /// Write the edited bytes back into the archive (same write-back path the
    /// other record edits use), leaving the editor open on the saved value.
    fn commit_hex_value(&mut self) {
        let value = match self.hex.as_ref() {
            Some(ed) => ed.bytes.clone(),
            None => return,
        };
        let (_, del_key, kind, bytes) = match self.rkyv_ctx() {
            Some(v) => v,
            None => return,
        };
        let n = value.len();
        self.rkyv_apply(
            crate::formats::set_value(&bytes, kind, &del_key, value),
            format!("value set ({} bytes)", n),
        );
        if let Some(ed) = self.hex.as_mut() {
            ed.mark_saved();
        }
    }

    fn commit_rename_record(&mut self, new_key: &str) {
        if new_key.is_empty() {
            self.notify("rename cancelled");
            return;
        }
        let (_, del_key, kind, bytes) = match self.rkyv_ctx() {
            Some(v) => v,
            None => return,
        };
        self.rkyv_apply(
            crate::formats::rename_record(&bytes, kind, &del_key, new_key),
            format!("renamed → {}", new_key),
        );
    }

    /// Recompute rkyv-derived state (strings + decoded records) after a write.
    fn reload_rkyv(&mut self) {
        let (strings, decoded) = match &self.store {
            Store::Rkyv(r) => (r.strings(MIN_STRING), crate::formats::try_decode(&r.bytes)),
            _ => return,
        };
        self.strings_truncated = strings.truncated;
        self.strings_scanned = strings.scanned;
        self.strings = strings.hits;
        self.decoded = decoded;
        let n = self.decoded.as_ref().map(|d| d.records.len()).unwrap_or(0);
        if self.record_idx >= n {
            self.record_idx = n.saturating_sub(1);
        }
        if n == 0 {
            self.rkyv_view = RkyvView::Info;
        }
    }

    // ----- SQLite operations ------------------------------------------------

    fn sqlite(&self) -> Option<&SqliteStore> {
        match &self.store {
            Store::Sqlite(s) => Some(s),
            _ => None,
        }
    }

    fn current_table(&self) -> Option<String> {
        self.sqlite()
            .and_then(|s| s.tables.get(self.table_idx).cloned())
    }

    fn current_rowid(&self) -> Option<i64> {
        self.rows
            .as_ref()
            .and_then(|r| r.rowids.get(self.row_idx).copied().flatten())
    }

    fn select_table(&mut self, idx: usize) {
        let n = self.sqlite().map(|s| s.tables.len()).unwrap_or(0);
        if n == 0 {
            return;
        }
        self.table_idx = idx.min(n - 1);
        self.page_offset = 0;
        self.row_idx = 0;
        self.col_idx = 0;
        // The sort column belongs to the table that was open.
        self.sort = None;
        self.load_table();
    }

    /// Sort the row grid by the column under the cursor. Pressing it again on
    /// the same column flips the direction; a third press clears the sort and
    /// returns to the table's natural `rowid` order.
    fn sort_by_current_column(&mut self) {
        let col = match self
            .rows
            .as_ref()
            .and_then(|r| r.columns.get(self.col_idx))
            .cloned()
        {
            Some(c) => c,
            None => return,
        };
        self.sort = match self.sort.take() {
            Some(s) if s.column == col && !s.desc => Some(Sort {
                column: col.clone(),
                desc: true,
            }),
            Some(s) if s.column == col => None,
            _ => Some(Sort {
                column: col.clone(),
                desc: false,
            }),
        };
        // A different ordering means a different first page.
        self.page_offset = 0;
        self.row_idx = 0;
        self.load_table();
        match &self.sort {
            Some(s) => {
                let dir = if s.desc { "descending" } else { "ascending" };
                self.notify(format!("sorted by {} {}", s.column, dir))
            }
            None => self.notify("sort cleared (rowid order)"),
        }
    }

    /// Move the sort to the next / previous column, keeping the direction.
    fn sort_shift_column(&mut self, forward: bool) {
        let columns = match self.rows.as_ref().map(|r| r.columns.clone()) {
            Some(c) if !c.is_empty() => c,
            _ => return,
        };
        let desc = self.sort.as_ref().is_some_and(|s| s.desc);
        let cur = self
            .sort
            .as_ref()
            .and_then(|s| columns.iter().position(|c| *c == s.column));
        let next = match cur {
            Some(i) if forward => (i + 1) % columns.len(),
            Some(i) => (i + columns.len() - 1) % columns.len(),
            // No sort yet: start from the column the cursor is on.
            None => self.col_idx.min(columns.len() - 1),
        };
        self.col_idx = next;
        self.sort = Some(Sort {
            column: columns[next].clone(),
            desc,
        });
        self.page_offset = 0;
        self.row_idx = 0;
        self.load_table();
        let dir = if desc { "descending" } else { "ascending" };
        self.notify(format!("sorted by {} {}", columns[next], dir));
    }

    fn load_table(&mut self) {
        let (table, res) = match (self.current_table(), self.sqlite()) {
            (Some(t), Some(s)) => {
                let r = s.rows(&t, PAGE, self.page_offset, self.sort.as_ref(), &self.filter);
                (t, r)
            }
            _ => return,
        };
        match res {
            Ok(v) => {
                self.rows = Some(v);
                if self.row_idx >= self.rows.as_ref().map(|r| r.rows.len()).unwrap_or(0) {
                    self.row_idx = 0;
                }
            }
            Err(e) => self.status = format!("load {}: {}", table, e),
        }
    }

    /// Step `cur` by `delta` positions through `visible`, clamped to its ends.
    /// Navigation has to walk the filtered list, or j/k would land on rows the
    /// filter has hidden.
    fn step_visible(visible: &[usize], cur: usize, delta: isize) -> Option<usize> {
        if visible.is_empty() {
            return None;
        }
        let pos = visible.iter().position(|&i| i == cur).unwrap_or(0) as isize;
        let next = (pos + delta).clamp(0, visible.len() as isize - 1) as usize;
        Some(visible[next])
    }

    /// Install a background decode's result once it arrives.
    fn poll_decode(&mut self) {
        let result = match self.decoding.as_ref() {
            Some(rx) => match rx.try_recv() {
                Ok(d) => d,
                Err(std::sync::mpsc::TryRecvError::Empty) => return,
                // The thread died without sending: treat it as undecodable.
                Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
            },
            None => return,
        };
        self.decoding = None;
        self.decoded = result;
        match &self.decoded {
            Some(d) => {
                let (format, records) = (d.format.clone(), d.records.len());
                self.rkyv_view = RkyvView::Records;
                self.notify(format!("{} · {} records", format, records));
            }
            None => self.notify("unrecognized archive — structural view"),
        }
    }

    /// A screenful, never zero.
    fn page_step(&self) -> usize {
        self.page_rows.max(1)
    }

    /// PageUp/PageDown (and `^F`/`^B`) for the SQLite panes: move the selection by
    /// a screenful, stepping to the next/previous SQL page at the edges.
    fn page_sqlite(&mut self, down: bool) {
        let step = self.page_step();
        match self.focus {
            Focus::Left => {
                let visible = self.visible_tables();
                let delta = if down {
                    step as isize
                } else {
                    -(step as isize)
                };
                if let Some(i) = Self::step_visible(&visible, self.table_idx, delta) {
                    self.select_table(i);
                }
            }
            Focus::Right => {
                let (loaded, total) = match &self.rows {
                    Some(r) => (r.rows.len(), r.total),
                    None => return,
                };
                if loaded == 0 {
                    return;
                }
                if down {
                    if self.row_idx + step < loaded {
                        self.row_idx += step;
                    } else if self.page_offset + PAGE < total {
                        self.page(PAGE);
                    } else {
                        self.row_idx = loaded - 1;
                    }
                } else if self.row_idx >= step {
                    self.row_idx -= step;
                } else if self.page_offset > 0 {
                    self.page(-PAGE);
                    // Land at the bottom of the page we just came back to.
                    self.row_idx = self.rows.as_ref().map(|r| r.rows.len()).unwrap_or(1) - 1;
                } else {
                    self.row_idx = 0;
                }
            }
        }
    }

    /// Move the selection by `delta` listed rows, whichever screen is showing.
    /// Used by the filter prompt, where the list stays navigable while typing.
    fn move_selection(&mut self, delta: isize) {
        match &self.store {
            Store::Sqlite(_) => match self.focus {
                Focus::Left => {
                    let visible = self.visible_tables();
                    if let Some(i) = Self::step_visible(&visible, self.table_idx, delta) {
                        self.select_table(i);
                    }
                }
                Focus::Right => {
                    let loaded = self.rows.as_ref().map(|r| r.rows.len()).unwrap_or(0);
                    if loaded == 0 {
                        return;
                    }
                    let next = (self.row_idx as isize + delta).clamp(0, loaded as isize - 1);
                    self.row_idx = next as usize;
                }
            },
            Store::Rkyv(_) => self.move_rkyv(delta),
        }
    }

    /// Move the rkyv selection by `delta` listed rows (the Hex view scrolls
    /// instead, since bytes are not filtered).
    fn move_rkyv(&mut self, delta: isize) {
        match self.rkyv_view {
            RkyvView::Records => {
                let visible = self.visible_records();
                if let Some(i) = Self::step_visible(&visible, self.record_idx, delta) {
                    self.record_idx = i;
                }
            }
            RkyvView::Strings => {
                let visible = self.visible_strings();
                if let Some(i) = Self::step_visible(&visible, self.string_idx, delta) {
                    self.string_idx = i;
                }
            }
            RkyvView::Hex => {
                let rows = match &self.store {
                    Store::Rkyv(r) => r.len().div_ceil(16),
                    _ => 0,
                };
                let next = (self.hex_row as isize + delta).max(0) as usize;
                self.hex_row = next.min(rows.saturating_sub(1));
            }
            RkyvView::Info => {}
        }
    }

    /// The same for the rkyv views, a screenful at a time.
    fn page_rkyv(&mut self, down: bool) {
        let step = self.page_step() as isize;
        self.move_rkyv(if down { step } else { -step });
    }

    fn page(&mut self, delta: i64) {
        if self.focus != Focus::Right {
            return;
        }
        let total = self.rows.as_ref().map(|r| r.total).unwrap_or(0);
        let next = (self.page_offset + delta).max(0);
        if next < total {
            self.page_offset = next;
            self.row_idx = 0;
            self.load_table();
        }
    }

    fn begin_edit_cell(&mut self) {
        if self.focus != Focus::Right {
            return;
        }
        let cur = self
            .rows
            .as_ref()
            .and_then(|r| r.rows.get(self.row_idx))
            .and_then(|row| row.get(self.col_idx))
            .cloned()
            .unwrap_or_default();
        if self.current_rowid().is_some() {
            self.open_modal(Mode::EditCell(cur));
        } else {
            self.notify("row has no rowid — cannot edit (WITHOUT ROWID table)");
        }
    }

    fn commit_edit_cell(&mut self, val: &str) {
        let (table, rowid, col) = match (
            self.current_table(),
            self.current_rowid(),
            self.rows
                .as_ref()
                .and_then(|r| r.columns.get(self.col_idx).cloned()),
        ) {
            (Some(t), Some(rid), Some(c)) => (t, rid, c),
            _ => return,
        };
        let res = self.sqlite().unwrap().update_cell(&table, rowid, &col, val);
        match res {
            Ok(()) => {
                self.notify(format!("updated {}.{}", table, col));
                self.load_table();
            }
            Err(e) => self.status = format!("update failed: {}", e),
        }
    }

    fn insert_row(&mut self) {
        let table = match self.current_table() {
            Some(t) => t,
            None => return,
        };
        match self.sqlite().unwrap().insert_blank(&table) {
            Ok(()) => {
                self.notify(format!("inserted default row into {}", table));
                self.load_table();
            }
            Err(e) => self.status = format!("insert failed: {}", e),
        }
    }

    fn delete_current_row(&mut self) {
        let (table, rowid) = match (self.current_table(), self.current_rowid()) {
            (Some(t), Some(r)) => (t, r),
            _ => return,
        };
        match self.sqlite().unwrap().delete_row(&table, rowid) {
            Ok(()) => {
                self.notify(format!("deleted row {} from {}", rowid, table));
                self.row_idx = self.row_idx.saturating_sub(1);
                self.load_table();
            }
            Err(e) => self.status = format!("delete failed: {}", e),
        }
    }

    fn run_sql(&mut self, sql: &str) {
        if sql.trim().is_empty() {
            return;
        }
        match self.sqlite().unwrap().exec(sql) {
            Ok(n) => {
                self.notify(format!("ok, {} row(s) affected", n));
                self.load_table();
            }
            Err(e) => self.status = format!("sql error: {}", e),
        }
    }

    /// `gg` — jump to the first table (left) or first row of the first page
    /// (right).
    fn goto_top(&mut self) {
        match self.focus {
            Focus::Left => self.select_table(0),
            Focus::Right => {
                self.page_offset = 0;
                self.row_idx = 0;
                self.load_table();
            }
        }
    }

    /// `G` — jump to the last table (left) or the last row of the last page
    /// (right).
    fn goto_bottom(&mut self) {
        match self.focus {
            Focus::Left => {
                let n = self.sqlite().map(|s| s.tables.len()).unwrap_or(0);
                if n > 0 {
                    self.select_table(n - 1);
                }
            }
            Focus::Right => {
                let total = self.rows.as_ref().map(|r| r.total).unwrap_or(0);
                if total > 0 {
                    self.page_offset = ((total - 1) / PAGE) * PAGE;
                    self.load_table();
                    let last = self.rows.as_ref().map(|r| r.rows.len()).unwrap_or(0);
                    self.row_idx = last.saturating_sub(1);
                }
            }
        }
    }

    // ----- rkyv navigation --------------------------------------------------

    fn rkyv_goto_top(&mut self) {
        match self.rkyv_view {
            RkyvView::Records => self.record_idx = 0,
            RkyvView::Strings => self.string_idx = 0,
            RkyvView::Hex => self.hex_row = 0,
            RkyvView::Info => {}
        }
    }

    fn rkyv_goto_bottom(&mut self) {
        match self.rkyv_view {
            RkyvView::Records => {
                self.record_idx = self
                    .decoded
                    .as_ref()
                    .map(|d| d.records.len().saturating_sub(1))
                    .unwrap_or(0);
            }
            RkyvView::Strings => self.string_idx = self.strings.len().saturating_sub(1),
            RkyvView::Hex => {
                let len = match &self.store {
                    Store::Rkyv(r) => r.len(),
                    _ => 0,
                };
                self.hex_row = len.saturating_sub(1) / 16;
            }
            RkyvView::Info => {}
        }
    }

    // ----- search (`/`, `n`, `N`) -------------------------------------------

    /// Move to the next (`forward`) or previous match of `self.search`.
    /// SQLite search scans the loaded page across all columns; rkyv search
    /// scans the string list or the raw bytes depending on the active view.
    fn search_next(&mut self, forward: bool) {
        if self.search.is_empty() {
            return;
        }
        match &self.store {
            Store::Sqlite(_) => self.search_sqlite(forward),
            Store::Rkyv(_) => self.search_rkyv(forward),
        }
    }

    fn search_sqlite(&mut self, forward: bool) {
        let term = self.search.to_lowercase();
        match self.focus {
            Focus::Left => {
                let tables = self.sqlite().map(|s| s.tables.clone()).unwrap_or_default();
                match find_next(tables.len(), self.table_idx, forward, |i| {
                    tables[i].to_lowercase().contains(&term)
                }) {
                    Some(i) => self.select_table(i),
                    None => self.status = format!("not found: {}", self.search),
                }
            }
            Focus::Right => self.search_sqlite_table(forward),
        }
    }

    /// Whole-table SQLite search (SQL-backed, not limited to the loaded page).
    /// Wraps around from the opposite edge when nothing is found ahead.
    fn search_sqlite_table(&mut self, forward: bool) {
        let (table, columns) = match (
            self.current_table(),
            self.rows.as_ref().map(|r| r.columns.clone()),
        ) {
            (Some(t), Some(c)) => (t, c),
            _ => return,
        };
        let outcome: Result<Option<(i64, i64)>, String> = {
            let sort = self.sort.clone();
            let s = self.sqlite().unwrap();
            // From the selected row, else from the edge the scan comes in from.
            let first = match self.current_rowid() {
                Some(from) => {
                    s.find_row(&table, &columns, &self.search, from, forward, sort.as_ref())
                }
                None => s.find_row_edge(&table, &columns, &self.search, forward, sort.as_ref()),
            };
            let rid = match first {
                Err(e) => Err(e.to_string()),
                Ok(Some(r)) => Ok(Some(r)),
                // Nothing ahead: wrap to the first/last match in display order.
                Ok(None) => s
                    .find_row_edge(&table, &columns, &self.search, forward, sort.as_ref())
                    .map_err(|e| e.to_string()),
            };
            match rid {
                Err(e) => Err(e),
                Ok(None) => Ok(None),
                Ok(Some(r)) => Ok(Some((
                    r,
                    s.rowid_ordinal(&table, r, sort.as_ref()).unwrap_or(1),
                ))),
            }
        };

        match outcome {
            Ok(Some((_rid, ord))) => {
                let idx0 = (ord - 1).max(0);
                self.page_offset = (idx0 / PAGE) * PAGE;
                self.load_table();
                self.row_idx = (idx0 - self.page_offset) as usize;
                let total = self.rows.as_ref().map(|r| r.total).unwrap_or(0);
                self.notify(format!("/{}  (row {} of {})", self.search, ord, total));
            }
            Ok(None) => self.status = format!("not found: {}", self.search),
            Err(e) => self.status = format!("search error: {}", e),
        }
    }

    fn search_rkyv(&mut self, forward: bool) {
        let term = self.search.to_lowercase();
        match self.rkyv_view {
            RkyvView::Records => {
                let keys: Vec<String> = self
                    .decoded
                    .as_ref()
                    .map(|d| d.records.iter().map(|r| r.key.to_lowercase()).collect())
                    .unwrap_or_default();
                match find_next(keys.len(), self.record_idx, forward, |i| {
                    keys[i].contains(&term)
                }) {
                    Some(i) => self.record_idx = i,
                    None => self.status = format!("not found: {}", self.search),
                }
            }
            RkyvView::Strings => {
                match find_next(self.strings.len(), self.string_idx, forward, |i| {
                    self.strings[i].text.to_lowercase().contains(&term)
                }) {
                    Some(i) => self.string_idx = i,
                    None => self.status = format!("not found: {}", self.search),
                }
            }
            RkyvView::Hex => {
                let bytes = match &self.store {
                    Store::Rkyv(r) => r.bytes.clone(),
                    _ => return,
                };
                let cur = self.hex_row * 16;
                match find_bytes(&bytes, self.search.as_bytes(), cur, forward) {
                    Some(off) => {
                        self.hex_row = off / 16;
                        self.notify(format!("/{}  (offset {:#x})", self.search, off));
                    }
                    None => self.status = format!("not found: {}", self.search),
                }
            }
            RkyvView::Info => {}
        }
    }

    // ----- rendering --------------------------------------------------------

    fn render(&mut self, f: &mut Frame) {
        let outer = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(f.area());
        // A screenful for paging: the body minus borders, and minus the header
        // row of whichever screen has one. Recomputed every frame so a resize is
        // picked up without any extra plumbing.
        let body = outer[0].height as usize;
        self.page_rows = match self.screen {
            // The detail screen's value pane sits under a 9-row field list.
            Screen::Detail => body.saturating_sub(11),
            // The row grid has a header row on top of its borders.
            Screen::Main if matches!(self.store, Store::Sqlite(_)) => body.saturating_sub(3),
            _ => body.saturating_sub(2),
        }
        .max(1);

        match self.screen {
            Screen::Detail => self.render_detail(f, outer[0]),
            Screen::HexEdit => self.render_hex(f, outer[0]),
            Screen::Top => {
                let t = self.ov.theme;
                if let Some(m) = self.top.as_ref() {
                    m.render(f, outer[0], &t);
                }
            }
            Screen::Schema => self.render_schema(f, outer[0]),
            Screen::Main => match &self.store {
                Store::Sqlite(_) => self.render_sqlite(f, outer[0]),
                Store::Rkyv(_) => self.render_rkyv(f, outer[0]),
            },
        }
        self.render_status(f, outer[1]);

        // Modal overlays.
        match &self.mode {
            Mode::EditCell(buf) => self.render_input(f, "edit cell (Enter=save, Esc=cancel)", buf),
            Mode::Command(buf) => self.render_input(f, "SQL (Enter=run, Esc=cancel)", buf),
            Mode::Search(buf) => self.render_input(f, "search / (Enter, Esc)", buf),
            Mode::AddRecord(buf) => self.render_input(f, "new record key (Enter=add, Esc)", buf),
            Mode::RenameRecord(buf) => self.render_input(f, "rename key to (Enter, Esc)", buf),
            Mode::ConfirmDelete => {
                let what = match self.store {
                    Store::Sqlite(_) => "row",
                    Store::Rkyv(_) => "record (rewrites the cache file)",
                };
                self.render_input(f, &format!("delete this {}? (y = yes, any = no)", what), "")
            }
            Mode::Normal => {}
        }

        self.ov.render(f, self.help_ctx());
    }

    fn render_detail(&self, f: &mut Frame, area: Rect) {
        let rows = Layout::vertical([Constraint::Length(9), Constraint::Min(3)]).split(area);

        // Top: field list for the current row/record.
        let mut fields: Vec<Line> = Vec::new();
        let title;
        match &self.store {
            Store::Sqlite(_) => {
                title = " row detail ".to_string();
                if let Some(rv) = &self.rows {
                    if let Some(row) = rv.rows.get(self.row_idx) {
                        for (i, col) in rv.columns.iter().enumerate() {
                            let sel = i == self.col_idx;
                            fields.push(Line::from(vec![
                                Span::styled(
                                    format!("{:<20}", truncate(col, 20)),
                                    Style::default().fg(if sel {
                                        self.ov.theme.accent
                                    } else {
                                        self.ov.theme.dim
                                    }),
                                ),
                                Span::raw(truncate(
                                    row.get(i).map(|s| s.as_str()).unwrap_or(""),
                                    80,
                                )),
                            ]));
                        }
                    }
                }
            }
            Store::Rkyv(_) => {
                title = " record detail ".to_string();
                if let Some(rec) = self
                    .decoded
                    .as_ref()
                    .and_then(|d| d.records.get(self.record_idx))
                {
                    fields.push(Line::from(vec![
                        Span::styled(
                            format!("{:<20}", "key"),
                            Style::default().fg(self.ov.theme.accent),
                        ),
                        Span::raw(truncate(&rec.key, 80)),
                    ]));
                    for (name, val) in &rec.fields {
                        fields.push(Line::from(vec![
                            Span::styled(
                                format!("{:<20}", truncate(name, 20)),
                                Style::default().fg(self.ov.theme.dim),
                            ),
                            Span::raw(val.clone()),
                        ]));
                    }
                }
            }
        }
        f.render_widget(
            Paragraph::new(fields).block(Block::default().borders(Borders::ALL).title(title)),
            rows[0],
        );

        // Bottom: value pane.
        let height = rows[1].height.saturating_sub(2) as usize;
        let lines = value_lines(
            &self.detail_value,
            self.value_render,
            self.detail_scroll,
            height,
        );
        f.render_widget(
            Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title(format!(
                " value — {} bytes — render: {} (v to cycle · y copy · Esc back) ",
                self.detail_value.len(),
                self.value_render.label()
            ))),
            rows[1],
        );
    }

    /// Open the write monitor over everything zdbview knows about, with the open
    /// file first since that is the one being edited.
    fn open_top(&mut self) {
        let mut targets = vec![match &self.store {
            Store::Sqlite(s) => (s.path.clone(), Kind::Sqlite),
            Store::Rkyv(r) => (r.path.clone(), Kind::Rkyv),
        }];
        targets.extend(watch_targets());
        let m = crate::monitor::Monitor::new(targets);
        if m.is_empty() {
            self.notify("nothing to watch yet");
            return;
        }
        let n = m.len();
        self.top = Some(m);
        self.screen = Screen::Top;
        self.notify(format!("watching {} files for writes", n));
    }

    fn key_top(&mut self, code: KeyCode) {
        let action = match self.top.as_mut() {
            Some(m) => m.on_key(code, self.page_rows.max(1)),
            None => {
                self.screen = Screen::Main;
                return;
            }
        };
        if let Some(note) = self.top.as_mut().and_then(|m| m.note.take()) {
            self.notify(note);
        }
        match action {
            crate::monitor::Action::None => {}
            crate::monitor::Action::Back => {
                self.top = None;
                self.screen = Screen::Main;
            }
            crate::monitor::Action::Quit => self.quit = true,
            // Opening from the monitor leaves the app the way `o` does, with the
            // chosen file carried out.
            crate::monitor::Action::Open(path) => {
                self.open_next = Some(path);
                self.back_to_files();
            }
        }
    }

    fn render_hex(&mut self, f: &mut Frame, area: Rect) {
        let theme = self.ov.theme;
        self.hex_area = area;
        if let Some(ed) = self.hex.as_mut() {
            ed.render(f, area, &theme);
        }
    }

    fn render_schema(&self, f: &mut Frame, area: Rect) {
        let mut lines: Vec<Line> = Vec::new();
        for (ty, name, sql) in &self.schema {
            lines.push(Line::from(vec![
                Span::styled(format!("{:<6}", ty), Style::default().fg(self.ov.theme.alt)),
                Span::styled(name.clone(), Style::default().add_modifier(Modifier::BOLD)),
            ]));
            for l in sql.lines() {
                lines.push(Line::from(Span::styled(
                    format!("    {}", l),
                    Style::default().fg(self.ov.theme.dim),
                )));
            }
            lines.push(Line::from(""));
        }
        let height = area.height.saturating_sub(2) as usize;
        let visible: Vec<Line> = lines
            .into_iter()
            .skip(self.schema_scroll)
            .take(height)
            .collect();
        f.render_widget(
            Paragraph::new(visible).block(Block::default().borders(Borders::ALL).title(format!(
                " schema — {} objects (j/k scroll · Esc back) ",
                self.schema.len()
            ))),
            area,
        );
    }

    fn render_sqlite(&mut self, f: &mut Frame, area: Rect) {
        let cols = Layout::horizontal([Constraint::Length(24), Constraint::Min(10)]).split(area);
        let (rect_left, rect_right) = (cols[0], cols[1]);

        let s = self.sqlite().unwrap();
        // Left: the tables the filter leaves listed.
        let visible: Vec<usize> = s
            .tables
            .iter()
            .enumerate()
            .filter(|(_, t)| filter_passes(&self.filter, t))
            .map(|(i, _)| i)
            .collect();
        let items: Vec<ListItem> = visible
            .iter()
            .map(|&i| ListItem::new(s.tables[i].clone()))
            .collect();
        let mut lstate = ListState::default();
        lstate.select(
            visible
                .iter()
                .position(|&i| i == self.table_idx)
                .or(Some(0)),
        );
        let left_border = self.pane_style(Focus::Left);
        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(left_border)
                    .title(if self.filter.is_empty() {
                        format!(
                            " {} — tables ({}) ",
                            s.path.file_name().and_then(|n| n.to_str()).unwrap_or("db"),
                            s.tables.len()
                        )
                    } else {
                        format!(
                            " tables {}/{}  /{} ",
                            visible.len(),
                            s.tables.len(),
                            self.filter
                        )
                    }),
            )
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
        f.render_stateful_widget(list, cols[0], &mut lstate);
        let off_left = lstate.selected().map(|_| lstate.offset()).unwrap_or(0);
        let mut off_right = 0usize;

        // Right: row grid.
        let title = match self.current_table() {
            Some(t) => {
                let total = self.rows.as_ref().map(|r| r.total).unwrap_or(0);
                let sorted = match &self.sort {
                    Some(s) => format!(" — sorted {} {}", s.column, arrow(s.desc)),
                    None => String::new(),
                };
                format!(
                    " {} — rows {}..{} of {}{} ",
                    t,
                    self.page_offset,
                    self.page_offset + self.rows.as_ref().map(|r| r.rows.len() as i64).unwrap_or(0),
                    total,
                    sorted
                )
            }
            None => " (no table) ".into(),
        };

        if let Some(rv) = &self.rows {
            let header = Row::new(
                rv.columns
                    .iter()
                    .enumerate()
                    .map(|(i, c)| {
                        let st = if i == self.col_idx && self.focus == Focus::Right {
                            Style::default()
                                .fg(self.ov.theme.accent)
                                .add_modifier(Modifier::BOLD)
                        } else {
                            Style::default().add_modifier(Modifier::BOLD)
                        };
                        // Mark the sorted column in its header.
                        let label = match &self.sort {
                            Some(s) if s.column == *c => format!("{} {}", c, arrow(s.desc)),
                            _ => c.clone(),
                        };
                        Cell::from(label).style(st)
                    })
                    .collect::<Vec<_>>(),
            );
            let body = rv.rows.iter().map(|row| {
                Row::new(
                    row.iter()
                        .map(|c| Cell::from(truncate(c, 40)))
                        .collect::<Vec<_>>(),
                )
            });
            let widths: Vec<Constraint> =
                rv.columns.iter().map(|_| Constraint::Length(20)).collect();
            let mut tstate = TableState::default();
            tstate.select(Some(self.row_idx));
            let table = Table::new(body, widths)
                .header(header)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(self.pane_style(Focus::Right))
                        .title(title),
                )
                .row_highlight_style(Style::default().add_modifier(Modifier::REVERSED));
            f.render_stateful_widget(table, cols[1], &mut tstate);
            off_right = tstate.offset();
        } else {
            let p = Paragraph::new("no rows").block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(self.pane_style(Focus::Right))
                    .title(title),
            );
            f.render_widget(p, cols[1]);
        }

        // Capture hit-test geometry for mouse clicks.
        self.click_left = rect_left;
        self.click_right = rect_right;
        self.off_left = off_left;
        self.off_right = off_right;
    }

    fn render_rkyv(&mut self, f: &mut Frame, area: Rect) {
        // Records mutates click geometry, so handle it before borrowing the store.
        if self.rkyv_view == RkyvView::Records {
            self.render_rkyv_records(f, area);
            return;
        }
        let r = match &self.store {
            Store::Rkyv(r) => r,
            _ => return,
        };
        match self.rkyv_view {
            RkyvView::Info => self.render_rkyv_info(f, area, r),
            RkyvView::Strings => self.render_rkyv_strings(f, area),
            RkyvView::Hex => self.render_rkyv_hex(f, area, r),
            RkyvView::Records => {}
        }
    }

    fn render_rkyv_records(&mut self, f: &mut Frame, area: Rect) {
        let cols =
            Layout::horizontal([Constraint::Percentage(45), Constraint::Min(10)]).split(area);
        self.click_records = cols[0];
        let d = match &self.decoded {
            Some(d) => d,
            None => return,
        };

        // Left: keys the filter leaves listed.
        let visible: Vec<usize> = d
            .records
            .iter()
            .enumerate()
            .filter(|(_, r)| filter_passes(&self.filter, &r.key))
            .map(|(i, _)| i)
            .collect();
        let items: Vec<ListItem> = visible
            .iter()
            .map(|&i| ListItem::new(truncate(&d.records[i].key, 60)))
            .collect();
        let mut st = ListState::default();
        st.select(
            visible
                .iter()
                .position(|&i| i == self.record_idx)
                .or(Some(0)),
        );
        let title = if self.filter.is_empty() {
            format!(" {}{} keys ", d.format, d.records.len())
        } else {
            format!(
                " {}{}/{} keys  /{} ",
                d.format,
                visible.len(),
                d.records.len(),
                self.filter
            )
        };
        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(self.ov.theme.accent))
                    .title(title),
            )
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
        f.render_stateful_widget(list, cols[0], &mut st);
        let off_records = st.offset();

        // Right: selected value — decoded scalar fields, then a hex dump.
        let mut lines: Vec<Line> = Vec::new();
        if let Some(rec) = d.records.get(self.record_idx) {
            for (name, val) in &rec.fields {
                lines.push(Line::from(vec![
                    Span::styled(
                        format!("{:<22}", name),
                        Style::default().fg(self.ov.theme.dim),
                    ),
                    Span::raw(val.clone()),
                ]));
            }
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                format!("value — {} bytes (hex):", rec.value.len()),
                Style::default().fg(self.ov.theme.primary),
            )));
            let rows = area.height.saturating_sub(6) as usize;
            for i in 0..rows {
                let off = i * 16;
                if off >= rec.value.len() {
                    break;
                }
                lines.push(Line::from(hexedit::hex_dump_line(
                    off,
                    &rec.value[off.min(rec.value.len())..(off + 16).min(rec.value.len())],
                )));
            }
        }
        let p =
            Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title(" value "));
        f.render_widget(p, cols[1]);
        self.off_records = off_records;
    }

    fn render_rkyv_info(&self, f: &mut Frame, area: Rect, r: &RkyvStore) {
        let mut lines = vec![
            Line::from(vec![
                Span::styled("file:    ", Style::default().fg(self.ov.theme.dim)),
                Span::raw(r.path.display().to_string()),
            ]),
            Line::from(vec![
                Span::styled("size:    ", Style::default().fg(self.ov.theme.dim)),
                Span::raw(format!("{} bytes", r.len())),
            ]),
            Line::from(vec![
                Span::styled("strings: ", Style::default().fg(self.ov.theme.dim)),
                Span::raw(if self.strings_truncated {
                    // Say so rather than implying the list is everything.
                    format!(
                        "{} runs (>= {} printable bytes) — capped, scanned first {}",
                        self.strings.len(),
                        MIN_STRING,
                        human_size(self.strings_scanned as u64)
                    )
                } else {
                    format!(
                        "{} runs (>= {} printable bytes)",
                        self.strings.len(),
                        MIN_STRING
                    )
                }),
            ]),
        ];

        match &self.decoded {
            Some(d) => {
                lines.push(Line::from(""));
                lines.push(Line::from(vec![
                    Span::styled("format:  ", Style::default().fg(self.ov.theme.dim)),
                    Span::styled(d.format.clone(), Style::default().fg(self.ov.theme.label)),
                ]));
                lines.push(Line::from(vec![
                    Span::styled("records: ", Style::default().fg(self.ov.theme.dim)),
                    Span::raw(d.records.len().to_string()),
                ]));
                lines.push(Line::from(""));
                for (name, val) in &d.header {
                    lines.push(Line::from(vec![
                        Span::styled(
                            format!("  {:<16}", name),
                            Style::default().fg(self.ov.theme.dim),
                        ),
                        Span::raw(val.clone()),
                    ]));
                }
                lines.push(Line::from(""));
                lines.push(Line::from(Span::styled(
                    "Views:  0 Records (key/value)  2 Strings  3 Hex",
                    Style::default().fg(self.ov.theme.dim),
                )));
            }
            None => {
                lines.push(Line::from(""));
                lines.push(Line::from(Span::styled(
                    "unrecognized rkyv archive: no matching format decoder.",
                    Style::default().fg(self.ov.theme.primary),
                )));
                lines.push(Line::from(Span::styled(
                    "rkyv stores no field names or type tags, so an unknown type",
                    Style::default().fg(self.ov.theme.primary),
                )));
                lines.push(Line::from(Span::styled(
                    "cannot be decoded generically — showing raw structure.",
                    Style::default().fg(self.ov.theme.primary),
                )));
                lines.push(Line::from(Span::styled(
                    "Views:  2 Strings (embedded text)  3 Hex (raw bytes)",
                    Style::default().fg(self.ov.theme.dim),
                )));
            }
        }
        let p = Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .title(" rkyv / binary — Info "),
        );
        f.render_widget(p, area);
    }

    fn render_rkyv_strings(&self, f: &mut Frame, area: Rect) {
        let visible = self.visible_strings();
        let items: Vec<ListItem> = visible
            .iter()
            .map(|&i| {
                let h = &self.strings[i];
                ListItem::new(Line::from(vec![
                    Span::styled(
                        format!("{:08x}  ", h.offset),
                        Style::default().fg(self.ov.theme.dim),
                    ),
                    Span::raw(truncate(&h.text, 200)),
                ]))
            })
            .collect();
        let mut st = ListState::default();
        st.select(
            visible
                .iter()
                .position(|&i| i == self.string_idx)
                .or(Some(0)),
        );
        let capped = if self.strings_truncated { "+" } else { "" };
        let title = if self.filter.is_empty() {
            format!(" Strings ({}{}) ", self.strings.len(), capped)
        } else {
            format!(
                " Strings ({}/{}{})  /{} ",
                visible.len(),
                self.strings.len(),
                capped,
                self.filter
            )
        };
        let list = List::new(items)
            .block(Block::default().borders(Borders::ALL).title(title))
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
        f.render_stateful_widget(list, area, &mut st);
    }

    fn render_rkyv_hex(&self, f: &mut Frame, area: Rect, r: &RkyvStore) {
        let rows_visible = area.height.saturating_sub(2) as usize;
        let start = self.hex_row * 16;
        let mut lines = Vec::new();
        for i in 0..rows_visible {
            let off = start + i * 16;
            if off >= r.len() {
                break;
            }
            lines.push(Line::from(r.hex_row(off)));
        }
        let p = Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title(format!(
            " Hex — offset {:#x} / {} bytes ",
            start,
            r.len()
        )));
        f.render_widget(p, area);
    }

    fn render_status(&self, f: &mut Frame, area: Rect) {
        let p = Paragraph::new(self.status.clone())
            .style(Style::default().fg(Color::Black).bg(Color::Gray));
        f.render_widget(p, area);
    }

    fn render_input(&self, f: &mut Frame, title: &str, buf: &str) {
        let area = centered(f.area(), 60, 3);
        f.render_widget(Clear, area);
        // Draw the buffer with a reversed block cursor over the char at the
        // cursor (or a trailing space when the cursor is at the end).
        let cur = self.input_cursor.min(buf.len());
        let (pre, rest) = buf.split_at(cur);
        let (at, post) = match rest.char_indices().nth(1) {
            Some((i, _)) => rest.split_at(i),
            None => (rest, ""),
        };
        let at_disp = if at.is_empty() { " " } else { at };
        let line = Line::from(vec![
            Span::raw(pre.to_string()),
            Span::styled(
                at_disp.to_string(),
                Style::default().add_modifier(Modifier::REVERSED),
            ),
            Span::raw(post.to_string()),
        ]);
        let p = Paragraph::new(line).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(self.ov.theme.accent))
                .title(format!(" {} ", title)),
        );
        f.render_widget(p, area);
    }

    fn pane_style(&self, which: Focus) -> Style {
        if self.focus == which {
            Style::default().fg(self.ov.theme.accent)
        } else {
            Style::default().fg(self.ov.theme.dim)
        }
    }
}

/// Recent-files picker shown when zdbview is launched with no file argument.
/// Returns the chosen file, or `None` if the user quits.
/// One row of the picker: a remembered file, or one the startup scan found.
pub struct Choice {
    pub path: PathBuf,
    pub kind: Kind,
    /// When this file was last opened (recent files only).
    pub opened: Option<std::time::SystemTime>,
    /// Recognized rkyv format, when the scan's magic sniff named one.
    pub format: Option<&'static str>,
    /// File size, for scan hits (recent rows show their age instead).
    pub size: Option<u64>,
    /// Last modification time, used to order scan hits newest-first.
    pub modified: Option<std::time::SystemTime>,
    /// Scan display priority (see `scan::Hit::rank`).
    rank: u8,
}

impl Choice {
    fn from_entry(e: &Entry) -> Self {
        Choice {
            path: e.path.clone(),
            kind: e.kind,
            opened: Some(e.opened),
            format: None,
            size: None,
            modified: None,
            rank: 0,
        }
    }

    fn from_hit(h: crate::scan::Hit) -> Self {
        Choice {
            path: h.path,
            kind: h.kind,
            opened: None,
            format: h.format,
            size: Some(h.size),
            modified: Some(h.modified),
            rank: h.rank,
        }
    }

    fn name(&self) -> &str {
        self.path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("?")
    }
}

/// What the picker returned: the file to open and the scheme it was showing.
pub struct Picked {
    pub path: PathBuf,
    pub theme: Theme,
}

/// Merge scan hits into the list, dropping any path already present (a recent
/// file the scan also found stays a recent file, keeping its age column).
fn merge_hits(choices: &mut Vec<Choice>, hits: Vec<crate::scan::Hit>) {
    for hit in hits {
        let dup = choices.iter().any(|c| {
            c.path == hit.path
                || (c.path.canonicalize().ok() == hit.path.canonicalize().ok()
                    && c.path.canonicalize().is_ok())
        });
        if !dup {
            choices.push(Choice::from_hit(hit));
        }
    }
    // Recent files keep their recency order at the top. Scan hits below them go
    // by rank first (recognized shards, then other rkyv archives, then
    // databases), newest-first within a rank, shallowest path breaking ties.
    let first_scanned = choices
        .iter()
        .position(|c| c.opened.is_none())
        .unwrap_or(choices.len());
    choices[first_scanned..].sort_by_key(|c| {
        (
            c.rank,
            std::cmp::Reverse(c.modified),
            c.path.components().count(),
        )
    });
}

/// Everything the picker needs: the remembered files, the scheme override, and
/// where its scan rows come from.
pub struct Picker<'a> {
    pub recent: &'a [Entry],
    /// The scheme to show. Carried from the previous screen when there was one,
    /// so a concurrent prefs write cannot change it mid-session.
    pub theme: Theme,
    /// Rows restored from the saved scan (appdata), shown immediately.
    pub cached: Vec<crate::scan::Hit>,
    /// How old those rows are, for the title.
    pub cache_age: Option<std::time::Duration>,
    /// A walk already in progress, when the cache was missing or stale.
    pub scan: Option<crate::scan::Scan>,
    /// Roots to walk when the user asks for a rescan with `r`.
    pub roots: Vec<crate::scan::Root>,
    /// Whether a finished walk may be written to appdata (not for `--scan`,
    /// whose roots are not the default set).
    pub persist: bool,
}

pub fn pick_mru(terminal: &mut DefaultTerminal, mut p: Picker<'_>) -> Result<Option<Picked>> {
    let entries = p.recent;
    let mut scan = p.scan.take();
    let mut cache_age = p.cache_age;
    // Hits are kept as well as merged so a finished walk can be saved.
    let mut scanned: Vec<crate::scan::Hit> = std::mem::take(&mut p.cached);
    // Recent files first, then whatever the scan turns up.
    let mut choices: Vec<Choice> = entries.iter().map(Choice::from_entry).collect();
    merge_hits(&mut choices, scanned.clone());

    // `/` filters the list: `view` holds the indices still listed and `sel` is a
    // position within it, so navigation and clicks address rows that are visible.
    let mut filter = String::new();
    let mut typing = false;
    let mut sel = 0usize;
    let mut pending_g = false;
    // The row `/` was pressed on, restored when the filter is cancelled.
    let mut before_filter = 0usize;
    // First row the list drew last frame, for mapping a click to an entry.
    let mut list_offset = 0usize;
    // The write monitor, when `w` has opened it over the list.
    let mut monitor: Option<crate::monitor::Monitor> = None;

    // The picker carries the same overlay layer as the main screens, so `h`,
    // `c` and `C` work here too — and the scheme it is showing is the one the
    // opened file gets, handed over rather than re-read.
    let mut ov = Overlays::new(p.theme);

    loop {
        // Pull in whatever the scan thread produced since the last frame, and
        // save the finished list so the next start does not walk again.
        let scanning = match scan.as_mut() {
            Some(sc) => {
                let hits = sc.drain();
                scanned.extend(hits.iter().cloned());
                merge_hits(&mut choices, hits);
                if sc.running {
                    Some(sc.found)
                } else {
                    if p.persist {
                        crate::scan::save_cache(&scanned);
                        cache_age = Some(std::time::Duration::ZERO);
                    }
                    scan = None;
                    None
                }
            }
            None => None,
        };

        // Rows the filter leaves listed, and a selection inside that list.
        let view: Vec<usize> = choices
            .iter()
            .enumerate()
            .filter(|(_, c)| filter_passes(&filter, c.path.to_str().unwrap_or("")))
            .map(|(i, _)| i)
            .collect();
        sel = sel.min(view.len().saturating_sub(1));

        // List height for paging: the body minus its borders.
        let page = terminal
            .size()
            .map(|s| s.height.saturating_sub(3) as usize)
            .unwrap_or(10)
            .max(1);
        let prompt = typing.then_some(filter.as_str());
        // The monitor takes the whole screen while it is up; the overlay layer
        // still draws on top of either.
        if let Some(m) = monitor.as_mut() {
            m.tick();
        }
        let ctx = if monitor.is_some() {
            HelpCtx::Top
        } else {
            HelpCtx::Picker
        };
        terminal.draw(|f| {
            match monitor.as_ref() {
                Some(m) => m.render(f, f.area(), &ov.theme),
                None => {
                    list_offset = render_picker(
                        f, &choices, &view, sel, &filter, prompt, scanning, cache_age, &ov.theme,
                    );
                }
            }
            ov.render(f, ctx);
        })?;
        if !event::poll(TICK)? {
            ov.expire_toast();
            continue;
        }
        let ev = event::read()?;
        ov.expire_toast();

        // While the monitor is up it owns the keys, except the overlay's own.
        if let Some(m) = monitor.as_mut() {
            match ev {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    if ov.on_key(key.code) {
                        continue;
                    }
                    let size = terminal.size().unwrap_or_default();
                    let page = crate::monitor::Monitor::page_rows(Rect::new(
                        0,
                        0,
                        size.width,
                        size.height,
                    ));
                    let action = m.on_key(key.code, page);
                    if let Some(note) = m.note.take() {
                        ov.toast(note);
                    }
                    match action {
                        crate::monitor::Action::None => {}
                        crate::monitor::Action::Back => monitor = None,
                        crate::monitor::Action::Quit => return Ok(None),
                        crate::monitor::Action::Open(path) => {
                            if let Some(sc) = &scan {
                                sc.cancel();
                            }
                            return Ok(Some(Picked {
                                path,
                                theme: ov.theme,
                            }));
                        }
                    }
                }
                Event::Mouse(mouse) => {
                    ov.on_mouse(mouse);
                }
                _ => {}
            }
            continue;
        }

        let last = view.len().saturating_sub(1);
        let pick = |i: usize| -> Option<PathBuf> { view.get(i).map(|&c| choices[c].path.clone()) };

        // Mouse: wheel moves the selection, a click opens the entry under it.
        if let Event::Mouse(m) = ev {
            if ov.on_mouse(m) {
                continue;
            }
            match m.kind {
                MouseEventKind::ScrollDown => sel = (sel + 1).min(last),
                MouseEventKind::ScrollUp => sel = sel.saturating_sub(1),
                MouseEventKind::Down(_) => {
                    // The list starts one row below the block's top border and is
                    // scrolled by `list_offset`; rows past the last entry select
                    // nothing.
                    let row = (m.row as usize).saturating_sub(1);
                    let clicked = row + list_offset;
                    if row < page && clicked < view.len() {
                        if let Some(sc) = &scan {
                            sc.cancel();
                        }
                        // Hand over the scheme on screen, so the file opens in it.
                        return Ok(pick(clicked).map(|path| Picked {
                            path,
                            theme: ov.theme,
                        }));
                    }
                }
                _ => {}
            }
            continue;
        }
        if let Event::Key(key) = ev {
            if key.kind != KeyEventKind::Press {
                continue;
            }
            // Ctrl-f / Ctrl-b page like the app's grids do.
            if key.modifiers.contains(KeyModifiers::CONTROL) {
                match key.code {
                    KeyCode::Char('f') => sel = (sel + page).min(last),
                    KeyCode::Char('b') => sel = sel.saturating_sub(page),
                    _ => {}
                }
                continue;
            }

            // While the `/` prompt is open every key edits the filter, and the
            // list shrinks to the matches as it is typed.
            if typing {
                match filter_prompt_key(key.code, &mut filter, &mut sel, last, page) {
                    Prompt::Open => {}
                    Prompt::Accept => typing = false,
                    Prompt::Cancel => {
                        // Drop the filter and go back to the row `/` was pressed on.
                        typing = false;
                        filter.clear();
                        sel = before_filter;
                    }
                }
                continue;
            }

            // Overlay keys (open or drive: h/? c C) come before the picker's own.
            if ov.on_key(key.code) {
                continue;
            }

            if key.code == KeyCode::Char('g') {
                if pending_g {
                    pending_g = false;
                    sel = 0;
                } else {
                    pending_g = true;
                }
                continue;
            }
            pending_g = false;
            match key.code {
                // Esc clears an applied filter first, then quits.
                KeyCode::Esc if !filter.is_empty() => {
                    filter.clear();
                    sel = 0;
                }
                KeyCode::Char('q') | KeyCode::Esc => {
                    if let Some(sc) = &scan {
                        sc.cancel();
                    }
                    return Ok(None);
                }
                KeyCode::Char('/') => {
                    typing = true;
                    filter.clear();
                    before_filter = sel;
                    sel = 0;
                }
                // The same write monitor the app screens show, over the files
                // listed here plus the rest of the watched set.
                KeyCode::Char('w') => {
                    let mut targets: Vec<(PathBuf, Kind)> = view
                        .iter()
                        .map(|&i| (choices[i].path.clone(), choices[i].kind))
                        .collect();
                    targets.extend(watch_targets());
                    let m = crate::monitor::Monitor::new(targets);
                    if m.is_empty() {
                        ov.toast("nothing to watch yet");
                    } else {
                        ov.toast(format!("watching {} files for writes", m.len()));
                        monitor = Some(m);
                    }
                }
                // Within a filtered list every row matches, so n/N simply step.
                KeyCode::Char('n') => sel = (sel + 1).min(last),
                KeyCode::Char('N') => sel = sel.saturating_sub(1),
                // `r` walks again (keeping the rows on screen until new ones
                // arrive); `R` also drops the saved scan first.
                KeyCode::Char('r') | KeyCode::Char('R') => {
                    if key.code == KeyCode::Char('R') {
                        crate::scan::clear_cache();
                    }
                    if let Some(sc) = &scan {
                        sc.cancel();
                    }
                    scanned.clear();
                    choices.retain(|c| c.opened.is_some());
                    sel = 0;
                    cache_age = None;
                    scan = Some(crate::scan::spawn(p.roots.clone()));
                    ov.toast("rescanning");
                }
                KeyCode::Char('G') => sel = last,
                // A screenful, from the height this frame was drawn at.
                KeyCode::PageDown => sel = (sel + page).min(last),
                KeyCode::PageUp => sel = sel.saturating_sub(page),
                KeyCode::Up | KeyCode::Char('k') => sel = sel.saturating_sub(1),
                KeyCode::Down | KeyCode::Char('j') => sel = (sel + 1).min(last),
                KeyCode::Enter => {
                    if let Some(path) = pick(sel) {
                        // Nothing more to walk once a file is chosen.
                        if let Some(sc) = &scan {
                            sc.cancel();
                        }
                        return Ok(Some(Picked {
                            path,
                            theme: ov.theme,
                        }));
                    }
                }
                _ => {}
            }
        }
    }
}

/// Archives up to this size are decoded inline; bigger ones go to a thread.
/// 12MB takes ~0.8s to validate, 382MB takes ~25s, so the line sits below the
/// point where a person would notice the wait.
const DECODE_INLINE_MAX: usize = 4 * 1024 * 1024;

/// Validate and decode `bytes` on another thread.
fn spawn_decode(bytes: Vec<u8>) -> std::sync::mpsc::Receiver<Option<Decoded>> {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let _ = tx.send(formats::try_decode(&bytes));
    });
    rx
}

/// What a key did to the picker's filter prompt.
#[derive(Debug, PartialEq, Eq)]
enum Prompt {
    /// Still typing.
    Open,
    /// Enter: keep the filter and close the prompt.
    Accept,
    /// Esc: discard it.
    Cancel,
}

/// Handle one key of the picker's `/` prompt. The list stays navigable while the
/// pattern is typed, so the arrows and paging move the selection instead of being
/// swallowed; only Left/Right belong to the pattern itself.
fn filter_prompt_key(
    code: KeyCode,
    filter: &mut String,
    sel: &mut usize,
    last: usize,
    page: usize,
) -> Prompt {
    match code {
        KeyCode::Esc => return Prompt::Cancel,
        KeyCode::Enter => return Prompt::Accept,
        KeyCode::Backspace => {
            filter.pop();
            *sel = 0;
        }
        KeyCode::Up => *sel = sel.saturating_sub(1),
        KeyCode::Down => *sel = (*sel + 1).min(last),
        KeyCode::PageUp => *sel = sel.saturating_sub(page),
        KeyCode::PageDown => *sel = (*sel + page).min(last),
        KeyCode::Home => *sel = 0,
        KeyCode::End => *sel = last,
        KeyCode::Char(c) => {
            filter.push(c);
            // A changed pattern means a different list; start at its top.
            *sel = 0;
        }
        _ => {}
    }
    Prompt::Open
}

#[allow(clippy::too_many_arguments)]
fn render_picker(
    f: &mut Frame,
    choices: &[Choice],
    view: &[usize],
    sel: usize,
    filter: &str,
    prompt: Option<&str>,
    scanning: Option<usize>,
    cache_age: Option<std::time::Duration>,
    t: &Theme,
) -> usize {
    let outer = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(f.area());
    let mut offset = 0usize;

    if view.is_empty() {
        let body = if !filter.is_empty() {
            vec![
                Line::from(""),
                Line::from(format!("  Nothing matches /{}", filter)),
                Line::from(""),
                Line::from(Span::styled(
                    "  Esc clears the filter",
                    Style::default().fg(t.dim),
                )),
            ]
        } else if scanning.is_some() {
            vec![
                Line::from(""),
                Line::from("  Scanning for databases and rkyv shards…"),
            ]
        } else {
            vec![
                Line::from(""),
                Line::from("  Nothing found."),
                Line::from(""),
                Line::from(Span::styled(
                    "  Open one with:  zdbview <file>",
                    Style::default().fg(t.dim),
                )),
                Line::from(Span::styled(
                    "  Or scan elsewhere:  zdbview --scan <dir>",
                    Style::default().fg(t.dim),
                )),
            ]
        };
        let p = Paragraph::new(body).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(t.accent))
                .title(" zdbview — files "),
        );
        f.render_widget(p, outer[0]);
    } else {
        let items: Vec<ListItem> = view
            .iter()
            .map(|&i| {
                let c = &choices[i];
                let dir = c.path.parent().and_then(|p| p.to_str()).unwrap_or("");
                let (badge, color) = match c.kind {
                    Kind::Sqlite => ("sqlite", t.primary),
                    Kind::Rkyv => ("rkyv  ", t.alt),
                };
                // Recent files show their age; scanned ones their size.
                let (age, age_style) = match (c.opened, c.size) {
                    (Some(when), _) => (mru::rel_age(when), Style::default().fg(t.dim)),
                    (None, Some(size)) => (human_size(size), Style::default().fg(t.label)),
                    (None, None) => ("found".to_string(), Style::default().fg(t.label)),
                };
                ListItem::new(Line::from(vec![
                    Span::styled(format!(" {} ", badge), Style::default().fg(color)),
                    Span::styled(
                        format!("{:<28}", truncate(c.name(), 28)),
                        Style::default().fg(t.accent).add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(format!("{:>10}  ", age), age_style),
                    Span::styled(truncate(dir, 52), Style::default().fg(t.label)),
                ]))
            })
            .collect();
        let mut st = ListState::default();
        st.select(Some(sel.min(view.len() - 1)));
        let recent = view
            .iter()
            .filter(|&&i| choices[i].opened.is_some())
            .count();
        let title = if !filter.is_empty() {
            // A filtered list says how much of the whole it is showing.
            format!(
                " zdbview — {}/{} files  /{} ",
                view.len(),
                choices.len(),
                filter
            )
        } else {
            match (scanning, cache_age) {
                (Some(found), _) => format!(
                    " zdbview — {} files ({} recent, scanning… {} found) ",
                    view.len(),
                    recent,
                    found
                ),
                // Saved scans are reused, so say how old the rows are.
                (None, Some(age)) => format!(
                    " zdbview — {} files ({} recent, scan {} · r rescans) ",
                    view.len(),
                    recent,
                    age_label(age)
                ),
                (None, None) => format!(" zdbview — {} files ({} recent) ", view.len(), recent),
            }
        };
        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(t.accent))
                    .title(title),
            )
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
        f.render_stateful_widget(list, outer[0], &mut st);
        offset = st.offset();
    }

    // Bottom line: the filter prompt while typing, else the selected row's
    // format, else the keys.
    let help = match prompt {
        Some(q) => {
            Paragraph::new(format!("/{}_", q)).style(Style::default().fg(Color::Black).bg(t.accent))
        }
        None => {
            let detail = view
                .get(sel)
                .and_then(|&i| choices[i].format)
                .map(|fmt| format!("  ·  {}", fmt))
                .unwrap_or_default();
            // Kept short so the selected row's format still fits beside it on a
            // narrow terminal; `h` lists the rest.
            Paragraph::new(format!(
                "j/k move · / filter · Enter open · c scheme · h help · q quit{}",
                detail
            ))
            .style(Style::default().fg(Color::Black).bg(t.help_key))
        }
    };
    f.render_widget(help, outer[1]);
    offset
}

/// Everything the write monitor watches besides the open file: the recent-files
/// list and the saved scan. Shared by the app and the picker so both watch the
/// same set.
pub fn watch_targets() -> Vec<(PathBuf, Kind)> {
    let mut targets: Vec<(PathBuf, Kind)> = crate::mru::load()
        .into_iter()
        .map(|e| (e.path, e.kind))
        .collect();
    if let Some(c) = crate::scan::load_cache() {
        targets.extend(c.hits.into_iter().map(|h| (h.path, h.kind)));
    }
    targets.retain(|(p, _)| p.is_file());
    targets
}

/// The scheme to start from: `--theme` wins, else the saved preference (with any
/// custom palette), else the default.
pub fn resolve_theme(theme_override: Option<ThemeName>) -> Theme {
    let prefs = crate::prefs::load();
    match (theme_override, prefs.custom) {
        (Some(name), _) => Theme::from_name(name),
        (None, Some(c)) => Theme::from_palette(prefs.theme, c),
        (None, None) => Theme::from_name(prefs.theme),
    }
}

/// Whether `hay` passes `filter` (case-insensitive substring; empty passes all).
fn filter_passes(filter: &str, hay: &str) -> bool {
    filter.is_empty() || hay.to_lowercase().contains(&filter.to_lowercase())
}

/// Find the next index (wrapping) from `from` for which `pred` holds, scanning
/// `forward` or backward. Returns `None` if nothing matches.
fn find_next(
    len: usize,
    from: usize,
    forward: bool,
    pred: impl Fn(usize) -> bool,
) -> Option<usize> {
    if len == 0 {
        return None;
    }
    for step in 1..=len {
        let i = if forward {
            (from + step) % len
        } else {
            (from + len - (step % len)) % len
        };
        if pred(i) {
            return Some(i);
        }
    }
    None
}

/// Find the byte offset of `needle` in `hay`, searching from just past `cur`
/// (or just before it, when not `forward`). Case-sensitive. `None` if absent.
fn find_bytes(hay: &[u8], needle: &[u8], cur: usize, forward: bool) -> Option<usize> {
    if needle.is_empty() || hay.len() < needle.len() {
        return None;
    }
    let last = hay.len() - needle.len();
    if forward {
        let start = (cur + 1).min(last + 1);
        (start..=last).find(|&i| &hay[i..i + needle.len()] == needle)
    } else {
        let start = cur.min(last + 1);
        (0..start)
            .rev()
            .find(|&i| &hay[i..i + needle.len()] == needle)
    }
}

/// Whether the point `(col,row)` falls inside `r`.
fn hit(r: Rect, col: u16, row: u16) -> bool {
    col >= r.x
        && col < r.x.saturating_add(r.width)
        && row >= r.y
        && row < r.y.saturating_add(r.height)
}

/// Move the cursor one char left (UTF-8-safe). Ported from iftoprs `FilterState::left`.
fn input_left(buf: &str, cur: usize) -> usize {
    if cur > 0 {
        buf[..cur]
            .char_indices()
            .next_back()
            .map(|(i, _)| i)
            .unwrap_or(0)
    } else {
        0
    }
}

/// Move the cursor one char right (UTF-8-safe). Ported from iftoprs `FilterState::right`.
fn input_right(buf: &str, cur: usize) -> usize {
    if cur < buf.len() {
        buf[cur..]
            .char_indices()
            .nth(1)
            .map(|(i, _)| cur + i)
            .unwrap_or(buf.len())
    } else {
        buf.len()
    }
}

/// Delete the word before the cursor (Ctrl+W). Ported from iftoprs
/// `FilterState::delete_word` — skips trailing whitespace, then the word,
/// stepping by real UTF-8 widths. Returns the new cursor position.
fn input_delete_word(buf: &mut String, cur: usize) -> usize {
    let s = &buf[..cur];
    let trimmed = s.trim_end();
    let word_start = match trimmed
        .char_indices()
        .rev()
        .find(|(_, c)| c.is_whitespace())
    {
        Some((i, c)) => i + c.len_utf8(),
        None => 0,
    };
    buf.drain(word_start..cur);
    word_start
}

/// Parse a value-input string: a `0x…` prefix is decoded as hex bytes (spaces
/// Lowercase hex of a byte slice.
/// Whether a byte slice is mostly printable/UTF-8 text (heuristic for Auto
/// value rendering): valid UTF-8 and < 10% control bytes.
fn looks_textual(bytes: &[u8]) -> bool {
    if bytes.is_empty() {
        return true;
    }
    if std::str::from_utf8(bytes).is_err() {
        return false;
    }
    let ctrl = bytes
        .iter()
        .filter(|&&b| b < 0x09 || (0x0e..0x20).contains(&b))
        .count();
    ctrl * 10 < bytes.len()
}

fn hex_string(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{:02x}", b));
    }
    s
}

/// Make a filename-safe token from a table/base name.
fn sanitize(name: &str) -> String {
    name.chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// Build the value-pane lines for `bytes` under `render`, starting at row
/// `scroll` (16 bytes/row), up to `height` rows.
fn value_lines(
    bytes: &[u8],
    render: ValueRender,
    scroll: usize,
    height: usize,
) -> Vec<Line<'static>> {
    if render == ValueRender::Disasm {
        return disasm_lines(bytes, scroll, height);
    }
    let as_text = match render {
        ValueRender::Text => true,
        ValueRender::Hex => false,
        ValueRender::Auto => looks_textual(bytes),
        ValueRender::Disasm => unreachable!(),
    };
    let mut lines = Vec::new();
    if as_text {
        let text = String::from_utf8_lossy(bytes);
        for line in text.lines().skip(scroll).take(height) {
            lines.push(Line::from(line.to_string()));
        }
    } else {
        for i in 0..height {
            let off = (scroll + i) * 16;
            if off >= bytes.len() {
                break;
            }
            lines.push(Line::from(hexedit::hex_dump_line(
                off,
                &bytes[off.min(bytes.len())..(off + 16).min(bytes.len())],
            )));
        }
    }
    lines
}

/// Disassemble the value as a fusevm::Chunk. Only functional with the `disasm`
/// feature; otherwise a one-line note.
#[cfg(feature = "disasm")]
fn disasm_lines(bytes: &[u8], scroll: usize, height: usize) -> Vec<Line<'static>> {
    match crate::disasm::disassemble(bytes) {
        Ok(all) => all
            .into_iter()
            .skip(scroll)
            .take(height)
            .map(Line::from)
            .collect(),
        Err(e) => vec![Line::from(format!("not a fusevm chunk: {e}"))],
    }
}

#[cfg(not(feature = "disasm"))]
fn disasm_lines(_bytes: &[u8], _scroll: usize, _height: usize) -> Vec<Line<'static>> {
    vec![Line::from(
        "rebuild with `--features disasm` for bytecode disassembly",
    )]
}

/// Truncate a display string to `max` chars, appending an ellipsis.
/// A saved scan's age, phrased for the picker title.
fn age_label(age: std::time::Duration) -> String {
    let secs = age.as_secs();
    match secs {
        0..=90 => "just now".to_string(),
        _ if secs < 3600 => format!("{}m old", secs / 60),
        _ if secs < 86_400 => format!("{}h old", secs / 3600),
        _ => format!("{}d old", secs / 86_400),
    }
}

/// Byte count in the largest unit that keeps it under four digits.
pub fn human_size(n: u64) -> String {
    const UNITS: [&str; 5] = ["B", "K", "M", "G", "T"];
    let mut size = n as f64;
    let mut unit = 0;
    while size >= 1024.0 && unit + 1 < UNITS.len() {
        size /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{} {}", n, UNITS[0])
    } else if size < 10.0 {
        format!("{:.1} {}", size, UNITS[unit])
    } else {
        format!("{:.0} {}", size, UNITS[unit])
    }
}

/// Sort-direction marker for a column header.
fn arrow(desc: bool) -> &'static str {
    if desc {
        ""
    } else {
        ""
    }
}

pub fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
        out.push('');
        out
    }
}

/// A centered rect `w` cols wide and `h` rows tall inside `area`.
fn centered(area: Rect, w: u16, h: u16) -> Rect {
    let w = w.min(area.width);
    let h = h.min(area.height);
    Rect {
        x: area.x + (area.width - w) / 2,
        y: area.y + (area.height - h) / 2,
        width: w,
        height: h,
    }
}

#[cfg(test)]
mod tests {
    use super::{
        find_bytes, find_next, hit, input_delete_word, input_left, input_right, App, Store,
    };
    use crate::mru::Entry;
    use crate::overlay::HelpCtx;
    use crate::rkyv_inspect::RkyvStore;
    use crate::sqlite::SqliteStore;
    use crate::store::Kind;
    use crate::theme::{Theme, ThemeName};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use ratatui::backend::TestBackend;
    use ratatui::layout::Rect;
    use ratatui::Terminal;

    /// A unique scratch path per call — these tests run concurrently.
    fn scratch(ext: &str) -> std::path::PathBuf {
        static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let seq = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let mut path = std::env::temp_dir();
        path.push(format!(
            "zdbview_app_{}_{}.{}",
            std::process::id(),
            seq,
            ext
        ));
        let _ = std::fs::remove_file(&path);
        path
    }

    /// An App over a throwaway binary file, on a fixed scheme so assertions
    /// don't depend on the developer's saved prefs.
    fn rkyv_app() -> App {
        let path = scratch("bin");
        std::fs::write(&path, b"zdbview overlay render test payload").unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let _ = std::fs::remove_file(&path);
        App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl))
    }

    /// An App over a SQLite table with `n` rows, for paging tests.
    fn sqlite_app_rows(n: usize) -> (App, std::path::PathBuf) {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute("CREATE TABLE t (a TEXT, b TEXT)", []).unwrap();
        for i in 0..n {
            conn.execute("INSERT INTO t VALUES (?1, 'y')", [i.to_string()])
                .unwrap();
        }
        drop(conn);
        let store = Store::Sqlite(SqliteStore::open(&path).unwrap());
        (
            App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl)),
            path,
        )
    }

    /// An App over arbitrary binary content.
    fn rkyv_app_with(bytes: &[u8]) -> App {
        let path = scratch("bin");
        std::fs::write(&path, bytes).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let _ = std::fs::remove_file(&path);
        App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl))
    }

    /// An App over a two-column SQLite table, for column-motion tests.
    fn sqlite_app() -> (App, std::path::PathBuf) {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute("CREATE TABLE t (a TEXT, b TEXT, c TEXT)", [])
            .unwrap();
        conn.execute("INSERT INTO t VALUES ('x', 'y', 'z')", [])
            .unwrap();
        drop(conn);
        let store = Store::Sqlite(SqliteStore::open(&path).unwrap());
        (
            App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl)),
            path,
        )
    }

    /// Render one frame and flatten the buffer into per-row strings.
    fn frame_rows(app: &mut App, w: u16, h: u16) -> Vec<String> {
        let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let buf = term.backend().buffer().clone();
        (0..buf.area().height)
            .map(|y| {
                (0..buf.area().width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect()
    }

    fn contains(rows: &[String], needle: &str) -> bool {
        rows.iter().any(|r| r.contains(needle))
    }

    fn press(app: &mut App, c: char) {
        app.on_key(KeyEvent::from(KeyCode::Char(c)));
    }

    /// The overlay openers must work from the app's screens, and keys the
    /// overlay layer doesn't own must still reach the app.
    #[test]
    fn overlay_keys_route_through_the_app() {
        let mut app = rkyv_app();
        press(&mut app, 'h');
        assert!(app.ov.help, "h must open help");
        press(&mut app, 'j');
        assert!(!app.ov.help, "any key closes help");

        press(&mut app, 'c');
        assert!(app.ov.chooser, "c must open the scheme chooser");
        press(&mut app, 'c');
        assert!(!app.ov.chooser);

        press(&mut app, 'C');
        assert!(app.ov.editor, "C must open the palette editor");
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(!app.ov.editor);

        // `e` belongs to the data screens, not the overlays.
        press(&mut app, 'e');
        assert!(!app.ov.active(), "e must not open an overlay");
    }

    /// `h` is the help key, so it must not double as a column motion; the
    /// arrows own that.
    #[test]
    fn columns_move_with_arrows_and_h_opens_help() {
        let (mut app, path) = sqlite_app();
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the row grid
        app.on_key(KeyEvent::from(KeyCode::Right));
        assert_eq!(app.col_idx, 1, "Right must move a column");
        app.on_key(KeyEvent::from(KeyCode::Left));
        assert_eq!(app.col_idx, 0, "Left must move back");

        app.on_key(KeyEvent::from(KeyCode::Right));
        press(&mut app, 'h');
        assert_eq!(app.col_idx, 1, "h must not move the column");
        assert!(app.ov.help, "h must open help instead");
        let _ = std::fs::remove_file(&path);
    }

    /// `s` cycles the row grid's sort on the cursor column (ascending →
    /// descending → off), reloads the page, and marks the column in its header.
    #[test]
    fn s_cycles_the_sort_on_the_cursor_column() {
        let (mut app, path) = sqlite_app();
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the row grid
        app.on_key(KeyEvent::from(KeyCode::Right)); // cursor on column `b`
        assert!(app.sort.is_none(), "no sort until asked for");

        press(&mut app, 's');
        let sort = app.sort.as_ref().expect("s must sort");
        assert_eq!(sort.column, "b");
        assert!(!sort.desc, "first press sorts ascending");
        let rows = frame_rows(&mut app, 100, 20);
        assert!(contains(&rows, "b ▲"), "ascending marker missing");
        assert!(contains(&rows, "sorted by b ascending"), "no sort toast");

        press(&mut app, 's');
        assert!(app.sort.as_ref().unwrap().desc, "second press flips it");
        let rows = frame_rows(&mut app, 100, 20);
        assert!(contains(&rows, "b ▼"), "descending marker missing");

        press(&mut app, 's');
        assert!(app.sort.is_none(), "third press clears the sort");

        // `>` walks the sort to the next column, keeping the direction.
        press(&mut app, '>');
        assert_eq!(app.sort.as_ref().unwrap().column, "b");
        press(&mut app, '>');
        assert_eq!(app.sort.as_ref().unwrap().column, "c");
        press(&mut app, '<');
        assert_eq!(app.sort.as_ref().unwrap().column, "b");

        // Selecting another table drops a sort that named its columns.
        app.on_key(KeyEvent::from(KeyCode::Tab));
        app.select_table(0);
        assert!(app.sort.is_none(), "sort must not survive a table switch");
        let _ = std::fs::remove_file(&path);
    }

    /// An App over a real recognized shard on disk, so record edits exercise the
    /// actual rkyv write-back.
    fn script_shard_app() -> (App, std::path::PathBuf) {
        let path = scratch("rkyv");
        std::fs::write(
            &path,
            crate::formats::test_script_shard_bytes("/tmp/a.sh", b"old"),
        )
        .unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        (
            App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl)),
            path,
        )
    }

    /// `e` on a record opens the ported hex editor pre-filled with the record's
    /// current bytes — the point of the port: no retyping the whole value.
    #[test]
    fn e_opens_the_hex_editor_on_the_current_value() {
        let (mut app, path) = script_shard_app();
        assert_eq!(app.screen, super::Screen::Main);
        press(&mut app, 'e');
        assert_eq!(app.screen, super::Screen::HexEdit);
        let ed = app.hex.as_ref().expect("editor open");
        assert_eq!(ed.bytes, b"old", "pre-filled with the record's value");
        assert_eq!(ed.label, "/tmp/a.sh");

        let rows = frame_rows(&mut app, 90, 16);
        assert!(contains(&rows, "hex editor"), "editor not drawn");
        assert!(contains(&rows, "6f 6c 64"), "hex cells for \"old\"");
        assert!(contains(&rows, "|old"), "ascii gutter");
        let _ = std::fs::remove_file(&path);
    }

    /// Edits written with `^s` go through the real archive write-back and are
    /// visible in the reloaded records.
    #[test]
    fn hex_editor_saves_edited_bytes_back_into_the_archive() {
        let (mut app, path) = script_shard_app();
        press(&mut app, 'e');
        // EDIT mode, ascii column, overwrite "old" with "new".
        press(&mut app, 'i');
        app.on_key(KeyEvent::from(KeyCode::Tab));
        for c in "new".chars() {
            press(&mut app, c);
        }
        assert_eq!(app.hex.as_ref().unwrap().bytes, b"new");
        assert!(app.hex.as_ref().unwrap().dirty);

        app.on_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
        assert!(!app.hex.as_ref().unwrap().dirty, "save clears dirty");
        assert_eq!(
            app.decoded.as_ref().unwrap().records[0].value,
            b"new".to_vec(),
            "the reloaded record must carry the edited bytes"
        );
        // And the file on disk really changed.
        let on_disk = std::fs::read(&path).unwrap();
        assert!(
            crate::formats::try_decode(&on_disk).unwrap().records[0].value == b"new".to_vec(),
            "write-back must reach the file"
        );

        // In EDIT mode letters are data, so leave it first; then `q` closes on a
        // single press because the buffer is clean.
        app.on_key(KeyEvent::from(KeyCode::Esc));
        press(&mut app, 'q');
        assert_eq!(app.screen, super::Screen::Main);
        assert!(app.hex.is_none());
        let _ = std::fs::remove_file(&path);
    }

    /// Inside the editor the overlay openers must not steal `h` or `c` — they are
    /// motions and hex digits there.
    #[test]
    fn hex_editor_keeps_h_and_c_for_itself() {
        let (mut app, path) = script_shard_app();
        press(&mut app, 'e');
        press(&mut app, 'l');
        press(&mut app, 'h'); // motion, not help
        assert!(!app.ov.help, "h must not open help inside the editor");
        assert_eq!(app.screen, super::Screen::HexEdit);

        press(&mut app, 'i');
        press(&mut app, 'c'); // a hex digit, not the chooser
        assert!(
            !app.ov.chooser,
            "c must not open the chooser inside the editor"
        );
        // 'c' set the high nibble of 'o' (0x6f), keeping the low one.
        assert_eq!(app.hex.as_ref().unwrap().bytes[0], 0xcf);
        let _ = std::fs::remove_file(&path);
    }

    fn scan_hit(
        path: &str,
        kind: Kind,
        format: Option<&'static str>,
        secs: u64,
        rank: u8,
    ) -> crate::scan::Hit {
        crate::scan::Hit {
            path: path.into(),
            kind,
            format,
            size: 1024,
            modified: std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs),
            rank,
        }
    }

    /// Scan hits are ordered by what the tool is for: recognized shards, then
    /// other rkyv archives, then databases — newest first within each group.
    #[test]
    fn scan_hits_are_ranked_before_being_shown() {
        let mut choices: Vec<super::Choice> = Vec::new();
        super::merge_hits(
            &mut choices,
            vec![
                scan_hit("/h/.zshrs/compsys.db", Kind::Sqlite, None, 300, 2),
                scan_hit("/h/.zshrs/images/a.rkyv", Kind::Rkyv, None, 100, 1),
                scan_hit(
                    "/h/.zshrs/scripts.rkyv",
                    Kind::Rkyv,
                    Some("zshrs script cache (ZRSC)"),
                    50,
                    0,
                ),
                scan_hit("/h/.zshrs/index.rkyv", Kind::Rkyv, None, 200, 1),
            ],
        );
        let order: Vec<&str> = choices.iter().map(|c| c.name()).collect();
        assert_eq!(
            order,
            vec!["scripts.rkyv", "index.rkyv", "a.rkyv", "compsys.db"],
            "recognized shard first, then rkyv newest-first, then databases"
        );
    }

    /// A recent file the scan also finds must not appear twice, and must keep its
    /// recency position and age column.
    #[test]
    fn scan_hits_do_not_duplicate_recent_files() {
        let path = scratch("db");
        std::fs::write(&path, b"x").unwrap();
        let entry = Entry {
            path: path.clone(),
            kind: Kind::Sqlite,
            opened: std::time::SystemTime::now(),
        };
        let mut choices: Vec<super::Choice> = vec![super::Choice::from_entry(&entry)];
        super::merge_hits(
            &mut choices,
            vec![
                crate::scan::Hit {
                    path: path.clone(),
                    kind: Kind::Sqlite,
                    format: None,
                    size: 1,
                    modified: std::time::SystemTime::now(),
                    rank: 2,
                },
                scan_hit("/h/other.db", Kind::Sqlite, None, 10, 2),
            ],
        );
        assert_eq!(choices.len(), 2, "the duplicate must be dropped");
        assert_eq!(choices[0].path, path);
        assert!(choices[0].opened.is_some(), "still a recent file");
        assert!(choices[1].path.ends_with("other.db"));
        let _ = std::fs::remove_file(&path);
    }

    /// The picker shows scan progress, the recent/scanned split, and the
    /// recognized format of the selected row.
    #[test]
    fn picker_shows_scan_progress_and_row_details() {
        let theme = crate::theme::Theme::from_name(ThemeName::NeonSprawl);
        let mut choices: Vec<super::Choice> = Vec::new();
        super::merge_hits(
            &mut choices,
            vec![scan_hit(
                "/h/.zshrs/scripts.rkyv",
                Kind::Rkyv,
                Some("zshrs script cache (ZRSC)"),
                50,
                0,
            )],
        );
        let render = |choices: &[super::Choice], scanning: Option<usize>| -> Vec<String> {
            let mut term = Terminal::new(TestBackend::new(100, 8)).unwrap();
            term.draw(|f| {
                let view: Vec<usize> = (0..choices.len()).collect();
                super::render_picker(f, choices, &view, 0, "", None, scanning, None, &theme);
            })
            .unwrap();
            let buf = term.backend().buffer().clone();
            (0..buf.area().height)
                .map(|y| {
                    (0..buf.area().width)
                        .map(|x| buf[(x, y)].symbol())
                        .collect::<String>()
                })
                .collect()
        };

        let rows = render(&choices, Some(1));
        assert!(
            contains(&rows, "scanning… 1 found"),
            "no progress in the title"
        );
        assert!(contains(&rows, "1 files (0 recent)") || contains(&rows, "1 files"));
        assert!(contains(&rows, "scripts.rkyv"));
        assert!(contains(&rows, "1.0 K"), "size column for a scanned row");
        assert!(
            contains(&rows, "zshrs script cache (ZRSC)"),
            "selected row's format on the bottom line"
        );

        // Once the scan is done the progress text goes away.
        let rows = render(&choices, None);
        assert!(!contains(&rows, "scanning"));

        // With nothing found at all, the empty state explains what to do.
        let rows = render(&[], None);
        assert!(contains(&rows, "Nothing found."));
        assert!(contains(&rows, "--scan"));
        // While still scanning, it says so instead.
        let rows = render(&[], Some(0));
        assert!(contains(&rows, "Scanning for databases"));
    }

    /// `/` filters the list as the pattern is typed — the iftoprs model — instead
    /// of hopping between matches.
    #[test]
    fn slash_filters_the_records_list_while_typing() {
        let path = scratch("rkyv");
        let recs: Vec<(String, Vec<u8>)> = ["alpha", "bravo", "charlie", "delta"]
            .iter()
            .map(|n| (format!("/tmp/{n}.sh"), vec![b'x']))
            .collect();
        std::fs::write(&path, crate::formats::test_script_shard_bytes_many(&recs)).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        assert_eq!(app.visible_records().len(), 4);

        press(&mut app, '/');
        press(&mut app, 'a');
        // Only keys containing "a" stay listed: alpha, bravo, charlie, delta all
        // do, so narrow further.
        press(&mut app, 'l');
        let listed: Vec<String> = app
            .visible_records()
            .iter()
            .map(|&i| app.decoded.as_ref().unwrap().records[i].key.clone())
            .collect();
        assert_eq!(listed.len(), 1, "got {listed:?}");
        assert!(listed[0].contains("alpha"));
        assert!(app.status.contains("1 match"), "got {:?}", app.status);
        // The selection sits on a listed row.
        assert!(app.visible_records().contains(&app.record_idx));

        // The rendered list shows only the match.
        let rows = frame_rows(&mut app, 100, 16);
        assert!(contains(&rows, "alpha"));
        assert!(!contains(&rows, "bravo"), "filtered-out key still drawn");
        assert!(contains(&rows, "1/4 keys"), "count missing from the title");

        // Backspacing widens the filter again.
        app.on_key(KeyEvent::from(KeyCode::Backspace));
        assert_eq!(app.visible_records().len(), 4, "'a' matches every key");

        // A pattern matching nothing empties the list and says so.
        for c in "zzz".chars() {
            press(&mut app, c);
        }
        assert!(app.visible_records().is_empty());
        assert!(app.status.contains("0 matches"), "got {:?}", app.status);

        // Esc drops the filter and restores the position.
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.filter.is_empty(), "Esc must clear the filter");
        assert_eq!(app.visible_records().len(), 4);
        assert_eq!(app.record_idx, 0);

        // Enter keeps it applied.
        press(&mut app, '/');
        for c in "brav".chars() {
            press(&mut app, c);
        }
        app.on_key(KeyEvent::from(KeyCode::Enter));
        assert_eq!(app.filter, "brav", "Enter keeps the filter");
        assert_eq!(app.visible_records().len(), 1);
        let _ = std::fs::remove_file(&path);
    }

    /// Navigation stays inside the filtered list.
    #[test]
    fn navigation_skips_filtered_out_rows() {
        let path = scratch("rkyv");
        let recs: Vec<(String, Vec<u8>)> = ["a_one", "b_skip", "a_two", "c_skip", "a_three"]
            .iter()
            .map(|n| (format!("/tmp/{n}.sh"), vec![b'x']))
            .collect();
        std::fs::write(&path, crate::formats::test_script_shard_bytes_many(&recs)).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        press(&mut app, '/');
        for c in "a_".chars() {
            press(&mut app, c);
        }
        app.on_key(KeyEvent::from(KeyCode::Enter));
        let visible = app.visible_records();
        assert_eq!(visible.len(), 3, "three keys start with a_");
        app.record_idx = visible[0];
        for expected in &visible[1..] {
            press(&mut app, 'j');
            assert_eq!(
                app.record_idx, *expected,
                "j must land on the next listed row"
            );
        }
        // At the end it stays put rather than falling onto a hidden row.
        press(&mut app, 'j');
        assert_eq!(app.record_idx, *visible.last().unwrap());
        press(&mut app, 'k');
        assert_eq!(app.record_idx, visible[1]);
        let _ = std::fs::remove_file(&path);
    }

    /// The Strings view filters the same way.
    #[test]
    fn slash_filters_the_strings_view() {
        let mut app = rkyv_app_with(b"\x00\x00alpha\x00\x00bravo\x00\x00charlie\x00\x00");
        app.on_key(KeyEvent::from(KeyCode::Char('2')));
        let all = app.visible_strings().len();
        assert!(all >= 3, "{:?}", app.strings);
        press(&mut app, '/');
        for c in "brav".chars() {
            press(&mut app, c);
        }
        let listed = app.visible_strings();
        assert_eq!(listed.len(), 1);
        assert!(app.strings[listed[0]].text.contains("bravo"));
        let rows = frame_rows(&mut app, 100, 16);
        assert!(contains(&rows, "bravo") && !contains(&rows, "alpha"));
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert_eq!(app.visible_strings().len(), all);
    }

    /// SQLite rows are filtered in SQL, so the whole table is covered and the
    /// totals follow the filter rather than the page.
    #[test]
    fn slash_filters_sqlite_rows_across_the_whole_table() {
        let (mut app, path) = sqlite_app_rows(60);
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the grid
        assert_eq!(app.rows.as_ref().unwrap().total, 60);
        press(&mut app, '/');
        press(&mut app, '4');
        let view = app.rows.as_ref().unwrap();
        // Rows 4, 14, 24, 34, 40..49, 54 contain a '4'.
        assert_eq!(view.total, 15, "total must count matches, not all rows");
        assert!(
            view.rows.iter().all(|r| r.iter().any(|c| c.contains('4'))),
            "every listed row must match: {:?}",
            view.rows
        );
        assert!(app.status.contains("15 matches"), "got {:?}", app.status);

        // Esc restores the unfiltered grid.
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert_eq!(app.rows.as_ref().unwrap().total, 60);
        assert!(app.filter.is_empty());
        let _ = std::fs::remove_file(&path);
    }

    /// The table list filters too.
    #[test]
    fn slash_filters_the_table_list() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        for t in ["users", "user_roles", "orders"] {
            conn.execute(&format!("CREATE TABLE {t} (x)"), []).unwrap();
        }
        drop(conn);
        let store = Store::Sqlite(SqliteStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        assert_eq!(app.visible_tables().len(), 3);
        press(&mut app, '/');
        for c in "user".chars() {
            press(&mut app, c);
        }
        assert_eq!(app.visible_tables().len(), 2);
        let rows = frame_rows(&mut app, 100, 16);
        assert!(contains(&rows, "users"));
        assert!(
            !contains(&rows, "orders"),
            "a filtered-out table is still on screen: {rows:#?}"
        );
        assert!(
            contains(&rows, "tables 2/3"),
            "count missing: {:?}",
            rows[0]
        );
        let _ = std::fs::remove_file(&path);
    }

    /// PageUp/PageDown must move by what is on screen. They used to be bound to
    /// the 500-row SQL window, which did nothing at all on a smaller table, and
    /// were missing outright from the Records and Strings views.
    #[test]
    fn paging_moves_by_a_screenful() {
        let (mut app, path) = sqlite_app_rows(120);
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the grid
                                                  // A 24-row terminal keeps 23 rows for the body (one is the status bar),
                                                  // of which the grid shows 20 (two borders and a header row).
        frame_rows(&mut app, 80, 24);
        assert_eq!(app.page_rows, 20);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.row_idx, 20, "PageDown moves one screenful");
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.row_idx, 40);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.row_idx, 20);
        // Ctrl-f / Ctrl-b do the same.
        app.on_key(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::CONTROL));
        assert_eq!(app.row_idx, 40);
        app.on_key(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::CONTROL));
        assert_eq!(app.row_idx, 20);
        // Paging down past the end stops on the last row, it does not wrap.
        for _ in 0..20 {
            app.on_key(KeyEvent::from(KeyCode::PageDown));
        }
        assert_eq!(app.row_idx, 119, "clamps to the last loaded row");
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.row_idx, 99);
        // And up past the start stops at the top.
        for _ in 0..20 {
            app.on_key(KeyEvent::from(KeyCode::PageUp));
        }
        assert_eq!(app.row_idx, 0);
        let _ = std::fs::remove_file(&path);

        // A smaller terminal pages by less.
        let (mut app, path) = sqlite_app_rows(120);
        app.on_key(KeyEvent::from(KeyCode::Tab));
        frame_rows(&mut app, 80, 12);
        assert_eq!(app.page_rows, 8);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.row_idx, 8);
        let _ = std::fs::remove_file(&path);
    }

    /// The rkyv views scroll their own index, and paging must reach all of them.
    #[test]
    fn paging_works_in_every_rkyv_view() {
        let mut app = rkyv_app_with(&vec![b'A'; 4096]);
        frame_rows(&mut app, 80, 24);
        let step = app.page_rows;
        assert!(step > 1);

        // Hex view: pages of rows, not a fixed 16 bytes.
        app.on_key(KeyEvent::from(KeyCode::Char('3')));
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.hex_row, step);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.hex_row, 0);

        // Strings view: one long run of 'A's makes exactly one entry, so paging
        // clamps rather than running away.
        app.on_key(KeyEvent::from(KeyCode::Char('2')));
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.string_idx, app.strings.len().saturating_sub(1));
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.string_idx, 0);

        // Info scrolls nothing, and must not panic.
        app.on_key(KeyEvent::from(KeyCode::Char('1')));
        app.on_key(KeyEvent::from(KeyCode::PageDown));
    }

    /// Records paging walks the record list.
    #[test]
    fn paging_walks_the_records_view() {
        let path = scratch("rkyv");
        // 40 records, so a page is bounded by the record count.
        let mut keys: Vec<(String, Vec<u8>)> = Vec::new();
        for i in 0..40 {
            keys.push((format!("/tmp/s{i:02}.sh"), vec![b'x']));
        }
        std::fs::write(&path, crate::formats::test_script_shard_bytes_many(&keys)).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        frame_rows(&mut app, 80, 14);
        let step = app.page_rows;
        assert_eq!(app.record_idx, 0);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.record_idx, step);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.record_idx, 0);
        for _ in 0..20 {
            app.on_key(KeyEvent::from(KeyCode::PageDown));
        }
        assert_eq!(app.record_idx, 39, "clamps to the last record");
        let _ = std::fs::remove_file(&path);
    }

    /// The detail screen's value pane and the schema view page too.
    #[test]
    fn paging_scrolls_the_detail_and_schema_screens() {
        let (mut app, path) = sqlite_app_rows(5);
        app.on_key(KeyEvent::from(KeyCode::Tab));
        app.on_key(KeyEvent::from(KeyCode::Enter)); // detail
        assert_eq!(app.screen, super::Screen::Detail);
        app.detail_value = vec![0u8; 16 * 400];
        frame_rows(&mut app, 80, 30);
        let step = app.page_rows;
        assert!(step > 1);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.detail_scroll, step);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.detail_scroll, 0);
        app.on_key(KeyEvent::from(KeyCode::Esc));

        app.on_key(KeyEvent::from(KeyCode::Char('S'))); // schema
        assert_eq!(app.screen, super::Screen::Schema);
        frame_rows(&mut app, 80, 30);
        let step = app.page_rows;
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.schema_scroll, step);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.schema_scroll, 0);
        let _ = std::fs::remove_file(&path);
    }

    /// Esc on the first level backs out to the file list; `q` is what quits. Esc
    /// inside a nested screen still just leaves that screen.
    #[test]
    fn esc_on_the_first_level_returns_to_the_file_list() {
        // rkyv main screen.
        let mut app = rkyv_app();
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.reopen, "Esc must ask for the file list");
        assert!(app.quit, "and end the app loop");

        // `q` still quits outright.
        let mut app = rkyv_app();
        press(&mut app, 'q');
        assert!(app.quit);
        assert!(!app.reopen, "q must not reopen the picker");

        // SQLite main screen behaves the same.
        let (mut app, path) = sqlite_app();
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.reopen && app.quit);
        let _ = std::fs::remove_file(&path);

        // A nested screen keeps Esc for backing out of itself.
        let (mut app, path) = script_shard_app();
        app.on_key(KeyEvent::from(KeyCode::Enter)); // detail
        assert_eq!(app.screen, super::Screen::Detail);
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert_eq!(app.screen, super::Screen::Main);
        assert!(
            !app.reopen,
            "Esc in a nested screen must not leave the file"
        );
        assert!(!app.quit);
        // From the main screen the next Esc does back out.
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.reopen && app.quit);
        let _ = std::fs::remove_file(&path);
    }

    /// `o` leaves the app loop asking for the picker again, rather than quitting.
    #[test]
    fn o_returns_to_the_file_picker() {
        let mut app = rkyv_app();
        assert!(!app.reopen);
        press(&mut app, 'o');
        assert!(app.reopen, "o must ask for the picker");
        assert!(app.quit, "and end the app loop");

        // Inside the hex editor `o` is an insert, not a way out.
        let (mut app, path) = script_shard_app();
        press(&mut app, 'e');
        let before = app.hex.as_ref().unwrap().bytes.len();
        press(&mut app, 'o');
        assert!(!app.reopen, "the editor keeps o for inserting a byte");
        assert_eq!(app.hex.as_ref().unwrap().bytes.len(), before + 1);
        let _ = std::fs::remove_file(&path);
    }

    /// The write monitor: `w` opens it, it shows the watched stores, and rows
    /// light up as bytes land.
    #[test]
    fn write_monitor_shows_live_writes() {
        use std::io::Write;
        let mut app = rkyv_app();
        press(&mut app, 'w');
        assert_eq!(app.screen, super::Screen::Top);
        let watcher = app.top.as_ref().expect("watcher running");
        assert!(
            !watcher.is_empty(),
            "the open file must be watched at least"
        );
        assert!(app.status.contains("watching"), "got {:?}", app.status);
        assert_eq!(app.help_ctx(), HelpCtx::Top);

        // Watch a file we can write to, then write to it.
        let path = scratch("rkyv");
        std::fs::write(&path, b"start").unwrap();
        app.top = Some(crate::monitor::Monitor::new([(path.clone(), Kind::Rkyv)]));
        let rows = frame_rows(&mut app, 110, 14);
        assert!(
            contains(&rows, "writes —"),
            "no monitor header: {:?}",
            rows[0]
        );
        assert!(contains(&rows, "activity"), "no column header");
        assert!(contains(&rows, "0 active"), "nothing should be active yet");

        {
            let mut f = std::fs::OpenOptions::new()
                .append(true)
                .open(&path)
                .unwrap();
            f.write_all(&[b'x'; 4096]).unwrap();
        }
        // Force a sample the way the event loop's tick does.
        let m = app.top.as_mut().unwrap();
        m.watcher.interval = std::time::Duration::ZERO;
        assert!(m.tick());
        m.watcher.interval = crate::watch::DEFAULT_INTERVAL;

        let rows = frame_rows(&mut app, 110, 14);
        assert!(contains(&rows, "1 active"), "the write was not noticed");
        assert!(contains(&rows, "4.0 K"), "written bytes missing: {rows:#?}");
        assert!(
            rows.iter().any(|r| r.contains('') || r.contains('')),
            "no activity sparkline drawn"
        );

        // Sorting, pausing and the sample interval are all reachable.
        let before = app.top.as_ref().unwrap().order;
        press(&mut app, 's');
        assert_ne!(app.top.as_ref().unwrap().order, before);
        assert!(app.status.contains("sorted by"));
        press(&mut app, 'p');
        assert!(app.top.as_ref().unwrap().watcher.paused);
        assert!(contains(&frame_rows(&mut app, 110, 14), "PAUSED"));
        press(&mut app, 'p');
        assert!(!app.top.as_ref().unwrap().watcher.paused);
        let iv = app.top.as_ref().unwrap().watcher.interval;
        press(&mut app, '+');
        assert!(
            app.top.as_ref().unwrap().watcher.interval < iv,
            "+ samples faster"
        );
        press(&mut app, '-');
        assert_eq!(app.top.as_ref().unwrap().watcher.interval, iv);

        // Enter hands the selected file to the caller instead of opening it here.
        app.on_key(KeyEvent::from(KeyCode::Enter));
        assert_eq!(app.open_next(), Some(path.clone()));
        assert!(app.reopen && app.quit);

        // `w` again (or Esc) leaves the monitor.
        let mut app = rkyv_app();
        press(&mut app, 'w');
        press(&mut app, 'w');
        assert_eq!(app.screen, super::Screen::Main);
        assert!(app.top.is_none(), "the watcher is dropped on the way out");
        let _ = std::fs::remove_file(&path);
    }

    /// Opening a file must keep the scheme the picker was showing. It used to
    /// re-read prefs, so a concurrent write (or any drift) reset the colours on
    /// open — "randomly resetting my colorscheme when I click a file".
    #[test]
    fn opening_a_file_keeps_the_picker_scheme() {
        let path = scratch("rkyv");
        std::fs::write(
            &path,
            crate::formats::test_script_shard_bytes("/tmp/a.sh", b"x"),
        )
        .unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());

        // Whatever prefs say, the handed-over scheme is what the app shows.
        let handed = Theme::from_name(ThemeName::BladeRunner);
        let app = App::with_theme(store, handed);
        assert_eq!(app.theme().name, ThemeName::BladeRunner);
        assert_eq!(app.theme().accent, handed.accent);

        // A custom palette survives the hand-over too, which `Theme::from_name`
        // alone would have flattened back to the scheme's stock colours.
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let custom = Theme::from_palette(ThemeName::BladeRunner, [10, 20, 30, 40, 50, 60]);
        let app = App::with_theme(store, custom);
        assert_eq!(app.theme().accent, ratatui::style::Color::Indexed(20));
        assert_eq!(app.theme().primary, ratatui::style::Color::Indexed(10));

        // And the app reports back whatever it ended on, so the picker resumes
        // in the same scheme.
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, handed);
        press(&mut app, 'c');
        app.on_key(KeyEvent::from(KeyCode::Down));
        let previewed = app.theme().name;
        assert_ne!(previewed, ThemeName::BladeRunner, "chooser previews live");
        assert_eq!(
            app.theme().name,
            previewed,
            "theme() reports the live scheme"
        );
        let _ = std::fs::remove_file(&path);
    }

    /// The arrows must keep working while a filter prompt is open — they were
    /// swallowed by the prompt, so the list froze as soon as `/` was pressed.
    #[test]
    fn arrows_navigate_while_the_filter_prompt_is_open() {
        // rkyv Records: three of five keys match, and Up/Down walk those three.
        let path = scratch("rkyv");
        let recs: Vec<(String, Vec<u8>)> = ["a_one", "b_skip", "a_two", "c_skip", "a_three"]
            .iter()
            .map(|n| (format!("/tmp/{n}.sh"), vec![b'x']))
            .collect();
        std::fs::write(&path, crate::formats::test_script_shard_bytes_many(&recs)).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        press(&mut app, '/');
        for c in "a_".chars() {
            press(&mut app, c);
        }
        let visible = app.visible_records();
        assert_eq!(visible.len(), 3);
        assert!(
            matches!(app.mode, super::Mode::Search(_)),
            "prompt must stay open"
        );

        app.on_key(KeyEvent::from(KeyCode::Down));
        assert!(
            matches!(app.mode, super::Mode::Search(_)),
            "Down must not close it"
        );
        assert_eq!(app.record_idx, visible[1], "Down moves within the matches");
        app.on_key(KeyEvent::from(KeyCode::Down));
        assert_eq!(app.record_idx, visible[2]);
        app.on_key(KeyEvent::from(KeyCode::Down));
        assert_eq!(app.record_idx, visible[2], "clamps at the last match");
        app.on_key(KeyEvent::from(KeyCode::Up));
        assert_eq!(app.record_idx, visible[1]);

        // Typing more still narrows from the top.
        press(&mut app, 't');
        assert_eq!(app.visible_records().len(), 2, "a_two and a_three");
        let _ = std::fs::remove_file(&path);

        // SQLite rows: Down moves inside the filtered page.
        let (mut app, path) = sqlite_app_rows(60);
        app.on_key(KeyEvent::from(KeyCode::Tab));
        press(&mut app, '/');
        press(&mut app, '4');
        assert_eq!(app.row_idx, 0);
        app.on_key(KeyEvent::from(KeyCode::Down));
        assert_eq!(app.row_idx, 1, "Down must move the filtered grid");
        app.on_key(KeyEvent::from(KeyCode::Up));
        assert_eq!(app.row_idx, 0);
        // Paging works from the prompt too.
        frame_rows(&mut app, 80, 24);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert!(app.row_idx > 0);
        assert!(matches!(app.mode, super::Mode::Search(_)), "still typing");
        let _ = std::fs::remove_file(&path);
    }

    /// The picker's prompt behaves the same way.
    #[test]
    fn picker_prompt_keys_navigate_and_edit() {
        use super::{filter_prompt_key, Prompt};
        let mut filter = String::new();
        let mut sel = 0usize;
        let (last, page) = (9usize, 4usize);

        // Typing narrows and resets to the top of the new list.
        assert_eq!(
            filter_prompt_key(KeyCode::Char('z'), &mut filter, &mut sel, last, page),
            Prompt::Open
        );
        assert_eq!(filter, "z");
        assert_eq!(sel, 0);

        // Arrows move the selection without touching the pattern.
        filter_prompt_key(KeyCode::Down, &mut filter, &mut sel, last, page);
        filter_prompt_key(KeyCode::Down, &mut filter, &mut sel, last, page);
        assert_eq!((sel, filter.as_str()), (2, "z"));
        filter_prompt_key(KeyCode::Up, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 1);
        filter_prompt_key(KeyCode::PageDown, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 5);
        filter_prompt_key(KeyCode::PageUp, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 1);
        filter_prompt_key(KeyCode::End, &mut filter, &mut sel, last, page);
        assert_eq!(sel, last, "End goes to the last match");
        filter_prompt_key(KeyCode::Home, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 0);
        // Clamped at both ends.
        filter_prompt_key(KeyCode::Up, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 0);
        sel = last;
        filter_prompt_key(KeyCode::Down, &mut filter, &mut sel, last, page);
        assert_eq!(sel, last);

        // Backspace edits and returns to the top.
        filter_prompt_key(KeyCode::Backspace, &mut filter, &mut sel, last, page);
        assert!(filter.is_empty());
        assert_eq!(sel, 0);

        assert_eq!(
            filter_prompt_key(KeyCode::Enter, &mut filter, &mut sel, last, page),
            Prompt::Accept
        );
        assert_eq!(
            filter_prompt_key(KeyCode::Esc, &mut filter, &mut sel, last, page),
            Prompt::Cancel
        );
    }

    /// The picker's `/` must remove rows, not just move the cursor.
    #[test]
    fn picker_filter_removes_rows_from_the_list() {
        let theme = crate::theme::Theme::from_name(ThemeName::NeonSprawl);
        let mut choices: Vec<super::Choice> = Vec::new();
        super::merge_hits(
            &mut choices,
            vec![
                scan_hit("/h/.zshrs/scripts.rkyv", Kind::Rkyv, None, 30, 1),
                scan_hit("/h/.zshrs/compsys.db", Kind::Sqlite, None, 20, 2),
                scan_hit("/h/.pythonrs/scripts.rkyv", Kind::Rkyv, None, 10, 1),
            ],
        );
        let render = |filter: &str| -> Vec<String> {
            let view: Vec<usize> = choices
                .iter()
                .enumerate()
                .filter(|(_, c)| super::filter_passes(filter, c.path.to_str().unwrap()))
                .map(|(i, _)| i)
                .collect();
            let mut term = Terminal::new(TestBackend::new(100, 10)).unwrap();
            term.draw(|f| {
                super::render_picker(f, &choices, &view, 0, filter, None, None, None, &theme);
            })
            .unwrap();
            let buf = term.backend().buffer().clone();
            (0..buf.area().height)
                .map(|y| {
                    (0..buf.area().width)
                        .map(|x| buf[(x, y)].symbol())
                        .collect::<String>()
                })
                .collect()
        };

        // Unfiltered: all three.
        let rows = render("");
        assert!(contains(&rows, "compsys.db"));
        assert!(contains(&rows, "3 files"));

        // Filtering by directory drops the pythonrs row entirely.
        let rows = render("zshrs");
        assert!(contains(&rows, "scripts.rkyv") && contains(&rows, "compsys.db"));
        assert!(
            !contains(&rows, ".pythonrs"),
            "a filtered-out row is still listed: {rows:#?}"
        );
        assert!(contains(&rows, "2/3 files"), "count missing: {:?}", rows[0]);
        assert!(contains(&rows, "/zshrs"), "the pattern must be shown");

        // Filtering by name works the same way.
        let rows = render("compsys");
        assert!(contains(&rows, "compsys.db") && !contains(&rows, "pythonrs"));
        assert!(contains(&rows, "1/3 files"));

        // No match: the list is empty and says how to get out.
        let rows = render("nothing-matches-this");
        assert!(contains(&rows, "Nothing matches"));
        assert!(contains(&rows, "Esc clears the filter"));
    }

    /// Rows restored from the saved scan are labelled with their age, so it is
    /// clear the list was not just walked.
    #[test]
    fn picker_titles_a_reused_scan_with_its_age() {
        let theme = crate::theme::Theme::from_name(ThemeName::NeonSprawl);
        let mut choices: Vec<super::Choice> = Vec::new();
        super::merge_hits(
            &mut choices,
            vec![scan_hit("/h/.zshrs/scripts.rkyv", Kind::Rkyv, None, 50, 1)],
        );
        let render = |age: Option<std::time::Duration>| -> Vec<String> {
            let mut term = Terminal::new(TestBackend::new(100, 6)).unwrap();
            term.draw(|f| {
                let view: Vec<usize> = (0..choices.len()).collect();
                super::render_picker(f, &choices, &view, 0, "", None, None, age, &theme);
            })
            .unwrap();
            let buf = term.backend().buffer().clone();
            (0..buf.area().height)
                .map(|y| {
                    (0..buf.area().width)
                        .map(|x| buf[(x, y)].symbol())
                        .collect::<String>()
                })
                .collect()
        };
        let rows = render(Some(std::time::Duration::from_secs(3 * 3600)));
        assert!(contains(&rows, "scan 3h old"), "age missing: {:?}", rows[0]);
        assert!(contains(&rows, "r rescans"), "no way to refresh advertised");
        // A walk that just finished says so instead of showing hours.
        let rows = render(Some(std::time::Duration::ZERO));
        assert!(contains(&rows, "just now"));
        // Without a saved scan the title is plain.
        let rows = render(None);
        assert!(!contains(&rows, "rescans"));
    }

    #[test]
    fn age_labels_read_naturally() {
        use std::time::Duration;
        assert_eq!(super::age_label(Duration::from_secs(5)), "just now");
        assert_eq!(super::age_label(Duration::from_secs(600)), "10m old");
        assert_eq!(super::age_label(Duration::from_secs(7200)), "2h old");
        assert_eq!(super::age_label(Duration::from_secs(3 * 86_400)), "3d old");
    }

    /// Opening a large archive must not block: the 382MB shard here took 25s to
    /// validate, which read as a hang. It now opens on the structural view and
    /// the decode lands later.
    #[test]
    fn a_large_archive_opens_without_blocking() {
        // A buffer past the inline limit that is not a recognized shard, so the
        // background decode returns None.
        let big = vec![0x41u8; super::DECODE_INLINE_MAX + 1024];
        let t0 = std::time::Instant::now();
        let mut app = rkyv_app_with(&big);
        let open = t0.elapsed();
        assert!(
            open < std::time::Duration::from_secs(2),
            "opening took {open:?}"
        );
        assert!(
            app.decoding.is_some(),
            "decode must be running in the background"
        );
        assert!(app.decoded.is_none(), "and not have blocked for the result");
        assert_eq!(app.rkyv_view, super::RkyvView::Info);
        assert!(app.status.contains("decoding"), "got {:?}", app.status);

        // Records is not reachable until it lands, and says so.
        app.on_key(KeyEvent::from(KeyCode::Char('0')));
        assert_eq!(app.rkyv_view, super::RkyvView::Info);
        assert!(
            app.status.contains("still decoding"),
            "got {:?}",
            app.status
        );

        // Wait for the thread, then install the result the way the loop does.
        let rx = app.decoding.as_ref().unwrap();
        let _ = rx.recv_timeout(std::time::Duration::from_secs(30));
        app.poll_decode();
        assert!(
            app.decoding.is_none(),
            "the receiver is dropped once it lands"
        );
        assert!(app.decoded.is_none(), "0x41 filler is not a shard");
        assert!(app.status.contains("unrecognized"), "got {:?}", app.status);

        // A small archive still decodes inline, so nothing changed for shards.
        let (app, path) = script_shard_app();
        assert!(app.decoding.is_none());
        assert!(app.decoded.is_some(), "small shards decode on open");
        let _ = std::fs::remove_file(&path);
    }

    /// String extraction is bounded, so a huge archive cannot stall the open.
    #[test]
    fn string_extraction_is_bounded() {
        // Alternating printable runs and NULs: one run per 8 bytes, far more runs
        // than the cap allows.
        let mut bytes = Vec::new();
        while bytes.len() < 400_000 {
            bytes.extend_from_slice(b"abcdefg\x00");
        }
        let path = scratch("bin");
        std::fs::write(&path, &bytes).unwrap();
        let store = RkyvStore::open(&path).unwrap();
        let t0 = std::time::Instant::now();
        let s = store.strings(4);
        let took = t0.elapsed();
        assert!(took < std::time::Duration::from_secs(1), "took {took:?}");
        assert!(s.hits.len() <= 20_000, "cap ignored: {}", s.hits.len());
        assert!(s.truncated, "truncation must be reported");
        let _ = std::fs::remove_file(&path);

        // A small file is complete, not flagged.
        let path = scratch("bin");
        std::fs::write(&path, b"hello\x00world\x00").unwrap();
        let store = RkyvStore::open(&path).unwrap();
        let s = store.strings(4);
        assert_eq!(s.hits.len(), 2);
        assert!(!s.truncated);
        assert_eq!(s.scanned, 12);
        let _ = std::fs::remove_file(&path);
    }

    /// Help lists the section for what is on screen.
    #[test]
    fn help_ctx_follows_the_screen() {
        assert_eq!(rkyv_app().help_ctx(), HelpCtx::Rkyv);
        let (app, path) = sqlite_app();
        assert_eq!(app.help_ctx(), HelpCtx::Sqlite);
        let _ = std::fs::remove_file(&path);

        let (mut app, path) = script_shard_app();
        press(&mut app, 'e');
        assert_eq!(app.help_ctx(), HelpCtx::HexEdit);
        let _ = std::fs::remove_file(&path);
    }

    /// Action results must raise a toast as well as land in the status bar.
    #[test]
    fn action_results_raise_a_toast() {
        let mut app = rkyv_app();
        assert!(app.ov.toast.is_none(), "no toast before any action");
        // Export on an unrecognized archive: reports that there is nothing to
        // write, without touching the filesystem.
        press(&mut app, 'x');
        let toast = app.ov.toast.as_ref().expect("an action must toast");
        assert!(!toast.text.is_empty());
        assert_eq!(app.status, toast.text, "status bar keeps the same text");
    }

    /// The overlay draws over the app's own screen, including a nested one.
    #[test]
    fn overlays_render_over_the_app_screens() {
        let mut app = rkyv_app();
        app.ov.help = true;
        let rows = frame_rows(&mut app, 100, 40);
        assert!(contains(&rows, "KEYBOARD SHORTCUTS"));
        assert!(contains(&rows, "RKYV"), "store section missing");

        app.ov.help = false;
        app.screen = super::Screen::Detail;
        app.ov.toast("copied 12 bytes to clipboard");
        let rows = frame_rows(&mut app, 100, 40);
        assert!(
            contains(&rows, "copied 12 bytes"),
            "toast missing on detail"
        );
    }

    #[test]
    fn cursor_left_right_utf8() {
        // "aé" — 'é' is 2 bytes, so byte offsets are 0,1,3.
        let s = "";
        assert_eq!(input_right(s, 0), 1); // past 'a'
        assert_eq!(input_right(s, 1), 3); // past 'é'
        assert_eq!(input_right(s, 3), 3); // at end, stays
        assert_eq!(input_left(s, 3), 1); // before 'é'
        assert_eq!(input_left(s, 1), 0);
        assert_eq!(input_left(s, 0), 0);
    }

    #[test]
    fn delete_word_skips_trailing_space() {
        let mut s = String::from("foo bar  ");
        let len = s.len();
        let cur = input_delete_word(&mut s, len);
        assert_eq!(s, "foo ");
        assert_eq!(cur, 4);
    }

    #[test]
    fn hit_testing() {
        let r = Rect::new(2, 3, 10, 5); // x=2..12, y=3..8
        assert!(hit(r, 2, 3));
        assert!(hit(r, 11, 7));
        assert!(!hit(r, 12, 3)); // just past right edge
        assert!(!hit(r, 2, 8)); // just past bottom edge
        assert!(!hit(r, 1, 3));
    }

    #[test]
    fn find_next_forward_wraps() {
        // matches at indices 1 and 3 of a length-5 range
        let pred = |i: usize| i == 1 || i == 3;
        assert_eq!(find_next(5, 0, true, pred), Some(1));
        assert_eq!(find_next(5, 1, true, pred), Some(3));
        assert_eq!(find_next(5, 3, true, pred), Some(1)); // wrap past end
        assert_eq!(find_next(5, 4, true, pred), Some(1));
    }

    #[test]
    fn find_next_backward_wraps() {
        let pred = |i: usize| i == 1 || i == 3;
        assert_eq!(find_next(5, 4, false, pred), Some(3));
        assert_eq!(find_next(5, 3, false, pred), Some(1));
        assert_eq!(find_next(5, 1, false, pred), Some(3)); // wrap past start
        assert_eq!(find_next(5, 0, false, pred), Some(3));
    }

    #[test]
    fn find_next_none_and_empty() {
        assert_eq!(find_next(5, 0, true, |_| false), None);
        assert_eq!(find_next(0, 0, true, |_| true), None);
    }

    #[test]
    fn find_bytes_forward_and_backward() {
        let hay = b"abXYabZZab"; // "ab" at 0, 4, 8
        assert_eq!(find_bytes(hay, b"ab", 0, true), Some(4));
        assert_eq!(find_bytes(hay, b"ab", 4, true), Some(8));
        assert_eq!(find_bytes(hay, b"ab", 8, true), None); // nothing after
        assert_eq!(find_bytes(hay, b"ab", 8, false), Some(4));
        assert_eq!(find_bytes(hay, b"ab", 4, false), Some(0));
        assert_eq!(find_bytes(hay, b"zz", 0, true), None); // case-sensitive
        assert_eq!(find_bytes(hay, b"", 0, true), None);
    }
}