podlib-gui 0.1.0

GUI for managing music libraries on USB-connected iPods (Nano 7G and classic click-wheel), built with egui/eframe
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
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
//! Thin UI layer: panels, confirm modals and the worker-thread plumbing.
//!
//! Every blocking step (sudo mount, eject sequence, library open) runs on
//! a background thread and reports through an mpsc channel; the UI only
//! drains it with `try_recv` (egui FAQ: never block the UI thread), and
//! workers wake the event loop via `ctx.request_repaint()`. The library
//! backend itself lives on its own persistent worker thread — see
//! [`crate::library`] for why.

use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, Receiver, TryRecvError};

use eframe::egui;
use egui_extras::{Column, TableBuilder};
use podlib::{Playlist, PlaylistId, Track, TrackDraft, TrackId};

use crate::device::{self, DeviceCandidate, MountError};
use crate::library::{
    changes_from_track, drafts_from_paths, guard_playlist_mutation, needs_transcode, panic_message,
    path_extension, plural, AUDIOBOOK_BIT, EditDialogFields, DraggedTracks, LibraryCommand,
    LibraryOutcome, LibrarySnapshot, LibraryWorker,
};
use crate::text_menu;

/// Row height of the track table rows, keeps the column grid aligned.
/// 26px (round 4 UX): a touch taller for a comfortable click/hover target.
const ROW_HEIGHT: f32 = 26.0;
/// Fixed column widths of the track table: artist/album/duration. The
/// title column takes the remainder (see `track_table`).
const ARTIST_COLUMN: f32 = 180.0;
const ALBUM_COLUMN: f32 = 200.0;
const DURATION_COLUMN: f32 = 64.0;
/// Width of the checkbox column (round 6 П2): one narrow first column
/// carrying the row checkbox; the header holds the tri-state «выбрать
/// все». Fits the 616px worst-case panel together with the other four
/// fixed columns (28+120+180+200+64 = 592).
const CHECK_COLUMN: f32 = 28.0;
/// Minimum width the central panel keeps for the track table: 28
/// (checkbox) + 100 (title, `at_least`) + 180 + 200 + 64 fixed columns
/// plus item spacing (round 6.5). The sidebar's width ceiling is
/// derived from it, so dragging the divider can never collapse the
/// table — egui itself clamps panel drags only at the screen edge.
const MIN_CENTRAL_PANEL_WIDTH: f32 = 616.0;
/// Height of one sidebar row (round 6 П1) — the table row height, so
/// both lists share one rhythm.
const SIDEBAR_ROW_HEIGHT: f32 = 26.0;
/// Left/right text inset inside a sidebar row. Identical for every
/// section (master / «Устройство» / «Плейлисты»): one geometry.
const SIDEBAR_ROW_INSET: f32 = 8.0;
/// Gap kept between a (clipped) row name and the right-aligned count.
const SIDEBAR_NAME_COUNT_GAP: f32 = 8.0;

/// Messages from worker threads to the UI.
enum DeviceEvent {
    /// Device mounted read-write; payload is the mount point plus
    /// whether THIS run performed the mount (round 5.3: only then does
    /// app close unmount it).
    Connected(Result<(PathBuf, bool), ConnectError>),
    Ejected(Result<(), String>),
}

#[derive(Debug)]
enum ConnectError {
    Mount { error: MountError, stderr: String },
    /// Worker thread panicked mid-operation; operation state is unknown.
    Internal(String),
}

/// One scanned device candidate with its resolved block device.
struct DeviceEntry {
    candidate: DeviceCandidate,
    block_dev: Option<PathBuf>,
}

/// Device currently connected through the GUI.
struct ConnectedDevice {
    block_dev: PathBuf,
    /// Hardware label from sysfs (e.g. «Apple iPod»), frozen at connect
    /// time so the app bar stays stable even if the scan list changes.
    label: String,
}

/// Error prepared for display: message + optional advice + raw tool output.
struct UiError {
    message: String,
    hint: Option<String>,
    stderr: Option<String>,
}

/// Decision of the confirm-on-close guard (F4).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CloseDecision {
    /// Nothing to do, or safe to let the window close.
    Allow,
    /// Cancel the OS close and open the confirmation modal.
    BlockWithConfirm,
}

/// Close-guard state machine: an OS close while an operation is in
/// flight would kill the detached worker thread mid-persist (possible
/// corruption of the DB on the device), so the first close is cancelled
/// and confirmed. After the user confirms, later close requests pass
/// through — no confirm loop. While idle the window closes as usual.
/// Round 5.3: what a confirmed window close does — a device mounted by
/// this app run is ejected first (the window closes when the eject
/// lands), anything else closes immediately.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CloseAction {
    EjectFirst,
    CloseNow,
}

fn close_confirmation_action(mounted_by_us: bool) -> CloseAction {
    if mounted_by_us {
        CloseAction::EjectFirst
    } else {
        CloseAction::CloseNow
    }
}

/// A deferred eject (close requested while the worker was busy) fires
/// as soon as the app is idle again.
fn deferred_eject_due(pending: bool, busy: bool, library_idle: bool) -> bool {
    pending && !busy && library_idle
}

/// Honest confirm texts (batch F): busy — the worker must not die
/// mid-write; idle with our mount — the close ejects the device, and
/// the eject needs the sudo password for it.
fn close_confirm_texts(busy: bool) -> (&'static str, &'static str) {
    if busy {
        (
            "Идёт операция с библиотекой",
            "Закрыть всё равно? Возможно повреждение базы на устройстве.",
        )
    } else {
        (
            "Закрыть podlib?",
            "Смонтированное устройство будет безопасно отключено перед \
             закрытием (понадобится пароль sudo).",
        )
    }
}

/// Retry hint for a failed eject (batch F): the library is already
/// closed and the button is available again, so a retry is safe.
/// Sudo-auth failures (classified by `classify_mount_failure`) get the
/// layout/Caps Lock wording; everything else keeps the honest «volume
/// may still be mounted».
fn ejected_failure_hint(failure: device::MountFailure) -> &'static str {
    match failure {
        device::MountFailure::WrongPassword => {
            "Пароль sudo отклонён — проверьте раскладку и Caps Lock. \
             Нажмите „Безопасно отключить“ ещё раз: библиотека уже \
             закрыта, том не тронут, повторный ввод пароля безопасен."
        }
        _ => {
            "Нажмите „Безопасно отключить“ ещё раз — библиотека уже \
             закрыта и повторная попытка безопасна; том мог остаться \
             смонтированным."
        }
    }
}
fn close_decision(
    close_requested: bool,
    operation_active: bool,
    close_confirmed: bool,
    mounted_by_us: bool,
) -> CloseDecision {
    if !close_requested || close_confirmed {
        return CloseDecision::Allow;
    }
    // Batch F: an idle close with a device mounted by this app must
    // also ask — the round 5.3 eject runs sudo steps and cannot be
    // done silently behind the user's back.
    if operation_active || mounted_by_us {
        return CloseDecision::BlockWithConfirm;
    }
    CloseDecision::Allow
}

/// Which operation the UI is waiting on; at most one at a time. Only
/// bookkeeping — the outcome itself carries the fresh snapshot and the
/// ready-made status text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PendingKind {
    Refresh,
    AddTracks,
    RemoveTrack,
    EditTrack,
    SetArtist,
    CreatePlaylist,
    DeletePlaylist,
    RenamePlaylist,
    AddToPlaylist,
    RemoveFromPlaylist,
}

/// Edit-dialog state: which track plus the text as shown on screen.
struct EditDialogState {
    id: TrackId,
    fields: EditDialogFields,
    error: Option<String>,
}

/// «Задать исполнителя» modal state: the selection snapshot plus the
/// typed value; lives in [`LibraryUi`] so both survive frames.
#[derive(Clone)]
struct SetArtistDialog {
    track_ids: Vec<TrackId>,
    value: String,
}

/// Round 8: rename modal state — which playlist plus the typed name as
/// shown on screen (prefilled with the current one at open time).
#[derive(Clone)]
struct RenamePlaylistDialog {
    id: PlaylistId,
    name: String,
}

/// Track-table choices collected during one frame, applied afterwards
/// (the render loop borrows the snapshot immutably; mutating actions
/// need the unique borrow back). Last menu click wins, as before.
#[derive(Default)]
struct TrackRowActions {
    edit: Option<TrackId>,
    add_to_playlist: Option<Vec<TrackId>>,
    delete: Option<TrackId>,
    /// Keyboard cursor move (the last touched row).
    select: Option<TrackId>,
    /// Click on a visible row: (index, ctrl, shift) — resolved by the
    /// caller against the visible list (apply_row_click).
    row_click: Option<(usize, bool, bool)>,
    /// «Убрать из плейлиста» in a playlist view: (playlist, member).
    remove_from_playlist: Option<(PlaylistId, TrackId)>,
    /// Round 6 П2: header checkbox toggled → target state (true =
    /// select all visible rows).
    select_all: Option<bool>,
    /// Round 6 П2: a row checkbox was clicked → explicit toggle of
    /// that id in the shared selection.
    checkbox_toggle: Option<TrackId>,
    /// Round 7: a sortable header was clicked → which column.
    sort_toggle: Option<TrackSortColumn>,
}

impl TrackRowActions {
    fn merge(&mut self, other: Self) {
        self.edit = other.edit.or(self.edit.take());
        self.add_to_playlist = other.add_to_playlist.or(self.add_to_playlist.take());
        self.delete = other.delete.or(self.delete.take());
        self.select = other.select.or(self.select.take());
        self.row_click = other.row_click.or(self.row_click.take());
        self.remove_from_playlist = other
            .remove_from_playlist
            .or(self.remove_from_playlist.take());
        self.select_all = other.select_all.or(self.select_all.take());
        self.checkbox_toggle = other.checkbox_toggle.or(self.checkbox_toggle.take());
        self.sort_toggle = other.sort_toggle.or(self.sort_toggle.take());
    }
}

/// Playlist-panel choices collected during one frame, applied after the
/// render loop (same borrow discipline as [`TrackRowActions`]).
#[derive(Default)]
struct PlaylistPanelActions {
    /// Tracks dropped onto a user playlist.
    add_drop: Option<(PlaylistId, Vec<TrackId>)>,
    /// Tracks dropped onto the master playlist: refused with a hint.
    master_drop: Option<String>,
    /// Tracks dropped onto a built-in device view: refused with a hint.
    view_drop: Option<String>,
    /// «Переименовать…»/«Удалить плейлист…» chosen on the master row:
    /// refused honestly (round 8: one shared refusal carries the name),
    /// no round trip to the device.
    master_rename: Option<String>,
    /// «Переименовать…» chosen on a user playlist row.
    rename_playlist: Option<PlaylistId>,
    delete_playlist: Option<PlaylistId>,
}

impl PlaylistPanelActions {
    fn merge(&mut self, other: Self) {
        self.add_drop = other.add_drop.or(self.add_drop.take());
        self.master_drop = other.master_drop.or(self.master_drop.take());
        self.view_drop = other.view_drop.or(self.view_drop.take());
        self.master_rename = other.master_rename.or(self.master_rename.take());
        self.rename_playlist = other.rename_playlist.or(self.rename_playlist.take());
        self.delete_playlist = other.delete_playlist.or(self.delete_playlist.take());
    }
}

/// Live library UI state: the worker handle plus a local snapshot that is
/// replaced wholesale after every operation (full re-list, KISS).
struct LibraryUi {
    worker: LibraryWorker,
    snapshot: LibrarySnapshot,
    /// Reply channel of the initial open; yields exactly one message.
    opening: Option<Receiver<LibraryOutcome>>,
    /// The single operation in flight, with its reply channel.
    pending: Option<(PendingKind, Receiver<LibraryOutcome>)>,
    // Dialog/confirm state (modal flags live here so they survive frames).
    /// Rows awaiting the delete confirmation: one or many (Ф3).
    confirm_delete_track: Option<Vec<TrackId>>,
    purge_media: bool,
    confirm_delete_playlist: Option<PlaylistId>,
    /// «Переименовать плейлист» modal state (round 8, sidebar ПКМ).
    rename_dialog: Option<RenamePlaylistDialog>,
    create_open: bool,
    new_playlist_name: String,
    edit_dialog: Option<EditDialogState>,
    /// Open «Задать исполнителя» modal over the multi-selection: the
    /// snapshot of the selection plus the typed value (dialog fields
    /// live here so they survive frames).
    set_artist_dialog: Option<SetArtistDialog>,
    picker_tracks: Option<Vec<TrackId>>,
    /// Sidebar view context (round 4.1 Ф2): master, a built-in device
    /// view or a user playlist.
    view: LibraryView,
    /// Keyboard cursor (the last touched row); arrows and Enter work
    /// through it without disturbing the multi-selection.
    selected_track: Option<TrackId>,
    /// Multi-selection in the central table, in click order.
    selected_tracks: Vec<TrackId>,
    /// Anchor row (round 6 tail nit-10): (index into the visible list,
    /// TrackId of the anchored row) for shift-range clicks. The id
    /// makes the anchor identity-checked: after a re-list that replaced
    /// the rows, a stale anchor is dropped instead of shift-selecting
    /// a foreign range.
    selection_anchor: Option<(usize, TrackId)>,
    /// Remaining rows of a multi-track delete (one in-flight worker
    /// command at a time; the chain continues on each Applied).
    delete_queue: Vec<TrackId>,
    /// Expanded books in the «Аудиокниги» view (round 5), keyed by
    /// album. All collapsed by default; stale keys (a book renamed or
    /// gone) simply never render — no fix-up needed.
    expanded_books: HashSet<String>,
    /// Round 6 П3: expanded groups of the music section's album/artist
    /// views (books keep their own set — the names are different
    /// domains). Same stale-key semantics.
    expanded_groups: HashSet<String>,
    /// Round 6 П3: display modes of the grouping-capable sections.
    /// «Музыка» defaults to the flat list; «Аудиокниги» keeps the
    /// round-5 books view as its default (no behavior change).
    music_mode: SectionMode,
    books_mode: SectionMode,
    /// Toolbar search box; empty string = no filter.
    search_query: String,
    /// Round 7: active column sort of the flat track table (`None` =
    /// default device order). Display state only — never written to
    /// the device.
    track_sort: Option<TrackSort>,
}

impl LibraryUi {
    /// Round 8 edge: after an Applied outcome the open playlist may be
    /// gone (delete). The view must not dangle on a dead PlaylistId —
    /// it falls back to the master view («Все треки»), and the stale
    /// track selection goes with it (the same clearing a sidebar
    /// switch performs). Any surviving view is untouched.
    fn drop_dangling_view(&mut self) {
        if let LibraryView::Playlist(id) = self.view {
            if self.snapshot.playlist(id).is_none() {
                self.view = LibraryView::Master;
                self.selected_tracks.clear();
                self.selection_anchor = None;
                self.selected_track = None;
            }
        }
    }
}

pub struct PodlibApp {
    /// Saved once (AppCreator) so worker threads can request repaints.
    ctx: egui::Context,
    devices: Vec<DeviceEntry>,
    selected: Option<usize>,
    password: String,
    confirm_mount: bool,
    confirm_eject: bool,
    /// Confirm-close modal is open: an operation was in flight when the
    /// user asked to close the window.
    confirm_close: bool,
    /// The user confirmed closing despite an in-flight operation; the
    /// guard lets subsequent close requests pass (no confirm loop).
    force_close: bool,
    start_mount: bool,
    start_eject: bool,
    busy: bool,
    status: String,
    error: Option<UiError>,
    rx: Option<Receiver<DeviceEvent>>,
    connected: Option<ConnectedDevice>,
    /// Present while a device is connected and its library worker is open.
    library: Option<LibraryUi>,
    /// Deferred «Убрать из плейлиста» from the toolbar (the request
    /// needs the worker free; collected during the render pass).
    pending_remove_from_playlist: Option<(PlaylistId, Vec<TrackId>)>,
    /// True when this app run is responsible for the safe unmount
    /// (round 5.3): closing the app then ejects the volume. Batch F:
    /// set for mounts we performed AND for adopted already-mounted
    /// volumes («Подключить» to a mount orphaned by a restart, or a
    /// foreign mount the owner deliberately connected to).
    mounted_by_us: bool,
    /// Open tag-review modal (round 5.5): an untagged batch is edited
    /// here before the regular AddTracks dispatch; lives on the app so
    /// it survives even while the library is opening.
    tag_review: Option<TagReview>,
    /// A confirmed close waits for the eject to finish before the
    /// window actually closes (round 5.3: close = safe unmount when
    /// the app created the mount).
    pending_close_after_eject: bool,
}

impl PodlibApp {
    pub fn new(ctx: egui::Context) -> Self {
        // WHY the theme follows the system: owner requirement (round 4
        // UX) — the app must not impose dark/light on the desktop.
        ctx.set_theme(egui::ThemePreference::System);
        let mut app = Self {
            ctx,
            devices: Vec::new(),
            selected: None,
            password: String::new(),
            confirm_mount: false,
            confirm_eject: false,
            confirm_close: false,
            force_close: false,
            start_mount: false,
            start_eject: false,
            busy: false,
            status: String::new(),
            error: None,
            rx: None,
            connected: None,
            library: None,
            pending_remove_from_playlist: None,
            mounted_by_us: false,
            pending_close_after_eject: false,
            tag_review: None,
        };
        app.refresh_devices();
        app
    }

    fn refresh_devices(&mut self) {
        self.devices = device::discover_devices()
            .into_iter()
            .map(|(candidate, block_dev)| DeviceEntry {
                block_dev,
                candidate,
            })
            .collect();
        self.selected = None;
    }

    fn selected_entry(&self) -> Option<&DeviceEntry> {
        self.selected.and_then(|index| self.devices.get(index))
    }

    // ---- event draining ----

    fn drain_events(&mut self) {
        // Take the receiver so event handlers can freely mutate `self`.
        let rx = match self.rx.take() {
            Some(rx) => rx,
            None => return,
        };
        loop {
            match rx.try_recv() {
                Ok(event) => self.handle_event(event),
                Err(TryRecvError::Empty) => break,
                Err(TryRecvError::Disconnected) => {
                    // Worker thread finished; nothing left to report.
                    self.busy = false;
                    return;
                }
            }
        }
        self.rx = Some(rx);
    }

    fn handle_event(&mut self, event: DeviceEvent) {
        self.busy = false;
        match event {
            DeviceEvent::Connected(Ok((mount, mounted_by_us))) => {
                self.mounted_by_us = mounted_by_us;
                let (block_dev, label) = self
                    .selected_entry()
                    .map(|entry| {
                        (
                            entry.block_dev.clone().unwrap_or_default(),
                            entry.candidate.label.clone(),
                        )
                    })
                    .unwrap_or_else(|| (Default::default(), "устройство".to_owned()));
                self.connected = Some(ConnectedDevice {
                    block_dev,
                    label,
                });
                self.status = "Открываю библиотеку…".to_owned();
                self.start_library(mount);
            }
            DeviceEvent::Connected(Err(error)) => {
                self.error = Some(match error {
                    ConnectError::Mount { error, stderr } => UiError {
                        message: error.to_string(),
                        hint: error.hint().map(str::to_owned),
                        stderr: Some(stderr),
                    },
                    ConnectError::Internal(message) => UiError {
                        message: format!("Внутренняя ошибка операции: {message}"),
                        hint: Some(
                            "Состояние операции после сбоя неизвестно; нажмите «Обновить»."
                                .to_owned(),
                        ),
                        stderr: None,
                    },
                });
                self.status.clear();
            }
            DeviceEvent::Ejected(Ok(())) => {
                self.connected = None;
                self.error = None;
                self.mounted_by_us = false;
                self.status = "Устройство безопасно отключено".to_owned();
                self.refresh_devices();
                // Round 5.3: a close requested while the device was
                // mounted completes after the eject lands.
                if self.pending_close_after_eject {
                    self.pending_close_after_eject = false;
                    self.force_close = true;
                    self.ctx.send_viewport_cmd(egui::ViewportCommand::Close);
                }
            }
            DeviceEvent::Ejected(Err(message)) => {
                // Batch F: a failed eject also cancels the pending close —
                // otherwise the deferred path would restart the eject every
                // idle frame (previously with an empty password again). The
                // window stays; the user can close it again, which now goes
                // through the password modal.
                self.pending_close_after_eject = false;
                // Batch F retry support: the library is already closed
                // (and `library_idle` counts None as idle), so the eject
                // button is available again — the hint says a retry is
                // safe. Sudo-auth failures get the layout/Caps Lock
                // wording, the rest keeps the honest «volume may still
                // be mounted».
                let hint = self.connected.is_some().then(|| {
                    ejected_failure_hint(device::classify_mount_failure(&message))
                        .to_owned()
                });
                self.error = Some(UiError {
                    message,
                    hint,
                    stderr: None,
                });
                self.status.clear();
            }
        }
    }

    // ---- library lifecycle ----

    /// Spawns the library worker for a freshly mounted volume. The
    /// backend is opened inside the worker thread (`Box<dyn
    /// LibraryBackend>` is not `Send` — see library.rs for the rationale).
    fn start_library(&mut self, mount: PathBuf) {
        let (worker, opened) = LibraryWorker::spawn(mount);
        self.library = Some(LibraryUi {
            worker,
            snapshot: LibrarySnapshot::default(),
            opening: Some(opened),
            pending: None,
            confirm_delete_track: None,
            purge_media: false,
            confirm_delete_playlist: None,
            rename_dialog: None,
            create_open: false,
            new_playlist_name: String::new(),
            edit_dialog: None,
            set_artist_dialog: None,
            picker_tracks: None,
            view: LibraryView::Master,
            selected_track: None,
            selected_tracks: Vec::new(),
            selection_anchor: None,
            delete_queue: Vec::new(),
            expanded_books: HashSet::new(),
            expanded_groups: HashSet::new(),
            music_mode: SectionMode::List,
            books_mode: SectionMode::Books,
            search_query: String::new(),
            track_sort: None,
        });
    }

    /// True while no library operation is in flight. Batch F: no library
    /// at all is also idle — after a failed eject the worker is closed
    /// (`None`), and the eject button plus the deferred-close paths must
    /// stay available for a retry.
    fn library_idle(&self) -> bool {
        self.library
            .as_ref()
            .is_none_or(|library| library.pending.is_none() && library.opening.is_none())
    }

    fn library_busy(&self) -> bool {
        self.library
            .as_ref()
            .is_some_and(|library| library.pending.is_some() || library.opening.is_some())
    }

    fn drain_library(&mut self) {
        // 1) The initial open result arrives on its own channel. Each
        // match arm re-borrows the field it needs so `self.library = None`
        // arms stay legal.
        let opening = self.library.as_mut().and_then(|library| library.opening.take());
        if let Some(rx) = opening {
            match rx.try_recv() {
                Ok(LibraryOutcome::Loaded(snapshot)) => {
                    if let Some(library) = self.library.as_mut() {
                        library.snapshot = snapshot;
                        // Russian plural forms: «1 трек», «2 трека», «5 треков».
                        let tracks = library.snapshot.tracks.len();
                        let playlists = library.snapshot.playlists.len();
                        self.status = format!(
                            "Подключено: {} {}, {} {}",
                            tracks,
                            plural(tracks, "трек", "трека", "треков"),
                            playlists,
                            plural(playlists, "плейлист", "плейлиста", "плейлистов"),
                        );
                    }
                }
                Ok(LibraryOutcome::Failed { message, hint }) => {
                    self.error = Some(UiError {
                        message,
                        hint,
                        stderr: None,
                    });
                    self.status.clear();
                    // Dead worker; the volume stays mounted.
                    self.library = None;
                }
                Err(TryRecvError::Empty) => {
                    if let Some(library) = self.library.as_mut() {
                        library.opening = Some(rx);
                    }
                }
                Err(TryRecvError::Disconnected) => {
                    self.error = Some(UiError {
                        message: "Воркер библиотеки завершился, не открыв её".to_owned(),
                        hint: Some("Подключите устройство заново.".to_owned()),
                        stderr: None,
                    });
                    self.library = None;
                }
                Ok(unexpected) => {
                    // The open channel yields exactly one message; anything
                    // else is a protocol bug. Keep waiting rather than lie.
                    let _ = unexpected;
                    if let Some(library) = self.library.as_mut() {
                        library.opening = Some(rx);
                    }
                }
            }
            if self.library.is_none() {
                return;
            }
        }

        // 2) The single pending operation, if any.
        let pending = self.library.as_mut().and_then(|library| library.pending.take());
        if let Some((kind, rx)) = pending {
            match rx.try_recv() {
                Ok(LibraryOutcome::Closed) => {
                    self.library = None;
                }
                Ok(LibraryOutcome::Loaded(snapshot)) => {
                    if let Some(library) = self.library.as_mut() {
                        library.snapshot = snapshot;
                    }
                    self.status = "Список обновлён".to_owned();
                }
                Ok(LibraryOutcome::Applied { snapshot, summary }) => {
                    if let Some(library) = self.library.as_mut() {
                        // Review 🟢-5: the applied operation may have
                        // removed tracks — dead ids must not stay in the
                        // selection, the toolbar would count rows that
                        // no longer exist and leak them into later
                        // actions. The anchor carries the same TrackId
                        // identity; dropping a stale one here mirrors
                        // `valid_anchor` (which would degenerate it to
                        // a plain click later anyway).
                        // M4 (batch edits): после «Задать исполнителя»
                        // ВСЕ выбранные сменили pid (контракт edit_track
                        // = remove+re-add) — осознанный сброс выделения
                        // вместо ремапа старых id на новые.
                        library
                            .selected_tracks
                            .retain(|id| snapshot.track(*id).is_some());
                        library.selection_anchor = library
                            .selection_anchor
                            .filter(|&(_, id)| snapshot.track(id).is_some());
                        library.snapshot = snapshot;
                        // Round 8 edge: the applied operation may have
                        // removed the OPEN playlist — the view must not
                        // dangle on a dead PlaylistId. Any other outcome
                        // (rename keeps the id) is untouched.
                        library.drop_dangling_view();
                    }
                    self.status = summary;
                    // Multi-delete chaining: fire the next queued
                    // RemoveTrack once the previous one landed.
                    if matches!(kind, PendingKind::RemoveTrack) {
                        self.continue_delete_chain();
                    }
                }
                Ok(LibraryOutcome::Failed { message, hint }) => {
                    self.error = Some(UiError {
                        message,
                        hint,
                        stderr: None,
                    });
                    self.status.clear();
                    // A failed step stops the delete chain: the error
                    // must be resolved before removing more rows.
                    if let Some(library) = self.library.as_mut() {
                        library.delete_queue.clear();
                    }
                }
                Err(TryRecvError::Empty) => {
                    if let Some(library) = self.library.as_mut() {
                        library.pending = Some((kind, rx));
                    }
                }
                Err(TryRecvError::Disconnected) => {
                    self.error = Some(UiError {
                        message: "Воркер библиотеки завершился во время операции".to_owned(),
                        hint: Some(
                            "Состояние операции неизвестно; отключите и подключите устройство \
                             заново."
                                .to_owned(),
                        ),
                        stderr: None,
                    });
                    self.library = None;
                }
            }
        }
    }

    /// Sends one library command and remembers to drain its reply. One
    /// operation at a time; failures to send are surfaced as UI errors.
    /// Multi-delete chaining (Ф3): the worker protocol allows one
    /// command in flight, so the remaining ids queue and fire as each
    /// RemoveTrack lands. The purge flag is read fresh per step (the
    /// dialog keeps it in state). A failed step cleared the queue
    /// before this runs — the error must be resolved first.
    fn continue_delete_chain(&mut self) {
        let next = self
            .library
            .as_ref()
            .and_then(|library| library.delete_queue.first().copied());
        let purge = self
            .library
            .as_ref()
            .map(|library| library.purge_media)
            .unwrap_or(false);
        if let Some(id) = next {
            if let Some(library) = self.library.as_mut() {
                library.delete_queue.remove(0);
            }
            self.library_request(
                LibraryCommand::RemoveTrack {
                    id,
                    purge_media: purge,
                },
                PendingKind::RemoveTrack,
                "Удаляю трек…",
            );
        }
    }

    /// Sends one library command and remembers to drain its reply. One
    /// operation at a time; failures to send are surfaced as UI errors.
    /// Returns `true` only when the worker accepted the command, so a
    /// caller can keep pre-send UI state (e.g. a modal with typed
    /// input) on a visible refusal.
    fn library_request(
        &mut self,
        command: LibraryCommand,
        kind: PendingKind,
        status: &str,
    ) -> bool {
        // No library at all is not "busy" — the honest refusal points at
        // connecting a device instead of a wait that would never end.
        let Some(library) = self.library.as_ref() else {
            self.error = Some(UiError {
                message: "Сначала подключите устройство".to_owned(),
                hint: None,
                stderr: None,
            });
            return false;
        };
        if library.pending.is_some() || library.opening.is_some() {
            // Never drop an action silently: buttons inside modals and
            // context-menu choices are not gated on idleness, so a busy
            // worker must refuse visibly instead of ignoring the request.
            self.error = Some(UiError {
                message: "Дождитесь завершения текущей операции".to_owned(),
                hint: None,
                stderr: None,
            });
            return false;
        }
        match library.worker.request(command) {
            Ok(rx) => {
                if let Some(library) = self.library.as_mut() {
                    library.pending = Some((kind, rx));
                }
                self.status = status.to_owned();
                true
            }
            Err(message) => {
                self.error = Some(UiError {
                    message,
                    hint: None,
                    stderr: None,
                });
                false
            }
        }
    }

    // ---- device worker threads ----

    fn spawn_connect(&mut self) {
        let Some(entry) = self.selected_entry() else {
            return;
        };
        let Some(block_dev) = entry.block_dev.clone() else {
            self.error = Some(UiError {
                message: "Не удалось определить блочное устройство по sysfs".to_owned(),
                hint: Some("Нажмите «Обновить» и выберите устройство заново.".to_owned()),
                stderr: None,
            });
            return;
        };
        let mount_path = entry.candidate.mount.clone();
        let Some((uid, gid)) = device::current_uid_gid() else {
            // W4: nothing has run yet, so the UI error must not claim a
            // mounted volume — surfaced locally, worker never spawned.
            self.error = Some(UiError {
                message: "не удалось определить uid/gid процесса".to_owned(),
                hint: None,
                stderr: None,
            });
            return;
        };
        // mkdir -p + rw-mount: one sequence for mounted and unmounted
        // candidates alike (mkdir -p on an existing path is a no-op).
        let steps = device::build_mount_sequence(&device::MountSpec {
            block_dev: block_dev.clone(),
            mount_path: mount_path.clone(),
            uid,
            gid,
        });
        let password = std::mem::take(&mut self.password);
        let ctx = self.ctx.clone();
        let (tx, rx) = channel();
        self.rx = Some(rx);
        self.busy = true;
        self.error = None;
        self.status = format!("Монтирование {} (rw)…", block_dev.display());
        std::thread::spawn(move || {
            // catch_unwind: a worker panic must still produce an event,
            // otherwise the UI would silently stay busy forever.
            let result = run_worker_step(
                || connect_device(password, steps, mount_path, block_dev.clone()),
                ConnectError::Internal,
            );
            let _ = tx.send(DeviceEvent::Connected(result));
            ctx.request_repaint(); // wake the sleeping event loop
        });
    }

    fn spawn_eject(&mut self) {
        let Some(connected) = self.connected.as_ref() else {
            return;
        };
        // Round 6.1: close library → sync → drain unmounts (one per
        // stacked mount of the devnode, per the /proc/mounts snapshot)
        // → power off the whole disk, strictly LAST.
        let block_dev = connected.block_dev.clone();
        // Round 6.2: EVERY shutdown step runs under sudo -S (password
        // over stdin, never argv) with this ONE password — the volume
        // was mounted by us as root, so a user-side unmount would pop a
        // polkit dialog (the second password prompt this round kills).
        // Taken here so it is consumed and cleared like in the connect
        // flow.
        let password = std::mem::take(&mut self.password);
        // Live-run diagnostic (round 6.2 F): sudo rejected the delivered
        // line once with «1 incorrect password attempt»; log the LENGTH
        // only — never the content — so an empty/short delivery is
        // distinguishable from a typed-but-rejected password.
        eprintln!(
            "[eject] пароль sudo: {} симв., ascii={}",
            password.chars().count(),
            password.bytes().all(|byte| byte.is_ascii()),
        );
        // Take the library out: the backend must be closed (and joined)
        // before the unmount sequence, on the eject thread itself.
        let library = self.library.take();
        let ctx = self.ctx.clone();
        let (tx, rx) = channel();
        self.rx = Some(rx);
        self.busy = true;
        self.error = None;
        self.status =
            "Отключение: закрытие библиотеки → sync → unmount → power-off…".to_owned();
        std::thread::spawn(move || {
            if let Some(library) = library {
                // Blocking close: the backend owns files on the mounted
                // volume, so it must be gone before sync/unmount.
                library.worker.close_and_join();
            }
            // catch_unwind: a worker panic must still produce an event,
            // otherwise the UI would silently stay busy forever.
            let result = run_worker_step(
                || {
                    // The mount snapshot decides the drain length: one
                    // unmount per stacked layer. The old code unmounted
                    // once, powered off, and only then tried to drain —
                    // behind a `?` — so power-off died on «The drive is
                    // in use» while sibling mounts were still alive.
                    let mounts = std::fs::read_to_string("/proc/mounts")
                        .map(|content| device::parse_proc_mounts(&content))
                        .unwrap_or_default();
                    let (steps, power_off) = device::build_shutdown_steps(
                        &block_dev,
                        Path::new("/sys/dev/block"),
                        &mounts,
                    );
                    // Same loop shape as the connect flow: each step
                    // under sudo, fail fast on the exit status, honest
                    // stderr in the message. WHY password lives across
                    // the whole loop: every sudo step consumes its own
                    // copy from stdin; it is dropped only after the
                    // last step, never stored anywhere.
                    for spec in steps.iter().chain(std::iter::once(&power_off)) {
                        let output = device::run_sudo_command(&password, spec)
                            .map_err(|error| device::shutdown_step_error(spec, &error.to_string()))?;
                        if !output.status.success() {
                            let stderr = String::from_utf8_lossy(&output.stderr);
                            return Err(device::shutdown_step_error(spec, &stderr));
                        }
                    }
                    drop(password);
                    Ok(())
                },
                |message| format!("внутренняя ошибка: {message}"),
            );
            let _ = tx.send(DeviceEvent::Ejected(result));
            ctx.request_repaint();
        });
    }

