spotatui 0.36.1

A Spotify client for the terminal written in Rust, powered by Ratatui
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
use crate::app::{
  ActiveBlock, AlbumTableContext, App, Artist, ArtistBlock, EpisodeTableContext, PlaylistFolder,
  PlaylistFolderItem, PlaylistFolderNode, PlaylistFolderNodeType, RouteId, ScrollableResultPages,
  SelectedAlbum, SelectedFullAlbum, SelectedFullShow, SelectedShow, TrackTableContext,
};
use crate::config::ClientConfig;
use crate::ui::util::create_artist_string;
use anyhow::anyhow;
use chrono::TimeDelta;
use reqwest::Method;
use rspotify::{
  model::{
    album::SimplifiedAlbum,
    artist::FullArtist,
    enums::{Country, RepeatState, SearchType},
    idtypes::{AlbumId, ArtistId, PlayContextId, PlayableId, PlaylistId, ShowId, TrackId, UserId},
    page::Page,
    playlist::PlaylistItem,
    recommend::Recommendations,
    search::SearchResult,
    show::SimplifiedShow,
    track::FullTrack,
    Market, PlayableItem,
  },
  prelude::*,
  AuthCodePkceSpotify,
};
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::{json, Value};
use std::{
  sync::{Arc, OnceLock},
  time::{Duration, Instant},
};
use tokio::sync::Mutex;
use tokio::try_join;

#[cfg(feature = "streaming")]
use crate::player::StreamingPlayer;
#[cfg(feature = "streaming")]
use librespot_connect::{LoadRequest, LoadRequestOptions, PlayingTrack};