    // ---- panels ----

    fn device_panel(&mut self, ui: &mut egui::Ui) {
        ui.heading("Устройство");
        ui.add_space(4.0);
        if ui
            .add_enabled(!self.busy, egui::Button::new("Обновить"))
            .clicked()
        {
            self.refresh_devices();
        }
        ui.separator();
        if self.devices.is_empty() {
            ui.label(
                "Устройства не найдены. Подключите устройство по USB и нажмите \
                 «Обновить» — podlib находит iPod по sysfs даже без automount.",
            );
            return;
        }
        egui::ScrollArea::vertical().show(ui, |ui| {
            // Selection is frozen while an operation runs (the worker
            // holds the chosen device).
            if self.busy {
                ui.disable();
            }
            for (index, entry) in self.devices.iter().enumerate() {
                let dev = entry
                    .block_dev
                    .as_deref()
                    .map(|dev| dev.display().to_string())
                    .unwrap_or_else(|| "блочное устройство не определено".to_owned());
                // Unmounted candidates show the planned mount point so
                // the user knows where «Подключить» will put the volume.
                let place = match entry.candidate.kind {
                    device::CandidateKind::Mounted => entry.candidate.mount.display().to_string(),
                    device::CandidateKind::Unmounted => format!(
                        "не смонтирован → будет в {}",
                        entry.candidate.mount.display()
                    ),
                };
                let text = format!("{}\n{}\n{}", entry.candidate.label, place, dev);
                ui.selectable_value(&mut self.selected, Some(index), text);
            }
        });
        ui.separator();
        let ready = !self.busy && self.connected.is_none() && self.selected.is_some();
        if ui
            .add_enabled(ready, egui::Button::new("Подключить"))
            .clicked()
        {
            self.password.clear();
            self.confirm_mount = true;
        }
    }

    /// Top app bar: app name left; device state and the eject button
    /// right. Replaces the old in-panel «podlib» heading.
    fn app_bar(&mut self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            ui.heading("podlib");
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                match self.connected.as_ref() {
                    Some(connected) => {
                        let ready = !self.busy && self.library_idle();
                        if ui
                            .add_enabled(ready, egui::Button::new("Безопасно отключить"))
                            .clicked()
                        {
                            self.password.clear();
                            self.confirm_eject = true;
                        }
                        // WHY a painted circle: there is no stock dot
                        // widget; a 4px filled circle reads as a status dot.
                        let (rect, _) =
                            ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover());
                        ui.painter()
                            .circle_filled(rect.center(), 4.0, egui::Color32::LIGHT_GREEN);
                        ui.label(
                            egui::RichText::new(format!(
                                "{} · {}",
                                connected.label,
                                connected.block_dev.display()
                            ))
                            .weak(),
                        );
                    }
                    None => {
                        ui.label(egui::RichText::new("Нет устройства").weak());
                    }
                }
            });
        });
    }

    /// Bottom status bar: operation progress / last result on the left
    /// (spinner while busy), the error in red — visible until replaced,
    /// with the full text + advice + stderr on hover — and the
    /// add-files hint moved here from the old toolbar.
    fn status_bar(&mut self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            let busy = self.busy || self.library_busy();
            if busy {
                ui.add(egui::Spinner::new());
                ui.label(&self.status);
            } else if !self.status.is_empty() {
                ui.label(&self.status);
            } else if self.error.is_none() {
                // Round 5.3 Ф1: the bar never looks empty/missing —
                // a neutral text keeps its height and presence.
                ui.label(egui::RichText::new("Готово").weak());
            }
            if let Some(error) = &self.error {
                ui.colored_label(egui::Color32::LIGHT_RED, &error.message)
                    .on_hover_text(error_tooltip(error));
            }
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                ui.label(
                    egui::RichText::new("Перетащите аудиофайлы в окно, чтобы добавить")
                        .weak(),
                );
            });
        });
    }

    /// Left sidebar once a device is connected: the master row, the
    /// built-in device views (media-kind filters) and user playlists,
    /// each selectable, with «+ Новый плейлист» at the bottom.
    /// Collects row choices (drop/delete/ПКМ) for post-frame applying.
    fn playlists_sidebar(&mut self, ui: &mut egui::Ui) -> PlaylistPanelActions {
        let menus_allowed = context_menu_allowed(self);
        let Some(library) = self.library.as_mut() else {
            return PlaylistPanelActions::default();
        };
        // Round 8: compact «+» right of the heading opens the existing
        // create modal (same state as the bottom button).
        ui.horizontal(|ui| {
            ui.heading("Плейлисты");
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                let add = ui
                    .small_button("+")
                    .on_hover_text("Новый плейлист");
                if add.clicked() {
                    library.create_open = true;
                    library.new_playlist_name.clear();
                }
            });
        });
        ui.add_space(4.0);
        let ordered = master_first(&library.snapshot.playlists);
        let master = ordered.iter().find(|playlist| playlist.is_master).copied();
        let views: Vec<&Playlist> = ordered
            .iter()
            .copied()
            .filter(|playlist| !playlist.is_master && playlist.distinguished_kind != 0)
            .collect();
        let user: Vec<&Playlist> = ordered
            .iter()
            .copied()
            .filter(|playlist| !playlist.is_master && playlist.distinguished_kind == 0)
            .collect();
        let mut actions = PlaylistPanelActions::default();
        let view_before = library.view;
        // auto_shrink(false): the list reserves the full height so the
        // button below lands at the panel bottom.
        egui::ScrollArea::vertical()
            .auto_shrink(false)
            .show(ui, |ui| {
                if let Some(playlist) = master {
                    actions.merge(playlist_row(
                        ui,
                        &library.snapshot,
                        playlist,
                        &mut library.view,
                        menus_allowed,
                    ));
                }
                if !views.is_empty() {
                    ui.label(egui::RichText::new("Устройство").weak().small());
                    for playlist in &views {
                        actions.merge(playlist_row(
                            ui,
                            &library.snapshot,
                            playlist,
                            &mut library.view,
                            menus_allowed,
                        ));
                    }
                }
                if !user.is_empty() {
                    ui.label(egui::RichText::new("Плейлисты").weak().small());
                    for playlist in &user {
                        actions.merge(playlist_row(
                            ui,
                            &library.snapshot,
                            playlist,
                            &mut library.view,
                            menus_allowed,
                        ));
                    }
                }
            });
        // A context switch must not drag the old table selection along.
        if library.view != view_before {
            library.selected_tracks.clear();
            library.selection_anchor = None;
            library.selected_track = None;
        }
        ui.separator();
        if ui.button("+ Новый плейлист").clicked() {
            library.create_open = true;
            library.new_playlist_name.clear();
        }
        actions
    }

    /// Central panel: toolbar (search + counter + selection actions)
    /// and the track table for the selected sidebar context. Applies
    /// everything it collects itself (borrow discipline: the render
    /// pass holds the library borrow, requests fire afterwards).
    fn library_view(&mut self, ui: &mut egui::Ui) {
        let menus_allowed = context_menu_allowed(self);
        let mut actions = TrackRowActions::default();
        let toolbar;
        {
            let Some(library) = self.library.as_mut() else {
                return;
            };
            let query = library.search_query.clone();
            let view = library.view;
            let cursor = library.selected_track;

            // Visible rows for the selected context: master → the whole
            // library listing, device view → tracks matching its media
            // kinds, user playlist → its members in order (rows that
            // vanished from the library are skipped).
            let (total, visible): (usize, Vec<&Track>) = match view {
                LibraryView::Master => (
                    library.snapshot.tracks.len(),
                    library.snapshot.tracks.iter().collect(),
                ),
                LibraryView::Media { distinguished } => {
                    let kinds = view_media_kinds(distinguished);
                    let matches: Vec<&Track> = library
                        .snapshot
                        .tracks
                        .iter()
                        .filter(|track| kinds.contains(&track.media_kind))
                        .collect();
                    (matches.len(), matches)
                }
                LibraryView::Playlist(id) => {
                    let members: Vec<&Track> = library
                        .snapshot
                        .playlist(id)
                        .map(|playlist| {
                            playlist
                                .unique_track_ids()
                                .into_iter()
                                .filter_map(|member| library.snapshot.track(member))
                                .collect()
                        })
                        .unwrap_or_default();
                    (members.len(), members)
                }
            };
            let filtered: Vec<&Track> = visible
                .iter()
                .copied()
                .filter(|track| matches_query(track, &query))
                .collect();
            // Round 7: `displayed` starts as the filtered list; the
            // flat-list branch re-sorts it (and only it) below, so the
            // grouped views keep their own internal order.
            let mut displayed: Vec<&Track> = filtered;
            let mut visible_ids: Vec<TrackId> = displayed.iter().map(|track| track.id).collect();
            let empty_view = matches!(view, LibraryView::Media { .. }) && total == 0;
            let empty_playlist = matches!(view, LibraryView::Playlist(_)) && total == 0;

            let idle = library.pending.is_none() && library.opening.is_none();
            let ctx = ui.ctx().clone();
            toolbar = search_toolbar(
                ui,
                SearchToolbarParams {
                    ctx: &ctx,
                    query: &mut library.search_query,
                    shown: displayed.len(),
                    total,
                    idle,
                    selection_len: library.selected_tracks.len(),
                    playlist_context: matches!(view, LibraryView::Playlist(_)),
                },
            );
            ui.add_space(4.0);

            // Round 6 П3: the unified view switcher over the
            // grouping-capable sections («Музыка»: список/альбомы/
            // исполнители; «Аудиокниги»: список/книги). The mode is
            // re-read after the switcher — a click applies THIS frame.
            // Search keeps working over every mode: the filter runs
            // before grouping (the grouped views receive `filtered`).
            let switchable = matches!(view, LibraryView::Media { distinguished: 4 | 5 });
            if switchable {
                let distinguished = match view {
                    LibraryView::Media { distinguished } => distinguished,
                    _ => 0,
                };
                let current = if distinguished == 4 {
                    &mut library.music_mode
                } else {
                    &mut library.books_mode
                };
                view_switcher(ui, section_modes(distinguished), current);
                ui.add_space(2.0);
            }
            let mode = match view {
                LibraryView::Media { distinguished: 4 } => library.music_mode,
                LibraryView::Media { distinguished: 5 } => library.books_mode,
                _ => SectionMode::List,
            };
            // Per-context (and per-mode) scroll id: switching sections
            // or modes starts a fresh scroll position.
            let table_id = match view {
                LibraryView::Master => egui::Id::unique(("track_table", 0u64)),
                LibraryView::Media { distinguished } => egui::Id::unique((
                    "track_table",
                    u64::try_from(distinguished.max(0)).unwrap_or(0),
                    mode as u64,
                )),
                LibraryView::Playlist(id) => {
                    egui::Id::unique(("track_table", id.to_bits()))
                }
            };

            if displayed.is_empty() {
                ui.centered_and_justified(|ui| {
                    ui.label(egui::RichText::new(empty_state_text(
                        library.snapshot.tracks.is_empty(),
                        &query,
                        empty_view,
                        empty_playlist,
                    )).weak());
                });
            } else if switchable && mode != SectionMode::List {
                // Grouped views (round 5 books + round 6 П3) share ONE
                // component; each mode keeps its own expanded set.
                let groups = match mode {
                    SectionMode::Albums => group_by_album(displayed.iter().copied()),
                    SectionMode::Artists => group_by_artist(displayed.iter().copied()),
                    _ => group_books(displayed.iter().copied()),
                };
                let expanded = if mode == SectionMode::Books {
                    &mut library.expanded_books
                } else {
                    &mut library.expanded_groups
                };
                actions.merge(groups_view(
                    ui,
                    GroupsViewParams {
                        ctx: &ctx,
                        tracks: &displayed,
                        groups: &groups,
                        selected_tracks: &library.selected_tracks,
                        cursor,
                        menus_allowed,
                        visible_ids: &visible_ids,
                        expanded,
                    },
                ));
            } else {
                // Round 7: the flat list sorts AFTER the filter, BEFORE
                // the render; visible_ids re-derive from the sorted
                // order so row-click indices stay in sync.
                displayed = sort_tracks(displayed, library.track_sort);
                visible_ids = displayed.iter().map(|track| track.id).collect();
                actions.merge(track_table(
                    ui,
                    &displayed,
                    &library.selected_tracks,
                    cursor,
                    view,
                    menus_allowed,
                    table_id,
                    library.track_sort,
                ));
            }

            // Round 7: a header click cycles the sort state (pure
            // [`next_track_sort`]).
            if let Some(column) = actions.sort_toggle.take() {
                library.track_sort = next_track_sort(library.track_sort, column);
            }

            // Row-click / «выбрать все» / checkbox resolution lives in
            // the pure [`resolve_selection_actions`] (review 🟡-3);
            // `cursor` is the value read before rendering and nothing
            // below has touched the field yet, so passing it back is a
            // no-op when no branch moves the cursor.
            let update = resolve_selection_actions(
                &library.selected_tracks,
                library.selection_anchor,
                cursor,
                &visible_ids,
                actions.row_click.take(),
                actions.select_all.take(),
                actions.checkbox_toggle.take(),
            );
            library.selected_tracks = update.selected_tracks;
            library.selection_anchor = update.selection_anchor;
            library.selected_track = update.selected_track;

            // Toolbar actions over the multi-selection.
            let selected = library.selected_tracks.clone();
            if toolbar.edit && selected.len() == 1 {
                let id = selected[0];
                if let Some(track) = library.snapshot.track(id) {
                    library.edit_dialog = Some(EditDialogState {
                        id,
                        fields: EditDialogFields::from_track(track),
                        error: None,
                    });
                }
            }
            if toolbar.add && !selected.is_empty() {
                library.picker_tracks = Some(selected.clone());
            }
            if toolbar.set_artist && !selected.is_empty() {
                library.set_artist_dialog = Some(SetArtistDialog {
                    track_ids: selected.clone(),
                    value: String::new(),
                });
            }
            if toolbar.remove && !selected.is_empty() {
                if let LibraryView::Playlist(playlist_id) = view {
                    self.pending_remove_from_playlist = Some((playlist_id, selected.clone()));
                } else {
                    library.confirm_delete_track = Some(selected.clone());
                    library.purge_media = false;
                }
            }
            drop(selected);

            // Keyboard navigation over the visible (filtered) rows.
            // WHY the focus gate: arrows/Enter in the search box or in
            // a modal TextEdit must keep their native meaning.
            let focused = ui.ctx().memory(|m| m.focused().is_some());
            if !focused {
                let (up, down, enter) = ui.ctx().input(|input| {
                    (
                        input.key_pressed(egui::Key::ArrowUp),
                        input.key_pressed(egui::Key::ArrowDown),
                        input.key_pressed(egui::Key::Enter),
                    )
                });
                if down {
                    if let Some(id) = next_selection(&visible_ids, cursor, 1) {
                        actions.select = Some(id);
                    }
                }
                if up {
                    if let Some(id) = next_selection(&visible_ids, cursor, -1) {
                        actions.select = Some(id);
                    }
                }
                if enter {
                    if let Some(id) = activated(&visible_ids, cursor) {
                        actions.edit = Some(id);
                    }
                }
            }
        }
        // Deferred worker requests (borrow discipline): refresh and the
        // playlist-member removal collected above.
        if toolbar.refresh {
            self.library_request(
                LibraryCommand::Refresh,
                PendingKind::Refresh,
                "Обновляю список…",
            );
        }
        if let Some((playlist, track_ids)) = self.pending_remove_from_playlist.take() {
            self.library_request(
                LibraryCommand::RemoveFromPlaylist {
                    playlist,
                    track_ids,
                },
                PendingKind::RemoveFromPlaylist,
                "Убираю из плейлиста…",
            );
        }
        self.apply_track_actions(actions);
    }

    /// Applies the row choices collected by [`track_table`].
    fn apply_track_actions(&mut self, actions: TrackRowActions) {
        if let Some(id) = actions.select {
            if let Some(library) = self.library.as_mut() {
                library.selected_track = Some(id);
            }
        }
        if let Some(id) = actions.edit {
            if let Some(library) = self.library.as_mut() {
                if let Some(track) = library.snapshot.track(id) {
                    library.edit_dialog = Some(EditDialogState {
                        id,
                        fields: EditDialogFields::from_track(track),
                        error: None,
                    });
                }
            }
        }
        if let Some(track_ids) = actions.add_to_playlist {
            if let Some(library) = self.library.as_mut() {
                library.picker_tracks = Some(track_ids);
            }
        }
        if let Some(id) = actions.delete {
            if let Some(library) = self.library.as_mut() {
                library.confirm_delete_track = Some(vec![id]);
                library.purge_media = false;
            }
        }
        if let Some((playlist, member)) = actions.remove_from_playlist {
            self.library_request(
                LibraryCommand::RemoveFromPlaylist {
                    playlist,
                    track_ids: vec![member],
                },
                PendingKind::RemoveFromPlaylist,
                "Убираю из плейлиста…",
            );
        }
    }

    /// Applies the panel choices collected during the frame.
    fn apply_playlist_actions(&mut self, actions: PlaylistPanelActions) {
        if let Some(name) = actions.master_drop {
            self.error = Some(UiError {
                message: format!("«{name}» — мастер-плейлист: добавлять в него нельзя"),
                hint: Some(
                    "Создайте пользовательский плейлист («+ Плейлист») и бросьте трек на него."
                        .to_owned(),
                ),
                stderr: None,
            });
        }
        if let Some(name) = actions.master_rename {
            // Same honest-refusal pattern as master_drop: the master is
            // the mirror of the library — deletion and renaming are
            // user-playlist operations, explained up front, no round
            // trip to the device.
            self.error = Some(UiError {
                message: format!("«{name}» — мастер-плейлист: его нельзя переименовать или удалить"),
                hint: Some(
                    "Изменять можно только пользовательские плейлисты.".to_owned(),
                ),
                stderr: None,
            });
        }
        if let Some((playlist, track_ids)) = actions.add_drop {
            self.library_request(
                LibraryCommand::AddToPlaylist {
                    playlist,
                    track_ids,
                },
                PendingKind::AddToPlaylist,
                "Добавляю в плейлист…",
            );
        }
        if let Some(id) = actions.rename_playlist {
            // Round 8: every rename/delete flows through the guard, so
            // master/system playlists can never reach the worker even
            // from a future caller of these actions.
            match self.guarded_playlist(id).map(|playlist| playlist.name.clone()) {
                Ok(name) => {
                    if let Some(library) = self.library.as_mut() {
                        library.rename_dialog = Some(RenamePlaylistDialog { id, name });
                    }
                }
                Err(message) => self.refuse_guarded(message),
            }
        }
        if let Some(id) = actions.delete_playlist {
            match self.guarded_playlist(id) {
                Ok(_) => {
                    if let Some(library) = self.library.as_mut() {
                        library.confirm_delete_playlist = Some(id);
                    }
                }
                Err(message) => self.refuse_guarded(message),
            }
        }
    }

    /// Looks a playlist up for a mutation and runs the guard. `Ok``
    /// carries the playlist so the caller can prefill dialogs from it.
    fn guarded_playlist(&self, id: PlaylistId) -> Result<&Playlist, String> {
        let library = self.library.as_ref().ok_or_else(|| {
            "Сначала подключите устройство".to_owned()
        })?;
        let playlist = library
            .snapshot
            .playlist(id)
            .ok_or_else(|| format!("Плейлист не найден (id {id})"))?;
        guard_playlist_mutation(playlist)?;
        Ok(playlist)
    }

    /// Shows a guard refusal as the standard error notice.
    fn refuse_guarded(&mut self, message: String) {
        self.error = Some(UiError {
            message,
            hint: Some(
                "Изменять можно только пользовательские плейлисты.".to_owned(),
            ),
            stderr: None,
        });
    }

    // ---- file drag-and-drop from the file manager ----

    fn collect_dropped_files(&mut self, ui: &egui::Ui) {
        // Copy the paths immediately: egui owns them for this frame only.
        let dropped: Vec<PathBuf> = ui
            .input(|input| {
                input
                    .raw
                    .dropped_files
                    .iter()
                    // path() is infallible on native (&Path, not Option).
                    .map(|file| PathBuf::from(file.path()))
                    .collect()
            });
        if dropped.is_empty() {
            return;
        }
        // Round 5.1 diagnostics (permanent): does winit deliver
        // Wayland drops at all, and how do they map to drafts? The
        // output lands in podlib-gui.log when run redirected.
        let names: Vec<String> = dropped
            .iter()
            .map(|path| path.display().to_string())
            .collect();
        eprintln!("[dnd] dropped {} file(s): {:?}", dropped.len(), names);
        let (drafts, skipped) = drafts_from_paths(&dropped);
        eprintln!(
            "[dnd] drafts {} ({} for transcode), skipped {}",
            drafts.len(),
            drafts
                .iter()
                .filter(|draft| needs_transcode(&path_extension(&draft.source_path)))
                .count(),
            skipped.len()
        );
        // Round 5.5: while the review modal is open new drops are
        // ignored (the user is mid-edit; dispatching behind their back
        // would lose the reviewed tags).
        if self.tag_review.is_some() {
            return;
        }
        if drafts.is_empty() {
            if !skipped.is_empty() {
                self.status = format!("Пропущены не-аудио файлы: {}", skipped.join(", "));
            }
            return;
        }
        let transcodes = drafts
            .iter()
            .filter(|draft| needs_transcode(&path_extension(&draft.source_path)))
            .count();
        // Round 5.5: any untagged draft in the batch opens the review
        // modal for the WHOLE batch instead of dispatching blind.
        if drafts.iter().any(is_untagged) {
            eprintln!(
                "[dnd] tag review opened ({} untagged of {})",
                drafts.iter().filter(|draft| is_untagged(draft)).count(),
                drafts.len()
            );
            self.tag_review = Some(open_tag_review(drafts));
            return;
        }
        let status = batch_add_status(drafts.len(), transcodes, &skipped);
        self.library_request(
            LibraryCommand::AddTracks(drafts),
            PendingKind::AddTracks,
            &status,
        );
    }

    // ---- modals ----

    /// F4: intercepts the OS close request while an operation is in
    /// flight, cancels it and opens the confirmation modal instead.
    /// Documented eframe 0.37 pattern: check
    /// `ctx.input(|i| i.viewport().close_requested())` during the frame
    /// and answer with `ViewportCommand::CancelClose`.
    fn guard_close_request(&mut self, ui: &egui::Ui) {
        let close_requested = ui.input(|input| input.viewport().close_requested());
        let operation_active = self.busy || self.library_busy();
        if close_decision(
            close_requested,
            operation_active,
            self.force_close,
            self.mounted_by_us,
        ) == CloseDecision::BlockWithConfirm
        {
            // CancelClose must be sent during this frame, or eframe exits.
            ui.ctx().send_viewport_cmd(egui::ViewportCommand::CancelClose);
            self.confirm_close = true;
        }
    }

    fn maybe_mount_modal(&mut self, ctx: &egui::Context) {
        if !self.confirm_mount {
            return;
        }
        let decision = password_modal(
            ctx,
            "confirm_mount",
            &mut self.password,
            "Подключить устройство (запись)",
            "Система монтирует том HFS+ только для чтения; для записи нужен \
             повторный mount с force. Пароль sudo нужен, потому что \
             монтирование — системное действие; он передаётся напрямую \
             команде sudo и нигде не сохраняется.",
            "Подключить",
        );
        if decision == PasswordModal::Confirmed {
            self.start_mount = true; // act after the frame (borrow rules)
        }
        if decision != PasswordModal::Open {
            self.confirm_mount = false;
        }
    }

    fn maybe_eject_modal(&mut self, ctx: &egui::Context) {
        if !self.confirm_eject {
            return;
        }
        // Round 6.1: power-off runs under sudo, so disconnect asks for
        // the same password as connect — one shared modal.
        let decision = password_modal(
            ctx,
            "confirm_eject",
            &mut self.password,
            "Безопасно отключить устройство?",
            "Будут выполнены: закрытие библиотеки, sync, unmount (с др\
             ейном слоёв) и power-off под sudo. Убедитесь, что операции \
             записи завершены. Пароль передаётся напрямую команде sudo и \
             нигде не сохраняется.",
            "Отключить",
        );
        if decision == PasswordModal::Confirmed {
            self.start_eject = true;
        }
        // Batch F: cancelling the eject also cancels the close that asked
        // for it — the window stays, and the deferred path cannot re-open
        // this modal every idle frame.
        if decision == PasswordModal::Cancelled && self.pending_close_after_eject {
            self.pending_close_after_eject = false;
        }
        if decision != PasswordModal::Open {
            self.confirm_eject = false;
        }
    }

    /// A close requested mid-operation (round 5.3) fires its eject as soon
    /// as the app goes idle again. Batch F (round 6.1 F3): the eject opens
    /// the shared password modal instead of starting directly — the direct
    /// start ran sudo on an empty password. Opening is harmless while the
    /// modal is already up; cancellation clears `pending_close_after_eject`
    /// (see `maybe_eject_modal`), so the prompt cannot loop.
    fn maybe_deferred_close_eject(&mut self) {
        if deferred_eject_due(self.pending_close_after_eject, self.busy, self.library_idle()) {
            self.confirm_eject = true;
        }
    }

    /// F4: asks before closing the window mid-operation. Confirming
    /// sends `ViewportCommand::Close`, which surfaces as a fresh close
    /// request the guard lets through (`force_close`).
    fn maybe_close_confirm_modal(&mut self, ctx: &egui::Context) {
        if !self.confirm_close {
            return;
        }
        let mut confirmed = false;
        let (title, body) = close_confirm_texts(self.busy || self.library_busy());
        let response = egui::Modal::new(egui::Id::unique("confirm_close")).show(ctx, |ui| {
            ui.set_width(440.0);
            ui.heading(title);
            ui.add_space(4.0);
            ui.label(body);
            ui.separator();
            // Enter confirms the primary action («Закрыть») at the
            // input level, regardless of focus — the same pattern as
            // the password modal (round 6.1 F3).
            if ui.input(|input| input.key_pressed(egui::Key::Enter)) {
                confirmed = true;
                ui.close();
            }
            ui.horizontal(|ui| {
                if ui.button("Отмена").clicked() {
                    ui.close();
                }
                if ui.button("Закрыть").clicked() {
                    confirmed = true;
                    ui.close();
                }
            });
        });
        if confirmed || response.should_close() {
            self.confirm_close = false;
        }
        if confirmed {
            self.apply_close_confirmation(ctx);
        }
    }

    /// What a confirmed window close does (round 5.3): a device mounted
    /// by this app run is ejected first — through the password modal
    /// (batch F), never a direct start with an empty password; a busy
    /// worker defers the eject until the app goes idle. Anything else
    /// closes immediately.
    fn apply_close_confirmation(&mut self, ctx: &egui::Context) {
        match close_confirmation_action(self.mounted_by_us) {
            CloseAction::EjectFirst => {
                self.pending_close_after_eject = true;
                if deferred_eject_due(true, self.busy, self.library_idle()) {
                    self.confirm_eject = true;
                }
            }
            CloseAction::CloseNow => {
                self.force_close = true;
                ctx.send_viewport_cmd(egui::ViewportCommand::Close);
            }
        }
    }

    /// Delete confirmation for one row or a multi-selection (Ф3).
    /// Confirming queues every id: the worker protocol allows one
    /// command in flight, so the chain continues on each Applied
    /// outcome (see `continue_delete_chain`).
    fn maybe_delete_track_modal(&mut self, ctx: &egui::Context) {
        let Some(track_ids) = self
            .library
            .as_ref()
            .and_then(|library| library.confirm_delete_track.clone())
        else {
            return;
        };
        let title_line = if track_ids.len() == 1 {
            let title = self
                .library
                .as_ref()
                .and_then(|library| library.snapshot.track(track_ids[0]))
                .map(|track| track.title.clone())
                .unwrap_or_default();
            format!("Удалить трек «{title}»?")
        } else {
            let count = track_ids.len();
            format!(
                "Удалить {} {}?",
                count,
                plural(count, "трек", "трека", "треков")
            )
        };
        let mut confirmed = false;
        let response = egui::Modal::new(egui::Id::unique("confirm_delete_track")).show(ctx, |ui| {
            ui.set_width(440.0);
            ui.heading(title_line);
            ui.add_space(4.0);
            ui.label("Треки исчезнут из библиотеки и всех плейлистов.");
            if let Some(library) = self.library.as_mut() {
                // The checkbox lives in the state so it survives frames.
                let label = if track_ids.len() == 1 {
                    "Удалить и медиа-файл с устройства"
                } else {
                    "Удалить и медиа-файлы с устройства"
                };
                ui.checkbox(&mut library.purge_media, label);
            }
            ui.label(
                egui::RichText::new(
                    "Без галочки аудиофайлы останутся на диске как «осиротевшие».",
                )
                .weak(),
            );
            ui.separator();
            // Enter confirms the primary action («Удалить») at the
            // input level, regardless of focus — the same pattern as
            // the password modal (round 6.1 F3).
            if ui.input(|input| input.key_pressed(egui::Key::Enter)) {
                confirmed = true;
                ui.close();
            }
            ui.horizontal(|ui| {
                if ui.button("Отмена").clicked() {
                    ui.close();
                }
                if ui.button("Удалить").clicked() {
                    confirmed = true;
                    ui.close();
                }
            });
        });
        if confirmed || response.should_close() {
            if let Some(library) = self.library.as_mut() {
                library.confirm_delete_track = None;
            }
        }
        if confirmed {
            let purge = self
                .library
                .as_ref()
                .map(|library| library.purge_media)
                .unwrap_or(false);
            let (first, rest) = match track_ids.split_first() {
                Some((first, rest)) => (*first, rest.to_vec()),
                None => return,
            };
            if let Some(library) = self.library.as_mut() {
                library.delete_queue = rest;
            }
            self.library_request(
                LibraryCommand::RemoveTrack {
                    id: first,
                    purge_media: purge,
                },
                PendingKind::RemoveTrack,
                "Удаляю трек…",
            );
        }
    }

    fn maybe_delete_playlist_modal(&mut self, ctx: &egui::Context) {
        let Some(playlist_id) = self
            .library
            .as_ref()
            .and_then(|library| library.confirm_delete_playlist)
        else {
            return;
        };
        let name = self
            .library
            .as_ref()
            .and_then(|library| library.snapshot.playlist(playlist_id))
            .map(|playlist| playlist.name.clone())
            .unwrap_or_default();
        let mut confirmed = false;
        let response =
            egui::Modal::new(egui::Id::unique("confirm_delete_playlist")).show(ctx, |ui| {
                ui.set_width(400.0);
                ui.heading(format!("Удалить плейлист «{name}»?"));
                ui.add_space(4.0);
                ui.label("Сами треки останутся в библиотеке.");
                ui.separator();
                // Enter confirms the primary action («Удалить») at the
                // input level, regardless of focus — the same pattern as
                // the password modal (round 6.1 F3).
                if ui.input(|input| input.key_pressed(egui::Key::Enter)) {
                    confirmed = true;
                    ui.close();
                }
                ui.horizontal(|ui| {
                    if ui.button("Отмена").clicked() {
                        ui.close();
                    }
                    if ui.button("Удалить").clicked() {
                        confirmed = true;
                        ui.close();
                    }
                });
            });
        if confirmed || response.should_close() {
            if let Some(library) = self.library.as_mut() {
                library.confirm_delete_playlist = None;
            }
        }
        if confirmed {
            self.library_request(
                LibraryCommand::DeletePlaylist { id: playlist_id },
                PendingKind::DeletePlaylist,
                "Удаляю плейлист…",
            );
        }
    }

    fn maybe_create_playlist_modal(&mut self, ctx: &egui::Context) {
        if !self.library.as_ref().is_some_and(|library| library.create_open) {
            return;
        }
        let mut confirmed = false;
        let mut name = String::new();
        let response = egui::Modal::new(egui::Id::unique("create_playlist")).show(ctx, |ui| {
            ui.set_width(380.0);
            ui.heading("Новый плейлист");
            ui.add_space(4.0);
            let Some(library) = self.library.as_mut() else {
                return;
            };
            ui.horizontal(|ui| {
                ui.label("Название:");
                let name = ui.add(
                    egui::TextEdit::singleline(&mut library.new_playlist_name)
                        .desired_width(240.0),
                );
                text_menu::attach_text_menu(&name);
            });
            name = library.new_playlist_name.clone();
            ui.separator();
            ui.horizontal(|ui| {
                if ui.button("Отмена").clicked() {
                    ui.close();
                }
                let ready = !library.new_playlist_name.trim().is_empty();
                if ui.add_enabled(ready, egui::Button::new("Создать")).clicked() {
                    confirmed = true;
                    ui.close();
                }
            });
        });
        if confirmed || response.should_close() {
            if let Some(library) = self.library.as_mut() {
                library.create_open = false;
            }
        }
        if confirmed && !name.trim().is_empty() {
            self.library_request(
                LibraryCommand::CreatePlaylist { name },
                PendingKind::CreatePlaylist,
                "Создаю плейлист…",
            );
        }
    }

    /// Round 8: «Переименовать плейлист», opened from the sidebar
    /// context menu. Same shape as the create modal, but the field is
    /// prefilled and Enter saves (the primary action) whenever the name
    /// is non-empty and actually changed — an unchanged/blank name keeps
    /// the dialog open instead of a pointless round trip.
    fn maybe_rename_playlist_modal(&mut self, ctx: &egui::Context) {
        let Some(library) = self.library.as_ref() else {
            return;
        };
        let Some(dialog) = library.rename_dialog.as_ref() else {
            return;
        };
        // The ready check needs the current name from the snapshot; both
        // values are copied out before the modal borrows `self` mutably.
        let dialog_id = dialog.id;
        let current_name = library
            .snapshot
            .playlist(dialog_id)
            .map(|playlist| playlist.name.clone());
        let mut confirmed = false;
        let mut typed = String::new();
        let response = egui::Modal::new(egui::Id::unique("rename_playlist")).show(ctx, |ui| {
            ui.set_width(380.0);
            ui.heading("Переименовать плейлист");
            ui.add_space(4.0);
            let Some(library) = self.library.as_mut() else {
                return;
            };
            let Some(dialog) = library.rename_dialog.as_mut() else {
                return;
            };
            ui.horizontal(|ui| {
                ui.label("Название:");
                let name = ui.add(
                    egui::TextEdit::singleline(&mut dialog.name)
                        .desired_width(240.0),
                );
                text_menu::attach_text_menu(&name);
            });
            typed = dialog.name.clone();
            ui.separator();
            // Enter confirms the primary action («Сохранить») only when
            // the name is real and different — the same rule the button
            // uses (D2 convention, as the confirm modals).
            let ready = !typed.trim().is_empty()
                && current_name.as_deref() != Some(typed.trim());
            if ready && ui.input(|input| input.key_pressed(egui::Key::Enter)) {
                confirmed = true;
                ui.close();
            }
            ui.horizontal(|ui| {
                if ui.button("Отмена").clicked() {
                    ui.close();
                }
                if ui
                    .add_enabled(ready, egui::Button::new("Сохранить"))
                    .clicked()
                {
                    confirmed = true;
                    ui.close();
                }
            });
        });
        if confirmed || response.should_close() {
            if let Some(library) = self.library.as_mut() {
                library.rename_dialog = None;
            }
        }
        if confirmed {
            let name = typed.trim().to_owned();
            self.library_request(
                LibraryCommand::RenamePlaylist {
                    id: dialog_id,
                    name,
                },
                PendingKind::RenamePlaylist,
                "Переименовываю плейлист…",
            );
        }
    }

    /// Batch «Задать исполнителя» over the multi-selection (round 6.3).
    /// One SetArtist command carries the whole batch — the worker loops
    /// ids and reports the honest per-id tail. An empty (whitespace
    /// only) value disables «Присвоить»: the domain treats a blank
    /// artist as «no value», so confirming would be a silent no-op.
    fn maybe_set_artist_modal(&mut self, ctx: &egui::Context) {
        let Some(dialog) = self
            .library
            .as_ref()
            .and_then(|library| library.set_artist_dialog.clone())
        else {
            return;
        };
        let count = dialog.track_ids.len();
        let mut confirmed = false;
        let mut artist = String::new();
        let response = egui::Modal::new(egui::Id::unique("set_artist")).show(ctx, |ui| {
            ui.set_width(440.0);
            let Some(library) = self.library.as_mut() else {
                return;
            };
            let Some(dialog) = library.set_artist_dialog.as_mut() else {
                return;
            };
            // The typed value appears in the heading as soon as it is
            // non-empty, mirroring the quoted-entity style of the delete
            // confirmation («Удалить трек «X»?»).
            let value_trimmed = dialog.value.trim().to_owned();
            if value_trimmed.is_empty() {
                ui.heading(format!(
                    "Присвоить исполнителя выбранным трекам ({count})?"
                ));
            } else {
                ui.heading(format!(
                    "Присвоить исполнителя «{value_trimmed}» выбранным трекам ({count})?"
                ));
            }
            ui.add_space(4.0);
            ui.horizontal(|ui| {
                ui.label("Исполнитель:");
                let field = ui.add(
                    egui::TextEdit::singleline(&mut dialog.value)
                        .hint_text("Артист")
                        .desired_width(300.0),
                );
                text_menu::attach_text_menu(&field);
                field.request_focus();
            });
            // N1: the command carries the TRIMMED value — the header and
            // the readiness gate both use the trimmed form, so an
            // untrimmed send would store an artist invisible to the user.
            artist = dialog.value.trim().to_owned();
            ui.separator();
            // Enter confirms at the input level regardless of focus —
            // the password-modal pattern (round 6.1 F3).
            let ready = !artist.trim().is_empty();
            if ready && ui.input(|input| input.key_pressed(egui::Key::Enter)) {
                confirmed = true;
                ui.close();
            }
            ui.horizontal(|ui| {
                if ui.button("Отмена").clicked() {
                    ui.close();
                }
                if ui.add_enabled(ready, egui::Button::new("Присвоить")).clicked() {
                    confirmed = true;
                    ui.close();
                }
            });
        });
        if confirmed || response.should_close() {
            if let Some(library) = self.library.as_mut() {
                library.set_artist_dialog = None;
            }
        }
        if confirmed && !artist.trim().is_empty() {
            self.library_request(
                LibraryCommand::SetArtist {
                    track_ids: dialog.track_ids,
                    artist,
                },
                PendingKind::SetArtist,
                "Задаю исполнителя…",
            );
        }
    }
    fn maybe_edit_track_modal(&mut self, ctx: &egui::Context) {
        if !self
            .library
            .as_ref()
            .is_some_and(|library| library.edit_dialog.is_some())
        {
            return;
        }
        let mut save = false;
        let response = egui::Modal::new(egui::Id::unique("edit_track")).show(ctx, |ui| {
            ui.set_width(500.0);
            ui.heading("Изменить трек");
            ui.add_space(4.0);
            ui.label(
                egui::RichText::new(
                    "Жанр не редактируется: библиотека не отдаёт его при чтении, \
                     и правка перезаписала бы его пустым значением.",
                )
                .weak(),
            );
            ui.add_space(4.0);
            let Some(library) = self.library.as_mut() else {
                return;
            };
            let Some(dialog) = library.edit_dialog.as_mut() else {
                return;
            };
            save = edit_track_dialog_fields(ui, dialog);
        });
        if !(save || response.should_close()) {
            return; // still open, nothing to apply
        }
        self.apply_edit_track_dialog(save);
    }

    /// Closes/commits the edit dialog: takes it out (the id survives by
    /// contract while the dialog stays open), diffs the fields and then
    /// sends EditTrack — or reopens with the validation error.
    fn apply_edit_track_dialog(&mut self, save: bool) {
        // Take the dialog out to work without nested borrows.
        let Some(library) = self.library.as_mut() else {
            return;
        };
        let Some(dialog) = library.edit_dialog.take() else {
            return;
        };
        if !save {
            return; // plain close: no request, id is untouched
        }
        let attempt = library
            .snapshot
            .track(dialog.id)
            .map(|track| changes_from_track(track, &dialog.fields));
        match attempt {
            // Unchanged dialog → no request, so the id survives by contract.
            Some(Ok(changes)) if changes.is_empty() => {
                self.status = "Изменений нет".to_owned();
            }
            Some(Ok(changes)) => {
                self.library_request(
                    LibraryCommand::EditTrack {
                        id: dialog.id,
                        changes,
                    },
                    PendingKind::EditTrack,
                    "Сохраняю изменения…",
                );
            }
            // Validation failure: reopen with the inline error.
            Some(Err(message)) => {
                if let Some(library) = self.library.as_mut() {
                    library.edit_dialog = Some(EditDialogState {
                        error: Some(message),
                        ..dialog
                    });
                }
            }
            // The track vanished between frames; keep the dialog closed.
            None => {}
        }
    }

    /// Applies the reviewed tags (round 5.5): dispatches the edited
    /// drafts through the regular AddTracks pipeline and closes the
    /// modal. An empty book title keeps the modal open with the
    /// near-field error (validation_attempted); an apply error lands
    /// in the status bar honestly, and a refused request (busy, no
    /// device) keeps the modal open with the typed tags.
    fn commit_tag_review(&mut self) {
        let Some(review) = self.tag_review.as_mut() else {
            return;
        };
        review.validation_attempted = true;
        if review.book_title.trim().is_empty() {
            return; // near-field error is rendered by the modal
        }
        // Kind-aware validation text (round 6 tail nit-8).
        let texts = tag_review_texts(review.kind_bits);
        match apply_tag_review(
            &review.drafts,
            &review.book_title,
            &review.author,
            &review.rows,
            texts.empty_title,
        ) {
            Ok(drafts) => {
                let transcodes = drafts
                    .iter()
                    .filter(|draft| needs_transcode(&path_extension(&draft.source_path)))
                    .count();
                let status = batch_add_status(drafts.len(), transcodes, &[]);
                // Send first, close on success only: a refusal keeps
                // the modal with the typed tags; the error itself is
                // already shown by library_request.
                if self.library_request(
                    LibraryCommand::AddTracks(drafts),
                    PendingKind::AddTracks,
                    &status,
                ) {
                    self.tag_review = None;
                }
            }
            Err(message) => {
                self.tag_review = None;
                self.error = Some(UiError {
                    message,
                    hint: None,
                    stderr: None,
                });
            }
        }
    }

    /// Round 5.5: the tag-review modal — common book/author fields and
    /// an inline per-file table (№, editable title, file name), the
    /// shared-prefix checkbox and honest near-field validation.
    fn maybe_tag_review_modal(&mut self, ctx: &egui::Context) {
        if self.tag_review.is_none() {
            return;
        }
        let mut cancelled = false;
        let mut committed = false;
        let response = egui::Modal::new(egui::Id::unique("tag_review_modal")).show(ctx, |ui| {
            let Some(review) = self.tag_review.as_mut() else {
                return;
            };
            // Kind-aware texts (round 6 tail nit-8): audiobooks speak
            // «книга/автор», music «альбом/исполнитель».
            let texts = tag_review_texts(review.kind_bits);
            let title = format!(
                "Добавление {}: проверьте теги ({} файлов)",
                texts.subject,
                review.rows.len()
            );
            ui.set_width(560.0);
            ui.heading(title);
            ui.add_space(4.0);
            ui.label("Общее для всех файлов");
            ui.horizontal(|ui| {
                ui.label(texts.title_field);
                let book_title = ui.add(
                    egui::TextEdit::singleline(&mut review.book_title)
                        .desired_width(320.0),
                );
                text_menu::attach_text_menu(&book_title);
            });
            if review.validation_attempted && review.book_title.trim().is_empty() {
                ui.colored_label(egui::Color32::LIGHT_RED, texts.empty_title);
            }
            ui.horizontal(|ui| {
                ui.label(texts.author_field);
                let author = ui.add(
                    egui::TextEdit::singleline(&mut review.author).desired_width(320.0),
                );
                text_menu::attach_text_menu(&author);
            });
            ui.add_space(6.0);
            if let Some(prefix) = review.prefix.clone() {
                if ui
                    .checkbox(
                        &mut review.strip_prefix,
                        format!("Убрать общий префикс из названий: «{prefix}»"),
                    )
                    .changed()
                {
                    // nit-9: only rows still showing the previous
                    // automatic value are re-derived — manual edits in
                    // the title column survive the toggle.
                    retoggle_prefix_titles(&mut review.rows, &prefix, review.strip_prefix);
                }
            }
            ui.label("Файлы — проверьте названия (Tab — переход между полями):");
            // Round 5.7 bug 2: NO dnd wrapper here — an empty-payload
            // drag source sat on top of the row and swallowed mouse
            // clicks, so the title TextEdit could only be focused via
            // Tab. Rows render directly; the focused TextEdit IS the
            // row selection («файл за файлом»).
            if review.row_rects.len() != review.rows.len()
                || review.row_edit_ids.len() != review.rows.len()
                || review.row_edit_rects.len() != review.rows.len()
            {
                review.row_rects = vec![egui::Rect::NOTHING; review.rows.len()];
                review.row_edit_ids = vec![egui::Id::NULL; review.rows.len()];
                review.row_edit_rects = vec![egui::Rect::NOTHING; review.rows.len()];
            }
            let focused_row: Cell<Option<usize>> = Cell::new(None);
            egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
                for (index, row) in review.rows.iter_mut().enumerate() {
                    let selected = review.selected_row == Some(index);
                    let row_area = ui.allocate_ui(
                        egui::vec2(ui.available_width(), 24.0),
                        |ui| {
                            if selected {
                                ui.painter().rect_filled(
                                    ui.max_rect(),
                                    2.0,
                                    ui.visuals().selection.bg_fill,
                                );
                            }
                            ui.horizontal(|ui| {
                                ui.label(format!("{:>2}.", row.track_number));
                                let title = ui.add(
                                    egui::TextEdit::singleline(&mut row.title)
                                        .desired_width(300.0)
                                        .id_salt(("tag_review_title", index)),
                                );
                                text_menu::attach_text_menu(&title);
                                review.row_edit_ids[index] = title.id;
                                review.row_edit_rects[index] = title.rect;
                                if title.has_focus() {
                                    focused_row.set(Some(index));
                                }
                                let file = &review.files[index];
                                ui.add(
                                    egui::Label::new(
                                        egui::RichText::new(file).weak().small(),
                                    )
                                    .truncate(),
                                )
                                .on_hover_text(file);
                            });
                        },
                    );
                    review.row_rects[index] = row_area.response.rect;
                    if row_area.response.clicked() {
                        review.selected_row = Some(index);
                    }
                }
            });
            // Keyboard navigation («файл за файлом») keeps the row
            // highlighted as long as its editor holds focus.
            if let Some(index) = focused_row.get() {
                review.selected_row = Some(index);
            }
            ui.separator();
            ui.horizontal(|ui| {
                if ui.button("Отмена").clicked() {
                    cancelled = true;
                    ui.close();
                }
                if ui.button(texts.add_button).clicked() {
                    review.validation_attempted = true;
                    if !review.book_title.trim().is_empty() {
                        committed = true;
                        ui.close();
                    }
                }
            });
        });
        // Round 5.7 bug 1: «Добавить книгу» sets committed AND calls
        // ui.close(), so should_close() is true in the SAME frame —
        // the old cancel-first order cleared the review before the
        // commit ran, and the dispatch never left the app. The commit
        // branch must be processed first.
        self.finish_tag_review_frame(committed, response.should_close(), cancelled);
    }

    /// Single decision point of the tag-review modal frame: a commit
    /// outranks a cancel/close (a click on «Добавить книгу» closes the
    /// modal in the same frame), otherwise any close/cancel drops the
    /// draft edits intentionally.
    fn finish_tag_review_frame(&mut self, committed: bool, should_close: bool, cancelled: bool) {
        if committed {
            self.commit_tag_review();
        } else if cancelled || should_close {
            self.tag_review = None;
        }
    }

    fn maybe_add_to_playlist_modal(&mut self, ctx: &egui::Context) {
        if !self
            .library
            .as_ref()
            .is_some_and(|library| library.picker_tracks.is_some())
        {
            return;
        }
        // Snapshot the choices so the modal closure stays borrow-free.
        let playlists: Vec<Playlist> = self
            .library
            .as_ref()
            .map(|library| library.snapshot.playlists.clone())
            .unwrap_or_default();
        let mut chosen: Option<PlaylistId> = None;
        let response = egui::Modal::new(egui::Id::unique("add_to_playlist")).show(ctx, |ui| {
            ui.set_width(360.0);
            ui.heading("Добавить в плейлист");
            ui.add_space(4.0);
            egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
                for playlist in &playlists {
                    let guarded = guard_playlist_mutation(playlist).is_err();
                    let label = if guarded {
                        format!("{} (нельзя)", playlist.name)
                    } else {
                        playlist.name.clone()
                    };
                    let width = ui.available_width() - 8.0;
                    if ui
                        .add_enabled(
                            !guarded,
                            egui::Button::new(label).min_size([width, 26.0].into()),
                        )
                        .clicked()
                    {
                        chosen = Some(playlist.id);
                        ui.close();
                    }
                }
            });
        });
        let (picker_after_close, add_request) = picker_close(
            chosen,
            response.should_close(),
            self.library.as_ref().and_then(|l| l.picker_tracks.clone()),
        );
        if let Some(library) = self.library.as_mut() {
            library.picker_tracks = picker_after_close;
        }
        if let Some((playlist, track_ids)) = add_request {
            self.library_request(
                LibraryCommand::AddToPlaylist {
                    playlist,
                    track_ids,
                },
                PendingKind::AddToPlaylist,
                "Добавляю в плейлист…",
            );
        }
    }
}

/// Snapshot of picker state after a close attempt: the new picker contents
/// (None = cleared) and, if a playlist was chosen, the (playlist, ids)
/// request payload. Ids are captured BEFORE the clear — see picker_close.
type PickerCloseResult = (
    Option<Vec<TrackId>>,
    Option<(PlaylistId, Vec<TrackId>)>,
);

/// Pure close-handling for the add-to-playlist picker. Track ids are
/// captured from the snapshot BEFORE the picker state clears: the previous
/// inline order cleared first and read after, so the worker received an
/// empty Vec and the UI claimed «Добавлено 0 треков» for a real request.
fn picker_close(
    chosen: Option<PlaylistId>,
    should_close: bool,
    picker_tracks: Option<Vec<TrackId>>,
) -> PickerCloseResult {
    let track_ids = picker_tracks.clone().unwrap_or_default();
    let cleared = chosen.is_some() || should_close;
    let state = if cleared { None } else { picker_tracks };
    let request = chosen.map(|playlist| (playlist, track_ids));
    (state, request)
}

/// Status line shown while a batch add runs (P4). The worker protocol
/// is one command → one reply, so per-file progress («Перекодирую i/M…»)
/// would require extending `LibraryCommand`/`LibraryOutcome` — and the
/// backend trait contract is out of bounds. Instead the wait is
/// announced honestly up front — including how many files need an
/// ffmpeg transcode (round 5.2) — meanwhile every button/menu is
/// disabled by the idle gates and the spinner shows in the status area.
fn batch_add_status(count: usize, transcode_count: usize, skipped: &[String]) -> String {
    let transcode_note = if transcode_count > 0 {
        format!(" ({transcode_count} с транскодом)")
    } else {
        String::new()
    };
    let mut status = format!(
        "Добавляется {} {}{}, это может занять время…",
        count,
        plural(count, "файл", "файла", "файлов"),
        transcode_note
    );
    if !skipped.is_empty() {
        status.push_str(&format!("; пропущены: {}", skipped.join(", ")));
    }
    status
}

// ---- round 4 UX: pure helpers (tested) ----

/// Case-insensitive substring search over title/artist/album. An empty
/// or blank query matches everything (the filter is off).
fn matches_query(track: &Track, query: &str) -> bool {
    let query = query.trim().to_lowercase();
    if query.is_empty() {
        return true;
    }
    [track.title.as_str()]
        .into_iter()
        .chain(track.artist.iter().map(String::as_str))
        .chain(track.album.iter().map(String::as_str))
        .any(|field| field.to_lowercase().contains(&query))
}

/// Sidebar ordering: the master playlist first, everything else keeps
/// its snapshot order (stable sort).
fn master_first(playlists: &[Playlist]) -> Vec<&Playlist> {
    let mut ordered: Vec<&Playlist> = playlists.iter().collect();
    ordered.sort_by_key(|playlist| !playlist.is_master);
    ordered
}

/// Next selection moving `delta` rows through the visible (filtered)
/// list, clamped at the edges. A stale or missing selection restarts
/// from the first row; an empty list selects nothing.
fn next_selection(visible: &[TrackId], current: Option<TrackId>, delta: isize) -> Option<TrackId> {
    if visible.is_empty() {
        return None;
    }
    let index = current
        .and_then(|id| visible.iter().position(|&candidate| candidate == id))
        .map_or(0, |index| {
            (index as isize + delta).clamp(0, visible.len() as isize - 1) as usize
        });
    Some(visible[index])
}

/// Enter activation: works only when the selection is actually visible.
fn activated(visible: &[TrackId], current: Option<TrackId>) -> Option<TrackId> {
    match current {
        Some(id) if visible.contains(&id) => Some(id),
        _ => None,
    }
}

/// Toolbar counter: «{N} треков», or «{N} из {total}» while filtering.
fn tracks_counter(shown: usize, total: usize, query: &str) -> String {
    if query.trim().is_empty() {
        format!(
            "{} {}",
            total,
            plural(total, "трек", "трека", "треков")
        )
    } else {
        format!("{} из {}", shown, total)
    }
}

// ---- round 4.1: view contexts and selection (pure helpers, tested) ----

/// What the central table shows (round 4.1 Ф2).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum LibraryView {
    /// Whole library listing (master view) — the default.
    #[default]
    Master,
    /// Built-in device view (firmware section) by `distinguished_kind`.
    Media { distinguished: i64 },
    /// A user playlist.
    Playlist(PlaylistId),
}

// ---- round 6 П3: section view modes ----

/// Display mode of a section's central panel. The switcher itself is
/// ONE component reused by every grouping-capable section; playlists
/// and the master stay flat lists (and never render it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum SectionMode {
    /// Flat track table (with the checkbox column).
    #[default]
    List,
    /// Grouped by album («Музыка»).
    Albums,
    /// Grouped by artist («Музыка»).
    Artists,
    /// Grouped by book = album («Аудиокниги», round 5 default).
    Books,
}

impl SectionMode {
    /// Switcher label.
    fn label(self) -> &'static str {
        match self {
            Self::List => "Список",
            Self::Albums => "Альбомы",
            Self::Artists => "Исполнители",
            Self::Books => "Книги",
        }
    }
}

/// Switcher modes of a built-in device view, in display order:
/// «Музыка» offers список/альбомы/исполнители, «Аудиокниги»
/// список/книги, the rest just the flat list (the switcher is not
/// rendered for them).
fn section_modes(distinguished_kind: i64) -> &'static [SectionMode] {
    match distinguished_kind {
        4 => &[SectionMode::List, SectionMode::Albums, SectionMode::Artists],
        5 => &[SectionMode::List, SectionMode::Books],
        _ => &[SectionMode::List],
    }
}

// ---- round 7: column sort of the flat track table ----

/// Sortable column of the track table header.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TrackSortColumn {
    Title,
    Artist,
    Album,
    Duration,
}

/// Active column sort (round 7). Pure UI state: it lives in
/// [`LibraryUi`] and is never written to the device.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct TrackSort {
    column: TrackSortColumn,
    descending: bool,
}

/// Header-click cycle (round 7): first click sorts ascending, the
/// second descending, the third returns to the default order. WHY the
/// explicit reset: a playlist view has a meaningful device order
/// (curated member sequence) and needs a way back to it; asc/desc
/// alone would trap the view in a sorted state forever.
fn next_track_sort(current: Option<TrackSort>, clicked: TrackSortColumn) -> Option<TrackSort> {
    match current {
        Some(sort) if sort.column == clicked => match sort.descending {
            false => Some(TrackSort {
                column: clicked,
                descending: true,
            }),
            true => None,
        },
        _ => Some(TrackSort {
            column: clicked,
            descending: false,
        }),
    }
}

/// One sort key of a track; an absent artist/album is an empty string.
/// Naive `Ord` (code-point order, case-sensitive): predictable, no
/// locale dependency, and desc is the exact reverse of asc.
fn sort_key(track: &Track, column: TrackSortColumn) -> std::borrow::Cow<'_, str> {
    match column {
        TrackSortColumn::Title => track.title.as_str().into(),
        TrackSortColumn::Artist => track.artist.as_deref().unwrap_or_default().into(),
        TrackSortColumn::Album => track.album.as_deref().unwrap_or_default().into(),
        TrackSortColumn::Duration => format!("{:012}", track.duration_ms).into(),
    }
}

/// Stable sort of the (already filtered) flat list, round 7. Applied
/// AFTER the search filter, BEFORE the render; equal keys keep their
/// incoming relative order, so «Обновить» never shuffles rows. The
/// duration sorts numerically via a zero-padded key.
fn sort_tracks(tracks: Vec<&Track>, sort: Option<TrackSort>) -> Vec<&Track> {
    let Some(sort) = sort else {
        return tracks;
    };
    let mut sorted = tracks;
    // Reverse the ORDERING, not the vec: sorting with a reversed
    // comparator keeps equal keys in their incoming order, so desc is
    // as stable as asc.
    sorted.sort_by(|a, b| {
        let ordering = sort_key(a, sort.column).cmp(&sort_key(b, sort.column));
        if sort.descending {
            ordering.reverse()
        } else {
            ordering
        }
    });
    sorted
}

/// The unified view switcher (round 6 П3): a segmented row of labels
/// directly over the table/content. Returns true when the active mode
/// changed. Theme-driven `selectable_label` — no custom colors, the
/// system theme decides (owner requirement, round 4).
fn view_switcher(ui: &mut egui::Ui, modes: &[SectionMode], current: &mut SectionMode) -> bool {
    let mut changed = false;
    ui.horizontal(|ui| {
        for mode in modes {
            let active = *mode == *current;
            if ui.selectable_label(active, mode.label()).clicked() && !active {
                *current = *mode;
                changed = true;
            }
        }
    });
    changed
}

/// Raw iTunesDB media-kind bits covered by a built-in device view.
/// Kinds follow the firmware: 1 = music, 2 = movie, 4 = podcast,
/// 8 = audiobook, 16 = TV show, 32 = music video. The rentals view
/// (7) is not representable as a media kind — it filters to nothing.
fn view_media_kinds(distinguished_kind: i64) -> &'static [u32] {
    match distinguished_kind {
        1 => &[2, 16, 32], // «Видео»: movies + TV + music videos
        2 => &[2],         // «Фильмы»
        3 => &[16],        // «Телешоу»
        4 => &[1],         // «Музыка»
        5 => &[8],         // «Аудиокниги»
        _ => &[],          // 0 (not a view), 7 («Прокат»), anything unknown
    }
}

/// One click on a visible table row resolved to selection state, in
/// index domain (indices into the current visible list). Plain click
/// resets to a single row; ctrl toggles the row; shift selects the
/// range from the anchor. The caller passes the anchor already
/// validated against the visible list length (a stale anchor — the
/// list shrank since the anchored click — is dropped there, so shift
/// degenerates to a plain click).
fn apply_row_click(
    selected: &[usize],
    anchor: Option<usize>,
    clicked: usize,
    ctrl: bool,
    shift: bool,
) -> (Vec<usize>, Option<usize>) {
    if shift {
        if let Some(start) = anchor {
            let (from, to) = if start <= clicked {
                (start, clicked)
            } else {
                (clicked, start)
            };
            let selected = (from..=to).collect();
            return (selected, Some(start));
        }
    }
    if ctrl {
        let mut selected = selected.to_vec();
        if let Some(position) = selected.iter().position(|&index| index == clicked) {
            selected.remove(position);
        } else {
            selected.push(clicked);
            selected.sort_unstable();
        }
        return (selected, anchor.or(Some(clicked)));
    }
    (vec![clicked], Some(clicked))
}

// ---- round 6 П2: checkbox multi-select (pure helpers, tested) ----

/// Tri-state of the «выбрать все» header checkbox against the visible
/// rows: every visible id selected → checked, none → unchecked,
/// anything between (including a partial-visibility edge) → dash.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SelectAllState {
    All,
    Some,
    None,
}

fn select_all_state(selected: &[TrackId], visible: &[TrackId]) -> SelectAllState {
    let hits = visible.iter().filter(|id| selected.contains(id)).count();
    match (hits == 0, hits == visible.len()) {
        (true, _) => SelectAllState::None,
        (_, true) => SelectAllState::All,
        (false, false) => SelectAllState::Some,
    }
}

/// Header-checkbox toggle: checking adds every visible id (the click
/// order of already-selected rows is preserved, new ones append in
/// visible order); unchecking removes exactly the visible ids, so a
/// selection made elsewhere (another view, out-of-filter rows)
/// survives. The result feeds the same `selected_tracks` — the single
/// selection mechanism (no parallel state).
fn apply_select_all(selected: &[TrackId], visible: &[TrackId], check: bool) -> Vec<TrackId> {
    if check {
        let mut result = selected.to_vec();
        for id in visible {
            if !result.contains(id) {
                result.push(*id);
            }
        }
        result
    } else {
        selected
            .iter()
            .copied()
            .filter(|id| !visible.contains(id))
            .collect()
    }
}

/// One checkbox click = an explicit toggle of that row in the shared
/// selection. Unlike a row click it never resets the rest, never moves
/// the shift anchor — and keeps the click order stable.
fn toggle_selected(selected: &[TrackId], id: TrackId) -> Vec<TrackId> {
    let mut result = selected.to_vec();
    match result.iter().position(|candidate| candidate == &id) {
        Some(position) => {
            result.remove(position);
        }
        None => result.push(id),
    }
    result
}

/// The stored shift-anchor is valid only if the row identity still
/// matches the visible list (round 6 tail nit-10): a boundary check
/// alone let a re-listed view shift-select a foreign range. Returns
/// the anchor index for `apply_row_click`, or None (shift then
/// degenerates to a plain click).
fn valid_anchor(anchor: Option<(usize, TrackId)>, visible: &[TrackId]) -> Option<usize> {
    anchor
        .filter(|&(index, id)| visible.get(index) == Some(&id))
        .map(|(index, _)| index)
}

/// The selection state after resolving one frame's row interactions.
struct SelectionUpdate {
    selected_tracks: Vec<TrackId>,
    selection_anchor: Option<(usize, TrackId)>,
    selected_track: Option<TrackId>,
}

/// Pure selection resolution (review 🟡-3: functions < 50 lines —
/// extracted from `library_view`): row clicks (plain/ctrl/shift),
/// «выбрать все» and a row-checkbox toggle, applied in that order to
/// the SAME `selected_tracks` — one selection mechanism. Checkbox
/// changes land here too, so the toolbar and the row clicks read the
/// same state. The cursor moves only where the mechanics demand it: a
/// row click targets the clicked row, a checkbox check targets the
/// toggled row; «выбрать все» rewrites the row set and deliberately
/// leaves the cursor put (review 🟡-1), so Enter/«Изменить…» keep the
/// row they had before the bulk edit.
fn resolve_selection_actions(
    selected_tracks: &[TrackId],
    selection_anchor: Option<(usize, TrackId)>,
    cursor: Option<TrackId>,
    visible_ids: &[TrackId],
    row_click: Option<(usize, bool, bool)>,
    select_all: Option<bool>,
    checkbox_toggle: Option<TrackId>,
) -> SelectionUpdate {
    let mut selection = SelectionUpdate {
        selected_tracks: selected_tracks.to_vec(),
        selection_anchor,
        selected_track: cursor,
    };

    // A click on a visible row resolves through apply_row_click
    // (plain/ctrl/shift) against the current visible list. The
    // anchor is identity-checked first (nit-10): a stale anchor
    // (the list shrank OR the row was replaced by a re-list) is
    // dropped, so shift degenerates to a plain click.
    if let Some((index, ctrl, shift)) = row_click {
        let anchor = valid_anchor(selection.selection_anchor, visible_ids);
        let selected_idx: Vec<usize> = selection
            .selected_tracks
            .iter()
            .filter_map(|id| visible_ids.iter().position(|candidate| candidate == id))
            .collect();
        let (new_indices, anchor_index) =
            apply_row_click(&selected_idx, anchor, index, ctrl, shift);
        selection.selected_tracks = new_indices
            .iter()
            .filter_map(|&index| visible_ids.get(index).copied())
            .collect();
        // Whatever anchor apply_row_click kept, the row identity
        // is recorded with it.
        selection.selection_anchor = anchor_index
            .and_then(|index| visible_ids.get(index).map(|&id| (index, id)));
        selection.selected_track = selection.selected_tracks.last().copied();
    }

    // «выбрать все» edits the row set only: the cursor stays put
    // (review 🟡-1) — a bulk selection is not a navigation act.
    if let Some(check) = select_all {
        selection.selected_tracks = apply_select_all(&selection.selected_tracks, visible_ids, check);
    }

    // A checkbox check moves the cursor to the toggled row (Enter
    // targets the last touched row); an uncheck leaves it where it is.
    if let Some(id) = checkbox_toggle {
        selection.selected_tracks = toggle_selected(&selection.selected_tracks, id);
        if selection.selected_tracks.contains(&id) {
            selection.selected_track = Some(id);
        }
    }

    selection
}