pub enum IoEvent {
  GetCurrentPlayback,
  /// After a track transition (e.g., EndOfTrack), ensure we don't end up paused on the next item.
  /// The payload is the previous track identifier (either base62 id or a `spotify:track:` URI).
  #[allow(dead_code)]
  EnsurePlaybackContinues(String),
  RefreshAuthentication,
  GetPlaylists,
  GetDevices,
  GetSearchResults(String, Option<Country>),
  SetTracksToTable(Vec<FullTrack>),
  GetPlaylistItems(PlaylistId<'static>, u32),
  GetCurrentSavedTracks(Option<u32>),
  StartPlayback(
    Option<PlayContextId<'static>>,
    Option<Vec<PlayableId<'static>>>,
    Option<usize>,
  ),
  UpdateSearchLimits(u32, u32),
  Seek(u32),
  NextTrack,
  PreviousTrack,
  Shuffle(bool), // desired shuffle state
  Repeat(RepeatState),
  PausePlayback,
  ChangeVolume(u8),
  GetArtist(ArtistId<'static>, String, Option<Country>),
  GetAlbumTracks(Box<SimplifiedAlbum>),
  GetRecommendationsForSeed(
    Option<Vec<ArtistId<'static>>>,
    Option<Vec<TrackId<'static>>>,
    Box<Option<FullTrack>>,
    Option<Country>,
  ),
  GetCurrentUserSavedAlbums(Option<u32>),
  CurrentUserSavedAlbumsContains(Vec<AlbumId<'static>>),
  CurrentUserSavedAlbumDelete(AlbumId<'static>),
  CurrentUserSavedAlbumAdd(AlbumId<'static>),
  UserUnfollowArtists(Vec<ArtistId<'static>>),
  UserFollowArtists(Vec<ArtistId<'static>>),
  UserFollowPlaylist(UserId<'static>, PlaylistId<'static>, Option<bool>),
  UserUnfollowPlaylist(UserId<'static>, PlaylistId<'static>),
  GetUser,
  ToggleSaveTrack(PlayableId<'static>),
  GetRecommendationsForTrackId(TrackId<'static>, Option<Country>),
  GetRecentlyPlayed,
  GetFollowedArtists(Option<ArtistId<'static>>),
  SetArtistsToTable(Vec<FullArtist>),
  UserArtistFollowCheck(Vec<ArtistId<'static>>),
  GetAlbum(AlbumId<'static>),
  TransferPlaybackToDevice(String, bool),
  #[allow(dead_code)]
  AutoSelectStreamingDevice(String, bool), // Auto-select a device by name (used for native streaming)
  GetAlbumForTrack(TrackId<'static>),
  CurrentUserSavedTracksContains(Vec<TrackId<'static>>),
  GetCurrentUserSavedShows(Option<u32>),
  CurrentUserSavedShowsContains(Vec<ShowId<'static>>),
  CurrentUserSavedShowDelete(ShowId<'static>),
  CurrentUserSavedShowAdd(ShowId<'static>),
  GetShowEpisodes(Box<SimplifiedShow>),
  GetShow(ShowId<'static>),
  GetCurrentShowEpisodes(ShowId<'static>, Option<u32>),
  AddItemToQueue(PlayableId<'static>),
  IncrementGlobalSongCount,
  FetchGlobalSongCount,
  GetLyrics(String, String, f64),
  /// Start playback from the user's saved tracks collection (Liked Songs)
  /// Takes the absolute position in the collection to start from
  /// NOTE: Currently unused - Spotify Web API doesn't support collection context URI
  /// Keeping for potential future use if Spotify adds support
  #[allow(dead_code)]
  StartCollectionPlayback(usize),
  /// Pre-fetch all saved tracks pages in background for seamless playback
  PreFetchAllSavedTracks,
  /// Pre-fetch all tracks from a playlist in background
  PreFetchAllPlaylistTracks(PlaylistId<'static>),
  /// Get user's top tracks for Discover feature (with time range)
  GetUserTopTracks(crate::app::DiscoverTimeRange),
  /// Get Top Artists Mix - fetches top artists and their top tracks
  GetTopArtistsMix,
  /// Fetch all playlist tracks and apply sorting
  FetchAllPlaylistTracksAndSort(PlaylistId<'static>),
}

pub struct Network {
  pub spotify: AuthCodePkceSpotify,
  large_search_limit: u32,
  small_search_limit: u32,
  pub client_config: ClientConfig,
  pub app: Arc<Mutex<App>>,
  #[cfg(feature = "streaming")]
  streaming_player: Option<Arc<StreamingPlayer>>,
}

#[derive(Deserialize, Debug)]
#[allow(non_snake_case)]
struct LrcResponse {
  syncedLyrics: Option<String>,
  plainLyrics: Option<String>,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct GlobalSongCountResponse {
  count: u64,
}

#[derive(Deserialize, Debug)]
struct ArtistSearchResponse {
  artists: Page<FullArtist>,
}

static SPOTIFY_API_PACING: OnceLock<Mutex<Option<Instant>>> = OnceLock::new();
const SPOTIFY_API_MIN_INTERVAL: Duration = Duration::from_millis(250);

impl Network {
  #[cfg(feature = "streaming")]
  pub fn new(
    spotify: AuthCodePkceSpotify,
    client_config: ClientConfig,
    app: &Arc<Mutex<App>>,
    streaming_player: Option<Arc<StreamingPlayer>>,
  ) -> Self {
    Network {
      spotify,
      large_search_limit: 50,
      small_search_limit: 4,
      client_config,
      app: Arc::clone(app),
      streaming_player,
    }
  }

  #[cfg(not(feature = "streaming"))]
  pub fn new(
    spotify: AuthCodePkceSpotify,
    client_config: ClientConfig,
    app: &Arc<Mutex<App>>,
  ) -> Self {
    Network {
      spotify,
      large_search_limit: 50,
      small_search_limit: 4,
      client_config,
      app: Arc::clone(app),
    }
  }

  /// Check if we're using native streaming AND it's the active playback device
  /// This ensures commands are routed correctly when user selects a different device like spotifyd
  #[cfg(feature = "streaming")]
  async fn is_native_streaming_active_for_playback(&self) -> bool {
    let player_connected = self
      .streaming_player
      .as_ref()
      .is_some_and(|p| p.is_connected());

    if !player_connected {
      return false;
    }

    // Get native device name once (no lock needed)
    let native_device_name = self
      .streaming_player
      .as_ref()
      .map(|p| p.device_name().to_lowercase());

    // Single lock acquisition - check all conditions in one go
    let app = self.app.lock().await;

    // If no context yet (e.g., at startup), use the app state flag which is
    // set when the native streaming device is activated/selected.
    let Some(ref ctx) = app.current_playback_context else {
      return app.is_streaming_active;
    };

    // First, check if the current playback device matches the native streaming device ID
    if let (Some(current_id), Some(native_id)) =
      (ctx.device.id.as_ref(), app.native_device_id.as_ref())
    {
      if current_id == native_id {
        return true;
      }
    }

    // Fallback: strict name match (case-insensitive)
    if let Some(native_name) = native_device_name.as_ref() {
      let current_device_name = ctx.device.name.to_lowercase();
      if current_device_name == native_name.as_str() {
        return true;
      }
    }

    // No match - not the active device
    false
  }

  /// Quick check if native streaming is connected (doesn't verify active device)
  #[cfg(feature = "streaming")]
  fn is_native_streaming_active(&self) -> bool {
    self
      .streaming_player
      .as_ref()
      .is_some_and(|p| p.is_connected())
  }

  #[allow(clippy::cognitive_complexity)]
  pub async fn handle_network_event(&mut self, io_event: IoEvent) {
    match io_event {
      IoEvent::RefreshAuthentication => {
        self.refresh_authentication().await;
      }
      IoEvent::EnsurePlaybackContinues(previous_track_id) => {
        self.ensure_playback_continues(previous_track_id).await;
      }
      IoEvent::GetPlaylists => {
        self.get_current_user_playlists().await;
      }
      IoEvent::GetUser => {
        self.get_user().await;
      }
      IoEvent::GetDevices => {
        self.get_devices().await;
      }
      IoEvent::GetCurrentPlayback => {
        self.get_current_playback().await;
      }
      IoEvent::SetTracksToTable(full_tracks) => {
        self.set_tracks_to_table(full_tracks).await;
      }
      IoEvent::GetSearchResults(search_term, country) => {
        self.get_search_results(search_term, country).await;
      }

      IoEvent::GetPlaylistItems(playlist_id, playlist_offset) => {
        self.get_playlist_tracks(playlist_id, playlist_offset).await;
      }
      IoEvent::GetCurrentSavedTracks(offset) => {
        self.get_current_user_saved_tracks(offset).await;
      }
      IoEvent::StartPlayback(context_uri, uris, offset) => {
        self.start_playback(context_uri, uris, offset).await;
      }
      IoEvent::UpdateSearchLimits(large_search_limit, small_search_limit) => {
        self.large_search_limit = large_search_limit;
        self.small_search_limit = small_search_limit;
      }
      IoEvent::Seek(position_ms) => {
        self.seek(position_ms).await;
      }
      IoEvent::NextTrack => {
        self.next_track().await;
      }
      IoEvent::PreviousTrack => {
        self.previous_track().await;
      }
      IoEvent::Repeat(repeat_state) => {
        self.repeat(repeat_state).await;
      }
      IoEvent::PausePlayback => {
        self.pause_playback().await;
      }
      IoEvent::ChangeVolume(volume) => {
        self.change_volume(volume).await;
      }
      IoEvent::GetArtist(artist_id, input_artist_name, country) => {
        self.get_artist(artist_id, input_artist_name, country).await;
      }
      IoEvent::GetAlbumTracks(album) => {
        self.get_album_tracks(album).await;
      }
      IoEvent::GetRecommendationsForSeed(seed_artists, seed_tracks, first_track, country) => {
        self
          .get_recommendations_for_seed(seed_artists, seed_tracks, first_track, country)
          .await;
      }
      IoEvent::GetCurrentUserSavedAlbums(offset) => {
        self.get_current_user_saved_albums(offset).await;
      }
      IoEvent::CurrentUserSavedAlbumsContains(album_ids) => {
        self.current_user_saved_albums_contains(album_ids).await;
      }
      IoEvent::CurrentUserSavedAlbumDelete(album_id) => {
        self.current_user_saved_album_delete(album_id).await;
      }
      IoEvent::CurrentUserSavedAlbumAdd(album_id) => {
        self.current_user_saved_album_add(album_id).await;
      }
      IoEvent::UserUnfollowArtists(artist_ids) => {
        self.user_unfollow_artists(artist_ids).await;
      }
      IoEvent::UserFollowArtists(artist_ids) => {
        self.user_follow_artists(artist_ids).await;
      }
      IoEvent::UserFollowPlaylist(playlist_owner_id, playlist_id, is_public) => {
        self
          .user_follow_playlist(playlist_owner_id, playlist_id, is_public)
          .await;
      }
      IoEvent::UserUnfollowPlaylist(user_id, playlist_id) => {
        self.user_unfollow_playlist(user_id, playlist_id).await;
      }

      IoEvent::ToggleSaveTrack(track_id) => {
        self.toggle_save_track(track_id).await;
      }
      IoEvent::GetRecommendationsForTrackId(track_id, country) => {
        self
          .get_recommendations_for_track_id(track_id, country)
          .await;
      }
      IoEvent::GetRecentlyPlayed => {
        self.get_recently_played().await;
      }
      IoEvent::GetFollowedArtists(after) => {
        self.get_followed_artists(after).await;
      }
      IoEvent::SetArtistsToTable(full_artists) => {
        self.set_artists_to_table(full_artists).await;
      }
      IoEvent::UserArtistFollowCheck(artist_ids) => {
        self.user_artist_check_follow(artist_ids).await;
      }
      IoEvent::GetAlbum(album_id) => {
        self.get_album(album_id).await;
      }
      IoEvent::TransferPlaybackToDevice(device_id, persist_device_id) => {
        self
          .transfert_playback_to_device(device_id, persist_device_id)
          .await;
      }
      #[cfg(feature = "streaming")]
      IoEvent::AutoSelectStreamingDevice(device_name, persist_device_id) => {
        self
          .auto_select_streaming_device(device_name, persist_device_id)
          .await;
      }
      #[cfg(not(feature = "streaming"))]
      IoEvent::AutoSelectStreamingDevice(..) => {} // No-op without native streaming
      IoEvent::GetAlbumForTrack(track_id) => {
        self.get_album_for_track(track_id).await;
      }
      IoEvent::Shuffle(shuffle_state) => {
        self.shuffle(shuffle_state).await;
      }
      IoEvent::CurrentUserSavedTracksContains(track_ids) => {
        self.current_user_saved_tracks_contains(track_ids).await;
      }
      IoEvent::GetCurrentUserSavedShows(offset) => {
        self.get_current_user_saved_shows(offset).await;
      }
      IoEvent::CurrentUserSavedShowsContains(show_ids) => {
        self.current_user_saved_shows_contains(show_ids).await;
      }
      IoEvent::CurrentUserSavedShowDelete(show_id) => {
        self.current_user_saved_shows_delete(show_id).await;
      }
      IoEvent::CurrentUserSavedShowAdd(show_id) => {
        self.current_user_saved_shows_add(show_id).await;
      }
      IoEvent::GetShowEpisodes(show) => {
        self.get_show_episodes(show).await;
      }
      IoEvent::GetShow(show_id) => {
        self.get_show(show_id).await;
      }
      IoEvent::GetCurrentShowEpisodes(show_id, offset) => {
        self.get_current_show_episodes(show_id, offset).await;
      }
      IoEvent::AddItemToQueue(item) => {
        self.add_item_to_queue(item).await;
      }
      IoEvent::IncrementGlobalSongCount => {
        self.increment_global_song_count().await;
      }
      IoEvent::FetchGlobalSongCount => {
        self.fetch_global_song_count().await;
      }
      IoEvent::GetLyrics(track, artist, duration) => {
        self.get_lyrics(track, artist, duration).await;
      }
      IoEvent::StartCollectionPlayback(offset) => {
        self.start_collection_playback(offset).await;
      }
      IoEvent::PreFetchAllSavedTracks => {
        // Spawn prefetch as a separate task to avoid blocking playback
        let spotify = self.spotify.clone();
        let app = self.app.clone();
        let large_search_limit = self.large_search_limit;
        tokio::spawn(async move {
          Self::prefetch_all_saved_tracks_task(spotify, app, large_search_limit).await;
        });
      }
      IoEvent::PreFetchAllPlaylistTracks(playlist_id) => {
        // Spawn prefetch as a separate task to avoid blocking playback
        let spotify = self.spotify.clone();
        let app = self.app.clone();
        let large_search_limit = self.large_search_limit;
        tokio::spawn(async move {
          Self::prefetch_all_playlist_tracks_task(spotify, app, large_search_limit, playlist_id)
            .await;
        });
      }
      IoEvent::GetUserTopTracks(time_range) => {
        self.get_user_top_tracks(time_range).await;
      }
      IoEvent::GetTopArtistsMix => {
        self.get_top_artists_mix().await;
      }
      IoEvent::FetchAllPlaylistTracksAndSort(playlist_id) => {
        self.fetch_all_playlist_tracks_and_sort(playlist_id).await;
      }
    };

    {
      let mut app = self.app.lock().await;
      app.is_loading = false;
    }
  }

  async fn handle_error(&mut self, e: anyhow::Error) {
    let mut app = self.app.lock().await;
    app.handle_error(e);
  }

  async fn show_status_message(&self, message: String, ttl_secs: u64) {
    let mut app = self.app.lock().await;
    app.status_message = Some(message);
    app.status_message_expires_at = Some(Instant::now() + Duration::from_secs(ttl_secs));
  }

  fn is_rate_limited_error(e: &anyhow::Error) -> bool {
    let text = e.to_string();
    text.contains("429") || text.contains("Too Many Requests") || text.contains("Too many requests")
  }

  fn is_transient_network_error(e: &anyhow::Error) -> bool {
    let text = e.to_string().to_lowercase();
    text.contains("error sending request for url")
      || text.contains("connection reset")
      || text.contains("connection refused")
      || text.contains("timed out")
      || text.contains("temporary failure")
      || text.contains("dns")
  }

  async fn pace_spotify_api_call() {
    let pacing_lock = SPOTIFY_API_PACING.get_or_init(|| Mutex::new(None));
    let mut last_request_started_at = pacing_lock.lock().await;

    if let Some(last) = *last_request_started_at {
      let elapsed = last.elapsed();
      if elapsed < SPOTIFY_API_MIN_INTERVAL {
        tokio::time::sleep(SPOTIFY_API_MIN_INTERVAL - elapsed).await;
      }
    }

    *last_request_started_at = Some(Instant::now());
  }

  async fn spotify_api_request_json_for(
    spotify: &AuthCodePkceSpotify,
    method: Method,
    path: &str,
    query: &[(&str, String)],
    body: Option<Value>,
  ) -> anyhow::Result<Value> {
    let mut url = reqwest::Url::parse("https://api.spotify.com/v1/")?.join(path)?;
    if !query.is_empty() {
      let mut qp = url.query_pairs_mut();
      for (k, v) in query {
        qp.append_pair(k, v);
      }
    }

    let client = reqwest::Client::new();
    let mut attempt: u8 = 0;
    let max_attempts: u8 = 4;
    let mut refreshed_after_unauthorized = false;

    loop {
      let access_token = {
        let token_lock = spotify.token.lock().await.expect("Failed to lock token");
        token_lock
          .as_ref()
          .map(|t| t.access_token.clone())
          .ok_or_else(|| anyhow!("No access token available"))?
      };

      Self::pace_spotify_api_call().await;

      let mut request = client
        .request(method.clone(), url.clone())
        .header("Authorization", format!("Bearer {}", access_token))
        .header("Content-Type", "application/json");

      if let Some(payload) = body.clone() {
        request = request.json(&payload);
      }

      let response = match request.send().await {
        Ok(response) => response,
        Err(e) => {
          if attempt + 1 < max_attempts && (e.is_connect() || e.is_timeout() || e.is_request()) {
            let backoff_secs = 1 + u64::from(attempt);
            tokio::time::sleep(Duration::from_secs(backoff_secs)).await;
            attempt += 1;
            continue;
          }
          return Err(anyhow!("Spotify API request failed: {}", e));
        }
      };
      if response.status().is_success() {
        let response_body = response.text().await?;
        if response_body.trim().is_empty() {
          return Ok(Value::Null);
        }
        return Ok(serde_json::from_str(&response_body)?);
      }

      let status = response.status();

      if status == reqwest::StatusCode::UNAUTHORIZED && !refreshed_after_unauthorized {
        match spotify.refresh_token().await {
          Ok(_) => {
            refreshed_after_unauthorized = true;
            continue;
          }
          Err(refresh_err) => {
            let body = response.text().await.unwrap_or_default();
            return Err(anyhow!(
              "Spotify API {} failed: {} (token refresh failed: {})",
              status,
              body,
              refresh_err
            ));
          }
        }
      }

      if status == reqwest::StatusCode::TOO_MANY_REQUESTS && attempt + 1 < max_attempts {
        let retry_after_secs = response
          .headers()
          .get("retry-after")
          .and_then(|h| h.to_str().ok())
          .and_then(|v| v.parse::<u64>().ok())
          .unwrap_or(1);

        let backoff_secs = retry_after_secs.max(1) + u64::from(attempt);
        tokio::time::sleep(Duration::from_secs(backoff_secs)).await;
        attempt += 1;
        continue;
      }

      let body = response.text().await.unwrap_or_default();
      return Err(anyhow!("Spotify API {} failed: {}", status, body));
    }
  }

  fn normalize_spotify_payload(value: &mut Value) {
    match value {
      Value::Object(map) => {
        if let Some(Value::Array(items)) = map.get_mut("items") {
          items.retain(|item| !item.is_null());
        }

        if map.contains_key("snapshot_id") && map.contains_key("owner") && map.contains_key("id") {
          if !map.contains_key("tracks") {
            if let Some(items_obj) = map.get("items").cloned() {
              map.insert("tracks".to_string(), items_obj);
            } else {
              map.insert("tracks".to_string(), json!({ "href": "", "total": 0 }));
            }
          }
        }

        if map.contains_key("added_at") && !map.contains_key("track") {
          if let Some(item_obj) = map.get("item").cloned() {
            map.insert("track".to_string(), item_obj);
          }
        }

        if map.contains_key("album")
          && map.contains_key("artists")
          && map.contains_key("track_number")
          && map.contains_key("duration_ms")
        {
          map
            .entry("available_markets".to_string())
            .or_insert_with(|| json!([]));
          map
            .entry("external_ids".to_string())
            .or_insert_with(|| json!({}));
          map.entry("linked_from".to_string()).or_insert(Value::Null);
          map
            .entry("popularity".to_string())
            .or_insert_with(|| json!(0));
        }

        if map.contains_key("media_type")
          && map.contains_key("languages")
          && map.contains_key("description")
          && map.contains_key("name")
        {
          map
            .entry("available_markets".to_string())
            .or_insert_with(|| json!([]));
          map
            .entry("publisher".to_string())
            .or_insert_with(|| json!(""));
        }

        if map.contains_key("album_type")
          && map.contains_key("artists")
          && map.contains_key("images")
          && map.contains_key("name")
        {
          if map.contains_key("tracks") {
            map
              .entry("available_markets".to_string())
              .or_insert(Value::Null);
            map
              .entry("external_ids".to_string())
              .or_insert_with(|| json!({}));
            map
              .entry("popularity".to_string())
              .or_insert_with(|| json!(0));
            map.entry("label".to_string()).or_insert(Value::Null);
          } else {
            map
              .entry("available_markets".to_string())
              .or_insert_with(|| json!([]));
          }
        }

        let looks_like_artist = map
          .get("type")
          .and_then(Value::as_str)
          .is_some_and(|t| t == "artist")
          || (map.contains_key("external_urls")
            && map.contains_key("name")
            && map.contains_key("id")
            && (map.contains_key("genres") || map.contains_key("images")));

        if looks_like_artist {
          map.entry("href".to_string()).or_insert_with(|| json!(""));
          map.entry("genres".to_string()).or_insert_with(|| json!([]));
          map.entry("images".to_string()).or_insert_with(|| json!([]));
          map
            .entry("followers".to_string())
            .or_insert_with(|| json!({ "href": null, "total": 0 }));
          map
            .entry("popularity".to_string())
            .or_insert_with(|| json!(0));
        }

        for child in map.values_mut() {
          Self::normalize_spotify_payload(child);
        }
      }
      Value::Array(values) => {
        values.retain(|item| !item.is_null());
        for child in values.iter_mut() {
          Self::normalize_spotify_payload(child);
        }
      }
      _ => {}
    }
  }

  async fn spotify_get_typed_compat_for<T: DeserializeOwned>(
    spotify: &AuthCodePkceSpotify,
    path: &str,
    query: &[(&str, String)],
  ) -> anyhow::Result<T> {
    let mut value =
      Self::spotify_api_request_json_for(spotify, Method::GET, path, query, None).await?;
    Self::normalize_spotify_payload(&mut value);
    Ok(serde_json::from_value(value)?)
  }

  async fn spotify_get_typed_compat<T: DeserializeOwned>(
    &self,
    path: &str,
    query: &[(&str, String)],
  ) -> anyhow::Result<T> {
    Self::spotify_get_typed_compat_for(&self.spotify, path, query).await
  }

  async fn library_contains_uris(&self, uris: &[String]) -> anyhow::Result<Vec<bool>> {
    Self::spotify_get_typed_compat_for(
      &self.spotify,
      "me/library/contains",
      &[("uris", uris.join(","))],
    )
    .await
  }

  async fn library_save_uris(&self, uris: &[String]) -> anyhow::Result<()> {
    Self::spotify_api_request_json_for(
      &self.spotify,
      Method::PUT,
      "me/library",
      &[],
      Some(json!({ "uris": uris })),
    )
    .await?;
    Ok(())
  }

  async fn library_remove_uris(&self, uris: &[String]) -> anyhow::Result<()> {
    Self::spotify_api_request_json_for(
      &self.spotify,
      Method::DELETE,
      "me/library",
      &[],
      Some(json!({ "uris": uris })),
    )
    .await?;
    Ok(())
  }

  async fn get_user(&mut self) {
    match self.spotify.me().await {
      Ok(user) => {
        let mut app = self.app.lock().await;
        app.user = Some(user);
      }
      Err(e) => {
        let err = anyhow!(e);
        if Self::is_rate_limited_error(&err) {
          self
            .show_status_message(
              "Spotify rate limit hit while loading profile. Retrying automatically.".to_string(),
              6,
            )
            .await;
          return;
        }
        self.handle_error(err).await;
      }
    }
  }

  async fn get_devices(&mut self) {
    if let Ok(devices_vec) = self.spotify.device().await {
      let mut app = self.app.lock().await;
      app.push_navigation_stack(RouteId::SelectedDevice, ActiveBlock::SelectDevice);
      if !devices_vec.is_empty() {
        // Wrap Vec<Device> in DevicePayload
        let result = rspotify::model::device::DevicePayload {
          devices: devices_vec,
        };
        app.devices = Some(result);
        // Select the first device in the list
        app.selected_device_index = Some(0);
      }
    }
  }

  async fn get_current_playback(&mut self) {
    // When using native streaming, the Spotify API returns stale server-side state
    // that doesn't reflect recent local changes (volume, shuffle, repeat, play/pause).
    // We need to preserve these local states and restore them after getting the API response.
    #[cfg(feature = "streaming")]
    let local_state: Option<(Option<u8>, bool, rspotify::model::RepeatState, Option<bool>)> =
      if self.is_native_streaming_active() {
        let app = self.app.lock().await;
        if let Some(ref ctx) = app.current_playback_context {
          let volume = self.streaming_player.as_ref().map(|p| p.get_volume());
          Some((
            volume,
            ctx.shuffle_state,
            ctx.repeat_state,
            app.native_is_playing,
          ))
        } else {
          // No existing context yet. DON'T override API values
          // Let the first API response set the true state from Spotify
          // The startup IoEvent::Shuffle call will sync our preference to Spotify
          None
        }
      } else {
        None
      };

    let context = self
      .spotify_get_typed_compat::<Option<rspotify::model::CurrentPlaybackContext>>(
        "me/player",
        &[("additional_types", "episode,track".to_string())],
      )
      .await;

    let mut app = self.app.lock().await;

    match context {
      #[allow(unused_mut)]
      Ok(Some(mut c)) => {
        app.instant_since_last_current_playback_poll = Instant::now();

        // Detect whether the native spotatui streaming device is the active Spotify device.
        // This prevents native-only state overrides (volume, play/pause, etc.) from leaking
        // into external devices like the Spotify desktop/mobile app.
        #[cfg(feature = "streaming")]
        let is_native_device = self.streaming_player.as_ref().is_some_and(|p| {
          if let (Some(current_id), Some(native_id)) =
            (c.device.id.as_ref(), app.native_device_id.as_ref())
          {
            return current_id == native_id;
          }
          let native_name = p.device_name().to_lowercase();
          c.device.name.to_lowercase() == native_name
        });

        #[cfg(feature = "streaming")]
        if is_native_device && app.native_device_id.is_none() {
          if let Some(id) = c.device.id.clone() {
            app.native_device_id = Some(id);
          }
        }

        // Process track info before storing context (avoids cloning)
        if let Some(ref item) = c.item {
          match item {
            PlayableItem::Track(track) => {
              if let Some(ref track_id) = track.id {
                let track_id_str = track_id.id().to_string();

                // Check if this is a new track
                if app.last_track_id.as_ref() != Some(&track_id_str) {
                  if app.user_config.behavior.enable_global_song_count {
                    app.dispatch(IoEvent::IncrementGlobalSongCount);
                  }

                  // Trigger lyrics fetch
                  let duration_secs = track.duration.num_seconds() as f64;
                  app.dispatch(IoEvent::GetLyrics(
                    track.name.clone(),
                    create_artist_string(&track.artists),
                    duration_secs,
                  ));

                  app.dispatch(IoEvent::CurrentUserSavedTracksContains(vec![track_id
                    .clone()
                    .into_static()]));
                }

                app.last_track_id = Some(track_id_str);
              };
            }
            PlayableItem::Episode(_episode) => { /*should map this to following the podcast show*/ }
          }
        };

        // Preserve local streaming states (API returns stale server-side state)
        #[cfg(feature = "streaming")]
        if is_native_device {
          if let Some((volume, shuffle, repeat, native_is_playing)) = local_state {
            if let Some(vol) = volume {
              c.device.volume_percent = Some(vol.into());
            }
            c.shuffle_state = shuffle;
            c.repeat_state = repeat;
            // Preserve play/pause state from native player events when available.
            if let Some(is_playing) = native_is_playing {
              c.is_playing = is_playing;
            }
          }
        }

        // On first load with native streaming AND native device is active,
        // override API shuffle with saved preference.
        // Skip this if using external device like spotifyd
        #[cfg(feature = "streaming")]
        if local_state.is_none() && is_native_device {
          c.shuffle_state = app.user_config.behavior.shuffle_enabled;
          // Proactively set native shuffle on first load to keep backend in sync
          if let Some(ref player) = self.streaming_player {
            let _ = player.set_shuffle(app.user_config.behavior.shuffle_enabled);
          }
        }

        app.current_playback_context = Some(c);

        // Update is_streaming_active based on whether the current device matches native streaming
        // This ensures correct polling interval (1s for external devices, 5s for native)
        #[cfg(feature = "streaming")]
        {
          app.is_streaming_active = is_native_device;
          if is_native_device {
            app.native_activation_pending = false;
          }
        }

        // Only clear native track info if API data matches the native player's track
        // This prevents stale API responses (returning old track) from clearing
        // the correct native track info we got from TrackChanged event
        if let Some(ref native_info) = app.native_track_info {
          if let Some(ref ctx) = app.current_playback_context {
            if let Some(ref item) = ctx.item {
              let api_track_name = match item {
                PlayableItem::Track(t) => &t.name,
                PlayableItem::Episode(e) => &e.name,
              };
              // Only clear if names match (API caught up to native player)
              if api_track_name == &native_info.name {
                app.native_track_info = None;
              }
            }
          }
        } else {
          app.native_track_info = None;
        }
      }
      Ok(None) => {
        app.instant_since_last_current_playback_poll = Instant::now();
      }
      Err(e) => {
        app.is_fetching_current_playback = false;

        let err = anyhow!(e);

        if Self::is_rate_limited_error(&err) {
          app.status_message = Some(
            "Spotify rate limit hit. Retrying automatically; please wait a few seconds."
              .to_string(),
          );
          app.status_message_expires_at = Some(Instant::now() + Duration::from_secs(6));
          app.instant_since_last_current_playback_poll = Instant::now();
          return;
        }

        if Self::is_transient_network_error(&err) {
          app.status_message = Some(
            "Temporary Spotify network error while polling playback; retrying automatically."
              .to_string(),
          );
          app.status_message_expires_at = Some(Instant::now() + Duration::from_secs(5));
          app.instant_since_last_current_playback_poll = Instant::now();
          return;
        }

        drop(app); // Release lock before error handler
        self.handle_error(err).await;
        return;
      }
    }

    app.seek_ms.take();
    app.is_fetching_current_playback = false;
  }

  async fn current_user_saved_tracks_contains(&mut self, ids: Vec<TrackId<'_>>) {
    let uris: Vec<String> = ids
      .iter()
      .map(|id| format!("spotify:track:{}", id.id()))
      .collect();

    match self.library_contains_uris(&uris).await {
      Ok(is_saved_vec) => {
        let mut app = self.app.lock().await;
        for (i, id) in ids.iter().enumerate() {
          if let Some(is_liked) = is_saved_vec.get(i) {
            if *is_liked {
              app.liked_song_ids_set.insert(id.id().to_string());
            } else {
              // The song is not liked, so check if it should be removed
              if app.liked_song_ids_set.contains(id.id()) {
                app.liked_song_ids_set.remove(id.id());
              }
            }
          };
        }
      }
      Err(e) => {
        let mut app = self.app.lock().await;
        app.status_message = Some(format!("Could not check liked track state: {}", e));
        app.status_message_expires_at = Some(Instant::now() + Duration::from_secs(5));
      }
    }
  }

  async fn get_playlist_tracks(&mut self, playlist_id: PlaylistId<'_>, playlist_offset: u32) {
    let path = format!("playlists/{}/items", playlist_id.id());
    match self
      .spotify_get_typed_compat::<Page<PlaylistItem>>(
        &path,
        &[
          ("limit", self.large_search_limit.to_string()),
          ("offset", playlist_offset.to_string()),
        ],
      )
      .await
    {
      Ok(playlist_tracks) => {
        self.set_playlist_tracks_to_table(&playlist_tracks).await;

        let mut app = self.app.lock().await;
        app.playlist_tracks = Some(playlist_tracks);
        app.push_navigation_stack(RouteId::TrackTable, ActiveBlock::TrackTable);
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn set_playlist_tracks_to_table(&mut self, playlist_track_page: &Page<PlaylistItem>) {
    let tracks = playlist_track_page
      .items
      .clone()
      .into_iter()
      .filter_map(|item| item.track)
      .filter_map(|track| match track {
        PlayableItem::Track(full_track) => Some(full_track),
        PlayableItem::Episode(_) => None,
      })
      .collect::<Vec<FullTrack>>();
    self.set_tracks_to_table(tracks).await;
  }

  async fn set_tracks_to_table(&mut self, tracks: Vec<FullTrack>) {
    // Extract track IDs before moving tracks (avoids clone of entire vector)
    let track_ids: Vec<TrackId<'static>> = tracks
      .iter()
      .filter_map(|item| item.id.as_ref().map(|id| id.clone().into_static()))
      .collect();

    let mut app = self.app.lock().await;

    // Apply pending selection if set
    let track_count = tracks.len();
    if track_count > 0 {
      if let Some(pending) = app.pending_track_table_selection.take() {
        app.track_table.selected_index = match pending {
          crate::app::PendingTrackSelection::First => 0,
          crate::app::PendingTrackSelection::Last => track_count.saturating_sub(1),
        };
      } else {
        // Clamp selected_index to valid range if no pending selection
        let max_index = track_count.saturating_sub(1);
        if app.track_table.selected_index > max_index {
          app.track_table.selected_index = max_index;
        }
      }
    } else {
      app.track_table.selected_index = 0;
    }

    app.track_table.tracks = tracks; // Move instead of clone

    app.dispatch(IoEvent::CurrentUserSavedTracksContains(track_ids));
  }

  async fn set_artists_to_table(&mut self, artists: Vec<FullArtist>) {
    let mut app = self.app.lock().await;
    app.artists = artists;
  }

  async fn get_current_user_saved_shows(&mut self, offset: Option<u32>) {
    let mut query = vec![("limit", self.large_search_limit.to_string())];
    if let Some(offset) = offset {
      query.push(("offset", offset.to_string()));
    }

    match self
      .spotify_get_typed_compat::<Page<rspotify::model::show::Show>>("me/shows", &query)
      .await
    {
      Ok(saved_shows) => {
        // not to show a blank page
        if !saved_shows.items.is_empty() {
          let mut app = self.app.lock().await;
          app.library.saved_shows.add_pages(saved_shows);
        }
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn current_user_saved_shows_contains(&mut self, show_ids: Vec<ShowId<'_>>) {
    let uris: Vec<String> = show_ids
      .iter()
      .map(|id| format!("spotify:show:{}", id.id()))
      .collect();
    match self.library_contains_uris(&uris).await {
      Ok(is_saved_vec) => {
        let mut app = self.app.lock().await;
        for (i, id) in show_ids.iter().enumerate() {
          if let Some(is_saved) = is_saved_vec.get(i) {
            if *is_saved {
              app.saved_show_ids_set.insert(id.id().to_string());
            } else {
              // The show is not saved, so check if it should be removed
              if app.saved_show_ids_set.contains(id.id()) {
                app.saved_show_ids_set.remove(id.id());
              }
            }
          };
        }
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn get_show_episodes(&mut self, show: Box<SimplifiedShow>) {
    let show_id = show.id.clone();
    let path = format!("shows/{}/episodes", show_id.id());
    let query = vec![
      ("limit", self.large_search_limit.to_string()),
      ("offset", "0".to_string()),
    ];
    match self
      .spotify_get_typed_compat::<Page<rspotify::model::show::SimplifiedEpisode>>(&path, &query)
      .await
    {
      Ok(episodes) => {
        if !episodes.items.is_empty() {
          let mut app = self.app.lock().await;
          app.library.show_episodes = ScrollableResultPages::new();
          app.library.show_episodes.add_pages(episodes);

          app.selected_show_simplified = Some(SelectedShow { show: *show });

          app.episode_table_context = EpisodeTableContext::Simplified;

          app.push_navigation_stack(RouteId::PodcastEpisodes, ActiveBlock::EpisodeTable);
        }
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn get_show(&mut self, show_id: ShowId<'_>) {
    let path = format!("shows/{}", show_id.id());
    match self
      .spotify_get_typed_compat::<rspotify::model::show::FullShow>(&path, &[])
      .await
    {
      Ok(show) => {
        let selected_show = SelectedFullShow { show };

        let mut app = self.app.lock().await;

        app.selected_show_full = Some(selected_show);

        app.episode_table_context = EpisodeTableContext::Full;
        app.push_navigation_stack(RouteId::PodcastEpisodes, ActiveBlock::EpisodeTable);
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn get_current_show_episodes(&mut self, show_id: ShowId<'_>, offset: Option<u32>) {
    let path = format!("shows/{}/episodes", show_id.id());
    let mut query = vec![("limit", self.large_search_limit.to_string())];
    if let Some(offset) = offset {
      query.push(("offset", offset.to_string()));
    }

    match self
      .spotify_get_typed_compat::<Page<rspotify::model::show::SimplifiedEpisode>>(&path, &query)
      .await
    {
      Ok(episodes) => {
        if !episodes.items.is_empty() {
          let mut app = self.app.lock().await;
          app.library.show_episodes.add_pages(episodes);
        }
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn get_search_results(&mut self, search_term: String, country: Option<Country>) {
    // Don't pass market to search - when market is specified, Spotify doesn't return
    // available_markets field, but rspotify 0.14 models require it for tracks/albums.
    // We'll handle null playlist fields by searching playlists separately without requiring all fields.
    let _market = country.map(Market::Country);

    let search_track = self.spotify.search(
      &search_term,
      SearchType::Track,
      None,
      None, // include_external
      Some(self.small_search_limit),
      Some(0),
    );

    let search_album = self.spotify.search(
      &search_term,
      SearchType::Album,
      None,
      None, // include_external
      Some(self.small_search_limit),
      Some(0),
    );

    let search_playlist = self.spotify.search(
      &search_term,
      SearchType::Playlist,
      None,
      None, // include_external
      Some(self.small_search_limit),
      Some(0),
    );

    let search_show = self.spotify.search(
      &search_term,
      SearchType::Show,
      None,
      None, // include_external
      Some(self.small_search_limit),
      Some(0),
    );

    let artist_query = vec![
      ("q", search_term.clone()),
      ("type", "artist".to_string()),
      ("limit", self.small_search_limit.to_string()),
      ("offset", "0".to_string()),
    ];

    // Run all futures concurrently
    let (main_search, playlist_search, artist_search) = tokio::join!(
      async { try_join!(search_track, search_album, search_show) },
      search_playlist,
      self.spotify_get_typed_compat::<ArtistSearchResponse>("search", &artist_query)
    );

    // Handle main search results
    let (track_result, album_result, show_result) = match main_search {
      Ok((
        SearchResult::Tracks(tracks),
        SearchResult::Albums(albums),
        SearchResult::Shows(shows),
      )) => (Some(tracks), Some(albums), Some(shows)),
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
        return;
      }
      _ => return,
    };

    let artist_result = artist_search.ok().map(|res| res.artists);

    // Handle playlist search separately since it can fail with null fields from Spotify API
    // Silently ignore playlist errors - this is a known Spotify API issue
    let playlist_result = match playlist_search {
      Ok(SearchResult::Playlists(playlists)) => Some(playlists),
      Err(_) => None,
      _ => None,
    };

    let mut app = self.app.lock().await;

    if let Some(ref album_results) = album_result {
      let artist_ids = album_results
        .items
        .iter()
        .filter_map(|item| {
          item
            .id
            .as_ref()
            .map(|id| ArtistId::from_id(id.id()).unwrap().into_static())
        })
        .collect();

      // Check if these artists are followed
      app.dispatch(IoEvent::UserArtistFollowCheck(artist_ids));

      let album_ids = album_results
        .items
        .iter()
        .filter_map(|album| {
          album
            .id
            .as_ref()
            .map(|id| AlbumId::from_id(id.id()).unwrap().into_static())
        })
        .collect();

      // Check if these albums are saved
      app.dispatch(IoEvent::CurrentUserSavedAlbumsContains(album_ids));
    }

    if let Some(ref show_results) = show_result {
      let show_ids = show_results
        .items
        .iter()
        .map(|show| show.id.clone().into_static())
        .collect();

      // check if these shows are saved
      app.dispatch(IoEvent::CurrentUserSavedShowsContains(show_ids));
    }

    app.search_results.tracks = track_result;
    app.search_results.artists = artist_result;
    app.search_results.albums = album_result;
    app.search_results.playlists = playlist_result;
    app.search_results.shows = show_result;
  }

  async fn get_current_user_saved_tracks(&mut self, offset: Option<u32>) {
    let mut query = vec![("limit", self.large_search_limit.to_string())];
    if let Some(offset) = offset {
      query.push(("offset", offset.to_string()));
    }

    match self
      .spotify_get_typed_compat::<Page<rspotify::model::SavedTrack>>("me/tracks", &query)
      .await
    {
      Ok(saved_tracks) => {
        let mut app = self.app.lock().await;
        app.track_table.tracks = saved_tracks
          .items
          .clone()
          .into_iter()
          .map(|item| item.track)
          .collect::<Vec<FullTrack>>();

        saved_tracks.items.iter().for_each(|item| {
          if let Some(track_id) = &item.track.id {
            app.liked_song_ids_set.insert(track_id.to_string());
          }
        });

        // Apply pending selection if set
        let track_count = app.track_table.tracks.len();
        if track_count > 0 {
          if let Some(pending) = app.pending_track_table_selection.take() {
            app.track_table.selected_index = match pending {
              crate::app::PendingTrackSelection::First => 0,
              crate::app::PendingTrackSelection::Last => track_count.saturating_sub(1),
            };
          }
        }

        app.library.saved_tracks.add_pages(saved_tracks);
        app.track_table.context = Some(TrackTableContext::SavedTracks);
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn start_playback(
    &mut self,
    context_id: Option<PlayContextId<'_>>,
    uris: Option<Vec<PlayableId<'_>>>,
    offset: Option<usize>,
  ) {
    // Check if we should use native streaming for playback
    #[cfg(feature = "streaming")]
    if self.is_native_streaming_active_for_playback().await {
      if let Some(ref player) = self.streaming_player {
        let activation_time = Instant::now();
        let should_transfer = {
          let app = self.app.lock().await;
          let activation_pending = app.native_activation_pending;
          let recent_activation = app
            .last_device_activation
            .is_some_and(|instant| instant.elapsed() < Duration::from_secs(5));
          if activation_pending {
            !recent_activation
          } else {
            !app.is_streaming_active && !recent_activation
          }
        };

        if should_transfer {
          let _ = player.transfer(None);
        }

        player.activate();
        {
          let mut app = self.app.lock().await;
          app.is_streaming_active = true;
          app.last_device_activation = Some(activation_time);
          app.native_activation_pending = false;
        }

        // For resume playback (no context, no uris)
        if context_id.is_none() && uris.is_none() {
          player.play();
          // Update UI state immediately
          let mut app = self.app.lock().await;
          if let Some(ctx) = &mut app.current_playback_context {
            ctx.is_playing = true;
          }
          return;
        }

        // For URI-based or context playback, use Spirc load directly.
        // The Web API may return 404 for native streaming devices (different OAuth session).
        let mut options = LoadRequestOptions {
          start_playing: true,
          seek_to: 0,
          context_options: None,
          playing_track: None,
        };

        let request = match (context_id, uris) {
          (Some(context), Some(track_uris)) => {
            if let Some(first_uri) = track_uris.first() {
              options.playing_track = Some(PlayingTrack::Uri(first_uri.uri()));
            } else if let Some(i) = offset.and_then(|i| u32::try_from(i).ok()) {
              options.playing_track = Some(PlayingTrack::Index(i));
            }
            LoadRequest::from_context_uri(context.uri(), options)
          }
          (Some(context), None) => {
            if let Some(i) = offset.and_then(|i| u32::try_from(i).ok()) {
              options.playing_track = Some(PlayingTrack::Index(i));
            }
            LoadRequest::from_context_uri(context.uri(), options)
          }
          (None, Some(track_uris)) => {
            if let Some(i) = offset.and_then(|i| u32::try_from(i).ok()) {
              options.playing_track = Some(PlayingTrack::Index(i));
            }
            let uris = track_uris.into_iter().map(|u| u.uri()).collect::<Vec<_>>();
            LoadRequest::from_tracks(uris, options)
          }
          (None, None) => {
            // Handled above as resume playback.
            player.play();
            let mut app = self.app.lock().await;
            if let Some(ctx) = &mut app.current_playback_context {
              ctx.is_playing = true;
            }
            return;
          }
        };

        match player.load(request) {
          Ok(()) => {
            // Best-effort: ensure we end up playing (some Connect flows load paused).
            player.play();

            // Update UI state immediately (TrackChanged/Playing events will refine state).
            let mut app = self.app.lock().await;
            app.song_progress_ms = 0;
            app.native_is_playing = Some(true);
            if let Some(ctx) = &mut app.current_playback_context {
              ctx.is_playing = true;
            }
          }
          Err(e) => {
            self.handle_error(e).await;
          }
        }

        return;
      }
    }

    // If Spotify reports a current playback context, target the active device by omitting
    // `device_id` (more robust when the user switches devices outside spotatui).
    // When there's no active playback context, fall back to the last saved device_id.
    let has_playback_context = {
      let app = self.app.lock().await;
      app.current_playback_context.is_some()
    };
    let device_id = if has_playback_context {
      None
    } else {
      self.client_config.device_id.as_deref()
    };

    // If we're starting playback at a specific position within a context (via a numeric offset),
    // temporarily disable shuffle to ensure the selected item plays first.
    // (When we start by explicit track URI, we don't need to touch shuffle.)
    let should_disable_shuffle = context_id.is_some() && uris.is_none() && offset.is_some();
    let mut original_shuffle_state = false;

    #[cfg(feature = "streaming")]
    let is_native = self.is_native_streaming_active_for_playback().await;
    #[cfg(not(feature = "streaming"))]
    let is_native = false;

    if should_disable_shuffle && !is_native {
      // Get current shuffle state (skip for native - API might fail)
      if let Ok(Some(playback)) = self.spotify.current_playback(None, None::<Vec<_>>).await {
        original_shuffle_state = playback.shuffle_state;
        if original_shuffle_state {
          // Temporarily disable shuffle
          let _ = self.spotify.shuffle(false, device_id).await;
          // Small delay to let the shuffle state update
          tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
        }
      }
    }

    // Check if we have both context and uris - this means play specific track within context
    let has_both = context_id.is_some() && uris.is_some();
    // Track if this is a resume (no new track) vs starting new content
    let is_resume = context_id.is_none() && uris.is_none();

    let result = if has_both {
      // Special case: Play a specific track within a context
      // This ensures the selected track plays first, even with shuffle enabled
      let context = context_id.unwrap();
      let track_uris = uris.unwrap();

      if let Some(first_uri) = track_uris.first() {
        let offset = rspotify::model::Offset::Uri(first_uri.uri());
        self
          .spotify
          .start_context_playback(context, device_id, Some(offset), None)
          .await
      } else {
        self
          .spotify
          .start_context_playback(context, device_id, None, None)
          .await
      }
    } else if let Some(context_id) = context_id {
      // Play from context, optionally starting at an offset within the context.
      let offset = offset
        .and_then(|i| i64::try_from(i).ok())
        .map(|i| rspotify::model::Offset::Position(chrono::Duration::milliseconds(i)));
      self
        .spotify
        .start_context_playback(context_id, device_id, offset, None)
        .await
    } else if let Some(mut uris) = uris {
      // For URI-based playback, reorder the list to put the selected track first
      // This ensures the user's selected track plays first, regardless of shuffle mode
      if let Some(offset_pos) = offset {
        if offset_pos < uris.len() && offset_pos > 0 {
          // Move the track at offset_pos to the front
          let selected = uris.remove(offset_pos);
          uris.insert(0, selected);
        }
      }

      self
        .spotify
        .start_uris_playback(uris, device_id, None, None)
        .await
    } else {
      // Resume playback - use native player if available for instant response
      #[cfg(feature = "streaming")]
      if self.is_native_streaming_active_for_playback().await {
        if let Some(ref player) = self.streaming_player {
          player.play();
          // Update UI state immediately
          let mut app = self.app.lock().await;
          if let Some(ctx) = &mut app.current_playback_context {
            ctx.is_playing = true;
          }
          return;
        }
      }
      self.spotify.resume_playback(device_id, None).await
    };

    match result {
      Ok(()) => {
        // Re-enable shuffle if it was on before
        if should_disable_shuffle && original_shuffle_state && !is_native {
          // Small delay to let playback start before re-enabling shuffle
          tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
          let _ = self.spotify.shuffle(true, device_id).await;
        }

        // Update playing state immediately
        // Only reset progress for new tracks, not for resume
        {
          let mut app = self.app.lock().await;
          if !is_resume {
            app.song_progress_ms = 0;
          }
          if let Some(ctx) = &mut app.current_playback_context {
            ctx.is_playing = true;
          }
        }

        // Wait for Spotify's API to sync before fetching updated state
        tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;
        self.get_current_playback().await;
      }
      Err(e) => {
        // For native streaming, if the API fails (404), try using native player directly
        #[cfg(feature = "streaming")]
        if is_native {
          if let Some(ref player) = self.streaming_player {
            // Activate and play - the Spirc will handle the actual playback
            player.activate();
            player.play();

            // Update UI state
            {
              let mut app = self.app.lock().await;
              app.song_progress_ms = 0;
              if let Some(ctx) = &mut app.current_playback_context {
                ctx.is_playing = true;
              }
            }

            // Small delay then fetch updated state
            tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
            self.get_current_playback().await;
            return;
          }
        }

        // Re-enable shuffle even on error if it was on before
        if should_disable_shuffle && original_shuffle_state {
          let _ = self.spotify.shuffle(true, device_id).await;
        }
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  /// Start playback from the user's saved tracks collection (Liked Songs)
  /// Uses a direct HTTP call since rspotify doesn't support the collection context URI
  async fn start_collection_playback(&mut self, offset: usize) {
    // Get user ID to construct collection context URI
    let user_id = {
      let app = self.app.lock().await;
      app.user.as_ref().map(|u| u.id.to_string())
    };

    let user_id = match user_id {
      Some(id) => id,
      None => {
        self.handle_error(anyhow!("User not logged in")).await;
        return;
      }
    };

    // Get access token from rspotify client
    let token = {
      let token_lock = self
        .spotify
        .token
        .lock()
        .await
        .expect("Failed to lock token");
      token_lock.as_ref().map(|t| t.access_token.clone())
    };

    let access_token = match token {
      Some(t) => t,
      None => {
        self
          .handle_error(anyhow!("No access token available"))
          .await;
        return;
      }
    };

    // Construct the collection context URI: spotify:user:{user_id}:collection
    let context_uri = format!("spotify:user:{}:collection", user_id);

    // Build the request body
    let mut body = serde_json::json!({
      "context_uri": context_uri,
      "offset": { "position": offset }
    });

    // Add device_id if configured
    if let Some(ref device_id) = self.client_config.device_id {
      body["device_id"] = serde_json::json!(device_id);
    }

    // Make the API request using reqwest
    let client = reqwest::Client::new();
    let url = match self.client_config.device_id.as_ref() {
      Some(device_id) => format!(
        "https://api.spotify.com/v1/me/player/play?device_id={}",
        device_id
      ),
      None => "https://api.spotify.com/v1/me/player/play".to_string(),
    };

    let result = client
      .put(&url)
      .header("Authorization", format!("Bearer {}", access_token))
      .header("Content-Type", "application/json")
      .json(&body)
      .send()
      .await;

    match result {
      Ok(response) => {
        if response.status().is_success() {
          // Reset progress and update playing state immediately
          {
            let mut app = self.app.lock().await;
            app.song_progress_ms = 0;
            if let Some(ctx) = &mut app.current_playback_context {
              ctx.is_playing = true;
            }
          }

          // Wait for Spotify's API to sync before fetching updated state
          tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;
          self.get_current_playback().await;
        } else {
          let error_text = response
            .text()
            .await
            .unwrap_or_else(|_| "Unknown error".to_string());
          self
            .handle_error(anyhow!(
              "Failed to start collection playback: {}",
              error_text
            ))
            .await;
        }
      }
      Err(e) => {
        self
          .handle_error(anyhow!("HTTP request failed: {}", e))
          .await;
      }
    }
  }

  /// Pre-fetch all saved tracks pages in background for seamless playback
  /// This loads all remaining pages that haven't been loaded yet
  /// Runs as a separate async task to avoid blocking other operations
  async fn prefetch_all_saved_tracks_task(
    spotify: AuthCodePkceSpotify,
    app: Arc<Mutex<App>>,
    large_search_limit: u32,
  ) {
    // Get current state
    let (current_total, pages_loaded) = {
      let app = app.lock().await;
      if let Some(saved_tracks) = app.library.saved_tracks.get_results(Some(0)) {
        (
          saved_tracks.total,
          app.library.saved_tracks.pages.len() as u32,
        )
      } else {
        return; // No saved tracks loaded yet
      }
    };

    // Calculate how many tracks we already have
    let tracks_loaded = pages_loaded * large_search_limit;

    // Fetch remaining pages (limit to reasonable amount to avoid memory issues)
    let max_tracks_to_prefetch = 500; // ~10 pages
    let mut offset = tracks_loaded;

    while offset < current_total && offset < tracks_loaded + max_tracks_to_prefetch {
      let query = vec![
        ("limit", large_search_limit.to_string()),
        ("offset", offset.to_string()),
      ];
      match Self::spotify_get_typed_compat_for::<Page<rspotify::model::SavedTrack>>(
        &spotify,
        "me/tracks",
        &query,
      )
      .await
      {
        Ok(saved_tracks) => {
          {
            let mut app = app.lock().await;
            // Add liked song IDs to the set
            saved_tracks.items.iter().for_each(|item| {
              if let Some(track_id) = &item.track.id {
                app.liked_song_ids_set.insert(track_id.to_string());
              }
            });
            // Add page to the saved tracks
            app.library.saved_tracks.pages.push(saved_tracks);
          }
          tokio::task::yield_now().await;
        }
        Err(_e) => {
          // Silently fail in background task - don't show errors to user
          break;
        }
      }
      offset += large_search_limit;
    }
  }

  /// Pre-fetch all tracks from a playlist in background
  /// Runs as a separate async task to avoid blocking other operations
  async fn prefetch_all_playlist_tracks_task(
    spotify: AuthCodePkceSpotify,
    app: Arc<Mutex<App>>,
    large_search_limit: u32,
    playlist_id: PlaylistId<'static>,
  ) {
    // Get current playlist state
    let current_total = {
      let app = app.lock().await;
      if let Some(playlist_tracks) = &app.playlist_tracks {
        playlist_tracks.total
      } else {
        return;
      }
    };

    // Get current offset
    let current_offset = {
      let app = app.lock().await;
      app.playlist_offset
    };

    // Fetch remaining pages (limit to avoid memory issues)
    let max_tracks_to_prefetch = 500; // ~10 pages
    let mut offset = current_offset + large_search_limit;

    while offset < current_total && offset < current_offset + max_tracks_to_prefetch {
      let path = format!("playlists/{}/items", playlist_id.id());
      let query = vec![
        ("limit", large_search_limit.to_string()),
        ("offset", offset.to_string()),
      ];
      match Self::spotify_get_typed_compat_for::<Page<PlaylistItem>>(&spotify, &path, &query).await
      {
        Ok(playlist_page) => {
          {
            let mut app = app.lock().await;
            // Extend playlist tracks items
            if let Some(ref mut existing) = app.playlist_tracks {
              existing.items.extend(playlist_page.items);
              existing.total = playlist_page.total; // Update total in case it changed
            }
          }
          tokio::task::yield_now().await;
        }
        Err(_e) => {
          break;
        }
      }
      offset += large_search_limit;
    }
  }

  /// Fetch all tracks from a playlist and apply sorting
  async fn fetch_all_playlist_tracks_and_sort(&mut self, playlist_id: PlaylistId<'_>) {
    use rspotify::model::PlayableItem;

    // Get current playlist total and sort state
    let (total, sort_state) = {
      let app = self.app.lock().await;
      let total = app.playlist_tracks.as_ref().map(|p| p.total).unwrap_or(0);
      let sort_state = app.playlist_sort;
      (total, sort_state)
    };

    if total == 0 {
      return;
    }

    // Collect all playlist items
    let mut all_items: Vec<rspotify::model::playlist::PlaylistItem> = Vec::new();
    let mut offset = 0;

    while offset < total {
      let path = format!("playlists/{}/items", playlist_id.id());
      let query = vec![
        ("limit", self.large_search_limit.to_string()),
        ("offset", offset.to_string()),
      ];
      match self
        .spotify_get_typed_compat::<Page<PlaylistItem>>(&path, &query)
        .await
      {
        Ok(page) => {
          all_items.extend(page.items);
        }
        Err(_e) => {
          break;
        }
      }
      offset += self.large_search_limit;
    }

    // Sort all items
    all_items.sort_by(|a, b| {
      let track_a = a.track.as_ref().and_then(|t| match t {
        PlayableItem::Track(track) => Some(track),
        PlayableItem::Episode(_) => None,
      });
      let track_b = b.track.as_ref().and_then(|t| match t {
        PlayableItem::Track(track) => Some(track),
        PlayableItem::Episode(_) => None,
      });

      let cmp = match (track_a, track_b) {
        (Some(ta), Some(tb)) => match sort_state.field {
          crate::sort::SortField::Default => std::cmp::Ordering::Equal,
          crate::sort::SortField::Name => ta.name.to_lowercase().cmp(&tb.name.to_lowercase()),
          crate::sort::SortField::Artist => {
            let artist_a = ta
              .artists
              .first()
              .map(|ar| ar.name.to_lowercase())
              .unwrap_or_default();
            let artist_b = tb
              .artists
              .first()
              .map(|ar| ar.name.to_lowercase())
              .unwrap_or_default();
            artist_a.cmp(&artist_b)
          }
          crate::sort::SortField::Album => ta
            .album
            .name
            .to_lowercase()
            .cmp(&tb.album.name.to_lowercase()),
          crate::sort::SortField::Duration => ta.duration.cmp(&tb.duration),
          crate::sort::SortField::DateAdded => a.added_at.cmp(&b.added_at),
        },
        (Some(_), None) => std::cmp::Ordering::Less,
        (None, Some(_)) => std::cmp::Ordering::Greater,
        (None, None) => std::cmp::Ordering::Equal,
      };

      if sort_state.order == crate::sort::SortOrder::Descending {
        cmp.reverse()
      } else {
        cmp
      }
    });

    // Extract tracks and update app state
    let sorted_tracks: Vec<rspotify::model::FullTrack> = all_items
      .iter()
      .filter_map(|item| item.track.as_ref())
      .filter_map(|track| match track {
        PlayableItem::Track(full_track) => Some(full_track.clone()),
        PlayableItem::Episode(_) => None,
      })
      .collect();

    // Update app state with sorted data
    let mut app = self.app.lock().await;

    // Update playlist_tracks with sorted items
    if let Some(ref mut playlist_tracks) = app.playlist_tracks {
      playlist_tracks.items = all_items;
      playlist_tracks.total = total;
    }

    // Update track table with sorted tracks
    app.track_table.tracks = sorted_tracks;
    app.track_table.selected_index = 0;
  }

  async fn seek(&mut self, position_ms: u32) {
    // Use native streaming player for instant seek (no network delay)
    #[cfg(feature = "streaming")]
    if self.is_native_streaming_active_for_playback().await {
      if let Some(ref player) = self.streaming_player {
        player.seek(position_ms);
        // Update UI immediately without API polling
        let mut app = self.app.lock().await;
        app.song_progress_ms = position_ms as u128;
        app.seek_ms = None;
        return;
      }
    }

    // Fallback to API-based seek
    let position = TimeDelta::milliseconds(position_ms as i64);

    // Don't pin commands to a saved device_id; target Spotify's currently active device.
    match self.spotify.seek_track(position, None).await {
      Ok(()) => {
        // Don't immediately refresh playback - rapid seeks cause out-of-order responses
        // that overwrite our target position. The normal polling cycle will update eventually.
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    };
  }

  async fn next_track(&mut self) {
    // Use native streaming player for instant skip (no network delay)
    // BUT only if native streaming device is the active playback device
    #[cfg(feature = "streaming")]
    if self.is_native_streaming_active_for_playback().await {
      if let Some(ref player) = self.streaming_player {
        player.activate();
        player.next();
        // librespot can occasionally land in a paused state after a skip.
        // Schedule a short delayed resume to avoid racing the track transition.
        let player = Arc::clone(player);
        tokio::spawn(async move {
          tokio::time::sleep(Duration::from_millis(300)).await;
          player.activate();
          player.play();
        });
        // Reset progress immediately for UI feedback
        let mut app = self.app.lock().await;
        app.song_progress_ms = 0;
        // The TrackChanged event will trigger GetCurrentPlayback for full metadata
        return;
      }
    }

    // Store if playing before skip for auto-resume
    let was_playing = {
      let mut app = self.app.lock().await;
      // Reset progress immediately for instant UI feedback
      app.song_progress_ms = 0;
      app
        .current_playback_context
        .as_ref()
        .map(|c| c.is_playing)
        .unwrap_or(false)
    };

    // API-based skip for external players (spotifyd, etc.)
    match self.spotify.next_track(None).await {
      Ok(()) => {
        // For external players, proactively resume if we were playing
        // Spotifyd often lands in paused state after skip
        if was_playing {
          tokio::time::sleep(Duration::from_millis(100)).await;
          let _ = self.spotify.resume_playback(None, None).await;
        }

        // Minimal delay then fetch updated state (reduced from 400ms total to ~150ms)
        tokio::time::sleep(Duration::from_millis(150)).await;
        self.get_current_playback().await;
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    };
  }

  async fn previous_track(&mut self) {
    // Use native streaming player for instant skip (no network delay)
    // BUT only if native streaming device is the active playback device
    #[cfg(feature = "streaming")]
    if self.is_native_streaming_active_for_playback().await {
      if let Some(ref player) = self.streaming_player {
        player.activate();
        player.prev();
        // librespot can occasionally land in a paused state after a skip.
        // Schedule a short delayed resume to avoid racing the track transition.
        let player = Arc::clone(player);
        tokio::spawn(async move {
          tokio::time::sleep(Duration::from_millis(300)).await;
          player.activate();
          player.play();
        });
        // Reset progress immediately for UI feedback
        let mut app = self.app.lock().await;
        app.song_progress_ms = 0;
        // The TrackChanged event will trigger GetCurrentPlayback for full metadata
        return;
      }
    }

    // Store if playing before skip for auto-resume
    let was_playing = {
      let mut app = self.app.lock().await;
      // Reset progress immediately for instant UI feedback
      app.song_progress_ms = 0;
      app
        .current_playback_context
        .as_ref()
        .map(|c| c.is_playing)
        .unwrap_or(false)
    };

    // API-based skip for external players (spotifyd, etc.)
    match self.spotify.previous_track(None).await {
      Ok(()) => {
        // For external players, proactively resume if we were playing
        // Spotifyd often lands in paused state after skip
        if was_playing {
          tokio::time::sleep(Duration::from_millis(100)).await;
          let _ = self.spotify.resume_playback(None, None).await;
        }

        // Minimal delay then fetch updated state (reduced from 400ms total to ~150ms)
        tokio::time::sleep(Duration::from_millis(150)).await;
        self.get_current_playback().await;
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    };
  }

  async fn shuffle(&mut self, desired_shuffle_state: bool) {
    let new_shuffle_state = desired_shuffle_state;
    let is_startup_sync = {
      let app = self.app.lock().await;
      app.current_playback_context.is_none()
    };

    // Prefer native streaming control when available AND active as playback device
    #[cfg(feature = "streaming")]
    if self.is_native_streaming_active_for_playback().await {
      if let Some(ref player) = self.streaming_player {
        // Try to set shuffle on the native player
        let shuffle_result = player.set_shuffle(new_shuffle_state);

        // Update UI and save config regardless of Spirc result
        // (Spirc might not be fully ready yet but we still want to save the preference)
        {
          let mut app = self.app.lock().await;
          if let Some(ctx) = &mut app.current_playback_context {
            ctx.shuffle_state = new_shuffle_state;
          }
          app.user_config.behavior.shuffle_enabled = new_shuffle_state;
          let _ = app.user_config.save_config();
        }

        // Log error but don't show error screen - suppress to avoid startup popups
        if let Err(_e) = shuffle_result {
          // Silently ignore - Spirc might not be ready yet
          // The shuffle state will be applied when playback starts
        }

        // Don't fall back to API - it will fail with 404 for native devices
        return;
      }
    }

    // Fallback: API-based shuffle for external devices (spotifyd, phone, etc.)
    // Update UI optimistically before API call for instant feedback
    {
      let mut app = self.app.lock().await;
      if let Some(ctx) = &mut app.current_playback_context {
        ctx.shuffle_state = new_shuffle_state;
      }
      app.user_config.behavior.shuffle_enabled = new_shuffle_state;
      let _ = app.user_config.save_config();
    }

    // Send API request (don't block on response)
    // Don't pin commands to a saved device_id; target Spotify's currently active device.
    if let Err(e) = self.spotify.shuffle(new_shuffle_state, None).await {
      let err = anyhow!(e);

      if Self::is_rate_limited_error(&err) {
        self
          .show_status_message(
            "Spotify rate limit hit while syncing shuffle. It will sync shortly.".to_string(),
            5,
          )
          .await;
        return;
      }

      // On startup we try to apply the saved shuffle preference before there is any active
      // playback device. Spotify returns a 404 in this case; don't show the error screen.
      if is_startup_sync {
        if let Some(rspotify::ClientError::Http(http)) = err.downcast_ref::<rspotify::ClientError>()
        {
          if let rspotify::http::HttpError::StatusCode(response) = http.as_ref() {
            if response.status().as_u16() == 404 {
              let mut app = self.app.lock().await;
              app.user_config.behavior.shuffle_enabled = new_shuffle_state;
              let _ = app.user_config.save_config();
              return;
            }
          }
        }
      }
      self.handle_error(err).await;
    }
  }

  async fn repeat(&mut self, repeat_state: RepeatState) {
    let next_repeat_state = match repeat_state {
      RepeatState::Off => RepeatState::Context,
      RepeatState::Context => RepeatState::Track,
      RepeatState::Track => RepeatState::Off,
    };

    // When using native streaming, update UI immediately and send command to player
    // The Web API returns 404 for native streaming devices
    #[cfg(feature = "streaming")]
    if self.is_native_streaming_active_for_playback().await {
      if let Some(ref player) = self.streaming_player {
        // Send the repeat command to the native player (current state, not next state)
        if let Err(e) = player.set_repeat(repeat_state) {
          self.handle_error(anyhow!(e)).await;
        }
      }
      // Update UI after sending command
      let mut app = self.app.lock().await;
      if let Some(ctx) = &mut app.current_playback_context {
        ctx.repeat_state = next_repeat_state;
      }
      return;
    }

    // Fallback: API-based repeat for external devices
    // Update UI optimistically before API call for instant feedback
    {
      let mut app = self.app.lock().await;
      if let Some(ctx) = &mut app.current_playback_context {
        ctx.repeat_state = next_repeat_state;
      }
    }

    // Send API request (don't block on response)
    // Don't pin commands to a saved device_id; target Spotify's currently active device.
    if let Err(e) = self.spotify.repeat(next_repeat_state, None).await {
      // Revert on error
      {
        let mut app = self.app.lock().await;
        if let Some(ctx) = &mut app.current_playback_context {
          ctx.repeat_state = repeat_state; // Revert to original state
        }
      }
      self.handle_error(anyhow!(e)).await;
    }
  }

  async fn pause_playback(&mut self) {
    // Use native streaming player for instant pause (no network delay)
    #[cfg(feature = "streaming")]
    if self.is_native_streaming_active_for_playback().await {
      if let Some(ref player) = self.streaming_player {
        player.pause();
        // Update UI state immediately
        let mut app = self.app.lock().await;
        if let Some(ctx) = &mut app.current_playback_context {
          ctx.is_playing = false;
        }
        return;
      }
    }

    // Fallback to API-based pause
    // Don't pin commands to a saved device_id; target Spotify's currently active device.
    match self.spotify.pause_playback(None).await {
      Ok(()) => {
        // Update UI immediately instead of full playback poll
        let mut app = self.app.lock().await;
        if let Some(ctx) = &mut app.current_playback_context {
          ctx.is_playing = false;
        }
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    };
  }

  async fn ensure_playback_continues(&mut self, previous_track_id: String) {
    // Let the backend transition to the next item first.
    tokio::time::sleep(Duration::from_millis(250)).await;
    self.get_current_playback().await;

    let (current_track_id, is_playing) = {
      let app = self.app.lock().await;
      let current_track_id = app
        .current_playback_context
        .as_ref()
        .and_then(|ctx| ctx.item.as_ref())
        .and_then(|item| match item {
          PlayableItem::Track(track) => track.id.as_ref().map(|id| id.id().to_string()),
          _ => None,
        });
      let is_playing = app
        .current_playback_context
        .as_ref()
        .map(|ctx| ctx.is_playing)
        .unwrap_or(false);
      (current_track_id, is_playing)
    };

    let Some(current_id) = current_track_id else {
      return;
    };

    let current_uri = format!("spotify:track:{current_id}");
    let is_new_track = previous_track_id != current_id && previous_track_id != current_uri;
    let should_resume = is_new_track && !is_playing;

    if should_resume {
      self.start_playback(None, None, None).await;
      // Refresh state so UI/clients converge quickly.
      self.get_current_playback().await;
    }
  }

  async fn change_volume(&mut self, volume_percent: u8) {
    // Use native streaming player for instant volume change (no network delay)
    #[cfg(feature = "streaming")]
    if self.is_native_streaming_active_for_playback().await {
      if let Some(ref player) = self.streaming_player {
        player.set_volume(volume_percent);
        // Update UI state immediately
        let mut app = self.app.lock().await;
        if let Some(ctx) = &mut app.current_playback_context {
          ctx.device.volume_percent = Some(volume_percent.into());
        }
        // Persist volume setting
        app.user_config.behavior.volume_percent = volume_percent;
        let _ = app.user_config.save_config();
        return;
      }
    }

    // Fallback to API-based volume control
    // Update UI optimistically before API call for instant feedback
    {
      let mut app = self.app.lock().await;
      if let Some(ctx) = &mut app.current_playback_context {
        ctx.device.volume_percent = Some(volume_percent.into());
      }
      // Persist volume setting
      app.user_config.behavior.volume_percent = volume_percent;
      let _ = app.user_config.save_config();
    }

    // Send API request (don't block on response)
    // Don't pin commands to a saved device_id; target Spotify's currently active device.
    if let Err(e) = self.spotify.volume(volume_percent, None).await {
      self.handle_error(anyhow!(e)).await;
    }
  }

  async fn get_artist(
    &mut self,
    artist_id: ArtistId<'_>,
    input_artist_name: String,
    country: Option<Country>,
  ) {
    // Avoid passing market here; restricted API payloads can omit fields required by rspotify models.
    let _market = country.map(Market::Country);

    // Use artist_albums_manual for explicit pagination control
    let albums = self.spotify.artist_albums_manual(
      artist_id.clone(),
      None,
      None,
      Some(self.large_search_limit),
      Some(0),
    );
    let artist_name = if input_artist_name.is_empty() {
      self
        .spotify
        .artist(artist_id.clone())
        .await
        .map(|full_artist| full_artist.name)
        .unwrap_or_default()
    } else {
      input_artist_name
    };
    match albums.await {
      Ok(albums) => {
        let top_tracks = self
          .spotify
          .artist_top_tracks(artist_id.clone(), None)
          .await
          .unwrap_or_default();
        // Try to fetch related artists, but don't fail if it's unavailable (deprecated endpoint)
        #[allow(deprecated)]
        let related_artist = self
          .spotify
          .artist_related_artists(artist_id.clone())
          .await
          .unwrap_or_else(|_| Vec::new());

        let mut app = self.app.lock().await;

        app.dispatch(IoEvent::CurrentUserSavedAlbumsContains(
          albums
            .items
            .iter()
            .filter_map(|item| {
              item
                .id
                .as_ref()
                .map(|id| AlbumId::from_id(id.id()).unwrap().into_static())
            })
            .collect(),
        ));

        app.artist = Some(Artist {
          artist_name,
          albums,
          related_artists: related_artist,
          top_tracks,
          selected_album_index: 0,
          selected_related_artist_index: 0,
          selected_top_track_index: 0,
          artist_hovered_block: ArtistBlock::TopTracks,
          artist_selected_block: ArtistBlock::Empty,
        });
        app.push_navigation_stack(RouteId::Artist, ActiveBlock::ArtistBlock);
      }
      Err(e) => {
        eprintln!("DEBUG: Error fetching artist: {:?}", e);
        self
          .handle_error(anyhow!("Failed to fetch artist: {}", e))
          .await;
      }
    }
  }

  async fn get_album_tracks(&mut self, album: Box<SimplifiedAlbum>) {
    if let Some(album_id) = &album.id {
      match self
        .spotify
        .album_track_manual(
          album_id.clone(),
          None,
          Some(self.large_search_limit),
          Some(0),
        )
        .await
      {
        Ok(tracks) => {
          let track_ids = tracks
            .items
            .iter()
            .filter_map(|item| {
              item
                .id
                .as_ref()
                .map(|id| TrackId::from_id(id.id()).unwrap().into_static())
            })
            .collect::<Vec<TrackId<'static>>>();

          let mut app = self.app.lock().await;
          app.selected_album_simplified = Some(SelectedAlbum {
            album: *album,
            tracks,
            selected_index: 0,
          });

          app.album_table_context = AlbumTableContext::Simplified;
          app.push_navigation_stack(RouteId::AlbumTracks, ActiveBlock::AlbumTracks);
          app.dispatch(IoEvent::CurrentUserSavedTracksContains(track_ids));
        }
        Err(e) => {
          self.handle_error(anyhow!(e)).await;
        }
      }
    }
  }

  async fn get_recommendations_for_seed(
    &mut self,
    seed_artists: Option<Vec<ArtistId<'static>>>,
    seed_tracks: Option<Vec<TrackId<'static>>>,
    first_track: Box<Option<FullTrack>>,
    country: Option<Country>,
  ) {
    let market = country.map(Market::Country);
    let seed_genres: Option<Vec<&str>> = None;

    match self
      .spotify
      .recommendations(
        [],                            // attributes (empty for now)
        seed_artists,                  // seed_artists
        seed_genres,                   // seed_genres
        seed_tracks,                   // seed_tracks
        market,                        // market
        Some(self.large_search_limit), // limit
      )
      .await
    {
      Ok(result) => {
        if let Some(mut recommended_tracks) = self.extract_recommended_tracks(&result).await {
          //custom first track
          if let Some(track) = *first_track {
            recommended_tracks.insert(0, track);
          }

          let track_ids = recommended_tracks
            .iter()
            .filter_map(|x| {
              x.id
                .as_ref()
                .map(|id| PlayableId::Track(id.clone().into_static()))
            })
            .collect::<Vec<PlayableId>>();

          self.set_tracks_to_table(recommended_tracks.clone()).await;

          let mut app = self.app.lock().await;
          app.recommended_tracks = recommended_tracks;
          app.track_table.context = Some(TrackTableContext::RecommendedTracks);

          if app.get_current_route().id != RouteId::Recommendations {
            app.push_navigation_stack(RouteId::Recommendations, ActiveBlock::TrackTable);
          };

          app.dispatch(IoEvent::StartPlayback(None, Some(track_ids), Some(0)));
        }
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn extract_recommended_tracks(
    &mut self,
    recommendations: &Recommendations,
  ) -> Option<Vec<FullTrack>> {
    let track_ids = recommendations
      .tracks
      .iter()
      .take(10)
      .filter_map(|track| track.id.clone())
      .collect::<Vec<TrackId>>();

    if track_ids.is_empty() {
      return Some(Vec::new());
    }

    let mut tracks = Vec::with_capacity(track_ids.len());
    for track_id in track_ids {
      let path = format!("tracks/{}", track_id.id());
      if let Ok(track) = self
        .spotify_get_typed_compat::<rspotify::model::track::FullTrack>(&path, &[])
        .await
      {
        tracks.push(track);
      }
    }

    if tracks.is_empty() {
      None
    } else {
      Some(tracks)
    }
  }

  async fn get_recommendations_for_track_id(
    &mut self,
    track_id: TrackId<'_>,
    country: Option<Country>,
  ) {
    if let Ok(track) = self.spotify.track(track_id.clone(), None).await {
      let track_id_list = vec![track_id.into_static()];
      self
        .get_recommendations_for_seed(None, Some(track_id_list), Box::new(Some(track)), country)
        .await;
    }
  }

  async fn toggle_save_track(&mut self, playable_id: PlayableId<'_>) {
    match playable_id {
      PlayableId::Track(track_id) => {
        let uri = format!("spotify:track:{}", track_id.id());
        match self.library_contains_uris(std::slice::from_ref(&uri)).await {
          Ok(saved) => {
            if saved.first() == Some(&true) {
              match self.library_remove_uris(std::slice::from_ref(&uri)).await {
                Ok(()) => {
                  let mut app = self.app.lock().await;
                  app.liked_song_ids_set.remove(track_id.id());
                }
                Err(e) => {
                  self.handle_error(anyhow!(e)).await;
                }
              }
            } else {
              match self.library_save_uris(std::slice::from_ref(&uri)).await {
                Ok(()) => {
                  let mut app = self.app.lock().await;
                  app.liked_song_ids_set.insert(track_id.id().to_string());
                  // Trigger the "Like" animation
                  app.liked_song_animation_frame = Some(10);
                }
                Err(e) => {
                  self.handle_error(anyhow!(e)).await;
                }
              }
            }
          }
          Err(e) => {
            self.handle_error(anyhow!(e)).await;
          }
        }
      }
      PlayableId::Episode(episode_id) => {
        // To save an episode, you save the show.
        // First, get the episode to find the show ID
        match self.spotify.get_an_episode(episode_id, None).await {
          Ok(episode) => {
            let show_id = episode.show.id;
            match self
              .spotify
              .check_users_saved_shows([show_id.clone()])
              .await
            {
              Ok(saved) => {
                if saved.first() == Some(&true) {
                  match self
                    .spotify
                    .remove_users_saved_shows([show_id.clone()], None)
                    .await
                  {
                    Ok(()) => {
                      let mut app = self.app.lock().await;
                      app.saved_show_ids_set.remove(show_id.id());
                    }
                    Err(e) => {
                      self.handle_error(anyhow!(e)).await;
                    }
                  }
                } else {
                  match self.spotify.save_shows([show_id.clone()]).await {
                    Ok(()) => {
                      let mut app = self.app.lock().await;
                      app.saved_show_ids_set.insert(show_id.id().to_string());
                    }
                    Err(e) => {
                      self.handle_error(anyhow!(e)).await;
                    }
                  }
                }
              }
              Err(e) => {
                self.handle_error(anyhow!(e)).await;
              }
            }
          }
          Err(e) => {
            self.handle_error(anyhow!(e)).await;
          }
        }
      }
    }
  }

  async fn get_followed_artists(&mut self, after: Option<ArtistId<'_>>) {
    // Convert after ID to string for the API call
    let mut query = vec![
      ("type", "artist".to_string()),
      ("limit", self.large_search_limit.to_string()),
    ];
    if let Some(after) = after.as_ref() {
      query.push(("after", after.id().to_string()));
    }

    match self
      .spotify_get_typed_compat::<rspotify::model::artist::CursorPageFullArtists>(
        "me/following",
        &query,
      )
      .await
    {
      Ok(saved_artists_page) => {
        let saved_artists = saved_artists_page.artists;
        let mut app = self.app.lock().await;
        app.artists = saved_artists.items.to_owned();
        app.library.saved_artists.add_pages(saved_artists);
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    };
  }

  async fn user_artist_check_follow(&mut self, artist_ids: Vec<ArtistId<'_>>) {
    let uris: Vec<String> = artist_ids
      .iter()
      .map(|id| format!("spotify:artist:{}", id.id()))
      .collect();
    if let Ok(are_followed) = self.library_contains_uris(&uris).await {
      let mut app = self.app.lock().await;
      artist_ids
        .iter()
        .zip(are_followed.iter())
        .for_each(|(id, &is_followed)| {
          if is_followed {
            app.followed_artist_ids_set.insert(id.id().to_string());
          } else {
            app.followed_artist_ids_set.remove(id.id());
          }
        });
    }
  }

  async fn get_current_user_saved_albums(&mut self, offset: Option<u32>) {
    let mut query = vec![("limit", self.large_search_limit.to_string())];
    if let Some(offset) = offset {
      query.push(("offset", offset.to_string()));
    }

    match self
      .spotify_get_typed_compat::<Page<rspotify::model::SavedAlbum>>("me/albums", &query)
      .await
    {
      Ok(saved_albums) => {
        // not to show a blank page
        if !saved_albums.items.is_empty() {
          let mut app = self.app.lock().await;
          app.library.saved_albums.add_pages(saved_albums);
        }
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    };
  }

  async fn current_user_saved_albums_contains(&mut self, album_ids: Vec<AlbumId<'_>>) {
    let uris: Vec<String> = album_ids
      .iter()
      .map(|id| format!("spotify:album:{}", id.id()))
      .collect();
    if let Ok(are_followed) = self.library_contains_uris(&uris).await {
      let mut app = self.app.lock().await;
      album_ids
        .iter()
        .zip(are_followed.iter())
        .for_each(|(id, &is_followed)| {
          if is_followed {
            app.saved_album_ids_set.insert(id.id().to_string());
          } else {
            app.saved_album_ids_set.remove(id.id());
          }
        });
    }
  }

  pub async fn current_user_saved_album_delete(&mut self, album_id: AlbumId<'_>) {
    let uri = format!("spotify:album:{}", album_id.id());
    match self.library_remove_uris(std::slice::from_ref(&uri)).await {
      Ok(_) => {
        self.get_current_user_saved_albums(None).await;
        let mut app = self.app.lock().await;
        app.saved_album_ids_set.remove(album_id.id());
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    };
  }

  async fn current_user_saved_album_add(&mut self, album_id: AlbumId<'_>) {
    let uri = format!("spotify:album:{}", album_id.id());
    match self.library_save_uris(std::slice::from_ref(&uri)).await {
      Ok(_) => {
        let mut app = self.app.lock().await;
        app.saved_album_ids_set.insert(album_id.id().to_string());
      }
      Err(e) => self.handle_error(anyhow!(e)).await,
    }
  }

  async fn current_user_saved_shows_delete(&mut self, show_id: ShowId<'_>) {
    let uri = format!("spotify:show:{}", show_id.id());
    match self.library_remove_uris(std::slice::from_ref(&uri)).await {
      Ok(_) => {
        self.get_current_user_saved_shows(None).await;
        let mut app = self.app.lock().await;
        app.saved_show_ids_set.remove(show_id.id());
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn current_user_saved_shows_add(&mut self, show_id: ShowId<'_>) {
    let uri = format!("spotify:show:{}", show_id.id());
    match self.library_save_uris(std::slice::from_ref(&uri)).await {
      Ok(_) => {
        self.get_current_user_saved_shows(None).await;
        let mut app = self.app.lock().await;
        app.saved_show_ids_set.insert(show_id.id().to_string());
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn user_unfollow_artists(&mut self, artist_ids: Vec<ArtistId<'_>>) {
    let uris: Vec<String> = artist_ids
      .iter()
      .map(|id| format!("spotify:artist:{}", id.id()))
      .collect();
    match self.library_remove_uris(&uris).await {
      Ok(_) => {
        self.get_followed_artists(None).await;
        let mut app = self.app.lock().await;
        artist_ids.iter().for_each(|id| {
          app.followed_artist_ids_set.remove(id.id());
        });
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn user_follow_artists(&mut self, artist_ids: Vec<ArtistId<'_>>) {
    let uris: Vec<String> = artist_ids
      .iter()
      .map(|id| format!("spotify:artist:{}", id.id()))
      .collect();
    match self.library_save_uris(&uris).await {
      Ok(_) => {
        self.get_followed_artists(None).await;
        let mut app = self.app.lock().await;
        artist_ids.iter().for_each(|id| {
          app.followed_artist_ids_set.insert(id.id().to_string());
        });
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn user_follow_playlist(
    &mut self,
    _playlist_owner_id: UserId<'_>,
    playlist_id: PlaylistId<'_>,
    is_public: Option<bool>,
  ) {
    let _ = is_public;
    let uri = format!("spotify:playlist:{}", playlist_id.id());
    match self.library_save_uris(std::slice::from_ref(&uri)).await {
      Ok(_) => {
        self.get_current_user_playlists().await;
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn user_unfollow_playlist(&mut self, _user_id: UserId<'_>, playlist_id: PlaylistId<'_>) {
    let uri = format!("spotify:playlist:{}", playlist_id.id());
    match self.library_remove_uris(std::slice::from_ref(&uri)).await {
      Ok(_) => {
        self.get_current_user_playlists().await;
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn get_current_user_playlists(&mut self) {
    // Step 1: Fetch ONLY the first page (single API call, fast)
    let first_query = vec![("limit", self.large_search_limit.to_string())];
    let first_page = match self
      .spotify_get_typed_compat::<Page<rspotify::model::playlist::SimplifiedPlaylist>>(
        "me/playlists",
        &first_query,
      )
      .await
    {
      Ok(p) => p,
      Err(e) => {
        let err = anyhow!(e);
        if Self::is_rate_limited_error(&err) {
          self
            .show_status_message(
              "Spotify rate limit hit while loading playlists. Will retry on next refresh."
                .to_string(),
              6,
            )
            .await;
          return;
        }
        self.handle_error(err).await;
        return;
      }
    };

    let total = first_page.total;
    let first_page_count = first_page.items.len() as u32;
    let first_page_items = first_page.items.clone();

    let (refresh_generation, preferred_playlist_id, preferred_folder_id, preferred_selected_index) = {
      let mut app = self.app.lock().await;
      let preferred_playlist_id = app.get_selected_playlist_id();
      let preferred_folder_id = app.current_playlist_folder_id;
      let preferred_selected_index = app.selected_playlist_index;
      app.playlist_refresh_generation = app.playlist_refresh_generation.saturating_add(1);
      (
        app.playlist_refresh_generation,
        preferred_playlist_id,
        preferred_folder_id,
        preferred_selected_index,
      )
    };

    // Step 2: Immediately populate app state with first page (flat list, no folders yet)
    {
      let mut app = self.app.lock().await;
      app.all_playlists = first_page_items.clone();
      app.playlists = Some(first_page);
      app.playlist_folder_nodes = None;
      app.playlist_folder_items = build_flat_playlist_items(&app.all_playlists);
      reconcile_playlist_selection(
        &mut app,
        preferred_playlist_id.as_deref(),
        preferred_folder_id,
        preferred_selected_index,
      );
    }

    // Step 3: Spawn background task to fetch remaining pages + rootlist folders
    let spotify = self.spotify.clone();
    let app = self.app.clone();
    let limit = self.large_search_limit;
    #[cfg(feature = "streaming")]
    {
      let streaming_player = self.streaming_player.clone();
      tokio::spawn(async move {
        Self::fetch_remaining_playlists_and_folders_task(
          spotify,
          app,
          limit,
          first_page_count,
          total,
          first_page_items,
          refresh_generation,
          preferred_playlist_id,
          preferred_folder_id,
          preferred_selected_index,
          streaming_player,
        )
        .await;
      });
    }
    #[cfg(not(feature = "streaming"))]
    {
      tokio::spawn(async move {
        Self::fetch_remaining_playlists_and_folders_task(
          spotify,
          app,
          limit,
          first_page_count,
          total,
          first_page_items,
          refresh_generation,
          preferred_playlist_id,
          preferred_folder_id,
          preferred_selected_index,
        )
        .await;
      });
    }
  }

  /// Background task: fetch remaining playlist pages and rootlist folders,
  /// then update app state with the complete folder hierarchy.
  async fn fetch_remaining_playlists_and_folders_task(
    spotify: AuthCodePkceSpotify,
    app: Arc<Mutex<App>>,
    limit: u32,
    first_page_count: u32,
    total: u32,
    mut all_playlists: Vec<rspotify::model::playlist::SimplifiedPlaylist>,
    refresh_generation: u64,
    preferred_playlist_id: Option<String>,
    preferred_folder_id: usize,
    preferred_selected_index: Option<usize>,
    #[cfg(feature = "streaming")] streaming_player: Option<Arc<StreamingPlayer>>,
  ) {
    let max_playlists: u32 = 10_000;

    // Streaming: spawn remaining pages fetch concurrently, await rootlist first
    // for early folder display, then collect remaining pages.
    #[cfg(feature = "streaming")]
    let (remaining_playlists, had_playlist_error, folder_nodes) = {
      // Spawn remaining playlist pages as a concurrent background task
      let remaining_handle = tokio::spawn(async move {
        let mut remaining = Vec::new();
        let mut offset = first_page_count;
        let mut had_error = false;
        while offset < total && offset < max_playlists {
          let query = vec![("limit", limit.to_string()), ("offset", offset.to_string())];
          match Self::spotify_get_typed_compat_for::<
            Page<rspotify::model::playlist::SimplifiedPlaylist>,
          >(&spotify, "me/playlists", &query)
          .await
          {
            Ok(page) => {
              let items_count = page.items.len() as u32;
              remaining.extend(page.items);
              if items_count < limit {
                break;
              }
              offset += items_count;
            }
            Err(e) => {
              had_error = true;
              eprintln!("Failed to fetch playlist page at offset {}: {}", offset, e);
              break;
            }
          }
          tokio::task::yield_now().await;
        }
        (remaining, had_error)
      });

      // Fetch rootlist folders (typically fast — single API call).
      // Runs concurrently with the remaining pages task spawned above.
      let folder_nodes = fetch_rootlist_folders(&streaming_player).await;

      // Intermediate update: apply folder structure to first-page playlists
      // immediately so users can see and navigate folders before all pages load.
      if folder_nodes.is_some() {
        let mut app_guard = app.lock().await;
        if app_guard.playlist_refresh_generation == refresh_generation {
          let folder_items = if let Some(ref nodes) = folder_nodes {
            structurize_playlist_folders(nodes, &app_guard.all_playlists)
          } else {
            build_flat_playlist_items(&app_guard.all_playlists)
          };
          app_guard.playlist_folder_nodes = folder_nodes.clone();
          app_guard.playlist_folder_items = folder_items;
          reconcile_playlist_selection(
            &mut app_guard,
            preferred_playlist_id.as_deref(),
            preferred_folder_id,
            preferred_selected_index,
          );
        }
      }

      // Wait for remaining playlist pages to finish
      let (remaining, had_error) = match remaining_handle.await {
        Ok(result) => result,
        Err(_) => (Vec::new(), true),
      };

      (remaining, had_error, folder_nodes)
    };

    // Non-streaming: no folder structure available, just fetch remaining pages
    #[cfg(not(feature = "streaming"))]
    let (remaining_playlists, had_playlist_error, folder_nodes) = {
      let mut remaining = Vec::new();
      let mut offset = first_page_count;
      let mut had_error = false;
      while offset < total && offset < max_playlists {
        let query = vec![("limit", limit.to_string()), ("offset", offset.to_string())];
        match Self::spotify_get_typed_compat_for::<
          Page<rspotify::model::playlist::SimplifiedPlaylist>,
        >(&spotify, "me/playlists", &query)
        .await
        {
          Ok(page) => {
            let items_count = page.items.len() as u32;
            remaining.extend(page.items);
            if items_count < limit {
              break;
            }
            offset += items_count;
          }
          Err(e) => {
            had_error = true;
            eprintln!("Failed to fetch playlist page at offset {}: {}", offset, e);
            break;
          }
        }
        tokio::task::yield_now().await;
      }
      let folder_nodes: Option<Vec<PlaylistFolderNode>> = None;
      (remaining, had_error, folder_nodes)
    };

    all_playlists.extend(remaining_playlists);

    // Update app state with complete data
    let mut app = app.lock().await;
    if app.playlist_refresh_generation != refresh_generation {
      return;
    }

    app.all_playlists = all_playlists;
    let first_items: Vec<_> = app
      .all_playlists
      .iter()
      .take(limit as usize)
      .cloned()
      .collect();
    let total_items = app.all_playlists.len() as u32;
    if let Some(playlists) = app.playlists.as_mut() {
      playlists.items = first_items;
      playlists.total = total_items;
      playlists.offset = 0;
      playlists.next = None;
      playlists.previous = None;
    }

    let folder_items = if let Some(ref nodes) = folder_nodes {
      structurize_playlist_folders(nodes, &app.all_playlists)
    } else {
      build_flat_playlist_items(&app.all_playlists)
    };

    app.playlist_folder_nodes = folder_nodes;
    app.playlist_folder_items = folder_items;

    reconcile_playlist_selection(
      &mut app,
      preferred_playlist_id.as_deref(),
      preferred_folder_id,
      preferred_selected_index,
    );

    if had_playlist_error {
      app.status_message = Some("Playlists partially loaded (network error)".to_string());
      app.status_message_expires_at = Some(Instant::now() + Duration::from_secs(4));
    }
  }

  async fn get_recently_played(&mut self) {
    let query = vec![("limit", self.large_search_limit.to_string())];
    match self
      .spotify_get_typed_compat::<rspotify::model::CursorBasedPage<rspotify::model::PlayHistory>>(
        "me/player/recently-played",
        &query,
      )
      .await
    {
      Ok(result) => {
        let track_ids = result
          .items
          .iter()
          .filter_map(|item| {
            item
              .track
              .id
              .as_ref()
              .map(|id| TrackId::from_id(id.id()).unwrap().into_static())
          })
          .collect::<Vec<TrackId<'static>>>();

        self.current_user_saved_tracks_contains(track_ids).await;

        let mut app = self.app.lock().await;

        app.recently_played.result = Some(result.clone());
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn get_album(&mut self, album_id: AlbumId<'_>) {
    match self.spotify.album(album_id, None).await {
      Ok(album) => {
        let selected_album = SelectedFullAlbum {
          album,
          selected_index: 0,
        };

        let mut app = self.app.lock().await;

        app.selected_album_full = Some(selected_album);
        app.album_table_context = AlbumTableContext::Full;
        app.push_navigation_stack(RouteId::AlbumTracks, ActiveBlock::AlbumTracks);
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn get_album_for_track(&mut self, track_id: TrackId<'_>) {
    match self.spotify.track(track_id, None).await {
      Ok(track) => {
        // It is unclear when the id can ever be None, but perhaps a track can be album-less. If
        // so, there isn't much to do here anyways, since we're looking for the parent album.
        let album_id = match track.album.id {
          Some(id) => id,
          None => return,
        };

        if let Ok(album) = self.spotify.album(album_id, None).await {
          // The way we map to the UI is zero-indexed, but Spotify is 1-indexed.
          let zero_indexed_track_number = track.track_number - 1;
          let selected_album = SelectedFullAlbum {
            album,
            // Overflow should be essentially impossible here, so we prefer the cleaner 'as'.
            selected_index: zero_indexed_track_number as usize,
          };

          let mut app = self.app.lock().await;

          app.selected_album_full = Some(selected_album.clone());
          app.saved_album_tracks_index = selected_album.selected_index;
          app.album_table_context = AlbumTableContext::Full;
          app.push_navigation_stack(RouteId::AlbumTracks, ActiveBlock::AlbumTracks);
        }
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  async fn transfert_playback_to_device(&mut self, device_id: String, persist_device_id: bool) {
    // Check if we're selecting the native streaming device
    // Native streaming uses Spirc (Spotify Connect) which doesn't work with the Web API's transfer_playback
    #[cfg(feature = "streaming")]
    {
      let is_native_device = if let Some(ref player) = self.streaming_player {
        // Get the device name from the streaming player
        let native_name = player.device_name().to_lowercase();
        let app = self.app.lock().await;
        let matches_cached_device = app.devices.as_ref().is_some_and(|payload| {
          payload
            .devices
            .iter()
            .any(|d| d.id.as_ref() == Some(&device_id) && d.name.to_lowercase() == native_name)
        });
        matches_cached_device || app.native_device_id.as_ref() == Some(&device_id)
      } else {
        false
      };

      if is_native_device {
        // For native streaming device, use Spirc activation instead of Web API
        // The Web API returns 404 for native streaming devices because they use
        // a different OAuth session (librespot-oauth)
        if let Some(ref player) = self.streaming_player {
          let activation_time = Instant::now();
          let should_transfer = {
            let app = self.app.lock().await;
            let recent_activation = app
              .last_device_activation
              .is_some_and(|instant| instant.elapsed() < Duration::from_secs(5));
            !app.native_activation_pending && !app.is_streaming_active && !recent_activation
          };

          {
            let mut app = self.app.lock().await;
            app.is_streaming_active = true;
            app.native_device_id = Some(device_id.clone());
            app.last_device_activation = Some(activation_time);
            app.native_activation_pending = true;
            app.instant_since_last_current_playback_poll = activation_time - Duration::from_secs(6);
          }

          let player = Arc::clone(player);
          let app = Arc::clone(&self.app);
          let device_id_for_task = device_id.clone();
          tokio::spawn(async move {
            if should_transfer {
              let _ = player.transfer(None);
            }

            player.activate();

            let mut app = app.lock().await;
            app.is_streaming_active = true;
            app.native_device_id = Some(device_id_for_task);
            app.last_device_activation = Some(activation_time);
            app.native_activation_pending = false;
            app.instant_since_last_current_playback_poll = activation_time - Duration::from_secs(6);
          });

          if persist_device_id {
            // Save device ID and pop navigation
            match self.client_config.set_device_id(device_id) {
              Ok(()) => {
                let mut app = self.app.lock().await;
                app.pop_navigation_stack();
              }
              Err(e) => {
                self.handle_error(e).await;
              }
            };
          } else {
            let mut app = self.app.lock().await;
            app.pop_navigation_stack();
          }
          return;
        }
      }
    }

    // Standard path for external devices (spotifyd, phone, etc.)
    match self.spotify.transfer_playback(&device_id, Some(true)).await {
      Ok(()) => {
        // We're explicitly selecting an external device, so immediately switch the UI/state
        // out of native streaming mode (the next playback poll will confirm).
        #[cfg(feature = "streaming")]
        {
          let mut app = self.app.lock().await;
          app.is_streaming_active = false;
          app.native_device_id = None;
          app.last_device_activation = None;
          app.native_activation_pending = false;
        }
        self.get_current_playback().await;
      }
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
        return;
      }
    };

    if persist_device_id {
      match self.client_config.set_device_id(device_id) {
        Ok(()) => {
          let mut app = self.app.lock().await;
          app.pop_navigation_stack();
        }
        Err(e) => {
          self.handle_error(e).await;
        }
      };
    } else {
      let mut app = self.app.lock().await;
      app.pop_navigation_stack();
    }
  }

  /// Auto-select a streaming device by name (used for native spotatui streaming)
  /// This will retry a few times since the device may take a moment to appear in Spotify's device list
  #[cfg(feature = "streaming")]
  async fn auto_select_streaming_device(&mut self, device_name: String, persist_device_id: bool) {
    // For native streaming, we use Spirc activation directly instead of the Web API's transfer_playback
    // The Web API returns 404 for native streaming devices because they use
    // a different OAuth session (librespot-oauth)

    // Wait a moment for the streaming player to fully register with Spotify Connect
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // Activate the native streaming device via Spirc
    if let Some(ref player) = self.streaming_player {
      let activation_time = Instant::now();
      let should_transfer = {
        let app = self.app.lock().await;
        let recent_activation = app
          .last_device_activation
          .is_some_and(|instant| instant.elapsed() < Duration::from_secs(5));
        !app.native_activation_pending && !app.is_streaming_active && !recent_activation
      };

      {
        let mut app = self.app.lock().await;
        app.is_streaming_active = true;
        app.native_activation_pending = true;
        app.last_device_activation = Some(activation_time);
        app.instant_since_last_current_playback_poll = activation_time - Duration::from_secs(6);
      }

      let player = Arc::clone(player);
      let app = Arc::clone(&self.app);
      tokio::spawn(async move {
        if should_transfer {
          let _ = player.transfer(None);
        }

        player.activate();

        let mut app = app.lock().await;
        app.is_streaming_active = true;
        app.native_activation_pending = false;
        app.last_device_activation = Some(activation_time);
        app.instant_since_last_current_playback_poll = activation_time - Duration::from_secs(6);
      });

      // Now try to get the device_id from Spotify's device list and save it
      // Retry a few times since the device may take a moment to appear
      for attempt in 0..2 {
        if attempt > 0 {
          tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        }

        match self.spotify.device().await {
          Ok(devices) => {
            // Find the device by name (case-insensitive)
            if let Some(device) = devices
              .iter()
              .find(|d| d.name.to_lowercase() == device_name.to_lowercase())
            {
              if let Some(device_id) = &device.id {
                if persist_device_id {
                  // Save device ID to config (don't use transfer_playback - just save the ID)
                  let _ = self.client_config.set_device_id(device_id.clone());
                }
                let mut app = self.app.lock().await;
                app.native_device_id = Some(device_id.clone());
                return;
              }
            }
          }
          Err(_) => {
            // Failed to get devices, will retry
            continue;
          }
        }
      }
    }
    // Silently fail after retries - user can still manually select device with 'd'
  }

  async fn refresh_authentication(&mut self) {
    // The new rspotify client handles token refreshing automatically.
    // This function is now a no-op.
  }

  async fn add_item_to_queue(&mut self, item: PlayableId<'_>) {
    match self.spotify.add_item_to_queue(item, None).await {
      Ok(()) => (),
      Err(e) => {
        self.handle_error(anyhow!(e)).await;
      }
    }
  }

  #[cfg(feature = "telemetry")]
  async fn increment_global_song_count(&self) {
    self.update_global_song_count(reqwest::Method::POST).await;
  }

  #[cfg(feature = "telemetry")]
  async fn fetch_global_song_count(&self) {
    self.update_global_song_count(reqwest::Method::GET).await;
  }

  #[cfg(feature = "telemetry")]
  async fn update_global_song_count(&self, method: reqwest::Method) {
    const TELEMETRY_ENDPOINT: &str = "https://spotatui-counter.spotatui.workers.dev";

    let app = Arc::clone(&self.app);

    // Fire-and-forget to avoid blocking other network events
    tokio::spawn(async move {
      let client = match reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(5))
        .build()
      {
        Ok(client) => client,
        Err(_) => {
          let mut app = app.lock().await;
          app.global_song_count_failed = true;
          return;
        }
      };

      let response = client
        .request(method, TELEMETRY_ENDPOINT)
        .header(reqwest::header::ACCEPT, "application/json")
        .send()
        .await;

      let parsed_response = match response {
        Ok(resp) => resp.json::<GlobalSongCountResponse>().await,
        Err(e) => Err(e),
      };

      match parsed_response {
        Ok(data) => {
          let mut app = app.lock().await;
          app.global_song_count = Some(data.count);
          app.global_song_count_failed = false;
        }
        Err(_) => {
          let mut app = app.lock().await;
          app.global_song_count_failed = true;
        }
      }
    });
  }

  #[cfg(not(feature = "telemetry"))]
  async fn increment_global_song_count(&self) {
    // No-op when telemetry feature is disabled
  }

  #[cfg(not(feature = "telemetry"))]
  async fn fetch_global_song_count(&self) {
    // No-op when telemetry feature is disabled
  }

  async fn get_lyrics(&mut self, track_name: String, artist_name: String, duration_sec: f64) {
    use crate::app::LyricsStatus;

    // Set loading state
    {
      let mut app = self.app.lock().await;
      app.lyrics_status = LyricsStatus::Loading;
      app.lyrics = None;
    }

    let client = reqwest::Client::new();
    let params = [
      ("artist_name", artist_name),
      ("track_name", track_name),
      ("duration", duration_sec.to_string()),
    ];

    match client
      .get("https://lrclib.net/api/get")
      .query(&params)
      .send()
      .await
    {
      Ok(resp) => {
        if let Ok(lrc_resp) = resp.json::<LrcResponse>().await {
          if let Some(synced) = lrc_resp.syncedLyrics {
            let parsed = self.parse_lrc(&synced);
            let mut app = self.app.lock().await;
            app.lyrics = Some(parsed);
            app.lyrics_status = LyricsStatus::Found;
          } else if let Some(plain) = lrc_resp.plainLyrics {
            let mut app = self.app.lock().await;
            app.lyrics = Some(vec![(0, plain)]);
            app.lyrics_status = LyricsStatus::Found;
          } else {
            let mut app = self.app.lock().await;
            app.lyrics_status = LyricsStatus::NotFound;
          }
        } else {
          let mut app = self.app.lock().await;
          app.lyrics_status = LyricsStatus::NotFound;
        }
      }
      Err(_) => {
        let mut app = self.app.lock().await;
        app.lyrics_status = LyricsStatus::NotFound;
      }
    }
  }

  fn parse_lrc(&self, lrc: &str) -> Vec<(u128, String)> {
    let mut lyrics = Vec::new();
    for line in lrc.lines() {
      if let Some(idx) = line.find(']') {
        if line.starts_with('[') && idx < line.len() {
          let time_part = &line[1..idx];
          let text_part = line[idx + 1..].trim().to_string();
          if let Some(time) = self.parse_time_ms(time_part) {
            lyrics.push((time, text_part));
          }
        }
      }
    }
    lyrics
  }

  fn parse_time_ms(&self, time_str: &str) -> Option<u128> {
    // mm:ss.xx
    let parts: Vec<&str> = time_str.split(':').collect();
    if parts.len() != 2 {
      return None;
    }
    let min: u128 = parts[0].parse().ok()?;

    let sec_parts: Vec<&str> = parts[1].split('.').collect();
    if sec_parts.len() != 2 {
      return None;
    }

    let sec: u128 = sec_parts[0].parse().ok()?;
    let ms_part = sec_parts[1];
    let ms: u128 = ms_part.parse().ok()?;

    // Detect if ms is 2 digits (centiseconds) or 3 digits
    let ms_val = if ms_part.len() == 2 { ms * 10 } else { ms };

    Some(min * 60000 + sec * 1000 + ms_val)
  }

  /// Fetch user's top tracks for the Discover feature
  async fn get_user_top_tracks(&mut self, time_range: crate::app::DiscoverTimeRange) {
    use crate::app::DiscoverTimeRange;
    use rspotify::model::TimeRange;

    let spotify_time_range = match time_range {
      DiscoverTimeRange::Short => TimeRange::ShortTerm,
      DiscoverTimeRange::Medium => TimeRange::MediumTerm,
      DiscoverTimeRange::Long => TimeRange::LongTerm,
    };

    let spotify_time_range_param = match spotify_time_range {
      TimeRange::ShortTerm => "short_term",
      TimeRange::MediumTerm => "medium_term",
      TimeRange::LongTerm => "long_term",
    };

    {
      let mut app = self.app.lock().await;
      app.discover_loading = true;
    }

    let query = vec![
      ("time_range", spotify_time_range_param.to_string()),
      ("limit", "50".to_string()),
      ("offset", "0".to_string()),
    ];

    let tracks = match self
      .spotify_get_typed_compat::<Page<FullTrack>>("me/top/tracks", &query)
      .await
    {
      Ok(page) => page.items,
      Err(e) => {
        let err = anyhow!(e);
        if Self::is_rate_limited_error(&err) {
          self
            .show_status_message(
              "Spotify rate limit hit while loading top tracks. Try again in a few seconds."
                .to_string(),
              6,
            )
            .await;
        } else {
          self.handle_error(err).await;
        }
        let mut app = self.app.lock().await;
        app.discover_loading = false;
        return;
      }
    };

    let mut app = self.app.lock().await;
    app.discover_top_tracks = tracks.clone();
    app.discover_loading = false;

    // Automatically switch to track table to show results
    app.track_table.tracks = tracks;
    app.track_table.context = Some(crate::app::TrackTableContext::DiscoverPlaylist);
    app.track_table.selected_index = 0;
    app.push_navigation_stack(
      crate::app::RouteId::TrackTable,
      crate::app::ActiveBlock::TrackTable,
    );
  }

  /// Fetch Top Artists Mix - fetches top artists and then their top tracks to create a mix
  async fn get_top_artists_mix(&mut self) {
    use rand::seq::SliceRandom;

    {
      let mut app = self.app.lock().await;
      app.discover_loading = true;
    }

    let artist_query = vec![
      ("time_range", "medium_term".to_string()),
      ("limit", "5".to_string()),
      ("offset", "0".to_string()),
    ];
    let artists = match self
      .spotify_get_typed_compat::<Page<FullArtist>>("me/top/artists", &artist_query)
      .await
    {
      Ok(page) => page.items,
      Err(e) => {
        let err = anyhow!(e);
        if Self::is_rate_limited_error(&err) {
          self
            .show_status_message(
              "Spotify rate limit hit while loading top artists. Try again in a few seconds."
                .to_string(),
              6,
            )
            .await;
        } else {
          self.handle_error(err).await;
        }
        let mut app = self.app.lock().await;
        app.discover_loading = false;
        return;
      }
    };

    let seed_artists = artists
      .iter()
      .take(5)
      .map(|artist| artist.id.clone())
      .map(|id| id.into_static())
      .collect::<Vec<ArtistId<'static>>>();

    let mut all_tracks = if seed_artists.is_empty() {
      Vec::new()
    } else {
      let seed_genres: Option<Vec<&str>> = None;
      let seed_tracks: Option<Vec<TrackId<'static>>> = None;
      match self
        .spotify
        .recommendations(
          [],
          Some(seed_artists),
          seed_genres,
          seed_tracks,
          None,
          Some(10),
        )
        .await
      {
        Ok(result) => self
          .extract_recommended_tracks(&result)
          .await
          .unwrap_or_default(),
        Err(_) => Vec::new(),
      }
    };

    if all_tracks.is_empty() {
      let fallback_query = vec![
        ("time_range", "medium_term".to_string()),
        ("limit", "50".to_string()),
        ("offset", "0".to_string()),
      ];
      all_tracks = self
        .spotify_get_typed_compat::<Page<FullTrack>>("me/top/tracks", &fallback_query)
        .await
        .map(|page| page.items)
        .unwrap_or_default();
    }

    // Shuffle the mix
    {
      let mut rng = rand::thread_rng();
      all_tracks.shuffle(&mut rng);
    }

    let mut app = self.app.lock().await;
    app.discover_artists_mix = all_tracks.clone();
    app.discover_loading = false;

    // Automatically switch to track table to show results
    app.track_table.tracks = all_tracks;
    app.track_table.context = Some(crate::app::TrackTableContext::DiscoverPlaylist);
    app.track_table.selected_index = 0;
    app.push_navigation_stack(
      crate::app::RouteId::TrackTable,
      crate::app::ActiveBlock::TrackTable,
    );
  }
}

/// Fetch folder hierarchy from Spotify's rootlist API (streaming feature only).
/// Standalone function usable from spawned background tasks.
/// Returns parsed folder nodes, or None if unavailable.
#[cfg(feature = "streaming")]
async fn fetch_rootlist_folders(
  streaming_player: &Option<Arc<StreamingPlayer>>,
) -> Option<Vec<PlaylistFolderNode>> {
  let player = streaming_player.as_ref()?;
  let session = player.session();

  // Request the full rootlist
  let bytes = match session.spclient().get_rootlist(0, Some(100_000)).await {
    Ok(b) => b,
    Err(e) => {
      eprintln!("Failed to fetch rootlist: {}", e);
      return None;
    }
  };

  // Parse the protobuf response
  use protobuf::Message;
  let selected: librespot_protocol::playlist4_external::SelectedListContent =
    match Message::parse_from_bytes(&bytes) {
      Ok(s) => s,
      Err(e) => {
        eprintln!("Failed to parse rootlist protobuf: {}", e);
        return None;
      }
    };

  let contents = selected.contents.as_ref()?;
  let items = &contents.items;

  // Parse URIs into folder tree using start-group/end-group markers
  Some(parse_rootlist_items(items))
}

fn build_flat_playlist_items(
  playlists: &[rspotify::model::playlist::SimplifiedPlaylist],
) -> Vec<PlaylistFolderItem> {
  playlists
    .iter()
    .enumerate()
    .map(|(idx, _)| PlaylistFolderItem::Playlist {
      index: idx,
      current_id: 0,
    })
    .collect()
}

fn reconcile_playlist_selection(
  app: &mut App,
  preferred_playlist_id: Option<&str>,
  preferred_folder_id: usize,
  preferred_selected_index: Option<usize>,
) {
  if app.playlist_folder_items.is_empty() {
    app.current_playlist_folder_id = 0;
    app.selected_playlist_index = None;
    return;
  }

  let folder_has_visible = |folder_id: usize, app: &App| {
    app.playlist_folder_items.iter().any(|item| match item {
      PlaylistFolderItem::Folder(folder) => folder.current_id == folder_id,
      PlaylistFolderItem::Playlist { current_id, .. } => *current_id == folder_id,
    })
  };

  app.current_playlist_folder_id = if folder_has_visible(preferred_folder_id, app) {
    preferred_folder_id
  } else {
    0
  };

  if let Some(playlist_id) = preferred_playlist_id {
    let visible_playlist_index = app
      .playlist_folder_items
      .iter()
      .filter(|item| app.is_playlist_item_visible_in_current_folder(item))
      .enumerate()
      .find_map(|(display_idx, item)| match item {
        PlaylistFolderItem::Playlist { index, .. } => app
          .all_playlists
          .get(*index)
          .filter(|playlist| playlist.id.id() == playlist_id)
          .map(|_| display_idx),
        PlaylistFolderItem::Folder(_) => None,
      });

    if let Some(display_idx) = visible_playlist_index {
      app.selected_playlist_index = Some(display_idx);
      return;
    }

    let mut target_folder: Option<usize> = None;
    for item in &app.playlist_folder_items {
      if let PlaylistFolderItem::Playlist { index, current_id } = item {
        if let Some(playlist) = app.all_playlists.get(*index) {
          if playlist.id.id() == playlist_id {
            target_folder = Some(*current_id);
            break;
          }
        }
      }
    }

    if let Some(folder_id) = target_folder {
      app.current_playlist_folder_id = folder_id;
      let display_idx = app
        .playlist_folder_items
        .iter()
        .filter(|item| app.is_playlist_item_visible_in_current_folder(item))
        .enumerate()
        .find_map(|(idx, item)| match item {
          PlaylistFolderItem::Playlist { index, .. } => app
            .all_playlists
            .get(*index)
            .filter(|playlist| playlist.id.id() == playlist_id)
            .map(|_| idx),
          PlaylistFolderItem::Folder(_) => None,
        });
      if let Some(idx) = display_idx {
        app.selected_playlist_index = Some(idx);
        return;
      }
    }
  }

  let visible_count = app.get_playlist_display_count();
  if visible_count == 0 {
    app.current_playlist_folder_id = 0;
    let root_count = app.get_playlist_display_count();
    app.selected_playlist_index = if root_count == 0 {
      None
    } else {
      Some(preferred_selected_index.unwrap_or(0).min(root_count - 1))
    };
    return;
  }

  app.selected_playlist_index = Some(preferred_selected_index.unwrap_or(0).min(visible_count - 1));
}

/// Parse rootlist item URIs into a tree of PlaylistFolderNodes.
/// URIs follow the pattern:
/// - `spotify:playlist:ID` — a playlist
/// - `spotify:start-group:GROUPID:FolderName` — start of a folder
/// - `spotify:end-group:GROUPID` — end of a folder
#[cfg(feature = "streaming")]
fn parse_rootlist_items(
  items: &[librespot_protocol::playlist4_external::Item],
) -> Vec<PlaylistFolderNode> {
  let mut root: Vec<PlaylistFolderNode> = Vec::new();
  let mut stack: Vec<Vec<PlaylistFolderNode>> = Vec::new();
  let mut name_stack: Vec<(String, String)> = Vec::new(); // (group_id, name)

  for item in items {
    let uri = item.uri();

    if let Some(rest) = uri.strip_prefix("spotify:start-group:") {
      // Format: GROUPID:FolderName (group ID and name separated by first colon)
      let (group_id, name) = match rest.find(':') {
        Some(pos) => (rest[..pos].to_string(), rest[pos + 1..].to_string()),
        None => (rest.to_string(), String::new()),
      };
      name_stack.push((group_id, name.clone()));
      stack.push(std::mem::take(&mut root));
      root = Vec::new();
    } else if uri.starts_with("spotify:end-group:") {
      // Pop the folder — wrap accumulated children into a folder node
      if let Some((group_id, name)) = name_stack.pop() {
        let children = std::mem::take(&mut root);
        root = stack.pop().unwrap_or_default();
        root.push(PlaylistFolderNode {
          name: Some(name),
          node_type: PlaylistFolderNodeType::Folder,
          uri: format!("spotify:folder:{}", group_id),
          children,
        });
      }
    } else {
      // Regular item (playlist, etc.)
      root.push(PlaylistFolderNode {
        name: None,
        node_type: PlaylistFolderNodeType::Playlist,
        uri: uri.to_string(),
        children: Vec::new(),
      });
    }
  }

  while let Some((group_id, name)) = name_stack.pop() {
    let children = std::mem::take(&mut root);
    root = stack.pop().unwrap_or_default();
    root.push(PlaylistFolderNode {
      name: Some(name),
      node_type: PlaylistFolderNodeType::Folder,
      uri: format!("spotify:folder:{}", group_id),
      children,
    });
  }

  root
}

/// Convert folder node tree + flat playlist list into a flat vector of PlaylistFolderItems
/// suitable for UI navigation. Each folder creates a "forward" entry (in parent folder)
/// and a "back" entry (inside the folder, pointing back to parent).
fn structurize_playlist_folders(
  nodes: &[PlaylistFolderNode],
  playlists: &[rspotify::model::playlist::SimplifiedPlaylist],
) -> Vec<PlaylistFolderItem> {
  use std::collections::HashMap;

  // Build a map of playlist ID -> index in the playlists vec
  let playlist_map: HashMap<String, usize> = playlists
    .iter()
    .enumerate()
    .map(|(idx, p)| (p.id.id().to_string(), idx))
    .collect();

  let mut items: Vec<PlaylistFolderItem> = Vec::new();
  let mut next_folder_id: usize = 1; // 0 is root
  let mut used_playlist_indices: std::collections::HashSet<usize> =
    std::collections::HashSet::new();

  fn walk(
    nodes: &[PlaylistFolderNode],
    current_folder_id: usize,
    items: &mut Vec<PlaylistFolderItem>,
    next_folder_id: &mut usize,
    playlist_map: &HashMap<String, usize>,
    used_playlist_indices: &mut std::collections::HashSet<usize>,
  ) {
    for node in nodes {
      match node.node_type {
        PlaylistFolderNodeType::Folder => {
          let folder_id = *next_folder_id;
          *next_folder_id += 1;

          let name = node.name.as_deref().unwrap_or("Unnamed Folder").to_string();

          // Forward entry: visible in parent, navigates into folder
          items.push(PlaylistFolderItem::Folder(PlaylistFolder {
            name: name.clone(),
            current_id: current_folder_id,
            target_id: folder_id,
          }));

          // Back entry: visible inside folder, navigates back to parent
          items.push(PlaylistFolderItem::Folder(PlaylistFolder {
            name: format!("\u{2190} {}", name),
            current_id: folder_id,
            target_id: current_folder_id,
          }));

          // Recurse into children
          walk(
            &node.children,
            folder_id,
            items,
            next_folder_id,
            playlist_map,
            used_playlist_indices,
          );
        }
        PlaylistFolderNodeType::Playlist => {
          // Extract playlist ID from URI (spotify:playlist:XXXXX)
          let playlist_id = node
            .uri
            .strip_prefix("spotify:playlist:")
            .unwrap_or(&node.uri);

          if let Some(&idx) = playlist_map.get(playlist_id) {
            items.push(PlaylistFolderItem::Playlist {
              index: idx,
              current_id: current_folder_id,
            });
            used_playlist_indices.insert(idx);
          }
          // If playlist not found in API results, skip it (could be unfollowed)
        }
      }
    }
  }

  walk(
    nodes,
    0,
    &mut items,
    &mut next_folder_id,
    &playlist_map,
    &mut used_playlist_indices,
  );

  // Add any playlists not found in the folder tree (orphans) to root level
  for (idx, _) in playlists.iter().enumerate() {
    if !used_playlist_indices.contains(&idx) {
      items.push(PlaylistFolderItem::Playlist {
        index: idx,
        current_id: 0,
      });
    }
  }

  items
}