/// Central-panel empty-state text: empty library, empty filter result,
/// empty device view or empty playlist — in that priority order.
fn empty_state_text(library_empty: bool, query: &str, empty_view: bool, empty_playlist: bool) -> String {
    if library_empty {
        "Перетащите аудиофайлы в окно, чтобы добавить".to_owned()
    } else if !query.trim().is_empty() {
        format!("Ничего не найдено по „{}“", query.trim())
    } else if empty_view {
        "В этом разделе устройства нет записей".to_owned()
    } else if empty_playlist {
        "Пустой плейлист. Перетащите треки из таблицы".to_owned()
    } else {
        // Unreachable with a non-empty library, but keep an honest text.
        "Перетащите аудиофайлы в окно, чтобы добавить".to_owned()
    }
}

/// Full error text for the status-bar tooltip: the one-line bar clips,
/// so message + advice + raw tool output live on hover.
fn error_tooltip(error: &UiError) -> String {
    let mut text = error.message.clone();
    if let Some(hint) = &error.hint {
        text.push('\n');
        text.push_str(hint);
    }
    if let Some(stderr) = &error.stderr {
        if !stderr.trim().is_empty() {
            text.push_str("\n\n");
            text.push_str(stderr);
        }
    }
    text
}

// ---- round 5 + 6 П3: track grouping (pure helpers, tested) ----

/// One named group (book / album / artist) with its tracks in display
/// order. Duration/count are derived from `track_ids` + the snapshot
/// at render time (single source of truth, KISS) — not stored here.
#[derive(Clone, Debug, PartialEq, Eq)]
struct TrackGroup {
    name: String,
    /// Secondary info line: the author of a book or album. `None` →
    /// the info line shows only the counters (the «Исполнители» view,
    /// where the name IS the artist).
    author: Option<String>,
    track_ids: Vec<TrackId>,
}

/// The album-as-book key: blank/missing tags collapse into one
/// fallback group (pinned last by the sort — see `group_books`).
const NO_ALBUM_GROUP: &str = "Без альбома";
/// The artist catch-all, pinned last in the «Исполнители» view.
const NO_ARTIST_GROUP: &str = "Неизвестный исполнитель";
/// Honest placeholder of the books view (round 5 behavior).
const UNKNOWN_BOOK_AUTHOR: &str = "Неизвестный автор";

fn album_group_key(track: &Track) -> String {
    track
        .album
        .as_deref()
        .map(str::trim)
        .filter(|album| !album.is_empty())
        .map(str::to_owned)
        .unwrap_or_else(|| NO_ALBUM_GROUP.to_owned())
}

/// Artist of a track for the «Исполнители» view: album_artist →
/// artist (the same fallback as the author line — Apple semantics);
/// blank/missing tags collapse into the pinned catch-all group.
fn artist_group_key(track: &Track) -> String {
    [track.album_artist.as_deref(), track.artist.as_deref()]
        .into_iter()
        .flatten()
        .map(str::trim)
        .find(|text| !text.is_empty())
        .map(str::to_owned)
        .unwrap_or_else(|| NO_ARTIST_GROUP.to_owned())
}

/// Sort key of a file inside its group: numbered discs/tracks first
/// (0 = «no number» sorts last among equals), then title
/// case-insensitively.
fn book_file_sort_key(track: &Track) -> (bool, u32, bool, u32, String) {
    (
        track.disc_number == 0,
        track.disc_number,
        track.track_number == 0,
        track.track_number,
        track.title.to_lowercase(),
    )
}

/// Shared grouping engine: buckets tracks by `key` (insertion order),
/// sorts buckets case-insensitively with the `catch_all` bucket pinned
/// last, then orders the members with `member_sort`.
fn group_tracks_by<'a>(
    tracks: impl IntoIterator<Item = &'a Track>,
    key: impl Fn(&Track) -> String,
    catch_all: &str,
    member_sort: impl Fn(&mut [&'a Track]),
) -> Vec<(String, Vec<&'a Track>)> {
    let mut buckets: Vec<(String, Vec<&Track>)> = Vec::new();
    for track in tracks {
        let group = key(track);
        match buckets.iter_mut().find(|(name, _)| *name == group) {
            Some((_, members)) => members.push(track),
            None => buckets.push((group, vec![track])),
        }
    }
    buckets.sort_by(|(a, _), (b, _)| {
        // The synthetic catch-all bucket pins last: real groups first,
        // the fallback below them.
        (a == catch_all)
            .cmp(&(b == catch_all))
            .then_with(|| a.to_lowercase().cmp(&b.to_lowercase()))
    });
    for (_, members) in &mut buckets {
        member_sort(members);
    }
    buckets
}

/// The author of a group: the first non-empty album_artist (Apple
/// semantics: the album artist outranks the track artist), then
/// artist, in the group's final file order.
fn resolved_author(members: &[&Track]) -> Option<String> {
    members
        .iter()
        .filter_map(|track| {
            track
                .album_artist
                .as_deref()
                .map(str::trim)
                .filter(|text| !text.is_empty())
                .map(str::to_owned)
                .or_else(|| {
                    track
                        .artist
                        .as_deref()
                        .map(str::trim)
                        .filter(|text| !text.is_empty())
                        .map(str::to_owned)
                })
        })
        .next()
}

/// Groups the (already filtered) audiobook tracks into books (round 5
/// behavior): albums case-insensitive, «Без альбома» last, files by
/// (disc, track, title); the author line always shows — honestly
/// «Неизвестный автор» when nobody is tagged.
fn group_books<'a>(tracks: impl IntoIterator<Item = &'a Track>) -> Vec<TrackGroup> {
    group_tracks_by(tracks, album_group_key, NO_ALBUM_GROUP, |members| {
        members.sort_by_key(|track| book_file_sort_key(track));
    })
    .into_iter()
    .map(|(name, members)| TrackGroup {
        author: Some(
            resolved_author(&members).unwrap_or_else(|| UNKNOWN_BOOK_AUTHOR.to_owned()),
        ),
        name,
        track_ids: members.iter().map(|track| track.id).collect(),
    })
    .collect()
}

/// Round 6 П3: the music view grouped by album — the same engine as
/// books («Без альбома» pinned last, files by disc/track/title), but
/// the author line stays honest: an untagged album shows no author.
fn group_by_album<'a>(tracks: impl IntoIterator<Item = &'a Track>) -> Vec<TrackGroup> {
    group_tracks_by(tracks, album_group_key, NO_ALBUM_GROUP, |members| {
        members.sort_by_key(|track| book_file_sort_key(track));
    })
    .into_iter()
    .map(|(name, members)| TrackGroup {
        author: resolved_author(&members),
        name,
        track_ids: members.iter().map(|track| track.id).collect(),
    })
    .collect()
}

/// Round 6 П3: the music view grouped by artist («Неизвестный
/// исполнитель» pinned last); the files of one artist are ordered by
/// album first, then by disc/track/title — a tiny discography.
fn group_by_artist<'a>(tracks: impl IntoIterator<Item = &'a Track>) -> Vec<TrackGroup> {
    group_tracks_by(tracks, artist_group_key, NO_ARTIST_GROUP, |members| {
        members.sort_by(|a, b| {
            album_group_key(a)
                .to_lowercase()
                .cmp(&album_group_key(b).to_lowercase())
                .then_with(|| book_file_sort_key(a).cmp(&book_file_sort_key(b)))
        });
    })
    .into_iter()
    .map(|(name, members)| TrackGroup {
        author: None,
        name,
        track_ids: members.iter().map(|track| track.id).collect(),
    })
    .collect()
}

/// One rendered line of the «Аудиокниги» view: a collapsible book
/// header or one of its files. A flat list so the proven index-based
/// selection (`apply_row_click`, anchor, keyboard) keeps working.
/// Total book duration as «H:MM» (sub-minute books show «0:00»).
fn format_total_duration(duration_ms: u64) -> String {
    let minutes = duration_ms / 60_000;
    format!("{}:{:02}", minutes / 60, minutes % 60)
}

// ---- round 5.5: tag review before add (pure helpers, tested) ----

/// A dropped draft has no artist AND no album — it needs the review
/// modal before it can land in the library with honest tags.
fn is_untagged(draft: &TrackDraft) -> bool {
    let empty = |text: &Option<String>| -> bool {
        text.as_deref().map(str::trim).unwrap_or("").is_empty()
    };
    empty(&draft.artist) && empty(&draft.album)
}

/// Longest common stem prefix (≥2 stems), trimmed back to a « - » or
/// space boundary, and only if at least 3 characters survive —
/// otherwise None and the prefix checkbox is not shown.
fn common_prefix(stems: &[String]) -> Option<String> {
    if stems.len() < 2 {
        return None;
    }
    let first = stems.first()?.chars().collect::<Vec<_>>();
    let mut shared = first.len();
    for stem in &stems[1..] {
        shared = shared.min(stem.chars().count());
        for (index, ch) in stem.chars().enumerate().take(shared) {
            if first[index] != ch {
                shared = index;
                break;
            }
        }
    }
    let prefix: String = first[..shared].iter().collect();
    let trimmed = match prefix.rfind(" - ") {
        Some(index) => prefix[..index].to_owned(),
        None => match prefix.rfind(' ') {
            Some(index) => prefix[..index].to_owned(),
            None => prefix.clone(),
        },
    };
    (trimmed.chars().count() >= 3).then_some(trimmed)
}

/// Trailing digits of a stem = the track number («… - 3» → 3,
/// «12» → 12, «12a»/«intro» → None).
fn trailing_number(stem: &str) -> Option<u32> {
    let digits: String = stem
        .chars()
        .rev()
        .take_while(char::is_ascii_digit)
        .collect::<String>()
        .chars()
        .rev()
        .collect();
    if digits.is_empty() {
        None
    } else {
        digits.parse().ok()
    }
}

/// Removes the shared prefix (with its « - »/space tail) from a title.
fn strip_prefix_in(title: &str, prefix: &str) -> String {
    title
        .strip_prefix(prefix)
        .map(|rest| {
            rest.trim_start_matches([' ', '-'])
                .trim_start()
                .to_owned()
        })
        .unwrap_or_else(|| title.to_owned())
}

// ---- round 6 tail nit-8: kind-aware tag-review texts ----

/// Field labels and messages of the tag-review modal, chosen by the
/// media kind: audiobooks speak «книга/автор», music speaks
/// «альбом/исполнитель». The check is the semantic audiobook BIT —
/// combined bits stay book-flavored.
struct TagReviewTexts {
    /// Subject of the heading («Добавление {subject}: …»).
    subject: &'static str,
    /// Label of the shared title field.
    title_field: &'static str,
    /// Label of the shared author field.
    author_field: &'static str,
    /// Near-field validation text for an empty title.
    empty_title: &'static str,
    /// The commit button.
    add_button: &'static str,
}

fn tag_review_texts(kind_bits: u32) -> TagReviewTexts {
    if kind_bits & AUDIOBOOK_BIT != 0 {
        TagReviewTexts {
            subject: "книги",
            title_field: "Название книги*",
            author_field: "Автор",
            empty_title: "Укажите название книги",
            add_button: "Добавить книгу",
        }
    } else {
        TagReviewTexts {
            subject: "музыки",
            title_field: "Альбом",
            author_field: "Исполнитель",
            empty_title: "Укажите название альбома",
            add_button: "Добавить музыку",
        }
    }
}

// ---- round 6 tail nit-9: prefix toggle keeps manual edits ----

/// Re-derives the automatic titles after the prefix-checkbox toggle,
/// but only for rows still showing the PREVIOUS automatic value — a
/// manually edited title survives (round 6 tail nit-9: the checkbox
/// used to overwrite every row from the raw file stem).
fn retoggle_prefix_titles(rows: &mut [TagRow], prefix: &str, strip_now: bool) {
    for row in rows {
        let auto_now = if strip_now {
            strip_prefix_in(&row.original_title, prefix)
        } else {
            row.original_title.clone()
        };
        let auto_before = if strip_now {
            row.original_title.clone()
        } else {
            strip_prefix_in(&row.original_title, prefix)
        };
        if row.title == auto_before {
            row.title = auto_now;
        }
    }
}

/// Applies the reviewed tags to the drafts: album/book title for all,
/// author as album_artist (when non-empty) AND as artist for drafts
/// without an own artist — the vendor's display_artist() persists
/// item.artist only, so unpropagated tracks stay nameless in «Песни» —
/// per-row title (an empty
/// edit falls back to the file stem) and track number. The empty-title
/// validation text is kind-aware (round 6 tail nit-8).
fn apply_tag_review(
    drafts: &[TrackDraft],
    book_title: &str,
    author: &str,
    rows: &[TagRow],
    empty_title_error: &str,
) -> Result<Vec<TrackDraft>, String> {
    let book = book_title.trim();
    if book.is_empty() {
        return Err(empty_title_error.to_owned());
    }
    let author = author.trim();
    Ok(drafts
        .iter()
        .zip(rows)
        .map(|(draft, row)| {
            let mut prepared = draft.clone();
            prepared.album = Some(book.to_owned());
            if !author.is_empty() {
                prepared.album_artist = Some(author.to_owned());
                // Propagate into `artist` when the draft has none: the
                // vendor's display_artist() persists item.artist only,
                // so without this the track stays nameless in «Песни».
                // A pre-existing artist is never overwritten.
                if prepared.artist.as_deref().is_none_or(str::is_empty) {
                    prepared.artist = Some(author.to_owned());
                }
            }
            let title = row.title.trim();
            prepared.title = if title.is_empty() {
                draft.title.clone()
            } else {
                title.to_owned()
            };
            prepared.track_number = row.track_number;
            prepared
        })
        .collect())
}

/// Prefill of the book title: the common parent directory name of the
/// batch (a dropped directory = the book); single stray files and
/// mixed parents prefill nothing.
fn prefill_book_title(drafts: &[TrackDraft]) -> String {
    if drafts.len() < 2 {
        return String::new();
    }
    let parent = drafts[0].source_path.parent();
    let Some(parent) = parent else {
        return String::new();
    };
    let same_parent = drafts
        .iter()
        .all(|draft| draft.source_path.parent() == Some(parent));
    if same_parent {
        parent
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or_default()
            .to_owned()
    } else {
        String::new()
    }
}

/// One editable file line of the review modal. `original_title` is
/// the untouched file stem — the reference for the prefix toggle to
/// detect (and spare) manual edits (round 6 tail nit-9).
#[derive(Clone, Debug, PartialEq, Eq)]
struct TagRow {
    title: String,
    original_title: String,
    track_number: u32,
}

/// State of the tag-review modal (round 5.5): the drafts are edited
/// here first and dispatched through the regular AddTracks pipeline on
/// «Добавить».
struct TagReview {
    drafts: Vec<TrackDraft>,
    kind_bits: u32,
    book_title: String,
    author: String,
    strip_prefix: bool,
    prefix: Option<String>,
    /// Display names of the source files (stable for the file column).
    files: Vec<String>,
    /// Screen rects of the rendered file rows (stable modal id), used
    /// by tests to simulate clicks on a row.
    row_rects: Vec<egui::Rect>,
    /// Widget ids of the per-row title edits (focus targeting in tests
    /// and keyboard routing).
    row_edit_ids: Vec<egui::Id>,
    /// Screen rects of the per-row title edits (click targeting).
    row_edit_rects: Vec<egui::Rect>,
    rows: Vec<TagRow>,
    selected_row: Option<usize>,
    validation_attempted: bool,
}

/// Opens the review modal for a batch: rows prefill from the file
/// stems (trailing digits become track numbers, otherwise the 1-based
/// position), the book title prefills from the common parent
/// directory, and the shared-prefix checkbox is pre-enabled when a
/// prefix was found.
fn open_tag_review(drafts: Vec<TrackDraft>) -> TagReview {
    let kind_bits = drafts.first().map(|d| d.media_kind_bits).unwrap_or(1);
    let stems: Vec<String> = drafts.iter().map(|d| d.title.clone()).collect();
    let prefix = common_prefix(&stems);
    let rows: Vec<TagRow> = drafts
        .iter()
        .enumerate()
        .map(|(index, draft)| TagRow {
            title: draft.title.clone(),
            original_title: draft.title.clone(),
            track_number: trailing_number(&draft.title)
                .unwrap_or(index as u32 + 1),
        })
        .collect();
    TagReview {
        kind_bits,
        book_title: prefill_book_title(&drafts),
        author: String::new(),
        strip_prefix: prefix.is_some(),
        prefix,
        files: drafts
            .iter()
            .map(|d| d.source_path.display().to_string())
            .collect(),
        row_rects: Vec::new(),
        row_edit_ids: Vec::new(),
        row_edit_rects: Vec::new(),
        rows,
        selected_row: None,
        validation_attempted: false,
        drafts,
    }
}

/// Actions requested from the table toolbar in one frame.
#[derive(Default)]
struct ToolbarActions {
    refresh: bool,
    edit: bool,
    add: bool,
    remove: bool,
    set_artist: bool,
}

/// Pictogram + tooltip of ONE action (round 7): glyph and label travel
/// together so no call site can pair them inconsistently. The glyphs
/// come from egui's bundled monochrome emoji fonts — the
/// `monochrome_emoji_fonts` feature (see workspace Cargo.toml);
/// coverage is pinned by a test.
struct ActionIcon {
    glyph: &'static str,
    tooltip: &'static str,
}

const ICON_REFRESH: ActionIcon = ActionIcon {
    glyph: "🔄",
    tooltip: "Обновить",
};
const ICON_EDIT: ActionIcon = ActionIcon {
    glyph: "✏",
    tooltip: "Изменить…",
};
const ICON_SET_ARTIST: ActionIcon = ActionIcon {
    glyph: "👤",
    tooltip: "Задать исполнителя…",
};
const ICON_ADD_TO_PLAYLIST: ActionIcon = ActionIcon {
    glyph: "📋",
    tooltip: "Добавить в плейлист…",
};
const ICON_REMOVE_FROM_PLAYLIST: ActionIcon = ActionIcon {
    glyph: "🚫",
    tooltip: "Убрать из плейлиста",
};
const ICON_DELETE: ActionIcon = ActionIcon {
    glyph: "🗑",
    tooltip: "Удалить…",
};

/// One pictogram button (round 7): glyph + hover tooltip with the
/// former label. Replaces the text labels to save toolbar width (the
/// owner's finding: text buttons crowded the search box at the 616px
/// worst case). THE single helper for every site offering these
/// actions — toolbar and context menus alike; tooltips keep the «…».
fn icon_button(ui: &mut egui::Ui, icon: &ActionIcon, enabled: bool) -> bool {
    ui.add_enabled(enabled, egui::Button::new(icon.glyph))
        .on_hover_text(icon.tooltip)
        .clicked()
}

/// Aggregated arguments for [`search_toolbar`] (UI chrome above the
/// track table); `ui` stays a plain argument per egui convention.
struct SearchToolbarParams<'a> {
    ctx: &'a egui::Context,
    query: &'a mut String,
    shown: usize,
    total: usize,
    idle: bool,
    selection_len: usize,
    playlist_context: bool,
}

/// Toolbar above the track table: search box (Ctrl+F focuses it when
/// nothing else holds focus), row counter and the selection actions —
/// always visible, enabled only for a non-empty selection (round 4.1
/// Ф3). In a playlist context the delete button becomes
/// «Убрать из плейлиста» (existing RemoveFromPlaylist command).
fn search_toolbar(ui: &mut egui::Ui, params: SearchToolbarParams<'_>) -> ToolbarActions {
    let SearchToolbarParams {
        ctx,
        query,
        shown,
        total,
        idle,
        selection_len,
        playlist_context,
    } = params;
    let mut toolbar = ToolbarActions::default();
    ui.horizontal(|ui| {
        // A stable root id (not id_salt) so Ctrl+F can request focus on
        // the exact box regardless of where the toolbar lands.
        let search_box_id = egui::Id::unique("podlib_search");
        if ctx.input(|input| input.key_pressed(egui::Key::F) && input.modifiers.ctrl)
            && ctx.memory(|memory| memory.focused().is_none())
        {
            ctx.memory_mut(|memory| memory.request_focus(search_box_id));
        }
        let query_before = query.clone();
        let search = ui.add(
            egui::TextEdit::singleline(query)
                .hint_text("Поиск…")
                .id(search_box_id)
                .desired_width(240.0),
        );
        text_menu::attach_text_menu(&search);
        ui.label(tracks_counter(shown, total, &query_before));
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            let enabled = idle && selection_len > 0;
            // Round 7: pictograms, first added = rightmost (unchanged
            // order). The delete button becomes «Убрать из плейлиста»
            // in a playlist context.
            if playlist_context {
                if icon_button(ui, &ICON_REMOVE_FROM_PLAYLIST, enabled) {
                    toolbar.remove = true;
                }
            } else if icon_button(ui, &ICON_DELETE, enabled) {
                toolbar.remove = true;
            }
            if icon_button(ui, &ICON_ADD_TO_PLAYLIST, enabled) {
                toolbar.add = true;
            }
            if icon_button(ui, &ICON_SET_ARTIST, enabled) {
                toolbar.set_artist = true;
            }
            if icon_button(ui, &ICON_EDIT, idle && selection_len == 1) {
                toolbar.edit = true;
            }
            if icon_button(ui, &ICON_REFRESH, idle) {
                toolbar.refresh = true;
            }
        });
    });
    toolbar
}

/// Column setup of the track table, shared with the layout test
/// (round 4.1 Ф4): a narrow checkbox column (round 6 П2), the title
/// takes the remainder with a 100px floor, the other three are exact
/// widths. WHY the floor: with `remainder` + fixed columns in a narrow
/// panel the remainder can collapse to 0 (`Sizing::to_lengths` clamps
/// negative remainders to 0) and the row loses its title entirely; the
/// floor keeps it readable. 100px (was 120 in round 4.1): the checkbox
/// column joined the same 616px worst case, and the title now floors
/// just under its 104px worst-case share instead of overflowing.
fn track_table_builder<'a>(ui: &'a mut egui::Ui, table_id: egui::Id) -> TableBuilder<'a> {
    TableBuilder::new(ui)
        .id_salt(table_id)
        .striped(true)
        .vscroll(true)
        .cell_layout(egui::Layout::left_to_right(egui::Align::Center))
        .column(Column::exact(CHECK_COLUMN).resizable(false))
        .column(Column::remainder().clip(true).resizable(false).at_least(100.0))
        .column(Column::exact(ARTIST_COLUMN).clip(true).resizable(false))
        .column(Column::exact(ALBUM_COLUMN).clip(true).resizable(false))
        .column(Column::exact(DURATION_COLUMN).resizable(false))
}

/// Left sidebar of the main layout: 160px floor (решение владельца,
/// 20.11.2026) and a ceiling that keeps MIN_CENTRAL_PANEL_WIDTH for the
/// track table — egui clamps panel drags only at the screen edge and
/// reserves nothing for the central panel, so without the ceiling the
/// divider can be pulled until the table disappears (round 6.5).
/// Shared by the production layout and the panel tests so the width
/// contract lives in exactly one place.
fn device_panel_builder(ui: &egui::Ui) -> egui::Panel {
    let screen_w = ui.input(|input| input.viewport_rect().width());
    egui::Panel::left("device_panel")
        .default_size(240.0)
        .resizable(true)
        .size_range(egui::Rangef::new(
            160.0,
            (screen_w - MIN_CENTRAL_PANEL_WIDTH).max(160.0),
        ))
}

/// Aggregated arguments for [`groups_view`] (grouped track views);
/// `ui` stays a plain argument per egui convention. `groups` arrive
/// precomputed (group_books / group_by_album / group_by_artist) — the
/// component is render-only (round 6 П3: ONE grouped-list component
/// for books, albums and artists).
struct GroupsViewParams<'a> {
    ctx: &'a egui::Context,
    tracks: &'a [&'a Track],
    groups: &'a [TrackGroup],
    selected_tracks: &'a [TrackId],
    cursor: Option<TrackId>,
    menus_allowed: bool,
    visible_ids: &'a [TrackId],
    expanded: &'a mut HashSet<String>,
}

/// The grouped view component (round 5 books / round 6 П3): groups
/// collapsed by default; a header click toggles the group; an expanded
/// group shows an info line (optional author · files · total duration)
/// and its file list. File rows reuse the proven selection machinery:
/// clicks report their index in `visible_ids` (headers are not
/// selectable — they toggle), so apply_row_click / anchor / toolbar /
/// keyboard all work unchanged.
fn groups_view(ui: &mut egui::Ui, params: GroupsViewParams<'_>) -> TrackRowActions {
    let GroupsViewParams {
        ctx,
        tracks,
        groups,
        selected_tracks,
        cursor,
        menus_allowed,
        visible_ids,
        expanded,
    } = params;
    let mut actions = TrackRowActions::default();
    if !expanded.is_empty() && ui.button("Свернуть все").clicked() {
        expanded.clear();
    }
    // Durations and titles for the infoblock/file rows; the groups
    // carry ids only (single source of truth, see TrackGroup).
    let by_id: HashMap<TrackId, &Track> =
        tracks.iter().map(|track| (track.id, *track)).collect();
    egui::ScrollArea::vertical()
        .auto_shrink(false)
        .show(ui, |ui| {
            for group in groups {
                let is_expanded = expanded.contains(&group.name);
                let arrow = if is_expanded { "▾" } else { "▸" };
                let total_ms: u64 = group
                    .track_ids
                    .iter()
                    .filter_map(|id| by_id.get(id).map(|t| u64::from(t.duration_ms)))
                    .sum();
                // First-class clickable row: ONE widget senses the
                // whole line and the content is painted directly —
                // child labels intercept clicks (and select as text),
                // retroactive .interact() does not win over them.
                let (rect, response) = ui.allocate_exact_size(
                    egui::vec2(ui.available_width(), ROW_HEIGHT),
                    egui::Sense::click(),
                );
                let painter = ui.painter();
                let visuals = ui.visuals();
                if is_expanded {
                    painter.rect_filled(rect, 4.0, visuals.widgets.inactive.bg_fill);
                }
                if response.hovered() {
                    painter.rect_filled(rect, 4.0, visuals.widgets.hovered.bg_fill);
                }
                let inner = rect.shrink2(egui::vec2(8.0, 0.0));
                let middle = rect.center().y;
                painter.text(
                    egui::pos2(inner.left(), middle),
                    egui::Align2::LEFT_CENTER,
                    format!("{arrow} {}", group.name),
                    egui::FontId::proportional(14.0),
                    visuals.strong_text_color(),
                );
                painter.text(
                    egui::pos2(inner.right(), middle),
                    egui::Align2::RIGHT_CENTER,
                    format!(
                        "{} · {}",
                        group.track_ids.len(),
                        format_total_duration(total_ms)
                    ),
                    egui::FontId::proportional(12.0),
                    visuals.weak_text_color(),
                );
                if response.clicked() {
                    // Insert-else-remove = toggle.
                    if !expanded.insert(group.name.clone()) {
                        expanded.remove(&group.name);
                    }
                }
                if is_expanded {
                    // One framed block: info line + file list (owner:
                    // «автор и сводка по книге — в одном выделенном
                    // блоке»); faint fill reads as a single card.
                    egui::Frame::default()
                        .fill(ui.visuals().extreme_bg_color)
                        .corner_radius(4.0)
                        .inner_margin(egui::Margin::same(6))
                        .show(ui, |ui| {
                            let files_text = format!(
                                "{} {}",
                                group.track_ids.len(),
                                plural(group.track_ids.len(), "файл", "файла", "файлов")
                            );
                            let total_text = format_total_duration(total_ms);
                            let info = match &group.author {
                                Some(author) => {
                                    format!("Автор: {author} · {files_text} · {total_text}")
                                }
                                None => format!("{files_text} · {total_text}"),
                            };
                            ui.label(egui::RichText::new(info).weak().size(13.0));
                            ui.add_space(2.0);
                            for (file_idx, track_id) in group.track_ids.iter().enumerate() {
                                let Some(track) = by_id.get(track_id) else {
                                    continue;
                                };
                                book_file_row(
                                    ui,
                                    ctx,
                                    selected_tracks,
                                    cursor,
                                    menus_allowed,
                                    visible_ids,
                                    file_idx,
                                    track,
                                    &mut actions,
                                );
                            }
                        });
                }
            }
        });
    actions
}

/// One audio file inside an expanded book: a painted row that senses
/// click/dblclick (selection machinery via visible_ids indices), ПКМ
/// menu, and drag — the payload is set manually on drag start.
#[allow(clippy::too_many_arguments)]
fn book_file_row(
    ui: &mut egui::Ui,
    ctx: &egui::Context,
    selected_tracks: &[TrackId],
    cursor: Option<TrackId>,
    menus_allowed: bool,
    visible_ids: &[TrackId],
    file_idx: usize,
    track: &Track,
    actions: &mut TrackRowActions,
) {
    let track_id = track.id;
    let selected = selected_tracks.contains(&track_id) || cursor == Some(track_id);
    let payload = DraggedTracks(vec![track_id]);
    let mut clicked = false;
    let mut double_clicked = false;
    // Manual drag source: sense click+drag on the painted row and set
    // the payload on drag start. `dnd_drag_source` re-renders the row
    // into a screen-space tooltip layer and translates by
    // `pointer - rect.center()` — panel coords vs screen coords mix,
    // throwing the row to the left screen edge (owner artifact).
    let (rect, response) = ui.allocate_exact_size(
        egui::vec2(ui.available_width(), ROW_HEIGHT),
        egui::Sense::click() | egui::Sense::drag(),
    );
    let painter = ui.painter();
    let visuals = ui.visuals();
    if selected {
        painter.rect_filled(rect, 2.0, visuals.selection.bg_fill);
    } else if response.hovered() {
        painter.rect_filled(rect, 2.0, visuals.widgets.hovered.bg_fill);
    }
    let inner = rect.shrink2(egui::vec2(4.0, 0.0));
    let middle = rect.center().y;
    painter.text(
        egui::pos2(inner.left(), middle),
        egui::Align2::LEFT_CENTER,
        format!("{}. {}", file_idx + 1, track.title),
        egui::FontId::proportional(14.0),
        visuals.text_color(),
    );
    painter.text(
        egui::pos2(inner.right(), middle),
        egui::Align2::RIGHT_CENTER,
        format_duration(track.duration_ms),
        egui::FontId::proportional(12.0),
        visuals.weak_text_color(),
    );
    let response = response.on_hover_cursor(egui::CursorIcon::Grab);
    if response.drag_started() {
        egui::DragAndDrop::set_payload(ctx, payload);
    }
    if response.clicked() {
        clicked = true;
    }
    if response.double_clicked() {
        double_clicked = true;
    }
    // Double-click wins over plain click (round 4).
    if double_clicked {
        actions.edit = Some(track_id);
        actions.select = Some(track_id);
    } else if clicked {
        let (ctrl, shift) = ctx.input(|input| (input.modifiers.ctrl, input.modifiers.shift));
        if let Some(index) = visible_ids.iter().position(|&candidate| candidate == track_id) {
            actions.row_click = Some((index, ctrl, shift));
        }
    }
    if menus_allowed {
        let mut choice = TrackRowActions::default();
        response.context_menu(|ui| {
            if icon_button(ui, &ICON_EDIT, true) {
                choice.edit = Some(track_id);
                ui.close();
            }
            if icon_button(ui, &ICON_ADD_TO_PLAYLIST, true) {
                choice.add_to_playlist = Some(vec![track_id]);
                ui.close();
            }
            ui.separator();
            if icon_button(ui, &ICON_DELETE, true) {
                choice.delete = Some(track_id);
                ui.close();
            }
        });
        actions.merge(choice);
    }
}

/// The tri-state «выбрать все» header checkbox (round 6 П2): a click
/// selects every visible row; from the checked state a click clears
/// them again. From the partial dash a click selects too — egui's
/// indeterminate flag is purely visual and does not invert the
/// toggle. Returns the requested target state when the widget was
/// clicked.
fn header_select_all(ui: &mut egui::Ui, state: SelectAllState) -> Option<bool> {
    let mut checked = state == SelectAllState::All;
    let response = ui.add(
        egui::Checkbox::without_text(&mut checked)
            .indeterminate(state == SelectAllState::Some),
    );
    response.changed().then_some(checked)
}

/// One sortable header cell (round 7): the strong label, suffixed
/// ▲/▼ while its column is the active sort. A click reports the
/// column — the caller owns the state machine ([`next_track_sort`]).
fn sortable_header(
    ui: &mut egui::Ui,
    label: &str,
    column: TrackSortColumn,
    sort: Option<TrackSort>,
) -> Option<TrackSortColumn> {
    let suffix = match sort {
        Some(sort) if sort.column == column => {
            if sort.descending {
                " ▼"
            } else {
                " ▲"
            }
        }
        _ => "",
    };
    let response = ui
        .add(
            egui::Label::new(egui::RichText::new(format!("{label}{suffix}")).strong())
                .sense(egui::Sense::click()),
        )
        .on_hover_cursor(egui::CursorIcon::PointingHand);
    response.clicked().then_some(column)
}

/// One checkbox cell of a table row (round 6 П2): an explicit toggle
/// of the row in the shared selection. A plain widget on purpose —
/// unlike the draggable title/artist/album/duration cells it must not
/// intercept or emit row clicks.
fn row_checkbox(ui: &mut egui::Ui, selected_tracks: &[TrackId], id: TrackId) -> Option<TrackId> {
    let mut checked = selected_tracks.contains(&id);
    let response = ui.add(egui::Checkbox::without_text(&mut checked));
    response.changed().then_some(id)
}

/// The track table (round 4): `egui_extras::TableBuilder` with striped
/// rows, per-context scroll state, clip + hover-tooltips, a right
/// aligned duration column, multi-row selection (Ф3: plain/ctrl/shift
/// clicks, toolbar actions; round 6 П2: checkbox column + «выбрать
/// все») and full-row drag. Round 7: the four data headers are
/// sortable (click → column, the caller owns the state). Collects row
/// choices without holding an app-state borrow.
#[allow(clippy::too_many_arguments)]
fn track_table(
    ui: &mut egui::Ui,
    tracks: &[&Track],
    selected_tracks: &[TrackId],
    cursor: Option<TrackId>,
    view: LibraryView,
    menus_allowed: bool,
    table_id: egui::Id,
    sort: Option<TrackSort>,
) -> TrackRowActions {
    let mut actions = TrackRowActions::default();
    // Modifiers at click time are the current input state: egui
    // processes clicks within their frame.
    let ctx = ui.ctx().clone();
    let visible_ids: Vec<TrackId> = tracks.iter().map(|track| track.id).collect();
    track_table_builder(ui, table_id)
        .header(ROW_HEIGHT, |mut header| {
            header.col(|ui| {
                if let Some(check) =
                    header_select_all(ui, select_all_state(selected_tracks, &visible_ids))
                {
                    actions.select_all = Some(check);
                }
            });
            header.col(|ui| {
                if let Some(column) = sortable_header(ui, "Название", TrackSortColumn::Title, sort)
                {
                    actions.sort_toggle = Some(column);
                }
            });
            header.col(|ui| {
                if let Some(column) =
                    sortable_header(ui, "Исполнитель", TrackSortColumn::Artist, sort)
                {
                    actions.sort_toggle = Some(column);
                }
            });
            header.col(|ui| {
                if let Some(column) = sortable_header(ui, "Альбом", TrackSortColumn::Album, sort) {
                    actions.sort_toggle = Some(column);
                }
            });
            header.col(|ui| {
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if let Some(column) =
                        sortable_header(ui, "Длит.", TrackSortColumn::Duration, sort)
                    {
                        actions.sort_toggle = Some(column);
                    }
                });
            });
        })
        .body(|mut body| {
            for (index, track) in tracks.iter().enumerate() {
                let track = *track;
                body.row(ROW_HEIGHT, |mut row| {
                    // Selection highlight straight from TableBuilder:
                    // every row of the multi-selection plus the cursor.
                    row.set_selected(selected_tracks.contains(&track.id) || cursor == Some(track.id));
                    // Round 6 П2: the checkbox column — an explicit
                    // toggle, kept out of the drag/click machinery.
                    row.col(|ui| {
                        if let Some(id) = row_checkbox(ui, selected_tracks, track.id) {
                            actions.checkbox_toggle = Some(id);
                        }
                    });
                    // WHY the same id for every cell: egui keys the drag
                    // payload by id; identical ids + identical payloads
                    // make all four cells drag the one row.
                    let row_id = egui::Id::unique(("track_row", track.id.to_bits()));
                    let payload = DraggedTracks(vec![track.id]);
                    let clicked = Cell::new(false);
                    let double_clicked = Cell::new(false);
                    row.col(|ui| {
                        draggable_cell(ui, row_id, &payload, &clicked, &double_clicked, |ui| {
                            ui.label(egui::RichText::new(&track.title).strong());
                        });
                    });
                    row.col(|ui| {
                        draggable_cell(ui, row_id, &payload, &clicked, &double_clicked, |ui| {
                            tooltip_label(ui, &track.artist);
                        });
                    });
                    row.col(|ui| {
                        draggable_cell(ui, row_id, &payload, &clicked, &double_clicked, |ui| {
                            tooltip_label(ui, &track.album);
                        });
                    });
                    row.col(|ui| {
                        draggable_cell(ui, row_id, &payload, &clicked, &double_clicked, |ui| {
                            // Table numbers read better right-aligned to
                            // the column edge.
                            ui.with_layout(
                                egui::Layout::right_to_left(egui::Align::Center),
                                |ui| ui.label(format_duration(track.duration_ms)),
                            );
                        });
                    });
                    // Double-click wins over plain click: the second
                    // click of a double-click also registers as clicked.
                    if double_clicked.get() {
                        actions.edit = Some(track.id);
                        actions.select = Some(track.id);
                    } else if clicked.get() {
                        let (ctrl, shift) =
                            ctx.input(|input| (input.modifiers.ctrl, input.modifiers.shift));
                        actions.row_click = Some((index, ctrl, shift));
                    }
                    if menus_allowed {
                        let mut choice = TrackRowActions::default();
                        // Union of the cell responses: the menu opens on
                        // a right-click anywhere in the row. Menu actions
                        // stay single-row (round 4.1: ПКМ unchanged).
                        row.response().context_menu(|ui| {
                            if icon_button(ui, &ICON_EDIT, true) {
                                choice.edit = Some(track.id);
                                ui.close();
                            }
                            if icon_button(ui, &ICON_ADD_TO_PLAYLIST, true) {
                                choice.add_to_playlist = Some(vec![track.id]);
                                ui.close();
                            }
                            if let LibraryView::Playlist(playlist_id) = view {
                                ui.separator();
                                if icon_button(ui, &ICON_REMOVE_FROM_PLAYLIST, true) {
                                    choice.remove_from_playlist =
                                        Some((playlist_id, track.id));
                                    ui.close();
                                }
                            }
                            ui.separator();
                            if icon_button(ui, &ICON_DELETE, true) {
                                choice.delete = Some(track.id);
                                ui.close();
                            }
                        });
                        actions.merge(choice);
                    }
                });
            }
        });
    actions
}

/// One draggable table cell: drag payload + click/double-click flags.
/// WHY per-cell drag sources: TableBuilder splits the row into cells,
/// so wrapping each cell keeps the whole row draggable.
fn draggable_cell(
    ui: &mut egui::Ui,
    row_id: egui::Id,
    payload: &DraggedTracks,
    clicked: &Cell<bool>,
    double_clicked: &Cell<bool>,
    add: impl FnOnce(&mut egui::Ui),
) {
    let response = ui
        .dnd_drag_source(row_id, payload.clone(), |ui| {
            ui.set_min_height(ROW_HEIGHT);
            add(ui);
        })
        .response;
    if response.clicked() {
        clicked.set(true);
    }
    if response.double_clicked() {
        double_clicked.set(true);
    }
}

/// Artist/album cell: clipped by the column, hovering shows the full text.
fn tooltip_label(ui: &mut egui::Ui, value: &Option<String>) {
    let response = ui.label(optional_text(value));
    if let Some(full) = value.as_deref().map(str::trim).filter(|text| !text.is_empty()) {
        response.on_hover_text(full);
    }
}

/// One sidebar row (round 6 П1): the selection spans the FULL panel
/// width — the standard list pattern — instead of ending at the text
/// (the old `selectable_value` hugged its label, so rows had ragged
/// widths). Name at a fixed left inset, count pinned to the right
/// edge; selected + hover are painted backgrounds. A too-long name is
/// clipped before the count and shows the full text on hover.
fn sidebar_row(ui: &mut egui::Ui, selected: bool, name: &str, count: &str) -> egui::Response {
    let (rect, response) = ui.allocate_exact_size(
        egui::vec2(ui.available_width(), SIDEBAR_ROW_HEIGHT),
        egui::Sense::click(),
    );
    let painter = ui.painter();
    let visuals = ui.visuals();
    if selected {
        painter.rect_filled(rect, 4.0, visuals.selection.bg_fill);
    } else if response.hovered() {
        painter.rect_filled(rect, 4.0, visuals.widgets.hovered.bg_fill);
    }
    let inner = rect.shrink2(egui::vec2(SIDEBAR_ROW_INSET, 0.0));
    let middle = rect.center().y;
    let count_galley = painter.layout_no_wrap(
        count.to_owned(),
        egui::FontId::proportional(12.0),
        visuals.weak_text_color(),
    );
    painter.text(
        egui::pos2(inner.right(), middle),
        egui::Align2::RIGHT_CENTER,
        count,
        egui::FontId::proportional(12.0),
        visuals.weak_text_color(),
    );
    // The name is laid out first and clipped to the room left of the
    // count: a long playlist title must never run under the numbers.
    let name_galley = painter.layout_no_wrap(
        name.to_owned(),
        egui::FontId::proportional(14.0),
        visuals.text_color(),
    );
    let name_width = (inner.width() - count_galley.size().x - SIDEBAR_NAME_COUNT_GAP).max(0.0);
    let name_clipped = name_galley.size().x > name_width;
    let name_clip = egui::Rect::from_min_max(
        egui::pos2(inner.left(), rect.top()),
        egui::pos2(inner.left() + name_width, rect.bottom()),
    );
    painter.with_clip_rect(name_clip).galley(
        egui::pos2(inner.left(), middle - 0.5 * name_galley.size().y),
        name_galley,
        visuals.text_color(),
    );
    if name_clipped {
        return response.on_hover_text(name);
    }
    response
}

/// One sidebar row wiring: painted full-width row (see [`sidebar_row`]),
/// click switches the central context, ПКМ offers rename and delete
/// (user playlists only; the master is refused honestly), drops add
/// tracks. Built-in device views accept no drops and no ПКМ: the
/// firmware owns them. «Все треки» only on the master; the others show
/// a count.
fn playlist_row(
    ui: &mut egui::Ui,
    snapshot: &LibrarySnapshot,
    playlist: &Playlist,
    view: &mut LibraryView,
    menus_allowed: bool,
) -> PlaylistPanelActions {
    let mut actions = PlaylistPanelActions::default();
    let is_view = playlist.distinguished_kind != 0;
    let count_text = if playlist.is_master {
        "Все треки".to_owned()
    } else if is_view {
        let kinds = view_media_kinds(playlist.distinguished_kind);
        let count = snapshot
            .tracks
            .iter()
            .filter(|track| kinds.contains(&track.media_kind))
            .count();
        format!("{} {}", count, plural(count, "трек", "трека", "треков"))
    } else {
        let count = playlist.unique_track_ids().len();
        format!("{} {}", count, plural(count, "трек", "трека", "треков"))
    };
    let row_view = if playlist.is_master {
        LibraryView::Master
    } else if is_view {
        LibraryView::Media {
            distinguished: playlist.distinguished_kind,
        }
    } else {
        LibraryView::Playlist(playlist.id)
    };
    let (_, dropped) = ui.dnd_drop_zone::<DraggedTracks, ()>(
        egui::Frame::default().inner_margin(egui::Margin::same(2)),
        |ui| {
            let selected = *view == row_view;
            let row = sidebar_row(ui, selected, &playlist.name, &count_text);
            if row.clicked() {
                *view = row_view;
            }
            if menus_allowed && !is_view {
                // Round 8: the approved UX menu — «Переименовать…» and
                // «Удалить плейлист…»; the master takes both choices and
                // is refused honestly (no dead menu items).
                let mut refused_master = None;
                row.context_menu(|ui| {
                    if ui.button("Переименовать…").clicked() {
                        if playlist.is_master {
                            refused_master = Some(playlist.name.clone());
                        } else {
                            actions.rename_playlist = Some(playlist.id);
                        }
                        ui.close();
                    }
                    if ui.button("Удалить плейлист…").clicked() {
                        if playlist.is_master {
                            refused_master = Some(playlist.name.clone());
                        } else {
                            actions.delete_playlist = Some(playlist.id);
                        }
                        ui.close();
                    }
                });
                if let Some(name) = refused_master {
                    actions.master_rename = Some(name);
                }
            }
        },
    );
    if let Some(dragged) = dropped {
        if playlist.is_master {
            actions.master_drop = Some(playlist.name.clone());
        } else if is_view {
            // The firmware owns built-in views: drops are refused
            // up front instead of a failed round trip.
            actions.view_drop = Some(playlist.name.clone());
        } else {
            actions.add_drop = Some((playlist.id, dragged.0.clone()));
        }
    }
    actions
}

/// Field editors of the edit-track dialog; returns true on «Сохранить».
/// Cancel closes via `ui.close()` (surfaces as `should_close`).
fn edit_track_dialog_fields(ui: &mut egui::Ui, dialog: &mut EditDialogState) -> bool {
    let mut save = false;
    // Local copy: egui closures each need their own `&mut` field handle.
    let mut fields = dialog.fields.clone();
    ui.horizontal(|ui| {
        ui.label("Название:      ");
        let title = ui.add(
            egui::TextEdit::singleline(&mut fields.title).desired_width(320.0),
        );
        text_menu::attach_text_menu(&title);
    });
    ui.horizontal(|ui| {
        ui.label("Исполнитель:  ");
        let artist = ui.add(
            egui::TextEdit::singleline(&mut fields.artist).desired_width(320.0),
        );
        text_menu::attach_text_menu(&artist);
    });
    ui.horizontal(|ui| {
        ui.label("Альбом:       ");
        let album = ui.add(
            egui::TextEdit::singleline(&mut fields.album).desired_width(320.0),
        );
        text_menu::attach_text_menu(&album);
    });
    ui.horizontal(|ui| {
        ui.label("Альбом-артист:");
        let album_artist = ui.add(
            egui::TextEdit::singleline(&mut fields.album_artist)
                .desired_width(320.0),
        );
        text_menu::attach_text_menu(&album_artist);
    });
    ui.horizontal(|ui| {
        ui.label("Трек №:       ");
        let track_number = ui.add(
            egui::TextEdit::singleline(&mut fields.track_number)
                .desired_width(60.0),
        );
        text_menu::attach_text_menu(&track_number);
        ui.label("Диск №:");
        let disc_number = ui.add(
            egui::TextEdit::singleline(&mut fields.disc_number)
                .desired_width(60.0),
        );
        text_menu::attach_text_menu(&disc_number);
    });
    dialog.fields = fields;
    if let Some(error) = &dialog.error {
        ui.colored_label(egui::Color32::LIGHT_RED, error);
    }
    ui.separator();
    ui.horizontal(|ui| {
        if ui.button("Отмена").clicked() {
            ui.close();
        }
        if ui.button("Сохранить").clicked() {
            save = true;
            ui.close();
        }
    });
    save
}

/// Headless table render for the Ф4 layout test: same builder config
/// as production, header cells measured via allocated rects. Five
/// columns since round 6 П2 (checkbox + four data columns).
#[cfg(test)]
fn render_measured_table(ui: &mut egui::Ui) -> Vec<egui::Rect> {
    let rects: [std::rc::Rc<std::cell::RefCell<Option<egui::Rect>>>; 5] =
        Default::default();
    let sinks = rects.clone();
    track_table_builder(ui, egui::Id::unique("test_table"))
        .header(ROW_HEIGHT, move |mut header| {
            for sink in sinks {
                header.col(move |ui| {
                    let (rect, _) = ui.allocate_exact_size(
                        egui::vec2(ui.available_width(), 16.0),
                        egui::Sense::hover(),
                    );
                    *sink.borrow_mut() = Some(rect);
                });
            }
        })
        .body(|mut body| {
            body.row(ROW_HEIGHT, |mut row| {
                row.col(|ui| {
                    ui.label("Alpha");
                });
                row.col(|ui| {
                    ui.label("Artist");
                });
                row.col(|ui| {
                    ui.label("Album");
                });
                row.col(|ui| {
                    ui.label("2:03");
                });
            });
        });
    rects
        .iter()
        .map(|cell| cell.borrow().expect("header cell must render"))
        .collect()
}

/// Missing tags render as an em dash instead of nothing.
fn optional_text(value: &Option<String>) -> String {
    value
        .as_deref()
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .map(str::to_owned)
        .unwrap_or_else(|| "—".to_owned())
}

/// `123456` ms → `2:03`; zero means unknown → em dash.
fn format_duration(duration_ms: u32) -> String {
    if duration_ms == 0 {
        return "—".to_owned();
    }
    let total_seconds = duration_ms / 1000;
    format!("{}:{:02}", total_seconds / 60, total_seconds % 60)
}

/// Gate for opening any context menu: every choice inside fires a
/// library request, and a busy worker must not even be offered more
/// work. Centralised so every menu site follows one rule.
fn context_menu_allowed(app: &PodlibApp) -> bool {
    app.library_idle()
}

/// Full-window overlay while files hover over the viewport.
fn draw_drop_overlay(ui: &egui::Ui, names: &[String]) {
    let ctx = ui.ctx();
    let painter =
        ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("drop_overlay")));
    let rect = ctx.content_rect();
    painter.rect_filled(rect, 12.0, egui::Color32::from_black_alpha(160));
    let font = egui::TextStyle::Heading.resolve(&ctx.global_style());
    let text = if names.len() == 1 {
        format!("Отпустите, чтобы добавить: {}", names[0])
    } else {
        format!("Отпустите, чтобы добавить файлы: {} шт.", names.len())
    };
    painter.text(
        rect.center(),
        egui::Align2::CENTER_CENTER,
        text,
        font,
        egui::Color32::WHITE,
    );
}

/// Outcome of one frame of the shared sudo-password modal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PasswordModal {
    /// Still open — keep showing it next frame.
    Open,
    /// The user confirmed (submit button, or Enter on a non-empty field).
    Confirmed,
    /// The user cancelled (Cancel button, Esc, backdrop click).
    Cancelled,
}

/// Stable id of the shared modal's password field (the autofocus
/// target), derived from the modal salt so each flow gets its own.
fn password_field_id(id_salt: &str) -> egui::Id {
    egui::Id::unique(id_salt).with("password_field")
}

/// Unified sudo-password modal (round 6.1) behind connect AND
/// disconnect: the field takes focus whenever nothing else holds it
/// (so it is focused the moment the modal opens — the search-box
/// pattern), Enter submits a non-empty password, Esc and the backdrop
/// click cancel, and the submit button stays disabled while the field
/// is empty. The password never leaves the app: the caller consumes
/// and clears it when the worker starts.
fn password_modal(
    ctx: &egui::Context,
    id_salt: &str,
    password: &mut String,
    heading: &str,
    body: &str,
    submit_label: &str,
) -> PasswordModal {
    let field_id = password_field_id(id_salt);
    let mut outcome = PasswordModal::Open;
    let response = egui::Modal::new(egui::Id::unique(id_salt)).show(ctx, |ui| {
        ui.set_width(440.0);
        ui.heading(heading);
        ui.add_space(4.0);
        ui.label(body);
        ui.add_space(6.0);
        ui.horizontal(|ui| {
            ui.label("Пароль sudo:");
            let password_field = ui.add(
                egui::TextEdit::singleline(password)
                    .password(true)
                    .desired_width(220.0)
                    .id(field_id),
            );
            text_menu::attach_secret_text_menu(&password_field);
            if ctx.memory(|memory| memory.focused().is_none()) {
                ctx.memory_mut(|memory| memory.request_focus(field_id));
            }
            // Enter submits a non-empty password; an empty one keeps
            // the modal open — the same rule as the disabled button.
            // Checked at the input level (not via the field's
            // lost_focus) so the shortcut works regardless of which
            // widget egui considers focused inside the modal.
            let submit_now =
                ui.input(|input| input.key_pressed(egui::Key::Enter)) && !password.is_empty();
            if submit_now {
                outcome = PasswordModal::Confirmed;
                ui.close();
            }
        });
        ui.separator();
        ui.horizontal(|ui| {
            if ui.button("Отмена").clicked() {
                outcome = PasswordModal::Cancelled;
                ui.close();
            }
            let ready = !password.is_empty();
            if ui
                .add_enabled(ready, egui::Button::new(submit_label))
                .clicked()
            {
                outcome = PasswordModal::Confirmed;
                ui.close();
            }
        });
    });
    // Esc / backdrop close the modal without an in-closure decision —
    // that is a cancellation too.
    if response.should_close() && outcome == PasswordModal::Open {
        outcome = PasswordModal::Cancelled;
    }
    outcome
}

/// Worker-thread body: run the sudo mount sequence (`mkdir -p`, then
/// rw-mount) and report the mount point plus whether this app run is
/// now responsible for the safe unmount. Round 5.3: an already-mounted
/// target is skipped (idempotent connect). Batch F: such a mount is
/// ADOPTED (`mounted_by_us = true`) — the old «not ours, do not
/// unmount» semantics left mounts orphaned by a podlib restart or
/// crash mounted rw forever (live incident). Foreign mounts the owner
/// connected to deliberately are adopted too — the price of keeping
/// this simple; ejecting them on close is accepted by the owner.
/// Round 6.3: the one foreign mount that must NOT be adopted is a
/// read-only automount (udisks2 on HFS+): reads work, every write
/// fails, so it is unmounted first and the usual mkdir+mount runs.
/// The library is NOT opened here: `Box<dyn LibraryBackend>` is not
/// `Send`, so it is opened on the library worker thread instead (see
/// library.rs).
/// What must happen before (or instead of) the mkdir+rw-mount sequence,
/// decided from the /proc/mounts snapshot (rounds 5.3 / batch F / 6.3).
enum ConnectPlan {
    /// Target already carries the same source rw — skip the mount and
    /// adopt it (mounted_by_us=true so closing ejects it).
    AdoptMounted,
    /// Honest refusal: another device already owns the target.
    Conflict(String),
    /// Target free (or the foreign ro automount was just removed): run
    /// the mkdir+rw-mount steps as usual.
    Mount,
}

/// Mount-time branch of the connect flow: /proc/mounts decides whether
/// the target is already mounted (adopt — idempotent connect, round
/// 5.3), mounted read-only by the system (one extra sudo unmount first
/// — round 6.3), mounted from another device (honest refusal), or free.
fn resolve_connect_plan(
    password: &str,
    mount_path: &Path,
    block_dev: &Path,
) -> Result<ConnectPlan, ConnectError> {
    let mounts = std::fs::read_to_string("/proc/mounts")
        .map(|content| device::parse_proc_mounts_full(&content))
        .unwrap_or_default();
    match device::decide_mount_full(&mounts, block_dev, mount_path) {
        device::MountDecision::AlreadyMounted => Ok(ConnectPlan::AdoptMounted),
        device::MountDecision::ForeignReadOnly => {
            // One extra sudo step; on success the target is free and the
            // caller proceeds with the usual mkdir+mount.
            unmount_foreign_ro_volume(password, block_dev)?;
            Ok(ConnectPlan::Mount)
        }
        device::MountDecision::ConflictsWith(other) => Ok(ConnectPlan::Conflict(other)),
        device::MountDecision::Free => Ok(ConnectPlan::Mount),
    }
}

fn connect_device(
    password: String, // owned: dropped right after the last command (W3)
    steps: Vec<device::CommandSpec>,
    mount_path: PathBuf,
    block_dev: PathBuf,
) -> Result<(PathBuf, bool), ConnectError> {
    // WHY the password lives across the whole flow: every sudo step
    // (ro-unmount, mount sequence) consumes its own copy from stdin;
    // it is dropped only after the last step, never stored anywhere.
    match resolve_connect_plan(&password, &mount_path, &block_dev)? {
        ConnectPlan::AdoptMounted => {
            drop(password);
            // Batch F (adoption): connecting to an already-mounted
            // volume makes its safe unmount this app's responsibility.
            return Ok((mount_path, true));
        }
        ConnectPlan::Conflict(other) => {
            drop(password);
            return Err(ConnectError::Mount {
                stderr: format!(
                    "{mount_path_display} уже смонтирован с {other} — подключение отменено.",
                    mount_path_display = mount_path.display()
                ),
                error: MountError::AlreadyMounted,
            });
        }
        ConnectPlan::Mount => {}
    }
    for spec in &steps {
        let output =
            device::run_sudo_command(&password, spec).map_err(|error| ConnectError::Mount {
                stderr: String::new(),
                error: MountError::Io(error),
            })?;
        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
        device::classify_mount_output(&output)
            .map_err(|error| ConnectError::Mount { error, stderr })?;
    }
    drop(password);
    Ok((mount_path, true))
}

/// Round 6.3: removes the foreign read-only mount blocking the connect
/// target (`udisksctl unmount -b <dev>` under sudo, password already in
/// hand). Review M1: sudo auth failures classify as WrongPassword —
/// the same hint and retry flow as the mount loop below; other failures
/// keep the honest read-only message with the tool's stderr.
fn unmount_foreign_ro_volume(password: &str, block_dev: &Path) -> Result<(), ConnectError> {
    let spec = device::build_unmount_command(block_dev);
    let output =
        device::run_sudo_command(password, &spec).map_err(|error| ConnectError::Mount {
            stderr: String::new(),
            error: MountError::Io(error),
        })?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
        return Err(ConnectError::Mount {
            error: device::unmount_failure_class(&stderr),
            stderr,
        });
    }
    Ok(())
}

/// Runs a worker body, converting a panic into an honest error value.
/// Without this a panicking worker drops the event sender, the UI sees
/// only `Disconnected` and unlocks silently — with no clue what broke.
fn run_worker_step<T, E>(
    body: impl FnOnce() -> Result<T, E> + std::panic::UnwindSafe,
    on_panic: impl FnOnce(String) -> E,
) -> Result<T, E> {
    std::panic::catch_unwind(body)
        .unwrap_or_else(|panic| Err(on_panic(panic_message(panic))))
}

impl eframe::App for PodlibApp {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        self.drain_events();
        self.drain_library();
        self.guard_close_request(ui);
        self.collect_dropped_files(ui);
        // A close requested mid-operation ejects the device as soon as
        // the app becomes idle (round 5.3) — through the shared password
        // modal (batch F), never by starting the sequence directly.
        self.maybe_deferred_close_eject();
        // A selected view deleted from the device falls back to the
        // master view (checked once per frame, before panels).
        if let Some(library) = self.library.as_mut() {
            let stale = match library.view {
                LibraryView::Master => false,
                LibraryView::Media { distinguished } => !library
                    .snapshot
                    .playlists
                    .iter()
                    .any(|playlist| playlist.distinguished_kind == distinguished),
                LibraryView::Playlist(id) => library.snapshot.playlist(id).is_none(),
            };
            if stale {
                library.view = LibraryView::Master;
            }
        }
        // 1) App bar: name + device state + eject.
        egui::Panel::top("app_bar")
            .default_size(48.0)
            .show(ui, |ui| self.app_bar(ui));
        // 2) Left sidebar: device list while disconnected, playlists
        //    once connected (the old right playlists panel is gone —
        //    it duplicated the central table). 240px (Ф4): leaves the
        //    table enough width for all four columns at ≥900px windows.
        //    The width ceiling comes from device_panel_builder: a drag
        //    (or a persisted oversized state) can never eat the central
        //    panel below MIN_CENTRAL_PANEL_WIDTH (round 6.5).
        device_panel_builder(ui).show(ui, |ui| {
                if self.connected.is_some() {
                    let actions = self.playlists_sidebar(ui);
                    self.apply_playlist_actions(actions);
                } else {
                    self.device_panel(ui);
                }
            });
        // 3) Status bar BEFORE the central panel (round 5.3 Ф1): a
        //    bottom panel declared after the central one shrinks to
        //    nothing — the central panel already claimed the space and
        //    the owner lost all feedback. egui lays panels out in
        //    declaration order; the central panel takes what remains.
        egui::Panel::bottom("status_bar")
            .default_size(34.0)
            .min_size(26.0) // round 5.3 Ф1: never collapses below one row
            .resizable(false)
            .show(ui, |ui| self.status_bar(ui));
        // 4) Central panel: the selected playlist context (master = the
        //    whole library), or a plain hint while disconnected.
        egui::CentralPanel::default().show(ui, |ui| {
            if self.connected.is_none() {
                ui.centered_and_justified(|ui| {
                    ui.label(
                        egui::RichText::new(
                            "Подключите устройство, чтобы работать с библиотекой",
                        )
                        .weak(),
                    );
                });
            } else if self.library.is_none() {
                ui.centered_and_justified(|ui| {
                    ui.colored_label(
                        egui::Color32::LIGHT_RED,
                        "Библиотека недоступна: воркер закрылся. Отключите и подключите \
                         устройство заново.",
                    );
                });
            } else {
                self.library_view(ui);
            }
        });
        // Hover preview above everything while files are dragged over us.
        let hovered: Vec<String> = ui
            .input(|input| {
                input
                    .raw
                    .hovered_files
                    .iter()
                    .filter_map(|file| {
                        file.path
                            .as_ref()
                            .map(|path| path.display().to_string())
                    })
                    .collect()
            });
        if !hovered.is_empty() {
            draw_drop_overlay(ui, &hovered);
        }
        let ctx = ui.ctx().clone();
        self.maybe_mount_modal(&ctx);
        self.maybe_eject_modal(&ctx);
        self.maybe_close_confirm_modal(&ctx);
        self.maybe_tag_review_modal(&ctx);
        self.maybe_delete_track_modal(&ctx);
        self.maybe_delete_playlist_modal(&ctx);
        self.maybe_create_playlist_modal(&ctx);
        self.maybe_rename_playlist_modal(&ctx);
        self.maybe_set_artist_modal(&ctx);
        self.maybe_edit_track_modal(&ctx);
        self.maybe_add_to_playlist_modal(&ctx);
        if self.start_mount {
            self.start_mount = false;
            self.spawn_connect();
        }
        if self.start_eject {
            self.start_eject = false;
            self.spawn_eject();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use podlib::{build_nano2g_fixture, FixtureTrack};
    use tempfile::TempDir;

    use super::*;

    const POLL: Duration = Duration::from_millis(2);
    const DEADLINE: usize = 2500; // ~5 s

    /// Headless app instance: `handle_event`/`drain_*` only touch plain
    /// state (strings, options, channels), no egui rendering.
    fn test_app() -> PodlibApp {
        PodlibApp::new(egui::Context::default())
    }

    fn sample_track(id: u64, title: &str) -> Track {
        Track {
            id: TrackId::from_bits(id),
            title: title.to_owned(),
            artist: Some("Artist".to_owned()),
            album: None,
            album_artist: None,
            duration_ms: 90_000,
            track_number: 1,
            disc_number: 1,
            size_bytes: 1024,
            has_artwork: false,
            media_kind: 1,
        }
    }

    fn sample_playlist(id: u64, name: &str) -> Playlist {
        Playlist {
            id: PlaylistId::from_bits(id),
            name: name.to_owned(),
            track_ids: Vec::new(),
            is_master: false,
            is_smart: false,
            distinguished_kind: 0,
        }
    }

    /// A mount with a one-track classic-device fixture.
    fn fixture_mount() -> TempDir {
        let dir = TempDir::new().unwrap();
        build_nano2g_fixture(
            dir.path(),
            &[FixtureTrack {
                title: "Alpha".to_owned(),
                artist: None,
                album: None,
                genre: None,
                file_name: "a.mp3".to_owned(),
                size_bytes: 2048,
                duration_ms: 120_000,
                track_number: 1,
                disc_number: 1,
            }],
            &[],
        )
        .unwrap();
        dir
    }

    /// Polls `drain_library` until `done` says stop or the deadline passes.
    fn pump(app: &mut PodlibApp, mut done: impl FnMut(&PodlibApp) -> bool) -> bool {
        for _ in 0..DEADLINE {
            app.drain_library();
            if done(app) {
                return true;
            }
            std::thread::sleep(POLL);
        }
        false
    }

    // ---- device round-1 behaviour (kept) ----

    #[test]
    fn panic_message_handles_common_payloads() {
        assert_eq!(panic_message(Box::new("str panic")), "str panic");
        assert_eq!(
            panic_message(Box::new(String::from("boxed panic"))),
            "boxed panic"
        );
        assert_eq!(panic_message(Box::new(7u32)), "причина не сообщена");
    }

    #[test]
    fn worker_panic_maps_to_internal_error() {
        let result: Result<PathBuf, ConnectError> =
            run_worker_step(|| panic!("worker exploded"), ConnectError::Internal);
        match result {
            Err(ConnectError::Internal(message)) => {
                assert!(message.contains("worker exploded"))
            }
            other => panic!("expected Err(Internal), got {other:?}"),
        }
    }

    #[test]
    fn panicked_worker_event_unlocks_ui_and_shows_error() {
        let mut app = test_app();
        app.busy = true;
        let (tx, rx) = channel();
        app.rx = Some(rx);
        let error: Result<(PathBuf, bool), ConnectError> =
            run_worker_step(|| panic!("worker exploded"), ConnectError::Internal);
        tx.send(DeviceEvent::Connected(error)).unwrap();
        drop(tx); // the panicking worker is gone: the channel closes
        app.drain_events();
        // The UI must be unlocked honestly, with the panic surfaced.
        assert!(!app.busy);
        let error = app.error.expect("panic must be shown as an error");
        assert!(error.message.contains("worker exploded"));
    }

    #[test]
    fn worker_without_panic_passes_result_through() {
        let result: Result<(PathBuf, bool), ConnectError> = run_worker_step(
            || Ok((PathBuf::from("/run/media/ipod"), true)),
            |_| unreachable!(),
        );
        assert_eq!(
            result.unwrap(),
            (PathBuf::from("/run/media/ipod"), true)
        );
    }

    // ---- library lifecycle through the real worker ----

    #[test]
    fn connected_event_opens_library_and_loads_snapshot() {
        let dir = fixture_mount();
        let mut app = test_app();
        app.handle_event(DeviceEvent::Connected(Ok((dir.path().to_owned(), true))));
        assert!(app.connected.is_some());
        assert!(app.library.is_some());
        let loaded = pump(&mut app, |app| {
            app.library
                .as_ref()
                .is_some_and(|library| library.opening.is_none())
        });
        assert!(loaded, "worker must deliver the initial listing");
        let library = app.library.as_ref().unwrap();
        assert_eq!(library.snapshot.tracks.len(), 1);
        assert_eq!(library.snapshot.tracks[0].title, "Alpha");
        assert!(app.status.contains("Подключено"));
        // P1: Russian plural forms — «1 трек», not «1 треков».
        assert!(
            app.status.contains("1 трек, 1 плейлист"),
            "got: {}",
            app.status
        );
        let library = app.library.take().unwrap();
        library.worker.close_and_join();
    }

    #[test]
    fn open_failure_reports_mounted_volume_and_drops_library() {
        let dir = TempDir::new().unwrap(); // no library inside
        let mut app = test_app();
        app.handle_event(DeviceEvent::Connected(Ok((dir.path().to_owned(), true))));
        let dropped = pump(&mut app, |app| app.library.is_none());
        assert!(dropped, "failed open must drop the library UI");
        let error = app.error.expect("open failure must be shown");
        // The volume IS mounted at this point — the message says so.
        assert!(error.message.contains("смонтирован"));
        assert!(app.connected.is_some(), "device stays connected");
    }

    // ---- pending-op state machine (manual channels, no waiting) ----

    fn app_with_open_library() -> (PodlibApp, TempDir) {
        let dir = fixture_mount();
        let mut app = test_app();
        app.handle_event(DeviceEvent::Connected(Ok((dir.path().to_owned(), true))));
        let settled = pump(&mut app, |app| {
            app.library
                .as_ref()
                .is_some_and(|library| library.opening.is_none())
        });
        assert!(settled, "fixture library must open in tests");
        (app, dir)
    }

    #[test]
    fn applied_outcome_updates_snapshot_and_status() {
        let (mut app, _dir) = app_with_open_library();
        let (tx, rx) = channel();
        app.library
            .as_mut()
            .unwrap()
            .pending = Some((PendingKind::AddTracks, rx));
        tx.send(LibraryOutcome::Applied {
            snapshot: LibrarySnapshot {
                tracks: vec![sample_track(1, "A"), sample_track(2, "B")],
                playlists: Vec::new(),
            },
            summary: "Добавлено 2 трека".to_owned(),
        })
        .unwrap();
        app.drain_library();
        let library = app.library.as_ref().unwrap();
        assert_eq!(library.snapshot.tracks.len(), 2, "snapshot replaced");
        assert!(library.pending.is_none(), "op must be settled");
        assert_eq!(app.status, "Добавлено 2 трека");
        assert!(app.error.is_none());
    }

    #[test]
    fn edit_outcome_reports_id_change_via_summary() {
        let (mut app, _dir) = app_with_open_library();
        let (tx, rx) = channel();
        app.library
            .as_mut()
            .unwrap()
            .pending = Some((PendingKind::EditTrack, rx));
        let mut track = sample_track(9, "Beta");
        track.duration_ms = 0; // renders as an em dash in the table
        tx.send(LibraryOutcome::Applied {
            snapshot: LibrarySnapshot {
                tracks: vec![track],
                playlists: Vec::new(),
            },
            summary: "Обновлено: «Beta» (новый id: 9)".to_owned(),
        })
        .unwrap();
        app.drain_library();
        let library = app.library.as_ref().unwrap();
        assert_eq!(library.snapshot.tracks[0].title, "Beta");
        assert_eq!(app.status, "Обновлено: «Beta» (новый id: 9)");
    }

    #[test]
    fn applied_prunes_dead_ids_from_selection_and_anchor() {
        // Review 🟢-5: after an applied operation the toolbar must not
        // count rows that no longer exist in the new snapshot.
        let (mut app, _dir) = app_with_open_library();
        let (tx, rx) = channel();
        {
            let library = app.library.as_mut().unwrap();
            library.pending = Some((PendingKind::RemoveTrack, rx));
            library.selected_tracks = vec![
                TrackId::from_bits(1),
                TrackId::from_bits(2),
                TrackId::from_bits(77), // removed by the operation
            ];
            // The anchor row vanished with the re-list: dropped instead
            // of surviving as a stale identity.
            library.selection_anchor = Some((2, TrackId::from_bits(77)));
        }
        tx.send(LibraryOutcome::Applied {
            snapshot: LibrarySnapshot {
                tracks: vec![sample_track(1, "A"), sample_track(2, "B")],
                playlists: Vec::new(),
            },
            summary: "Удалено".to_owned(),
        })
        .unwrap();
        app.drain_library();
        let library = app.library.as_ref().unwrap();
        assert_eq!(
            library.selected_tracks,
            vec![TrackId::from_bits(1), TrackId::from_bits(2)],
            "dead ids must leave the selection"
        );
        assert_eq!(
            library.selection_anchor, None,
            "a stale anchor must be dropped"
        );
    }

    #[test]
    fn failed_outcome_shows_error_but_keeps_library() {
        let (mut app, _dir) = app_with_open_library();
        let (tx, rx) = channel();
        app.library
            .as_mut()
            .unwrap()
            .pending = Some((PendingKind::DeletePlaylist, rx));
        tx.send(LibraryOutcome::Failed {
            message: "Плейлист 16 — встроенный, его нельзя изменять".to_owned(),
            hint: Some("Мастер-плейлист доступен только для чтения".to_owned()),
        })
        .unwrap();
        app.drain_library();
        assert!(app.library.is_some(), "backend failure must not kill the UI");
        assert!(app.library.as_ref().unwrap().pending.is_none());
        let error = app.error.expect("backend failure must be shown");
        assert!(error.message.contains("встроенный"));
        assert!(error.hint.is_some());
    }

    #[test]
    fn disconnected_worker_drops_library_and_explains() {
        let (mut app, _dir) = app_with_open_library();
        let (tx, rx) = channel();
        app.library
            .as_mut()
            .unwrap()
            .pending = Some((PendingKind::Refresh, rx));
        drop(tx); // worker died mid-operation
        app.drain_library();
        assert!(app.library.is_none());
        let error = app.error.expect("dead worker must be reported");
        assert!(error.message.contains("завершился"));
    }

    #[test]
    fn closed_outcome_drops_library() {
        let (mut app, _dir) = app_with_open_library();
        let (tx, rx) = channel();
        app.library
            .as_mut()
            .unwrap()
            .pending = Some((PendingKind::Refresh, rx));
        tx.send(LibraryOutcome::Closed).unwrap();
        app.drain_library();
        assert!(app.library.is_none());
    }

    #[test]
    fn ejected_error_keeps_connected_and_hints_reconnect() {
        let (mut app, _dir) = app_with_open_library();
        // spawn_eject takes the library before starting the sequence;
        // simulate that here.
        app.library = None;
        let (tx, rx) = channel();
        tx.send(DeviceEvent::Ejected(Err("unmount failed".to_owned()))).unwrap();
        app.rx = Some(rx);
        app.drain_events();
        assert!(app.connected.is_some(), "failed eject keeps the device");
        let error = app.error.expect("eject failure must be shown");
        assert!(error.hint.is_some());
        // Batch F: the generic hint now offers the safe retry instead of
        // pushing the user to reconnect.
        let hint = error.hint.unwrap();
        assert!(
            hint.contains("ещё раз") && hint.contains("безопасна"),
            "got: {hint}"
        );
    }

    // ---- busy-worker refusal and menu gate (F2 / P2) ----

    #[test]
    fn request_without_library_asks_to_connect_first() {
        // P2: with no library at all there is no operation to wait for —
        // the refusal must point at connecting a device instead.
        let mut app = test_app();
        assert!(app.library.is_none());
        app.library_request(
            LibraryCommand::Refresh,
            PendingKind::Refresh,
            "Обновляю список…",
        );
        let error = app
            .error
            .expect("request without a library must be refused");
        assert!(
            error.message.contains("подключите"),
            "got: {}",
            error.message
        );
        assert!(
            !error.message.contains("Дождитесь"),
            "there is no operation to wait for"
        );
    }

    #[test]
    fn picker_close_captures_ids_before_clearing() {
        // Regression (release review, round 3): clearing the picker before
        // reading ids sent an empty AddToPlaylist with a lying
        // «Добавлено 0 треков» status for a real user action.
        let ids = vec![TrackId::from_bits(7), TrackId::from_bits(9)];
        let (state, request) =
            picker_close(Some(PlaylistId::from_bits(42)), false, Some(ids.clone()));
        assert_eq!(state, None, "chosen playlist must close the picker");
        assert_eq!(request, Some((PlaylistId::from_bits(42), ids)));
    }

    #[test]
    fn picker_close_without_choice_clears_and_sends_nothing() {
        let (state, request) = picker_close(None, true, Some(vec![TrackId::from_bits(1)]));
        assert_eq!(state, None);
        assert_eq!(request, None);

        // Neither chosen nor closed: picker state survives for the next frame.
        let (state, request) = picker_close(None, false, Some(vec![TrackId::from_bits(1)]));
        assert_eq!(state, Some(vec![TrackId::from_bits(1)]));
        assert_eq!(request, None);
    }

    #[test]
    fn busy_worker_rejects_new_request_visibly() {
        let (mut app, _dir) = app_with_open_library();
        let (_tx, rx) = channel();
        app.library.as_mut().unwrap().pending = Some((PendingKind::Refresh, rx));
        // A request while the worker is busy must be refused visibly,
        // not dropped silently: the user's action deserves an answer.
        app.library_request(
            LibraryCommand::CreatePlaylist {
                name: "Mix".to_owned(),
            },
            PendingKind::CreatePlaylist,
            "Создаю плейлист…",
        );
        let error = app
            .error
            .expect("busy refusal must be visible to the user");
        assert!(
            error.message.contains("Дождитесь завершения"),
            "got: {}",
            error.message
        );
        // The in-flight operation is untouched.
        let library = app.library.as_ref().unwrap();
        assert!(matches!(library.pending, Some((PendingKind::Refresh, _))));
        assert!(
            !app.status.contains("Создаю плейлист"),
            "status must not announce the rejected request"
        );
    }

    #[test]
    fn context_menu_gate_tracks_library_state() {
        let (mut app, _dir) = app_with_open_library();
        assert!(context_menu_allowed(&app), "idle app opens context menus");
        let (_tx, rx) = channel();
        app.library.as_mut().unwrap().pending = Some((PendingKind::Refresh, rx));
        assert!(
            !context_menu_allowed(&app),
            "pending operation must gate context menus"
        );
        // The initial open counts as busy too.
        let (_tx2, rx2) = channel();
        let library = app.library.as_mut().unwrap();
        library.pending = None;
        library.opening = Some(rx2);
        assert!(
            !context_menu_allowed(&app),
            "library opening must gate context menus too"
        );
    }

    // ---- close guard state machine (F4, headless) ----

    #[test]
    fn close_while_idle_closes_without_confirm() {
        assert_eq!(
            close_decision(true, false, false, false),
            CloseDecision::Allow,
            "idle window without our mount closes as usual"
        );
    }

    #[test]
    fn close_while_operation_active_blocks_and_asks() {
        assert_eq!(
            close_decision(true, true, false, false),
            CloseDecision::BlockWithConfirm,
            "mid-operation close must not kill the worker thread"
        );
    }

    /// Batch F: an idle close with a device mounted by this app must ask
    /// before closing — the round 5.3 eject needs the sudo password and
    /// must never run silently.
    #[test]
    fn close_while_idle_with_our_mount_blocks_and_asks() {
        assert_eq!(
            close_decision(true, false, false, true),
            CloseDecision::BlockWithConfirm,
            "our mount must be ejected before the window closes"
        );
        // Without the mount the same idle close stays a plain Allow.
        assert_eq!(
            close_decision(true, false, false, false),
            CloseDecision::Allow,
            "not-our-device close behaviour is unchanged"
        );
    }

    #[test]
    fn confirmed_close_passes_through_even_while_busy() {
        assert_eq!(
            close_decision(true, true, true, false),
            CloseDecision::Allow,
            "the user already chose to close: no confirm loop"
        );
        assert_eq!(
            close_decision(true, true, true, true),
            CloseDecision::Allow,
            "a confirmed close is not re-asked even with our mount"
        );
    }

    #[test]
    fn no_close_request_is_a_noop() {
        assert_eq!(close_decision(false, true, false, true), CloseDecision::Allow);
        assert_eq!(close_decision(false, false, true, true), CloseDecision::Allow);
    }

    /// Batch F: the idle+mounted case now reaches the confirm modal too,
    /// so its text must not claim an operation is in flight.
    #[test]
    fn close_confirm_texts_are_honest_for_idle_mount() {
        let (busy_title, _) = close_confirm_texts(true);
        let (idle_title, idle_body) = close_confirm_texts(false);
        assert_eq!(busy_title, "Идёт операция с библиотекой");
        assert_ne!(idle_title, busy_title, "idle close is not an operation");
        assert!(
            idle_body.contains("безопасно отключено"),
            "idle text must say the device is ejected, got: {idle_body}"
        );
        assert!(
            idle_body.contains("пароль"),
            "idle text must warn about the sudo password, got: {idle_body}"
        );
    }

    // ---- close = safe unmount for app-created mounts (round 5.3 Ф3) ----

    #[test]
    fn confirmed_close_ejects_first_only_for_app_created_mounts() {
        assert_eq!(
            close_confirmation_action(true),
            CloseAction::EjectFirst,
            "the app created the mount: unmount before closing"
        );
        assert_eq!(
            close_confirmation_action(false),
            CloseAction::CloseNow,
            "an externally mounted volume is not our responsibility"
        );
    }

    #[test]
    fn deferred_eject_fires_only_when_idle() {
        assert!(deferred_eject_due(true, false, true), "idle → eject now");
        assert!(!deferred_eject_due(true, true, false), "busy → wait");
        assert!(!deferred_eject_due(false, false, true), "no pending close");
    }

    // ---- status bar visibility (round 5.3 Ф1) ----

    /// Регрессия живого прогона 5.2: bottom-панель, объявленная ПОСЛЕ
    /// CentralPanel, схлопывалась до нуля (центральная забирала всё
    /// оставшееся место) и владелец терял все статусы и ошибки. Новый
    /// порядок (bottom до central) обязан держать высоту ≥ 26px.
    #[test]
    fn status_bar_panel_stays_visible_when_declared_before_central() {
        // The regression of live run 5.2: a bottom panel declared AFTER
        // the central one collapsed to nothing (the central panel had
        // already claimed the remaining space) and the owner lost every
        // status and error. The new order (bottom before central) must
        // keep the full panel height — animations disabled so a single
        // frame measures the settled layout.
        egui::__run_test_ui(|ui| {
            ui.style_mut().animation_time = 0.0;
            egui::Panel::top("r53_top").default_size(40.0).show(ui, |ui| {
                ui.label("podlib");
            });
            egui::Panel::left("r53_left").default_size(120.0).show(ui, |ui| {
                ui.label("sidebar");
            });
            let bottom = egui::Panel::bottom("r53_bottom")
                .default_size(34.0)
                .min_size(26.0)
                .resizable(false)
                .show(ui, |ui| {
                    ui.label("Готово");
                });
            assert!(
                bottom.response.rect.height() >= 26.0,
                "status bar collapsed: {} px",
                bottom.response.rect.height()
            );
            egui::CentralPanel::default().show(ui, |ui| {
                ui.label("central");
            });
        });
    }

    // ---- sidebar vs central panel (round 6.5) ----

    /// Реплика живого прогона 6.2–6.4: разделитель сайдбара оттянут до
    /// правого края окна — egui клампит драг только по экрану и не
    /// резервирует место под центральную панель, поэтому таблица
    /// схлопывается в ноль. Размер панели персистится между кадрами,
    /// поэтому «оттянули в прошлой сессии» = засеянный PanelState с
    /// шириной всего окна. Контракт раунда 6.5: центральная панель
    /// держит минимум MIN_CENTRAL_PANEL_WIDTH.
    #[test]
    fn fully_dragged_sidebar_cannot_collapse_the_central_panel() {
        egui::__run_test_ui(|ui| {
            ui.style_mut().animation_time = 0.0;
            let screen_w = ui.input(|input| input.viewport_rect().width());
            let panel_id = ui.scope_id().with_salt(egui::IdSalt::new("device_panel"));
            ui.ctx().data_mut(|data| {
                data.insert_persisted(
                    panel_id,
                    egui::PanelState {
                        outer_rect: egui::Rect::from_min_size(
                            egui::Pos2::ZERO,
                            egui::vec2(screen_w, 600.0),
                        ),
                    },
                );
            });
            egui::Panel::top("app_bar").default_size(48.0).show(ui, |ui| {
                ui.label("podlib");
            });
            let sidebar = device_panel_builder(ui).show(ui, |ui| {
                // Realistic content: sidebar rows span the full panel
                // width (see sidebar_row_spans_the_full_panel_width), so
                // the panel paints at its full reserved size. Empty
                // content would let egui shrink the frame to the row
                // minimum and hide the whole regression.
                ui.allocate_exact_size(
                    egui::vec2(ui.available_width(), 10.0),
                    egui::Sense::hover(),
                );
            });
            egui::Panel::bottom("status_bar").default_size(34.0).show(ui, |_ui| {});
            let central = egui::CentralPanel::default().show(ui, |ui| {
                ui.label("central");
            });
            let sidebar_rect = sidebar.response.rect;
            let central_rect = central.response.rect;
            assert!(
                sidebar_rect.right() <= central_rect.left() + 0.5,
                "sidebar ({sidebar_rect:?}) overlaps the central panel ({central_rect:?})"
            );
            assert!(
                central_rect.width() >= MIN_CENTRAL_PANEL_WIDTH,
                "a fully dragged sidebar left the central panel only {} px \
                 (minimum is {MIN_CENTRAL_PANEL_WIDTH})",
                central_rect.width()
            );
        });
    }

    /// Sweep ширины окна 900/800/700/500: панели не пересекаются, а
    /// чекбокс и название таблицы (первые две колонки) остаются внутри
    /// центральной панели. Правые колонки на узких окнах деградируют
    /// клипом (clip(true)) — это осознанное решение раунда 6.5.
    #[test]
    fn sidebar_and_central_panel_stay_disjoint_across_window_widths() {
        for width in [900.0, 800.0, 700.0, 500.0] {
            let ctx = egui::Context::default();
            let mut output = ctx.run_ui(
                egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(
                        egui::Pos2::ZERO,
                        egui::vec2(width, 600.0),
                    )),
                    ..Default::default()
                },
                |ui| {
                    ui.style_mut().animation_time = 0.0;
                    egui::Panel::top("app_bar").default_size(48.0).show(ui, |_ui| {});
                    let sidebar = device_panel_builder(ui).show(ui, |ui| {
                        // Same full-width content contract as the
                        // fully-dragged test above: the panel must paint
                        // at its reserved size for disjointness to mean
                        // anything.
                        ui.allocate_exact_size(
                            egui::vec2(ui.available_width(), 10.0),
                            egui::Sense::hover(),
                        );
                    });
                    egui::Panel::bottom("status_bar").default_size(34.0).show(ui, |_ui| {});
                    let mut header = Vec::new();
                    let central = egui::CentralPanel::default().show(ui, |ui| {
                        header = render_measured_table(ui);
                    });
                    let sidebar_rect = sidebar.response.rect;
                    let central_rect = central.response.rect;
                    assert!(
                        sidebar_rect.right() <= central_rect.left() + 0.5,
                        "at {width}px: sidebar ({sidebar_rect:?}) overlaps the \
                         central panel ({central_rect:?})"
                    );
                    for (name, rect) in [("чекбокс", header[0]), ("название", header[1])] {
                        assert!(
                            rect.right() <= central_rect.right() + 0.5
                                && rect.left() >= central_rect.left() - 0.5,
                            "at {width}px: колонка {name} ({rect:?}) вышла за \
                             пределы центральной панели ({central_rect:?})"
                        );
                    }
                },
            );
            output.textures_delta.clear();
        }
    }

    // ---- pure UI helpers ----

    #[test]
    fn duration_formats_minutes_seconds_and_unknown() {
        assert_eq!(format_duration(0), "—");
        assert_eq!(format_duration(1_000), "0:01");
        assert_eq!(format_duration(123_456), "2:03");
        assert_eq!(format_duration(3_600_000), "60:00");
    }

    #[test]
    fn optional_text_renders_em_dash_for_missing_tags() {
        assert_eq!(optional_text(&Some("X".to_owned())), "X");
        assert_eq!(optional_text(&Some("   ".to_owned())), "—");
        assert_eq!(optional_text(&None), "—");
    }

    // ---- batch-add status (P4) ----

    #[test]
    fn batch_add_status_announces_the_wait_and_skips() {
        assert_eq!(
            batch_add_status(1, 0, &[]),
            "Добавляется 1 файл, это может занять время…"
        );
        assert_eq!(
            batch_add_status(2, 0, &[]),
            "Добавляется 2 файла, это может занять время…"
        );
        assert_eq!(
            batch_add_status(30, 0, &[]),
            "Добавляется 30 файлов, это может занять время…"
        );
        assert_eq!(
            batch_add_status(3, 0, &["notes.txt".to_owned(), "noext".to_owned()]),
            "Добавляется 3 файла, это может занять время…; \
             пропущены: notes.txt, noext"
        );
        assert_eq!(
            batch_add_status(5, 2, &[]),
            "Добавляется 5 файлов (2 с транскодом), это может занять время…"
        );
    }

    // ---- search filter (round 4 UX) ----

    fn searchable_track(title: &str, artist: Option<&str>, album: Option<&str>) -> Track {
        Track {
            id: TrackId::from_bits(1),
            title: title.to_owned(),
            artist: artist.map(str::to_owned),
            album: album.map(str::to_owned),
            album_artist: None,
            duration_ms: 90_000,
            track_number: 1,
            disc_number: 1,
            size_bytes: 1024,
            has_artwork: false,
            media_kind: 1,
        }
    }

    #[test]
    fn empty_or_blank_query_matches_everything() {
        let track = searchable_track("Anything", Some("Whoever"), Some("Whatever"));
        assert!(matches_query(&track, ""));
        assert!(matches_query(&track, "   "));
    }

    #[test]
    fn query_matches_title_case_insensitively() {
        let track = searchable_track("Moonlight Sonata", None, None);
        assert!(matches_query(&track, "moon"));
        assert!(matches_query(&track, "SONATA"));
        assert!(matches_query(&track, "light son"));
        // Latin vs Cyrillic differs — no accidental matches.
        assert!(!matches_query(&track, "лунная"));
    }

    #[test]
    fn query_matches_cyrillic_case_insensitively() {
        let track = searchable_track("Лунная соната", None, None);
        assert!(matches_query(&track, "лунная"));
        assert!(matches_query(&track, "Соната"));
        assert!(!matches_query(&track, "moon"));
    }

    #[test]
    fn query_matches_artist_and_album_too() {
        let track = searchable_track("Title", Some("Beethoven"), Some("Classics"));
        assert!(matches_query(&track, "beeth"));
        assert!(matches_query(&track, "class"));
        assert!(!matches_query(&track, "mozart"));
    }

    #[test]
    fn missing_tags_are_not_searched_and_do_not_panic() {
        let track = searchable_track("Title", None, None);
        // «—» is a render artifact of empty tags, never part of the data:
        // it must not match a track whose tags are missing.
        assert!(!matches_query(&track, "—"));
        assert!(!matches_query(&track, "beeth"));
    }

    // ---- sidebar ordering: master first (round 4 UX) ----

    fn playlist_of(id: u64, name: &str, is_master: bool) -> Playlist {
        Playlist {
            id: PlaylistId::from_bits(id),
            name: name.to_owned(),
            track_ids: Vec::new(),
            is_master,
            is_smart: false,
            distinguished_kind: 0,
        }
    }

    #[test]
    fn master_first_keeps_master_first_and_rest_in_order() {
        let playlists = vec![
            playlist_of(1, "Медиатека", true),
            playlist_of(2, "Джаз", false),
            playlist_of(3, "Рок", false),
        ];
        let ordered: Vec<String> = master_first(&playlists)
            .into_iter()
            .map(|playlist| playlist.name.clone())
            .collect();
        assert_eq!(ordered, ["Медиатека", "Джаз", "Рок"]);
    }

    #[test]
    fn master_first_moves_master_from_the_middle_to_front() {
        let playlists = vec![
            playlist_of(2, "Джаз", false),
            playlist_of(1, "Медиатека", true),
            playlist_of(3, "Рок", false),
        ];
        let ordered: Vec<String> = master_first(&playlists)
            .into_iter()
            .map(|playlist| playlist.name.clone())
            .collect();
        assert_eq!(ordered, ["Медиатека", "Джаз", "Рок"]);
    }

    #[test]
    fn master_first_handles_empty_and_masterless_lists() {
        let empty: Vec<Playlist> = Vec::new();
        assert!(master_first(&empty).is_empty());
        let playlists = vec![playlist_of(2, "Джаз", false), playlist_of(3, "Рок", false)];
        let ordered: Vec<String> = master_first(&playlists)
            .into_iter()
            .map(|playlist| playlist.name.clone())
            .collect();
        assert_eq!(ordered, ["Джаз", "Рок"]);
    }

    // ---- keyboard navigation over the visible rows (round 4 UX) ----

    fn ids(bits: &[u64]) -> Vec<TrackId> {
        bits.iter().map(|&b| TrackId::from_bits(b)).collect()
    }

    #[test]
    fn navigation_on_empty_list_selects_nothing() {
        let visible: Vec<TrackId> = Vec::new();
        assert_eq!(next_selection(&visible, None, 1), None);
        assert_eq!(next_selection(&visible, None, -1), None);
    }

    #[test]
    fn navigation_without_selection_starts_at_first_row() {
        let visible = ids(&[10, 20, 30]);
        assert_eq!(next_selection(&visible, None, 1), Some(TrackId::from_bits(10)));
        assert_eq!(next_selection(&visible, None, -1), Some(TrackId::from_bits(10)));
    }

    #[test]
    fn navigation_moves_to_the_neighbour_and_clamps_at_edges() {
        let visible = ids(&[10, 20, 30]);
        let first = TrackId::from_bits(10);
        let middle = TrackId::from_bits(20);
        let last = TrackId::from_bits(30);
        assert_eq!(next_selection(&visible, Some(first), 1), Some(middle));
        assert_eq!(next_selection(&visible, Some(middle), -1), Some(first));
        assert_eq!(next_selection(&visible, Some(first), -1), Some(first), "up from top clamps");
        assert_eq!(next_selection(&visible, Some(last), 1), Some(last), "down from bottom clamps");
    }

    #[test]
    fn navigation_of_stale_selection_starts_over() {
        // e.g. the selected row was filtered out or removed: arrows
        // restart from the top instead of jumping anywhere.
        let visible = ids(&[10, 20, 30]);
        let stale = TrackId::from_bits(99);
        assert_eq!(next_selection(&visible, Some(stale), 1), Some(TrackId::from_bits(10)));
        assert_eq!(next_selection(&visible, Some(stale), -1), Some(TrackId::from_bits(10)));
    }

    #[test]
    fn activation_requires_a_visible_selection() {
        let visible = ids(&[10, 20]);
        assert_eq!(activated(&visible, Some(TrackId::from_bits(20))), Some(TrackId::from_bits(20)));
        assert_eq!(activated(&visible, None), None);
        assert_eq!(activated(&visible, Some(TrackId::from_bits(99))), None);
        let empty: Vec<TrackId> = Vec::new();
        assert_eq!(activated(&empty, Some(TrackId::from_bits(10))), None);
    }

    // ---- round 5.5: tag review modal ----

    fn tag_draft(
        stem: &str,
        artist: Option<&str>,
        album: Option<&str>,
        bits: u32,
    ) -> TrackDraft {
        let mut draft =
            TrackDraft::new(PathBuf::from(format!("/drop/{stem}.mp3")), stem).unwrap();
        draft.artist = artist.map(str::to_owned);
        draft.album = album.map(str::to_owned);
        draft.media_kind_bits = bits;
        draft
    }

    #[test]
    fn is_untagged_flags_only_artist_and_album_absence() {
        assert!(is_untagged(&tag_draft("a", None, None, 1)));
        assert!(is_untagged(&tag_draft("a", Some("  "), Some(""), 1)));
        assert!(!is_untagged(&tag_draft("a", Some("Artist"), None, 1)));
        assert!(!is_untagged(&tag_draft("a", None, Some("Album"), 1)));
    }

    #[test]
    fn common_prefix_trims_to_a_boundary_and_needs_3_chars() {
        // The live case: directory «Skazka o ribake i ribki» with files
        // «… - 1..5» → the whole repeating prefix is stripped.
        let stems: Vec<String> = (1..=5)
            .map(|n| format!("Skazka o ribake i ribki - {n}"))
            .collect();
        assert_eq!(
            common_prefix(&stems).as_deref(),
            Some("Skazka o ribake i ribki")
        );
        // No shared prefix at all.
        assert_eq!(common_prefix(&["alpha".to_owned(), "beta".to_owned()]), None);
        // Shared but too short.
        assert_eq!(common_prefix(&["ab1".to_owned(), "ab2".to_owned()]), None);
        // A single stem never shows the checkbox.
        assert_eq!(common_prefix(&["Skazka o ribake i ribki - 1".to_owned()]), None);
    }

    #[test]
    fn trailing_number_reads_the_stem_tail() {
        assert_eq!(
            trailing_number("Skazka o ribake i ribki - 1"),
            Some(1)
        );
        assert_eq!(trailing_number("Chapter 12"), Some(12));
        assert_eq!(trailing_number("12"), Some(12));
        assert_eq!(trailing_number("track-07"), Some(7));
        assert_eq!(trailing_number("12a"), None);
        assert_eq!(trailing_number("intro"), None);
    }

    #[test]
    fn apply_tag_review_fills_fields_validates_and_falls_back_to_stem() {
        let drafts = vec![
            tag_draft("Skazka - 1", None, None, 8),
            tag_draft("Skazka - 2", None, None, 8),
        ];
        let rows = vec![
            TagRow { title: "Глава 1".to_owned(), original_title: "Skazka - 1".to_owned(), track_number: 1 },
            TagRow { title: String::new(), original_title: "Skazka - 2".to_owned(), track_number: 2 }, // empty → stem
        ];
        // Empty book title is rejected with the KIND-aware near-field
        // text (nit-8): books say «книги», music says «альбома».
        assert_eq!(
            apply_tag_review(&drafts, "   ", "Пушкин", &rows, "Укажите название книги")
                .unwrap_err(),
            "Укажите название книги"
        );
        assert_eq!(
            apply_tag_review(&drafts, "  ", "Пушкин", &rows, "Укажите название альбома")
                .unwrap_err(),
            "Укажите название альбома"
        );
        let applied =
            apply_tag_review(&drafts, "Сказка о рыбаке", "Пушкин", &rows, "ignored").unwrap();
        assert_eq!(applied.len(), 2);
        for draft in &applied {
            assert_eq!(draft.album.as_deref(), Some("Сказка о рыбаке"));
            assert_eq!(draft.album_artist.as_deref(), Some("Пушкин"));
        }
        assert_eq!(applied[0].title, "Глава 1");
        assert_eq!(applied[0].track_number, 1);
        assert_eq!(applied[1].title, "Skazka - 2", "empty edit falls back to stem");
        assert_eq!(applied[1].track_number, 2);
        // An empty author must NOT overwrite the draft's artist field.
        let no_author = apply_tag_review(&drafts, "Книга", "", &rows, "x").unwrap();
        assert_eq!(no_author[0].album_artist, None);
    }

    /// The author lands in `album_artist` AND in `artist` when the draft
    /// has no own artist: the vendor's display_artist() writes
    /// item.artist only, so without the propagation the track never
    /// shows up in the «Песни» list (round 6.4).
    #[test]
    fn tag_review_propagates_author_to_artist_when_artist_is_empty() {
        let drafts = vec![
            tag_draft("Ch1", None, None, 8),
            // A pre-existing artist wins: propagation fills only blanks.
            tag_draft("Ch2", Some("Свой артист"), None, 8),
        ];
        let rows = vec![
            TagRow { title: "Глава 1".to_owned(), original_title: "Ch1".to_owned(), track_number: 1 },
            TagRow { title: "Глава 2".to_owned(), original_title: "Ch2".to_owned(), track_number: 2 },
        ];
        let applied = apply_tag_review(&drafts, "Книга", "Котэ", &rows, "x").unwrap();
        assert_eq!(applied[0].artist.as_deref(), Some("Котэ"));
        assert_eq!(applied[0].album_artist.as_deref(), Some("Котэ"));
        assert_eq!(applied[1].artist.as_deref(), Some("Свой артист"));
        assert_eq!(applied[1].album_artist.as_deref(), Some("Котэ"));
        // No author at all — nothing to propagate.
        let no_author = apply_tag_review(&drafts, "Книга", "", &rows, "x").unwrap();
        assert_eq!(no_author[0].artist, None);
    }

    // ---- tail nit-8: kind-aware texts ----

    #[test]
    fn tag_review_texts_speak_books_for_books_and_music_for_music() {
        // Books: the audiobook BIT decides (combined bits stay book).
        let books = tag_review_texts(8);
        assert_eq!(books.title_field, "Название книги*");
        assert_eq!(books.author_field, "Автор");
        assert_eq!(books.empty_title, "Укажите название книги");
        assert_eq!(books.add_button, "Добавить книгу");
        assert_eq!(tag_review_texts(9).title_field, "Название книги*");

        let music = tag_review_texts(1);
        assert_eq!(music.title_field, "Альбом");
        assert_eq!(music.author_field, "Исполнитель");
        assert_eq!(music.empty_title, "Укажите название альбома");
        assert_eq!(music.add_button, "Добавить музыку");
        assert!(music.subject.contains("музыки"));
    }

    // ---- tail nit-9: the prefix toggle spares manual edits ----

    #[test]
    fn prefix_toggle_rederives_only_untouched_rows() {
        let prefix = "Skazka";
        let mut rows = vec![
            TagRow {
                title: "Skazka - 1".to_owned(),
                original_title: "Skazka - 1".to_owned(),
                track_number: 1,
            },
            // The user edited this one before touching the checkbox.
            TagRow {
                title: "Моё название".to_owned(),
                original_title: "Skazka - 2".to_owned(),
                track_number: 2,
            },
        ];
        // OFF: nothing was stripped yet — every row already shows its
        // automatic (original) value, so nothing changes.
        retoggle_prefix_titles(&mut rows, prefix, false);
        assert_eq!(rows[0].title, "Skazka - 1");
        assert_eq!(rows[1].title, "Моё название");
        // ON: untouched rows strip; the manual edit survives.
        retoggle_prefix_titles(&mut rows, prefix, true);
        assert_eq!(rows[0].title, "1", "stem minus the «Skazka - » prefix");
        assert_eq!(rows[1].title, "Моё название", "manual edit kept");
        // OFF again: the untouched row returns to the stem; the manual
        // edit is still there.
        retoggle_prefix_titles(&mut rows, prefix, false);
        assert_eq!(rows[0].title, "Skazka - 1");
        assert_eq!(rows[1].title, "Моё название");
    }

    #[test]
    fn prefix_toggle_restores_a_previously_stripped_row() {
        let prefix = "Book";
        let mut rows = vec![TagRow {
            title: "5".to_owned(),
            original_title: "Book - 5".to_owned(),
            track_number: 5,
        }];
        // OFF: the stripped automatic value is the "previous auto", so
        // it re-derives to the full stem.
        retoggle_prefix_titles(&mut rows, prefix, false);
        assert_eq!(rows[0].title, "Book - 5");
    }

    #[test]
    fn open_tag_review_prefills_rows_prefix_and_book_title() {
        let drafts = vec![
            tag_draft("Skazka o ribake i ribki - 1", None, None, 8),
            tag_draft("Skazka o ribake i ribki - 2", None, None, 8),
            tag_draft("Skazka o ribake i ribki - 3", None, None, 8),
        ];
        let review = open_tag_review(drafts);
        assert_eq!(review.kind_bits, 8);
        assert_eq!(review.rows[0].title, "Skazka o ribake i ribki - 1");
        assert_eq!(review.rows[0].track_number, 1, "trailing digits win");
        assert_eq!(review.rows[2].track_number, 3);
        assert_eq!(
            review.prefix.as_deref(),
            Some("Skazka o ribake i ribki")
        );
        assert!(review.strip_prefix, "found prefix → checkbox pre-enabled");
        assert_eq!(review.book_title, "drop", "common parent dir name prefills");
    }

    #[derive(Debug)]
    struct TestDroppedFile(PathBuf);

    impl egui::DroppedFile for TestDroppedFile {
        fn path(&self) -> &std::path::Path {
            &self.0
        }

        fn bytes(&self) -> Result<Vec<u8>, String> {
            std::fs::read(&self.0).map_err(|error| error.to_string())
        }
    }

    /// Round 5.5 end-to-end (headless): an untagged directory drop
    /// opens the review modal INSTEAD of dispatching; after editing the
    /// common fields and one row, «Добавить» dispatches the edited
    /// drafts through the regular AddTracks pipeline.
    #[test]
    fn untagged_drop_opens_review_modal_then_dispatches_edited_drafts() {
        let (mut app, _dir) = app_with_open_library();
        let dir = TempDir::new().unwrap();
        std::fs::create_dir_all(dir.path().join("book")).unwrap();
        // Round 6.1 B1: dispatched drafts must survive the duration
        // probe, so the drop sources are real audio (ffmpeg AAC), not
        // garbage bytes.
        let mut sources = Vec::new();
        for name in ["01", "02"] {
            let path = dir.path().join(format!("book/{name}.m4a"));
            let generated = std::process::Command::new("ffmpeg")
                .args([
                    "-f",
                    "lavfi",
                    "-i",
                    "sine=frequency=440:duration=0.2",
                    "-c:a",
                    "aac",
                    &path.display().to_string(),
                ])
                .output()
                .expect("run ffmpeg");
            assert!(
                generated.status.success(),
                "fixture ffmpeg failed: {}",
                String::from_utf8_lossy(&generated.stderr)
            );
            sources.push(path);
        }
        let first = sources[0].clone();
        let second = sources[1].clone();

        // Frame 1: the directory drop.
        egui::__run_test_ui(|ui| {
            ui.input_mut(|input| {
                input.raw.dropped_files = vec![
                    std::sync::Arc::new(TestDroppedFile(first.clone()))
                        as std::sync::Arc<dyn egui::DroppedFile + Send + Sync>,
                    std::sync::Arc::new(TestDroppedFile(second.clone()))
                        as std::sync::Arc<dyn egui::DroppedFile + Send + Sync>,
                ];
            });
            app.collect_dropped_files(ui);
        });
        let review = app
            .tag_review
            .as_ref()
            .expect("an untagged drop must open the review modal");
        assert_eq!(review.rows.len(), 2);
        assert_eq!(review.book_title, "book", "the directory name prefills");
        assert!(
            app.library
                .as_ref()
                .unwrap()
                .pending
                .is_none(),
            "nothing is dispatched until the review is applied"
        );

        // Frame 2: the user edits fields (modal body)…
        let review = app.tag_review.as_mut().unwrap();
        review.book_title = "Сказка о рыбаке".to_owned();
        review.author = "Пушкин".to_owned();
        review.rows[1].title = "Глава 2".to_owned();
        review.rows[1].track_number = 2;
        // …and presses «Добавить книгу»: the button marks the frame
        // committed AND closes the modal, so the frame ends with
        // committed=true AND should_close=true (round 5.7 bug 1 — the
        // old cancel-first order swallowed exactly this combination).
        egui::__run_test_ui(|ui| {
            app.maybe_tag_review_modal(&ui.ctx().clone());
        });
        app.finish_tag_review_frame(true, true, false);

        let pending = app
            .library
            .as_ref()
            .unwrap()
            .pending
            .as_ref()
            .expect("AddTracks must be dispatched after the review");
        assert!(matches!(pending.0, PendingKind::AddTracks));
        let settled = pump(&mut app, |app| {
            app.library
                .as_ref()
                .is_some_and(|library| library.pending.is_none())
        });
        assert!(settled, "the batch must complete");
        let library = app.library.as_ref().unwrap();
        assert_eq!(library.snapshot.tracks.len(), 3, "fixture Alpha + 2 files");
        let chapter_two = library
            .snapshot
            .tracks
            .iter()
            .find(|track| track.title == "Глава 2")
            .expect("the edited title must land");
        assert_eq!(chapter_two.album.as_deref(), Some("Сказка о рыбаке"));
        // NOTE: the classic fixture parser never returns album_artist
        // (project.rs keeps it None), so it is asserted in
        // apply_tag_review_fills_fields… on the drafts themselves; on
        // the 7G device libopod stores and returns it.
        assert_eq!(chapter_two.track_number, 2);
        assert!(app.tag_review.is_none(), "the modal closes after applying");
        let library = app.library.take().unwrap();
        library.worker.close_and_join();
    }

    #[test]
    fn finish_frame_commit_outranks_same_frame_close() {
        // Round 5.7 bug 1: a real «Добавить книгу» click closes the
        // modal in the same frame (should_close=true) — the commit must
        // still win. Without a library the dispatched request answers
        // with the honest «подключите устройство» error, which proves
        // the request actually REACHED the dispatch path (the old
        // cancel-first order swallowed it silently). The refusal keeps
        // the modal with the typed tags: user input is not lost to a
        // busy/no-device worker (minor-5).
        let mut app = test_app();
        let draft = tag_draft("Skazka - 1", None, None, 8);
        let mut review = open_tag_review(vec![draft]);
        review.book_title = "Книга".to_owned(); // valid title → commit dispatches
        app.tag_review = Some(review);
        app.finish_tag_review_frame(true, true, false);
        let error = app
            .error
            .as_ref()
            .expect("committed request must reach the dispatch path");
        assert!(error.message.contains("подключите"), "got: {}", error.message);
        assert!(app.tag_review.is_some(), "refusal keeps the typed modal open");
    }

    #[test]
    fn finish_frame_cancel_drops_the_draft() {
        let mut app = test_app();
        let draft = tag_draft("Skazka - 1", None, None, 8);
        app.tag_review = Some(open_tag_review(vec![draft]));
        app.finish_tag_review_frame(false, true, false);
        assert!(app.tag_review.is_none(), "cancel drops the draft");
        assert!(app.error.is_none(), "cancel dispatches nothing");
    }

    // ---- round 6.1 F3: shared sudo-password modal ----

    /// Runs one headless frame through both password modals (the same
    /// order as the production `ui()`), feeding extra input events.
    fn password_modal_frame(app: &mut PodlibApp, ctx: &egui::Context, events: Vec<egui::Event>) {
        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1200.0, 800.0),
            )),
            events,
            ..Default::default()
        };
        let mut output = ctx.run_ui(input, |ui| {
            ui.style_mut().animation_time = 0.0;
            app.maybe_mount_modal(&ui.ctx().clone());
            app.maybe_eject_modal(&ui.ctx().clone());
        });
        output.textures_delta.clear();
    }

    fn enter_pressed() -> egui::Event {
        egui::Event::Key {
            key: egui::Key::Enter,
            pressed: true,
            physical_key: None,
            repeat: false,
            modifiers: egui::Modifiers::default(),
        }
    }

    fn escape_pressed() -> egui::Event {
        egui::Event::Key {
            key: egui::Key::Escape,
            pressed: true,
            physical_key: None,
            repeat: false,
            modifiers: egui::Modifiers::default(),
        }
    }

    #[test]
    fn password_modal_autofocuses_the_field() {
        let mut app = test_app();
        app.confirm_mount = true;
        let ctx = egui::Context::default();
        password_modal_frame(&mut app, &ctx, Vec::new());
        assert_eq!(
            ctx.memory(|memory| memory.focused()),
            Some(password_field_id("confirm_mount")),
            "the password field must take focus the moment the modal opens"
        );
    }

    #[test]
    fn eject_modal_autofocuses_its_own_field() {
        let mut app = test_app();
        app.confirm_eject = true;
        let ctx = egui::Context::default();
        password_modal_frame(&mut app, &ctx, Vec::new());
        assert_eq!(
            ctx.memory(|memory| memory.focused()),
            Some(password_field_id("confirm_eject")),
            "each flow focuses its own field, not the other flow's"
        );
        assert!(!app.start_eject && app.confirm_eject, "still open");
    }

    #[test]
    fn password_modal_enter_submits_non_empty_password() {
        let mut app = test_app();
        app.confirm_mount = true;
        let ctx = egui::Context::default();
        password_modal_frame(&mut app, &ctx, Vec::new()); // open + autofocus
        app.password = "sudo-pass".to_owned();
        password_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        assert!(!app.confirm_mount, "modal must close on Enter");
        assert!(app.start_mount, "Enter on a non-empty password confirms");
    }

    #[test]
    fn password_modal_enter_on_empty_password_keeps_it_open() {
        let mut app = test_app();
        app.confirm_mount = true;
        let ctx = egui::Context::default();
        password_modal_frame(&mut app, &ctx, Vec::new());
        password_modal_frame(&mut app, &ctx, vec![enter_pressed()]); // empty field
        assert!(app.confirm_mount, "an empty password must not confirm");
        assert!(!app.start_mount);
    }

    #[test]
    fn password_modal_esc_cancels() {
        let mut app = test_app();
        app.confirm_eject = true;
        app.password = "x".to_owned();
        let ctx = egui::Context::default();
        password_modal_frame(&mut app, &ctx, Vec::new());
        password_modal_frame(&mut app, &ctx, vec![escape_pressed()]);
        assert!(!app.confirm_eject, "Esc closes the modal");
        assert!(!app.start_eject, "Esc does not start the eject");
    }

    // ---- batch F: EVERY eject collects the password through the modal ----

    /// Live bug: a confirmed window close (round 5.3, mounted by us)
    /// started the eject directly, bypassing the password modal, and the
    /// first sudo step failed with an empty password. The close path must
    /// open the shared modal instead.
    #[test]
    fn close_confirm_with_mount_opens_password_modal_before_eject() {
        let (mut app, _dir) = app_with_open_library();
        app.mounted_by_us = true;
        app.confirm_close = true;
        let ctx = egui::Context::default();
        confirm_modal_frame(&mut app, &ctx, Vec::new()); // open
        confirm_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        assert!(!app.confirm_close, "modal must close on Enter");
        assert!(
            app.confirm_eject,
            "the eject must ask for the password (modal open)"
        );
        assert!(
            !app.start_eject,
            "the eject must not start before the password is entered"
        );
        assert!(
            app.pending_close_after_eject,
            "the window still closes after the eject lands"
        );
    }

    /// Cancelling the eject password modal also cancels the close that
    /// asked for it: the window stays, nothing restarts.
    #[test]
    fn cancel_eject_password_modal_cancels_pending_close() {
        let mut app = test_app();
        app.pending_close_after_eject = true;
        app.confirm_eject = true;
        let ctx = egui::Context::default();
        password_modal_frame(&mut app, &ctx, Vec::new()); // open
        password_modal_frame(&mut app, &ctx, vec![escape_pressed()]);
        assert!(!app.confirm_eject, "Esc closes the modal");
        assert!(!app.start_eject, "Esc does not start the eject");
        assert!(
            !app.pending_close_after_eject,
            "a cancelled eject must not keep the window waiting to close"
        );
    }

    /// Live bug, second half: a failed eject kept `pending_close_after_eject`
    /// set, so the deferred path restarted the (empty-password) eject every
    /// idle frame. The failure must cancel the pending close.
    #[test]
    fn ejected_error_cancels_pending_close() {
        let (mut app, _dir) = app_with_open_library();
        app.library = None; // spawn_eject closes the library before the steps
        app.connected = Some(ConnectedDevice {
            block_dev: PathBuf::from("/dev/test"),
            label: "test".to_owned(),
        });
        app.pending_close_after_eject = true;
        let (tx, rx) = channel();
        tx.send(DeviceEvent::Ejected(Err("sudo failed".to_owned()))).unwrap();
        app.rx = Some(rx);
        app.drain_events();
        assert!(
            !app.pending_close_after_eject,
            "a failed eject must cancel the pending window close"
        );
        assert!(
            !app.start_eject,
            "the deferred path must not immediately restart the eject"
        );
    }

    // ---- batch F: a failed eject must allow a retry ----

    /// Live bug: after a failed eject the library worker is closed
    /// (`library = None`), and `library_idle()` returned false for None —
    /// so «Безопасно отключить» stayed disabled forever. No library means
    /// nothing is in flight.
    #[test]
    fn library_idle_is_true_without_a_library() {
        let app = test_app();
        assert!(app.library.is_none());
        assert!(
            app.library_idle(),
            "no library means nothing is in flight"
        );
    }

    #[test]
    fn library_idle_with_pending_operation_is_false() {
        let (mut app, _dir) = app_with_open_library();
        let (_tx, rx) = channel();
        app.library.as_mut().unwrap().pending = Some((PendingKind::Refresh, rx));
        assert!(!app.library_idle(), "an in-flight operation is not idle");
    }

    /// Live run: wrong sudo password → eject fails → the button must be
    /// ready again (the library is already closed) and the hint must
    /// explain the retry is safe and point at the layout/Caps Lock.
    #[test]
    fn wrong_password_eject_failure_offers_retry() {
        let (mut app, _dir) = app_with_open_library();
        app.library = None; // spawn_eject closed it before the sudo steps
        app.connected = Some(ConnectedDevice {
            block_dev: PathBuf::from("/dev/test"),
            label: "test".to_owned(),
        });
        let (tx, rx) = channel();
        tx.send(DeviceEvent::Ejected(Err(
            "sudo: 1 incorrect password attempt".to_owned(),
        )))
        .unwrap();
        app.rx = Some(rx);
        app.drain_events();
        let ready = !app.busy && app.library_idle(); // app_bar gating
        assert!(ready, "the eject button must be available again");
        let error = app.error.as_ref().expect("failure must be shown");
        let hint = error.hint.as_ref().expect("retry hint must be shown");
        assert!(
            hint.contains("раскладку"),
            "wrong-password hint must mention the layout, got: {hint}"
        );
        assert!(
            hint.contains("ещё раз"),
            "wrong-password hint must offer a retry, got: {hint}"
        );
    }

    /// A non-password eject failure keeps the honest «volume may still be
    /// mounted» wording but must also offer the safe retry.
    #[test]
    fn other_eject_failure_hint_mentions_retry() {
        let (mut app, _dir) = app_with_open_library();
        app.library = None;
        app.connected = Some(ConnectedDevice {
            block_dev: PathBuf::from("/dev/test"),
            label: "test".to_owned(),
        });
        let (tx, rx) = channel();
        tx.send(DeviceEvent::Ejected(Err("umount: target is busy".to_owned())))
            .unwrap();
        app.rx = Some(rx);
        app.drain_events();
        let error = app.error.as_ref().expect("failure must be shown");
        let hint = error.hint.as_ref().expect("retry hint must be shown");
        assert!(
            hint.contains("ещё раз") && hint.contains("безопасна"),
            "generic hint must offer the safe retry, got: {hint}"
        );
        assert!(
            !hint.contains("раскладку"),
            "layout wording is only for sudo-auth failures, got: {hint}"
        );
    }

    /// Full retry path: after the failed eject (library None) the owner
    /// presses «Безопасно отключить» again, enters the password, and the
    /// second eject starts.
    #[test]
    fn failed_eject_allows_full_retry() {
        let (mut app, _dir) = app_with_open_library();
        app.library = None;
        app.connected = Some(ConnectedDevice {
            block_dev: PathBuf::from("/dev/test"),
            label: "test".to_owned(),
        });
        let (tx, rx) = channel();
        tx.send(DeviceEvent::Ejected(Err(
            "sudo: 1 incorrect password attempt".to_owned(),
        )))
        .unwrap();
        app.rx = Some(rx);
        app.drain_events();
        // The app-bar press: only possible when the button is enabled.
        assert!(
            !app.busy && app.library_idle(),
            "the eject button must be enabled for the retry"
        );
        app.password.clear();
        app.confirm_eject = true;
        let ctx = egui::Context::default();
        password_modal_frame(&mut app, &ctx, Vec::new()); // open + autofocus
        app.password = "right-pass".to_owned();
        password_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        assert!(
            app.start_eject,
            "the retried eject must start from the password modal"
        );
        assert!(!app.confirm_eject, "the modal closed on confirm");
    }

    /// The deferred path (close confirmed while busy) opens the password
    /// modal when the app goes idle; repeated frames keep the modal open
    /// without ever starting the eject behind the user's back.
    #[test]
    fn deferred_close_eject_goes_through_password_modal() {
        let (mut app, _dir) = app_with_open_library();
        app.pending_close_after_eject = true;
        let ctx = egui::Context::default();
        // Frame 1: the app goes idle → the deferred path opens the modal.
        app.maybe_deferred_close_eject();
        password_modal_frame(&mut app, &ctx, Vec::new());
        assert!(app.confirm_eject, "idle → the password modal opens");
        assert!(!app.start_eject, "no direct eject start");
        assert!(app.pending_close_after_eject, "the close is still pending");
        // Frame 2: the deferred path fires again while the modal is up —
        // it must stay a no-op, not duplicate or start anything.
        app.maybe_deferred_close_eject();
        password_modal_frame(&mut app, &ctx, Vec::new());
        assert!(app.confirm_eject, "the modal is still open");
        assert!(!app.start_eject, "still no direct eject start");
    }

    /// Live bug: closing the window by a WM hotkey while idle (no
    /// operation in flight) with a device mounted by this app closed
    /// instantly — no confirm, no eject, the volume stayed mounted rw.
    /// The close guard must ask first, and the confirm must lead into
    /// the password modal (batch F), never a direct eject.
    #[test]
    fn idle_close_with_our_mount_asks_and_ejects_through_password() {
        let (mut app, _dir) = app_with_open_library();
        app.mounted_by_us = true;
        let ctx = egui::Context::default();
        // Frame 1: the WM close request arrives while the app is idle.
        let mut viewports = egui::ViewportIdMap::default();
        viewports.insert(
            egui::ViewportId::ROOT,
            egui::ViewportInfo {
                events: vec![egui::ViewportEvent::Close],
                ..Default::default()
            },
        );
        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1200.0, 800.0),
            )),
            viewports,
            ..Default::default()
        };
        let mut output = ctx.run_ui(input, |ui| {
            ui.style_mut().animation_time = 0.0;
            app.guard_close_request(ui);
            let ctx = ui.ctx().clone();
            app.maybe_close_confirm_modal(&ctx);
        });
        output.textures_delta.clear();
        let cancelled = output
            .viewport_output
            .get(&egui::ViewportId::ROOT)
            .is_some_and(|viewport| {
                viewport.commands.contains(&egui::ViewportCommand::CancelClose)
            });
        assert!(
            cancelled,
            "the close must be cancelled this frame, or eframe exits"
        );
        assert!(app.confirm_close, "idle close with our mount must ask");
        assert!(!app.force_close, "the window must not close silently");
        assert!(
            !app.start_eject,
            "no eject without the user's password"
        );
        // Frame 2: the user confirms — the eject goes through the
        // password modal (batch F), the window stays pending.
        confirm_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        assert!(!app.confirm_close, "modal must close on Enter");
        assert!(
            app.confirm_eject,
            "confirming the close opens the password modal"
        );
        assert!(app.pending_close_after_eject, "the window waits for the eject");
        assert!(!app.start_eject, "the eject still waits for the password");
    }

    // ---- round 6.2 D2: Enter in the confirm modals ----

    /// Runs one headless frame through the confirm modals (the same
    /// order as the production `ui()`), feeding extra input events.
    fn confirm_modal_frame(app: &mut PodlibApp, ctx: &egui::Context, events: Vec<egui::Event>) {
        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1200.0, 800.0),
            )),
            events,
            ..Default::default()
        };
        let mut output = ctx.run_ui(input, |ui| {
            ui.style_mut().animation_time = 0.0;
            let ctx = ui.ctx().clone();
            app.maybe_close_confirm_modal(&ctx);
            app.maybe_delete_track_modal(&ctx);
            app.maybe_delete_playlist_modal(&ctx);
            app.maybe_rename_playlist_modal(&ctx);
        });
        output.textures_delta.clear();
    }

    #[test]
    fn close_confirm_modal_enter_confirms() {
        let mut app = test_app();
        app.confirm_close = true;
        let ctx = egui::Context::default();
        confirm_modal_frame(&mut app, &ctx, Vec::new()); // open
        assert!(app.confirm_close, "still open before Enter");
        confirm_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        assert!(!app.confirm_close, "modal must close on Enter");
        assert!(app.force_close, "Enter confirms the close (no own mount)");
    }

    #[test]
    fn delete_track_modal_enter_confirms() {
        let (mut app, _dir) = app_with_open_library();
        let track_id = app.library.as_ref().unwrap().snapshot.tracks[0].id;
        app.library.as_mut().unwrap().confirm_delete_track = Some(vec![track_id]);
        let ctx = egui::Context::default();
        confirm_modal_frame(&mut app, &ctx, Vec::new()); // open
        confirm_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        let library = app.library.as_ref().unwrap();
        assert!(
            library.confirm_delete_track.is_none(),
            "modal must close on Enter"
        );
        assert!(
            matches!(library.pending, Some((PendingKind::RemoveTrack, _))),
            "Enter confirms the primary action «Удалить»"
        );
        assert!(library.delete_queue.is_empty(), "single track: no queue");
    }

    #[test]
    fn delete_track_modal_esc_cancels() {
        // Esc already worked via should_close; the Enter addition must
        // not break it.
        let (mut app, _dir) = app_with_open_library();
        let track_id = app.library.as_ref().unwrap().snapshot.tracks[0].id;
        app.library.as_mut().unwrap().confirm_delete_track = Some(vec![track_id]);
        let ctx = egui::Context::default();
        confirm_modal_frame(&mut app, &ctx, Vec::new()); // open
        confirm_modal_frame(&mut app, &ctx, vec![escape_pressed()]);
        let library = app.library.as_ref().unwrap();
        assert!(library.confirm_delete_track.is_none(), "Esc closes");
        assert!(library.pending.is_none(), "Esc dispatches nothing");
    }

    #[test]
    fn delete_playlist_modal_enter_confirms() {
        let (mut app, _dir) = app_with_open_library();
        app.library.as_mut().unwrap().confirm_delete_playlist = Some(PlaylistId::from_bits(1));
        let ctx = egui::Context::default();
        confirm_modal_frame(&mut app, &ctx, Vec::new()); // open
        confirm_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        let library = app.library.as_ref().unwrap();
        assert!(
            library.confirm_delete_playlist.is_none(),
            "modal must close on Enter"
        );
        assert!(
            matches!(library.pending, Some((PendingKind::DeletePlaylist, _))),
            "Enter confirms the primary action «Удалить»"
        );
    }

    // ---- round 8: playlist rename (sidebar context menu) ----

    #[test]
    fn sidebar_rename_action_opens_prefilled_dialog() {
        let (mut app, _dir) = app_with_open_library();
        app.library.as_mut().unwrap().snapshot.playlists = vec![sample_playlist(100, "Mix")];
        app.apply_playlist_actions(PlaylistPanelActions {
            rename_playlist: Some(PlaylistId::from_bits(100)),
            ..PlaylistPanelActions::default()
        });
        let dialog = app.library.as_ref().unwrap().rename_dialog.as_ref().unwrap();
        assert_eq!(dialog.id, PlaylistId::from_bits(100));
        assert_eq!(dialog.name, "Mix", "the field is prefilled with the name");
    }

    #[test]
    fn sidebar_master_rename_action_is_refused_honestly() {
        let (mut app, _dir) = app_with_open_library();
        app.apply_playlist_actions(PlaylistPanelActions {
            master_rename: Some("Медиатека".to_owned()),
            ..PlaylistPanelActions::default()
        });
        let app_error = app.error.as_ref().unwrap();
        assert!(app_error.message.contains("мастер"), "got: {}", app_error.message);
        assert!(app.library.as_ref().unwrap().rename_dialog.is_none());
    }

    #[test]
    fn sidebar_guard_blocks_delete_and_rename_of_system_playlists() {
        let (mut app, _dir) = app_with_open_library();
        let mut view = sample_playlist(200, "Аудиокниги");
        view.distinguished_kind = 8;
        app.library.as_mut().unwrap().snapshot.playlists = vec![view];
        app.apply_playlist_actions(PlaylistPanelActions {
            delete_playlist: Some(PlaylistId::from_bits(200)),
            rename_playlist: Some(PlaylistId::from_bits(200)),
            ..PlaylistPanelActions::default()
        });
        let library = app.library.as_ref().unwrap();
        assert!(
            library.confirm_delete_playlist.is_none(),
            "a system playlist must not reach the delete confirm"
        );
        assert!(
            library.rename_dialog.is_none(),
            "a system playlist must not reach the rename dialog"
        );
        assert!(app.error.is_some(), "the refusal is explained");
    }

    fn rename_modal_frame(app: &mut PodlibApp, ctx: &egui::Context, events: Vec<egui::Event>) {
        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1200.0, 800.0),
            )),
            events,
            ..Default::default()
        };
        let mut output = ctx.run_ui(input, |ui| {
            ui.style_mut().animation_time = 0.0;
            let ctx = ui.ctx().clone();
            app.maybe_rename_playlist_modal(&ctx);
        });
        output.textures_delta.clear();
    }

    #[test]
    fn rename_modal_enter_saves_prefilled_field() {
        let (mut app, _dir) = app_with_open_library();
        app.library.as_mut().unwrap().snapshot.playlists = vec![sample_playlist(100, "Mix")];
        app.library.as_mut().unwrap().rename_dialog = Some(RenamePlaylistDialog {
            id: PlaylistId::from_bits(100),
            name: "Mix".to_owned(),
        });
        let ctx = egui::Context::default();
        rename_modal_frame(&mut app, &ctx, Vec::new()); // open
        // Typing happens in the field state; simulate it programmatically.
        app.library.as_mut().unwrap().rename_dialog.as_mut().unwrap().name = "Renamed".to_owned();
        rename_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        let library = app.library.as_ref().unwrap();
        assert!(library.rename_dialog.is_none(), "Enter saves and closes");
        assert!(
            matches!(library.pending, Some((PendingKind::RenamePlaylist, _))),
            "Enter dispatches the rename"
        );
    }

    #[test]
    fn rename_modal_esc_cancels_without_dispatch() {
        let (mut app, _dir) = app_with_open_library();
        app.library.as_mut().unwrap().rename_dialog = Some(RenamePlaylistDialog {
            id: PlaylistId::from_bits(100),
            name: "Mix".to_owned(),
        });
        let ctx = egui::Context::default();
        rename_modal_frame(&mut app, &ctx, Vec::new()); // open
        rename_modal_frame(&mut app, &ctx, vec![escape_pressed()]);
        let library = app.library.as_ref().unwrap();
        assert!(library.rename_dialog.is_none(), "Esc closes");
        assert!(library.pending.is_none(), "Esc dispatches nothing");
    }

    #[test]
    fn rename_modal_refuses_empty_and_unchanged_names() {
        let (mut app, _dir) = app_with_open_library();
        app.library.as_mut().unwrap().snapshot.playlists = vec![sample_playlist(100, "Mix")];
        app.library.as_mut().unwrap().rename_dialog = Some(RenamePlaylistDialog {
            id: PlaylistId::from_bits(100),
            name: "Mix".to_owned(),
        });
        let ctx = egui::Context::default();
        rename_modal_frame(&mut app, &ctx, Vec::new()); // open
        // Unchanged name: Enter must keep the dialog open, no dispatch.
        rename_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        assert!(app.library.as_ref().unwrap().rename_dialog.is_some());
        assert!(app.library.as_ref().unwrap().pending.is_none());
        // Whitespace-only: same honest refusal.
        app.library
            .as_mut()
            .unwrap()
            .rename_dialog
            .as_mut()
            .unwrap()
            .name = "   ".to_owned();
        rename_modal_frame(&mut app, &ctx, vec![enter_pressed()]);
        let library = app.library.as_ref().unwrap();
        assert!(library.rename_dialog.is_some(), "still open");
        assert!(library.pending.is_none(), "nothing dispatched");
    }

    #[test]
    fn deleting_the_open_playlist_returns_to_master() {
        let (mut app, _dir) = app_with_open_library();
        let track_id = app.library.as_ref().unwrap().snapshot.tracks[0].id;
        {
            let library = app.library.as_mut().unwrap();
            library.snapshot.playlists = vec![sample_playlist(100, "Mix")];
            library.view = LibraryView::Playlist(PlaylistId::from_bits(100));
            library.selected_tracks = vec![track_id];
            library.selected_track = Some(track_id);
            library.selection_anchor = Some((0, track_id));
        }
        let (tx, rx) = channel();
        app.library
            .as_mut()
            .unwrap()
            .pending = Some((PendingKind::DeletePlaylist, rx));
        tx.send(LibraryOutcome::Applied {
            snapshot: LibrarySnapshot {
                tracks: app.library.as_ref().unwrap().snapshot.tracks.clone(),
                playlists: Vec::new(),
            },
            summary: "Плейлист удалён".to_owned(),
        })
        .unwrap();
        app.drain_library();
        let library = app.library.as_ref().unwrap();
        assert_eq!(library.view, LibraryView::Master, "no dead view");
        assert!(library.selected_tracks.is_empty());
        assert!(library.selected_track.is_none());
        assert!(library.selection_anchor.is_none());
    }

    #[test]
    fn deleting_another_playlist_keeps_the_open_view() {
        let (mut app, _dir) = app_with_open_library();
        app.library.as_mut().unwrap().snapshot.playlists =
            vec![sample_playlist(100, "Mix"), sample_playlist(101, "Trip")];
        app.library.as_mut().unwrap().view =
            LibraryView::Playlist(PlaylistId::from_bits(100));
        let (tx, rx) = channel();
        app.library
            .as_mut()
            .unwrap()
            .pending = Some((PendingKind::DeletePlaylist, rx));
        tx.send(LibraryOutcome::Applied {
            snapshot: LibrarySnapshot {
                tracks: app.library.as_ref().unwrap().snapshot.tracks.clone(),
                playlists: vec![sample_playlist(100, "Mix")],
            },
            summary: "Плейлист удалён".to_owned(),
        })
        .unwrap();
        app.drain_library();
        assert_eq!(
            app.library.as_ref().unwrap().view,
            LibraryView::Playlist(PlaylistId::from_bits(100)),
            "the open playlist survived — the view must stay"
        );
    }

    #[test]
    fn focused_title_edit_selects_its_row() {
        // Round 5.7 bug 2 regression: the row title is a plain TextEdit
        // now (no drag wrapper swallowing clicks); whatever way the
        // user focuses it — mouse click (standard egui behavior, no
        // interceptor anymore) or Tab — the FOCUSED edit selects its
        // row. Focus is simulated programmatically here (headless).
        let draft = tag_draft("Skazka - 1", None, None, 8);
        let mut app = test_app();
        app.tag_review = Some(open_tag_review(vec![
            draft,
            tag_draft("Skazka - 2", None, None, 8),
        ]));
        let ctx = egui::Context::default();
        // Frame 1: render the modal — row edit ids become known.
        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1200.0, 800.0),
            )),
            ..Default::default()
        };
        let mut output = ctx.run_ui(input, |ui| {
            ui.style_mut().animation_time = 0.0;
            app.maybe_tag_review_modal(&ui.ctx().clone());
        });
        output.textures_delta.clear();
        let title_id = app.tag_review.as_ref().unwrap().row_edit_ids[1];
        assert_ne!(title_id, egui::Id::NULL, "row edit id must be recorded");
        assert_ne!(
            ctx.memory(|memory| memory.focused()),
            Some(title_id),
            "no focus before focusing"
        );

        // Frame 2: focus row 1's editor (as a mouse click / Tab would).
        ctx.memory_mut(|memory| memory.request_focus(title_id));
        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1200.0, 800.0),
            )),
            ..Default::default()
        };
        let mut output = ctx.run_ui(input, |ui| {
            ui.style_mut().animation_time = 0.0;
            app.maybe_tag_review_modal(&ui.ctx().clone());
        });
        output.textures_delta.clear();
        assert_eq!(
            ctx.memory(|memory| memory.focused()),
            Some(title_id),
            "the title TextEdit keeps focus"
        );
        assert_eq!(
            app.tag_review.as_ref().unwrap().selected_row,
            Some(1),
            "the focused row is the selected row"
        );
    }

    #[test]
    fn commit_without_book_title_keeps_modal_and_sets_validation() {
        let (mut app, _dir) = app_with_open_library();
        let draft = tag_draft("Skazka - 1", None, None, 8);
        app.tag_review = Some(open_tag_review(vec![draft]));
        app.commit_tag_review();
        let review = app.tag_review.as_ref().expect("modal stays open");
        assert!(review.validation_attempted, "near-field error is shown");
        assert!(
            app.library.as_ref().unwrap().pending.is_none(),
            "nothing dispatched on an empty book title"
        );
        app.library.take().unwrap().worker.close_and_join();
    }

    // ---- audiobook grouping (round 5) ----

    /// Book-file constructor: album/author/disk/track/duration per field.
    #[allow(clippy::too_many_arguments)]
    fn book_track(
        id: u64,
        title: &str,
        album: Option<&str>,
        album_artist: Option<&str>,
        artist: Option<&str>,
        disc: u32,
        number: u32,
        duration_ms: u32,
    ) -> Track {
        Track {
            id: TrackId::from_bits(id),
            title: title.to_owned(),
            artist: artist.map(str::to_owned),
            album: album.map(str::to_owned),
            album_artist: album_artist.map(str::to_owned),
            duration_ms,
            track_number: number,
            disc_number: disc,
            size_bytes: 1024,
            has_artwork: false,
            media_kind: 8,
        }
    }

    #[test]
    fn books_group_by_album_with_author_fallbacks() {
        let tracks = vec![
            book_track(1, "Глава 1", Some("Сказки"), Some("Народ"), Some("Иной"), 1, 1, 60_000),
            book_track(2, "Глава 2", Some("Сказки"), Some("  "), Some("Иной"), 1, 2, 60_000),
            book_track(3, "Песня", Some("   "), None, Some("Певец"), 1, 1, 30_000),
        ];
        let groups = group_books(&tracks);
        assert_eq!(groups.len(), 2);
        // Album artist wins over the track artist; blank cells are skipped.
        assert_eq!(groups[0].name, "Сказки");
        assert_eq!(groups[0].author.as_deref(), Some("Народ"));
        assert_eq!(
            groups[0].track_ids,
            [TrackId::from_bits(1), TrackId::from_bits(2)]
        );
        // A blank album is its own group.
        assert_eq!(groups[1].name, "Без альбома");
        assert_eq!(groups[1].author.as_deref(), Some("Певец"));
    }

    #[test]
    fn books_and_files_sort_deterministically() {
        let tracks = vec![
            book_track(1, "глава", Some("Б"), None, None, 1, 3, 60_000),
            book_track(2, "пролог", Some("а"), None, None, 0, 5, 60_000),
            book_track(3, "эпилог", Some("Б"), None, None, 2, 1, 60_000),
            // No disc → after all discs; no number → after numbered ones.
            book_track(4, "без номера", Some("а"), None, None, 0, 0, 60_000),
            // Equal disc+number: title decides, case-insensitively.
            book_track(5, "Бета", Some("Б"), None, None, 1, 1, 60_000),
            book_track(6, "альфа", Some("Б"), None, None, 1, 1, 60_000),
        ];
        let groups = group_books(&tracks);
        let albums: Vec<&str> = groups.iter().map(|g| g.name.as_str()).collect();
        assert_eq!(albums, ["а", "Б"], "groups sort case-insensitively");
        // Group «а»: no-disc file after… actually both files are
        // disc-less: numbered (#5) before unnumbered.
        assert_eq!(groups[0].track_ids, [TrackId::from_bits(2), TrackId::from_bits(4)]);
        // Group «Б»: disc 1 before disc 2; equal disc+number → title
        // case-insensitively («альфа» < «Бета» < «глава»).
        assert_eq!(
            groups[1].track_ids,
            [
                TrackId::from_bits(6),
                TrackId::from_bits(5),
                TrackId::from_bits(1),
                TrackId::from_bits(3),
            ]
        );
        // Author: first non-empty album_artist/artist in file order —
        // here nobody has any → the honest placeholder.
        assert_eq!(groups[0].author.as_deref(), Some("Неизвестный автор"));
    }

    #[test]
    fn no_album_group_pins_last_after_real_books() {
        let tracks = vec![
            book_track(1, "Файл", Some("Ясно"), None, None, 1, 1, 60_000),
            book_track(2, "Файл", None, None, None, 1, 1, 60_000),
        ];
        let groups = group_books(&tracks);
        let albums: Vec<&str> = groups.iter().map(|g| g.name.as_str()).collect();
        assert_eq!(albums, ["Ясно", "Без альбома"], "the catch-all group goes last");
    }

    #[test]
    fn book_without_any_artist_is_unknown() {
        let tracks = vec![book_track(1, "Файл", None, None, None, 1, 1, 60_000)];
        let groups = group_books(&tracks);
        assert_eq!(groups[0].name, "Без альбома");
        assert_eq!(groups[0].author.as_deref(), Some("Неизвестный автор"));
    }

    // ---- music grouping: albums and artists (round 6 П3) ----

    #[test]
    fn albums_group_like_books_but_honest_about_the_author() {
        let tracks = vec![
            book_track(1, "Трек", Some("Заря"), Some("Группа"), None, 1, 2, 60_000),
            book_track(2, "Трек", Some("заря"), Some("  "), Some("Кто-то"), 1, 1, 60_000),
            book_track(3, "Сингл", None, None, None, 1, 1, 30_000),
        ];
        let groups = group_by_album(&tracks);
        let names: Vec<&str> = groups.iter().map(|g| g.name.as_str()).collect();
        // Case-insensitive SORT; buckets stay exact (round-5 books
        // semantics: tag-case variants are separate entries).
        assert_eq!(names, ["Заря", "заря", "Без альбома"]);
        // Member order inside the album: track #2 (no 1) before #1.
        assert_eq!(groups[0].track_ids, [TrackId::from_bits(1)]);
        assert_eq!(groups[1].track_ids, [TrackId::from_bits(2)]);
        // Author: first non-empty album_artist in file order.
        assert_eq!(groups[0].author.as_deref(), Some("Группа"));
        // An album without any artist shows NO author segment (books
        // use the «Неизвестный автор» placeholder instead).
        assert_eq!(groups[2].author, None);
    }

    #[test]
    fn artists_group_by_album_artist_then_artist() {
        let tracks = vec![
            book_track(1, "Трек", Some("Альбом"), Some("Би-2"), None, 1, 1, 60_000),
            book_track(2, "Трек", Some("Альбом"), None, Some("Би-2"), 1, 2, 60_000),
            book_track(3, "Гость", Some("Сборник"), Some("Сплин"), None, 1, 1, 60_000),
            book_track(4, "Без тегов", None, None, None, 1, 1, 30_000),
        ];
        let groups = group_by_artist(&tracks);
        let names: Vec<&str> = groups.iter().map(|g| g.name.as_str()).collect();
        // Case-insensitive; album_artist outranks track artist; the
        // «Неизвестный исполнитель» catch-all pins last.
        assert_eq!(names, ["Би-2", "Сплин", "Неизвестный исполнитель"]);
        assert_eq!(
            groups[0].track_ids,
            [TrackId::from_bits(1), TrackId::from_bits(2)],
            "the artist's files stay in one group"
        );
        // The name IS the artist — no author segment.
        assert_eq!(groups[0].author, None);
    }

    #[test]
    fn artist_members_order_by_album_then_file() {
        let tracks = vec![
            book_track(1, "Позже", Some("Альбом Б"), None, Some("Рокер"), 1, 1, 60_000),
            book_track(2, "Раньше", Some("альбом а"), None, Some("Рокер"), 1, 1, 60_000),
            book_track(3, "Азбука", Some("Альбом Б"), None, Some("Рокер"), 1, 1, 60_000),
        ];
        let groups = group_by_artist(&tracks);
        assert_eq!(groups.len(), 1);
        // Tiny discography: albums case-insensitively first («альбом
        // а» < «Альбом Б»), then the file order inside each album
        // (equal disc+number → title ci: «Азбука» < «Позже»).
        assert_eq!(
            groups[0].track_ids,
            [TrackId::from_bits(2), TrackId::from_bits(3), TrackId::from_bits(1)]
        );
    }

    #[test]
    fn section_modes_per_builtin_view() {
        assert_eq!(
            section_modes(4),
            [SectionMode::List, SectionMode::Albums, SectionMode::Artists]
        );
        assert_eq!(section_modes(5), [SectionMode::List, SectionMode::Books]);
        // Any other section (and master/playlists) has only the flat
        // list — the switcher is not rendered there.
        assert_eq!(section_modes(2), [SectionMode::List]);
        assert_eq!(section_modes(0), [SectionMode::List]);
    }

    #[test]
    fn switcher_labels_are_owner_facing_russian() {
        assert_eq!(SectionMode::List.label(), "Список");
        assert_eq!(SectionMode::Albums.label(), "Альбомы");
        assert_eq!(SectionMode::Artists.label(), "Исполнители");
        assert_eq!(SectionMode::Books.label(), "Книги");
    }

    #[test]
    fn total_duration_formats_hours_minutes() {
        assert_eq!(format_total_duration(0), "0:00");
        assert_eq!(format_total_duration(47_000), "0:00", "sub-minute stays 0:00");
        assert_eq!(format_total_duration(60_000), "0:01");
        assert_eq!(format_total_duration(3_600_000), "1:00");
        assert_eq!(format_total_duration(3_780_000), "1:03");
    }

    // ---- toolbar counter and empty-states (round 4 UX) ----

    #[test]
    fn counter_shows_total_without_query_and_ratio_with_it() {
        assert_eq!(tracks_counter(3, 3, ""), "3 трека");
        assert_eq!(tracks_counter(3, 5, ""), "5 треков");
        assert_eq!(tracks_counter(3, 1, ""), "1 трек");
        assert_eq!(tracks_counter(3, 5, "abc"), "3 из 5");
        // Whitespace counts as «no query»: the total is shown.
        assert_eq!(tracks_counter(0, 5, "   "), "5 треков");
    }

    #[test]
    fn empty_state_texts_follow_the_spec() {
        assert_eq!(
            empty_state_text(true, "", false, false),
            "Перетащите аудиофайлы в окно, чтобы добавить"
        );
        assert_eq!(
            empty_state_text(false, "  джаз  ", false, false),
            "Ничего не найдено по „джаз“"
        );
        assert_eq!(
            empty_state_text(false, "", false, true),
            "Пустой плейлист. Перетащите треки из таблицы"
        );
    }

    // ---- status-bar error tooltip (round 4 UX) ----

    #[test]
    fn error_tooltip_gathers_message_hint_and_nonempty_stderr() {
        let plain = UiError {
            message: "Не удалось определить блочное устройство".to_owned(),
            hint: None,
            stderr: None,
        };
        assert_eq!(error_tooltip(&plain), plain.message);

        let with_stderr = UiError {
            message: "mount failed".to_owned(),
            hint: Some("Проверьте пароль".to_owned()),
            stderr: Some("\n".to_owned()), // whitespace-only → skipped
        };
        assert_eq!(
            error_tooltip(&with_stderr),
            "mount failed\nПроверьте пароль"
        );

        let full = UiError {
            message: "mount failed".to_owned(),
            hint: None,
            stderr: Some("mount: bad option".to_owned()),
        };
        assert_eq!(error_tooltip(&full), "mount failed\n\nmount: bad option");
    }

    // ---- device-view media kinds (round 4.1 Ф2) ----

    #[test]
    fn view_media_kinds_per_firmware_views() {
        assert_eq!(view_media_kinds(4), &[1]);         // «Музыка»
        assert_eq!(view_media_kinds(5), &[8]);         // «Аудиокниги»
        assert_eq!(view_media_kinds(2), &[2]);         // «Фильмы»
        assert_eq!(view_media_kinds(3), &[16]);        // «Телешоу»
        assert_eq!(view_media_kinds(1), &[2, 16, 32]); // «Видео» — всё видео
        assert_eq!(view_media_kinds(7), &([]) as &[u32]);          // «Прокат» — не представим
        assert_eq!(view_media_kinds(0), &([]) as &[u32]);          // обычный/мастер-плейлист
        assert_eq!(view_media_kinds(11), &([]) as &[u32]);         // classic podcast — неизвестен
    }

    // ---- row click → selection (round 4.1 Ф3) ----

    #[test]
    fn plain_click_resets_selection_to_one() {
        let (selected, anchor) = apply_row_click(&[0, 3], Some(3), 5, false, false);
        assert_eq!(selected, [5]);
        assert_eq!(anchor, Some(5));
    }

    #[test]
    fn ctrl_click_toggles_preserving_order() {
        // Toggle off an already selected row.
        let (selected, anchor) = apply_row_click(&[2, 4], Some(2), 4, true, false);
        assert_eq!(selected, [2]);
        assert_eq!(anchor, Some(2), "ctrl keeps the anchor");
        // Toggle on a new row.
        let (selected, anchor) = apply_row_click(&[2], Some(2), 7, true, false);
        assert_eq!(selected, [2, 7]);
        assert_eq!(anchor, Some(2));
    }

    #[test]
    fn shift_click_selects_the_range_from_anchor() {
        let (selected, anchor) = apply_row_click(&[2], Some(2), 6, false, true);
        assert_eq!(selected, [2, 3, 4, 5, 6]);
        assert_eq!(anchor, Some(2), "shift keeps the anchor for further shifts");
        // Backwards shift works too.
        let (selected, anchor) = apply_row_click(&[5], Some(5), 1, false, true);
        assert_eq!(selected, [1, 2, 3, 4, 5]);
        assert_eq!(anchor, Some(5));
    }

    #[test]
    fn shift_without_anchor_acts_like_plain_click() {
        let (selected, anchor) = apply_row_click(&[1, 2], None, 6, false, true);
        assert_eq!(selected, [6]);
        assert_eq!(anchor, Some(6));
    }

    // ---- checkbox multi-select (round 6 П2) ----

    #[test]
    fn select_all_states_follow_visible_coverage() {
        let visible = ids(&[1, 2, 3]);
        assert_eq!(select_all_state(&ids(&[]), &visible), SelectAllState::None);
        assert_eq!(select_all_state(&ids(&[1]), &visible), SelectAllState::Some);
        assert_eq!(
            select_all_state(&ids(&[1, 2, 3]), &visible),
            SelectAllState::All
        );
        // A selection that covers nothing visible stays unchecked.
        assert_eq!(select_all_state(&ids(&[9]), &visible), SelectAllState::None);
        // An empty view has nothing to select.
        assert_eq!(select_all_state(&ids(&[1]), &ids(&[])), SelectAllState::None);
    }

    #[test]
    fn toggle_all_on_partial_selection_selects_everything() {
        let visible = ids(&[1, 2, 3]);
        let result = apply_select_all(&ids(&[1]), &visible, true);
        assert_eq!(result, ids(&[1, 2, 3]), "partial → all");
    }

    #[test]
    fn unchecking_all_keeps_rows_outside_the_view() {
        let visible = ids(&[1, 2, 3]);
        let selected = ids(&[1, 2, 3, 9]); // 9 lives in another view
        let result = apply_select_all(&selected, &visible, false);
        assert_eq!(result, ids(&[9]));
    }

    #[test]
    fn selecting_all_twice_does_not_duplicate() {
        let visible = ids(&[1, 2]);
        let result = apply_select_all(&ids(&[1, 2]), &visible, true);
        assert_eq!(result, ids(&[1, 2]));
    }

    #[test]
    fn checkbox_toggle_is_an_explicit_flip() {
        let selected = ids(&[1, 3]);
        assert_eq!(
            toggle_selected(&selected, TrackId::from_bits(5)),
            ids(&[1, 3, 5])
        );
        assert_eq!(
            toggle_selected(&selected, TrackId::from_bits(3)),
            ids(&[1])
        );
    }

    // ---- tail nit-10: shift anchor is identity-checked ----

    #[test]
    fn anchor_survives_only_while_the_row_identity_matches() {
        let visible = ids(&[10, 20, 30]);
        // Same index, same row → valid.
        assert_eq!(valid_anchor(Some((1, TrackId::from_bits(20))), &visible), Some(1));
        // The list shrank → out of bounds → invalid.
        assert_eq!(valid_anchor(Some((3, TrackId::from_bits(99))), &visible), None);
        // A re-list put a DIFFERENT row at the anchor index: the old
        // code shifted from here; now the anchor is dropped.
        assert_eq!(valid_anchor(Some((1, TrackId::from_bits(99))), &visible), None);
        // No anchor at all.
        assert_eq!(valid_anchor(None, &visible), None);
    }

    #[test]
    fn shift_from_a_relisted_anchor_degenerates_to_plain_click() {
        let visible = ids(&[10, 20, 30]);
        // The anchor row (id 20) vanished in a re-list; index 1 now
        // holds id 99. The identity check drops the anchor, so the
        // shift click acts like a plain click on the row (the old
        // boundary-only check would select a foreign range).
        let anchor = valid_anchor(Some((1, TrackId::from_bits(99))), &visible);
        let (selected, new_anchor) = apply_row_click(&[], anchor, 2, false, true);
        assert_eq!(selected, [2]);
        assert_eq!(new_anchor, Some(2));
    }

    // ---- selection resolution (review 🟡-3: extracted from
    // library_view as a pure function) ----

    #[test]
    fn resolution_plain_click_from_empty_selection_targets_the_row() {
        let visible = ids(&[10, 20, 30]);
        let update = resolve_selection_actions(
            &ids(&[]),
            None,
            None,
            &visible,
            Some((1, false, false)),
            None,
            None,
        );
        assert_eq!(update.selected_tracks, ids(&[20]));
        assert_eq!(update.selection_anchor, Some((1, TrackId::from_bits(20))));
        assert_eq!(update.selected_track, Some(TrackId::from_bits(20)));
    }

    #[test]
    fn resolution_shift_degenerates_when_the_anchor_row_is_gone() {
        // The anchor identity (id 99 claimed at index 1) no longer
        // matches the visible list: the shift click must act as a plain
        // click, not select a foreign range.
        let visible = ids(&[10, 20, 30]);
        let update = resolve_selection_actions(
            &ids(&[]),
            Some((1, TrackId::from_bits(99))),
            Some(TrackId::from_bits(30)),
            &visible,
            Some((2, false, true)),
            None,
            None,
        );
        assert_eq!(update.selected_tracks, ids(&[30]));
        assert_eq!(update.selection_anchor, Some((2, TrackId::from_bits(30))));
        assert_eq!(update.selected_track, Some(TrackId::from_bits(30)));
    }

    #[test]
    fn resolution_select_all_keeps_hidden_rows_and_the_cursor() {
        // Rows hidden by the search (id 9) survive; the cursor stays on
        // its previous row (review 🟡-1) — Enter must not retarget to
        // the bottom visible row; the anchor is untouched as well.
        let visible = ids(&[1, 2, 3]);
        let update = resolve_selection_actions(
            &ids(&[9]),
            Some((0, TrackId::from_bits(9))),
            Some(TrackId::from_bits(9)),
            &visible,
            None,
            Some(true),
            None,
        );
        assert_eq!(update.selected_tracks, ids(&[9, 1, 2, 3]));
        assert_eq!(update.selection_anchor, Some((0, TrackId::from_bits(9))));
        assert_eq!(update.selected_track, Some(TrackId::from_bits(9)), "cursor put");
    }

    #[test]
    fn resolution_uncheck_all_clears_only_visible_and_keeps_the_cursor() {
        let visible = ids(&[1, 2, 3]);
        let update = resolve_selection_actions(
            &ids(&[1, 2, 3, 9]),
            Some((0, TrackId::from_bits(1))),
            Some(TrackId::from_bits(3)),
            &visible,
            None,
            Some(false),
            None,
        );
        assert_eq!(update.selected_tracks, ids(&[9]), "out-of-view rows survive");
        assert_eq!(update.selected_track, Some(TrackId::from_bits(3)), "cursor put");
    }

    #[test]
    fn resolution_checkbox_toggle_moves_the_cursor_only_on_check() {
        let visible = ids(&[1, 2]);
        // Checking: the cursor moves to the toggled row.
        let check = resolve_selection_actions(
            &ids(&[1]),
            None,
            Some(TrackId::from_bits(1)),
            &visible,
            None,
            None,
            Some(TrackId::from_bits(2)),
        );
        assert_eq!(check.selected_tracks, ids(&[1, 2]));
        assert_eq!(check.selected_track, Some(TrackId::from_bits(2)));
        // Unchecking: the cursor stays where it was.
        let uncheck = resolve_selection_actions(
            &ids(&[1, 2]),
            None,
            Some(TrackId::from_bits(1)),
            &visible,
            None,
            None,
            Some(TrackId::from_bits(2)),
        );
        assert_eq!(uncheck.selected_tracks, ids(&[1]));
        assert_eq!(uncheck.selected_track, Some(TrackId::from_bits(1)), "cursor put");
    }

    // ---- table columns fit the panel (round 4.1 Ф4) ----

    /// Worst-case central content width at a 900px window: 900 − 240
    /// sidebar − panel margins − vscroll bar. All five columns must be
    /// visible with a ≥100px title (round 6 П2: the checkbox column
    /// shares the same width — the title's worst case is 104px).
    #[test]
    fn table_columns_fit_narrow_panel_with_100px_title() {
        let rects: std::rc::Rc<std::cell::RefCell<Vec<egui::Rect>>> = Default::default();
        let sink = rects.clone();
        egui::__run_test_ui(|ui| {
            ui.allocate_ui(egui::vec2(616.0, 400.0), |ui| {
                let columns = render_measured_table(ui);
                *sink.borrow_mut() = columns;
            });
        });
        let rects = rects.borrow();
        assert_eq!(rects.len(), 5, "five header cells must render");
        let panel_right = 616.0;
        for (index, rect) in rects.iter().enumerate() {
            assert!(
                rect.right() <= panel_right + 1.0,
                "column {index} overflows the panel: {rect:?}"
            );
            assert!(rect.width() > 20.0, "column {index} collapsed: {rect:?}");
        }
        assert_eq!(rects[0].width(), CHECK_COLUMN, "checkbox column is fixed");
        assert!(rects[1].width() >= 100.0, "title ≥ 100px, got {}", rects[1].width());
        assert!(rects[4].left() >= rects[3].right(), "columns must not overlap");
    }

    // ---- sidebar geometry (round 6 П1) ----

    /// The selection must span the whole panel width (the standard list
    /// pattern), not end at the text like the old selectable_value.
    #[test]
    fn sidebar_row_spans_the_full_panel_width() {
        let rect: std::rc::Rc<std::cell::RefCell<Option<egui::Rect>>> = Default::default();
        let sink = rect.clone();
        egui::__run_test_ui(|ui| {
            ui.allocate_ui(egui::vec2(240.0, 120.0), |ui| {
                let response = sidebar_row(ui, true, "Плейлист", "5 треков");
                *sink.borrow_mut() = Some(response.rect);
            });
        });
        let rect = rect.borrow().expect("the row must render");
        assert!((rect.width() - 240.0).abs() < 0.5, "full width, got {rect:?}");
    }

    // ---- toolbar pictograms (round 7) ----

    /// The pictograms and sort arrows ride on fonts bundled INTO egui
    /// (the `monochrome_emoji_fonts` feature — see workspace
    /// Cargo.toml). This test pins the feature: drop it and every
    /// toolbar icon silently becomes tofu.
    #[test]
    fn toolbar_glyphs_are_covered_by_the_bundled_fonts() {
        let ctx = egui::Context::default();
        // Fonts initialize on the first pass; the atlas delta is
        // dropped explicitly (same as egui::__run_test_ui).
        let output = ctx.run_ui(egui::RawInput::default(), |_| {});
        output.drop_without_applying_deltas();
        // has_glyphs needs &mut; fonts_mut is the mutating reader.
        ctx.fonts_mut(|fonts| {
            for text in [
                ICON_REFRESH.glyph,
                ICON_EDIT.glyph,
                ICON_SET_ARTIST.glyph,
                ICON_ADD_TO_PLAYLIST.glyph,
                ICON_REMOVE_FROM_PLAYLIST.glyph,
                ICON_DELETE.glyph,
            ] {
                assert!(
                    fonts.has_glyphs(&egui::FontId::default(), text),
                    "no bundled font covers {text:?}"
                );
            }
        });
    }

    /// The owner's finding (23.11): the text buttons crowded out the
    /// search box at the 616px worst case. The pictogram row must stay
    /// clear of the search box: its leftmost extent sits right of the
    /// search box's right edge plus the item spacing. Both toolbar
    /// variants checked (playlist «🚫» and library «🗑» as the first
    /// right-to-left button).
    #[test]
    fn icon_row_clears_the_search_box_at_the_narrow_panel() {
        for first_icon in [ICON_DELETE, ICON_REMOVE_FROM_PLAYLIST] {
            let search_right: std::rc::Rc<std::cell::Cell<f32>> = Default::default();
            let icons_left: std::rc::Rc<std::cell::Cell<f32>> = Default::default();
            let spacing_x: std::rc::Rc<std::cell::Cell<f32>> = Default::default();
            let search_sink = search_right.clone();
            let icons_sink = icons_left.clone();
            let spacing_sink = spacing_x.clone();
            let mut query = String::new();
            egui::__run_test_ui(|ui| {
                ui.allocate_ui(egui::vec2(616.0, 60.0), |ui| {
                    // The toolbar composition: search box → counter →
                    // the right-aligned action row.
                    let search = ui.add(
                        egui::TextEdit::singleline(&mut query)
                            .hint_text("Поиск…")
                            .desired_width(240.0),
                    );
                    ui.label(tracks_counter(123, 456, "поиск"));
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        icon_button(ui, &first_icon, true);
                        icon_button(ui, &ICON_ADD_TO_PLAYLIST, true);
                        icon_button(ui, &ICON_SET_ARTIST, true);
                        icon_button(ui, &ICON_EDIT, true);
                        icon_button(ui, &ICON_REFRESH, true);
                        icons_sink.set(ui.min_rect().left());
                    });
                    search_sink.set(search.rect.right());
                    spacing_sink.set(ui.spacing().item_spacing.x);
                });
            });
            let limit = search_right.get() + spacing_x.get();
            assert!(
                icons_left.get() >= limit,
                "{:?}: icon row (left {}) overlaps the search box (right {} + spacing {})",
                first_icon.glyph,
                icons_left.get(),
                search_right.get(),
                spacing_x.get()
            );
        }
    }

    // ---- column sort of the flat table (round 7) ----

    #[test]
    fn header_click_cycles_asc_desc_then_back_to_default() {
        let asc = Some(TrackSort {
            column: TrackSortColumn::Title,
            descending: false,
        });
        let desc = Some(TrackSort {
            column: TrackSortColumn::Title,
            descending: true,
        });
        assert_eq!(next_track_sort(None, TrackSortColumn::Title), asc);
        assert_eq!(next_track_sort(asc, TrackSortColumn::Title), desc);
        assert_eq!(
            next_track_sort(desc, TrackSortColumn::Title),
            None,
            "the third click returns to the default (device) order — a \
             playlist view needs a way back to its curated order"
        );
        // A click on another column restarts ascending.
        assert_eq!(
            next_track_sort(desc, TrackSortColumn::Duration),
            Some(TrackSort {
                column: TrackSortColumn::Duration,
                descending: false,
            })
        );
    }

    #[test]
    fn sort_orders_titles_and_reverses_with_the_direction() {
        let tracks = [
            book_track(1, "Вишня", None, None, None, 1, 1, 10_000),
            book_track(2, "Азбука", None, None, None, 1, 1, 20_000),
            book_track(3, "Море", None, None, None, 1, 1, 30_000),
        ];
        let refs: Vec<&Track> = tracks.iter().collect();
        fn titles(sorted: Vec<&Track>) -> Vec<&str> {
            sorted.iter().map(|track| track.title.as_str()).collect()
        }
        assert_eq!(
            titles(sort_tracks(
                refs.clone(),
                Some(TrackSort {
                    column: TrackSortColumn::Title,
                    descending: false,
                })
            )),
            ["Азбука", "Вишня", "Море"]
        );
        assert_eq!(
            titles(sort_tracks(
                refs,
                Some(TrackSort {
                    column: TrackSortColumn::Title,
                    descending: true,
                })
            )),
            ["Море", "Вишня", "Азбука"]
        );
    }

    #[test]
    fn equal_keys_keep_their_order_across_sorts() {
        // «Обновить» re-lists the tracks from the device: rows with
        // equal keys must not shuffle between two sorts of the same
        // input (the sort is stable).
        let tracks = [
            book_track(1, "Same", None, None, Some("A"), 1, 1, 10_000),
            book_track(2, "Same", None, None, Some("B"), 1, 1, 20_000),
            book_track(3, "Same", None, None, Some("C"), 1, 1, 30_000),
        ];
        let refs: Vec<&Track> = tracks.iter().collect();
        let sort = Some(TrackSort {
            column: TrackSortColumn::Title,
            descending: false,
        });
        let ids = |sorted: Vec<&Track>| -> Vec<u64> {
            sorted.iter().map(|track| track.id.to_bits()).collect()
        };
        let first = ids(sort_tracks(refs.clone(), sort));
        let second = ids(sort_tracks(refs.clone(), sort));
        assert_eq!(first, [1, 2, 3], "equal titles keep the input order");
        assert_eq!(first, second, "stable across «Обновить» re-lists");
        let desc = Some(TrackSort {
            column: TrackSortColumn::Title,
            descending: true,
        });
        // All keys equal → the descending pass reorders nothing either.
        assert_eq!(ids(sort_tracks(refs, desc)), [1, 2, 3]);
    }

    #[test]
    fn sort_applies_after_the_search_filter() {
        // library_view composes filter first, sort second: the sort
        // orders the filtered subset, not the whole list.
        let tracks = [
            book_track(1, "джаз утро", None, None, None, 1, 1, 10_000),
            book_track(2, "рок вечер", None, None, None, 1, 1, 20_000),
            book_track(3, "джаз ночь", None, None, None, 1, 1, 30_000),
        ];
        let refs: Vec<&Track> = tracks.iter().collect();
        let filtered: Vec<&Track> = refs
            .into_iter()
            .filter(|track| matches_query(track, "джаз"))
            .collect();
        let sorted = sort_tracks(
            filtered,
            Some(TrackSort {
                column: TrackSortColumn::Title,
                descending: false,
            }),
        );
        let titles: Vec<&str> = sorted.iter().map(|track| track.title.as_str()).collect();
        assert_eq!(titles, ["джаз ночь", "джаз утро"]);
    }

    #[test]
    fn missing_artist_sorts_as_empty_text() {
        // Naive Ord: an absent key is an empty string, so it sorts
        // first ascending — and desc is the exact reverse.
        let tracks = [
            book_track(1, "T", Some("Alb1"), None, Some("Певец"), 1, 1, 10_000),
            book_track(2, "T", Some("Alb2"), None, None, 1, 1, 20_000),
        ];
        let refs: Vec<&Track> = tracks.iter().collect();
        let sorted = sort_tracks(
            refs,
            Some(TrackSort {
                column: TrackSortColumn::Artist,
                descending: false,
            }),
        );
        assert_eq!(sorted[0].id.to_bits(), 2, "the artist-less track sorts first");
    }

    #[test]
    fn duration_sorts_numerically_not_lexically() {
        let tracks = [
            book_track(1, "a", None, None, None, 1, 1, 9_500),
            book_track(2, "b", None, None, None, 1, 1, 600_000),
            book_track(3, "c", None, None, None, 1, 1, 65_000),
        ];
        let refs: Vec<&Track> = tracks.iter().collect();
        let sorted = sort_tracks(
            refs,
            Some(TrackSort {
                column: TrackSortColumn::Duration,
                descending: false,
            }),
        );
        let ids: Vec<u64> = sorted.iter().map(|track| track.id.to_bits()).collect();
        assert_eq!(ids, [1, 3, 2]);
    }
}