kopuz-pages 0.8.2

A modern, lightweight music player built with Rust and Dioxus.
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
use std::collections::HashMap;
use std::time::Duration;

use components::track_row::TrackRow;
use config::{AppConfig, MusicService};
use dioxus::prelude::*;
use reader::models::Track;
use server::ytmusic::discover::{DiscoverHome, DiscoverItem, DiscoverShelf, YtArtist};
use tracing::Instrument;

/// Tracks the id (playlist_id or MPRE… album browse id) that last
/// initiated playback through a Discover surface. Album and playlist
/// tiles read this to decide whether to render a play or pause icon
/// in their hover overlay, and whether the click should
/// fetch+enqueue or just toggle the player. Cleared when a
/// stand-alone song starts playing from a SongCard so we don't
/// incorrectly show "playing" on the album that previously played.
#[derive(Clone, Copy)]
pub struct DiscoverNowPlaying(pub Signal<Option<String>>);

/// Hover-prefetched track lists keyed by the id the user would click —
/// playlist_id or MPRE… browse id. Populated by Card's onmouseenter
/// handler (after a short hover delay) and consumed by
/// play_playlist_async, so when the user actually clicks Play the
/// tracks are already in memory and playback can start without
/// waiting on a browse roundtrip.
#[derive(Clone, Copy)]
pub struct DiscoverPrefetchCache(pub Signal<HashMap<String, Vec<Track>>>);

#[component]
#[tracing::instrument(name = "render.discover_home", skip_all)]
pub fn DiscoverPage(
    on_select_album: EventHandler<String>,
    on_select_playlist: EventHandler<(String, String)>,
    on_open_artist: EventHandler<(String, String)>,
    on_search_artist: EventHandler<String>,
) -> Element {
    let config = use_context::<Signal<AppConfig>>();
    let active_source = use_context::<Signal<::server::source::ActiveSource>>();
    let mut shelves = use_signal(Vec::<DiscoverShelf>::new);
    let mut continuation = use_signal(|| None::<String>);
    let mut loading_more = use_signal(|| false);
    let mut initial_loading = use_signal(|| true);
    let mut error = use_signal(|| None::<String>);

    // Discover is a capability of the active source, not a hardcoded service —
    // gate on it (and on the active source, not the configured server).
    let discover_supported = active_source.read().capabilities().discover;

    use_effect(move || {
        if !discover_supported {
            initial_loading.set(false);
            return;
        }
        if !shelves.peek().is_empty() {
            return;
        }
        let home_span = tracing::info_span!("discover.load_home");
        let signed_in = config
            .peek()
            .server
            .as_ref()
            .and_then(|s| s.access_token.as_ref())
            .is_some();
        if !signed_in {
            error.set(Some("not signed in".to_string()));
            initial_loading.set(false);
            return;
        }
        let source = active_source.peek().clone();
        spawn(
            async move {
                match source.discover_home().await {
                    Ok(home) => {
                        apply_home(home, &mut shelves, &mut continuation);
                        error.set(None);
                    }
                    Err(e) => error.set(Some(e.to_string())),
                }
                initial_loading.set(false);
            }
            .instrument(home_span),
        );
    });

    if !discover_supported {
        return rsx! {
            div { class: "flex items-center justify-center h-full text-white/60 p-12 text-center",
                p { "{i18n::t(\"discover_requires_ytmusic\")}" }
            }
        };
    }

    let load_more = move || {
        let Some(token) = continuation.peek().clone() else {
            return;
        };
        if *loading_more.peek() {
            return;
        }
        loading_more.set(true);
        let more_span = tracing::info_span!("discover.load_more");
        let source = active_source.peek().clone();
        spawn(
            async move {
                match source.discover_continuation(&token).await {
                    Ok(home) => apply_home(home, &mut shelves, &mut continuation),
                    Err(e) => error.set(Some(e.to_string())),
                }
                loading_more.set(false);
            }
            .instrument(more_span),
        );
    };

    use_effect(move || {
        let mut load_more = load_more;
        spawn(async move {
            let mut eval = document::eval(
                r#"
                const sentinel = document.getElementById('discover-sentinel');
                if (sentinel) {
                    const obs = new IntersectionObserver((entries) => {
                        for (const e of entries) {
                            if (e.isIntersecting) {
                                dioxus.send('load-more');
                            }
                        }
                    }, { rootMargin: '600px' });
                    obs.observe(sentinel);
                }
                "#,
            );
            while let Ok(v) = eval.recv::<serde_json::Value>().await {
                if v.as_str() == Some("load-more") {
                    load_more();
                }
            }
        });
    });

    rsx! {
        div { class: "p-6 md:p-10 max-w-[1600px] mx-auto",
            h1 { class: "text-3xl md:text-4xl font-black text-white mb-2", "{i18n::t(\"discover\")}" }
            div { class: "h-px bg-white/10 mb-8" }

            if *initial_loading.read() {
                div { class: "flex justify-center py-24",
                    i { class: "fa-solid fa-arrows-rotate fa-spin text-2xl text-white/60" }
                }
            } else if let Some(err) = error.read().clone() {
                div { class: "py-12 text-rose-400 text-sm",
                    "{i18n::t_with(\"discover_failed\", &[(\"error\", err.clone())])}"
                }
            }

            for (idx, shelf) in shelves.read().iter().enumerate() {
                ShelfRow {
                    key: "{idx}",
                    shelf: shelf.clone(),
                    scroll_id: format!("discover-shelf-{idx}"),
                    on_select_album: on_select_album,
                    on_select_playlist: on_select_playlist,
                    on_open_artist: on_open_artist,
                    on_search_artist: on_search_artist,
                }
            }

            div { id: "discover-sentinel", class: "h-8" }

            if *loading_more.read() {
                div { class: "flex items-center justify-center gap-3 py-6 text-white/50 text-xs",
                    i { class: "fa-solid fa-arrows-rotate fa-spin" }
                    span { "{i18n::t(\"discover_more_loading\")}" }
                }
            }
        }
    }
}

fn apply_home(
    home: DiscoverHome,
    shelves: &mut Signal<Vec<DiscoverShelf>>,
    continuation: &mut Signal<Option<String>>,
) {
    shelves.write().extend(home.shelves);
    continuation.set(home.continuation);
}

#[component]
fn ShelfRow(
    shelf: DiscoverShelf,
    scroll_id: String,
    on_select_album: EventHandler<String>,
    on_select_playlist: EventHandler<(String, String)>,
    on_open_artist: EventHandler<(String, String)>,
    on_search_artist: EventHandler<String>,
) -> Element {
    if shelf.is_song_list {
        return rsx! { SongListShelf {
            shelf: shelf.clone(),
            on_select_playlist: on_select_playlist,
        } };
    }
    let scroll_left = scroll_id.clone();
    let scroll_right = scroll_id.clone();
    rsx! {
        section { class: "mb-12",
            div { class: "flex items-end justify-between mb-5 gap-4",
                div { class: "min-w-0",
                    if let Some(strap) = shelf.strapline.clone() {
                        p { class: "text-[10px] font-bold mb-0.5 text-white/40", "{strap}" }
                    }
                    h2 { class: "text-2xl md:text-3xl font-bold text-white truncate", "{shelf.title}" }
                }
                div { class: "flex gap-2 shrink-0",
                    button {
                        class: "w-8 h-8 rounded-full bg-white/5 hover:bg-white/10 flex items-center justify-center text-white transition-all hover:scale-105 cursor-pointer",
                        onclick: move |_| {
                            let _ = document::eval(&format!(
                                "document.getElementById('{}').scrollBy({{ left: -800, behavior: 'smooth' }})",
                                scroll_left
                            ));
                        },
                        i { class: "fa-solid fa-chevron-left text-xs" }
                    }
                    button {
                        class: "w-8 h-8 rounded-full bg-white/5 hover:bg-white/10 flex items-center justify-center text-white transition-all hover:scale-105 cursor-pointer",
                        onclick: move |_| {
                            let _ = document::eval(&format!(
                                "document.getElementById('{}').scrollBy({{ left: 800, behavior: 'smooth' }})",
                                scroll_right
                            ));
                        },
                        i { class: "fa-solid fa-chevron-right text-xs" }
                    }
                }
            }
            div {
                id: "{scroll_id}",
                class: "flex items-start gap-5 pb-3 pt-1 scrollbar-hide scroll-smooth -mx-2 px-2",
                style: "overflow-x: auto; overflow-y: hidden;",
                for (idx, item) in shelf.items.iter().enumerate() {
                    DiscoverTile {
                        key: "{idx}",
                        item: item.clone(),
                        on_select_album: on_select_album,
                        on_select_playlist: on_select_playlist,
                        on_open_artist: on_open_artist,
                        on_search_artist: on_search_artist,
                    }
                }
            }
        }
    }
}

/// Vertical song-list shelf for the artist page "Top songs" section.
/// YT only returns the first 5 rows inline and ships a `more_browse_id`
/// (a `VL…` playlist id) that points at the full songs playlist; we
/// expose that as a "Show all songs" button which navigates through
/// `on_select_playlist` into the existing `DiscoverPlaylistDetail`
/// viewer (which already paginates).
#[component]
fn SongListShelf(
    shelf: DiscoverShelf,
    on_select_playlist: EventHandler<(String, String)>,
) -> Element {
    let mut ctrl = use_context::<hooks::use_player_controller::PlayerController>();
    let mut now_playing = use_context::<DiscoverNowPlaying>().0;
    let tracks: Vec<Track> = shelf
        .items
        .iter()
        .filter_map(|i| match i {
            DiscoverItem::Song(t) => Some((**t).clone()),
            _ => None,
        })
        .collect();
    let title_for_more = shelf.title.clone();
    let more = shelf.more_browse_id.clone();
    rsx! {
        section { class: "mb-12",
            div { class: "flex items-end justify-between mb-5 gap-4",
                h2 { class: "text-2xl md:text-3xl font-bold text-white truncate", "{shelf.title}" }
                if let Some(more) = more {
                    button {
                        class: "text-xs font-bold text-white/60 hover:text-white cursor-pointer transition-colors",
                        onclick: move |_| {
                            on_select_playlist.call((more.clone(), title_for_more.clone()))
                        },
                        "{i18n::t(\"discover_show_all\")}"
                    }
                }
            }
            div { class: "flex flex-col",
                {
                    // Shared menu / playing state across the rows.
                    let mut active_menu_path = use_signal(|| None::<reader::TrackId>);
                    let mut current_playing_path = use_signal(|| None::<reader::TrackId>);
                    rsx! {
                        for (idx, track) in tracks.iter().enumerate() {
                            {
                                let track = track.clone();
                                let tracks_for_play = tracks.clone();
                                let cover_url = utils::jellyfin_image::resolve_track_cover(
                                    track.cover.as_deref(),
                                    &track.id.key(),
                                    &track.album_id,
                                    "",
                                    None,
                                    96,
                                    80,
                                )
                                .map(utils::cover_url_from_string);
                                let track_for_play = track.clone();
                                let track_for_menu = track.clone();
                                let track_path_for_match = track.id.clone();
                                let is_current = current_playing_path.read().as_ref()
                                    == Some(&track_path_for_match);
                                let is_menu_open = active_menu_path.read().as_ref()
                                    == Some(&track.id);
                                rsx! {
                                    TrackRow {
                                        key: "{idx}",
                                        track: track.clone(),
                                        cover_url,
                                        on_start_radio: components::track_row::radio_handler(track.clone()),
                                        row_num: Some(idx + 1),
                                        is_menu_open,
                                        is_currently_playing: is_current,
                                        hide_delete: true,
                                        on_play: move |_| {
                                            let mut queue = tracks_for_play.clone();
                                            let start = queue
                                                .iter()
                                                .position(|x| x.id == track_for_play.id)
                                                .unwrap_or(0);
                                            queue.rotate_left(start);
                                            current_playing_path.set(Some(track_for_play.id.clone()));
                                            // Top Songs is a preview — clear the
                                            // discover source so no album/playlist
                                            // tile incorrectly shows the pause
                                            // overlay while one of these plays.
                                            now_playing.set(None);
                                            ctrl.play_queue_linear(queue);
                                        },
                                        on_click_menu: move |_| {
                                            let p = track_for_menu.id.clone();
                                            if active_menu_path.read().as_ref() == Some(&p) {
                                                active_menu_path.set(None);
                                            } else {
                                                active_menu_path.set(Some(p));
                                            }
                                        },
                                        on_close_menu: move |_| active_menu_path.set(None),
                                        on_add_to_playlist: move |_| {
                                            active_menu_path.set(None);
                                        },
                                        on_delete: move |_| active_menu_path.set(None),
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#[component]
fn DiscoverTile(
    item: DiscoverItem,
    on_select_album: EventHandler<String>,
    on_select_playlist: EventHandler<(String, String)>,
    on_open_artist: EventHandler<(String, String)>,
    on_search_artist: EventHandler<String>,
) -> Element {
    let ctrl = use_context::<hooks::use_player_controller::PlayerController>();
    let now_playing = use_context::<DiscoverNowPlaying>().0;
    let cache = use_context::<DiscoverPrefetchCache>().0;
    match item {
        DiscoverItem::Song(track) => {
            rsx! { SongCard { track: (*track).clone() } }
        }
        DiscoverItem::Playlist {
            playlist_id,
            title,
            subtitle,
            thumbnail,
        } => {
            let title_for_click = title.clone();
            let pid_for_play = playlist_id.clone();
            let pid_for_source = playlist_id.clone();
            rsx! {
                Card {
                    title: title,
                    subtitle: subtitle,
                    thumbnail: thumbnail,
                    rounded_full: false,
                    onclick: move |_| {
                        on_select_playlist.call((playlist_id.clone(), title_for_click.clone()))
                    },
                    on_play: EventHandler::new(move |_| {
                        play_playlist_async(pid_for_play.clone(), ctrl, now_playing, cache);
                    }),
                    source_id: Some(pid_for_source),
                }
            }
        }
        DiscoverItem::Album {
            browse_id,
            title,
            subtitle,
            thumbnail,
        } => {
            let bid_for_click = browse_id.clone();
            let bid_for_play = browse_id.clone();
            let bid_for_source = browse_id.clone();
            rsx! {
                Card {
                    title: title,
                    subtitle: subtitle,
                    thumbnail: thumbnail,
                    rounded_full: false,
                    onclick: move |_| {
                        on_select_album.call(bid_for_click.clone())
                    },
                    on_play: EventHandler::new(move |_| {
                        play_playlist_async(bid_for_play.clone(), ctrl, now_playing, cache);
                    }),
                    source_id: Some(bid_for_source),
                }
            }
        }
        DiscoverItem::Artist {
            channel_id,
            name,
            thumbnail,
        } => {
            let cid = channel_id.clone();
            let name_for_click = name.clone();
            rsx! {
                Card {
                    title: name.clone(),
                    subtitle: String::new(),
                    thumbnail: thumbnail,
                    rounded_full: true,
                    onclick: move |_| on_open_artist.call((cid.clone(), name_for_click.clone())),
                    on_play: None,
                    source_id: None,
                }
            }
        }
        DiscoverItem::Mood {
            title, thumbnail, ..
        } => rsx! {
            Card {
                title: title,
                subtitle: String::new(),
                thumbnail: thumbnail,
                rounded_full: false,
                onclick: move |_| {},
                on_play: None,
                source_id: None,
            }
        },
    }
}

/// Shared "play whatever this id resolves to" used by both Playlist
/// and Album tiles. MPRE… ids go through the album browse endpoint,
/// everything else through the playlist entries endpoint.
///
/// Flips `is_loading` true SYNCHRONOUSLY on the calling frame so the
/// player bar shows the spinner the instant the user clicks — the
/// fetch + stream resolution takes a beat, and without this the click
/// felt unresponsive. The signal gets cleared by `play_queue_linear`
/// once playback actually begins (or by the early-return branches if
/// the fetch fails / returns nothing).
fn play_playlist_async(
    id: String,
    mut ctrl: hooks::use_player_controller::PlayerController,
    mut now_playing: Signal<Option<String>>,
    cache: Signal<HashMap<String, Vec<Track>>>,
) {
    ctrl.is_loading.set(true);
    now_playing.set(Some(id.clone()));
    // Cache hit from hover-prefetch — start playback synchronously, no
    // network roundtrip needed. This is the path that makes Discover
    // tiles feel like Favorites: warm data, instant playback.
    if let Some(tracks) = cache.peek().get(&id).cloned()
        && !tracks.is_empty()
    {
        ctrl.play_queue_linear(tracks);
        return;
    }
    let play_span = tracing::info_span!("discover.play_playlist", playlist_id = %id);
    spawn(
        async move {
            let mut cache_writer = cache;
            // Shared failure path: release is_loading AND let go of the
            // now_playing tag so the tile drops out of phantom-pause state
            // and a subsequent click can retry through the normal play path
            // rather than landing on ctrl.toggle() against an unrelated
            // currently-playing track.
            let fail = |ctrl: &mut hooks::use_player_controller::PlayerController,
                        now_playing: &mut Signal<Option<String>>| {
                ctrl.is_loading.set(false);
                now_playing.set(None);
            };
            let source = ctrl.active_source.peek().clone();

            // Albums come back in a single browse hit.
            if id.starts_with("MPRE") {
                match source.fetch_album_tracks(&id).await {
                    Ok(tracks) if !tracks.is_empty() => {
                        // Warm the cache for the next click on the same
                        // tile — without this the MPRE branch repaid full
                        // network roundtrip for every cold click.
                        cache_writer.write().insert(id, tracks.clone());
                        ctrl.play_queue_linear(tracks);
                    }
                    _ => fail(&mut ctrl, &mut now_playing),
                }
                return;
            }

            // Playlists give the first ~100 rows on the initial browse and
            // paginate the rest via continuation cursors — pull them page by
            // page so the first batch starts playing instantly while the tail
            // fills in (dedup spans pages, so it's tracked here).
            let mut started = false;
            let mut accumulated = Vec::<Track>::new();
            let mut seen = std::collections::HashSet::<String>::new();
            let mut cursor: Option<String> = None;
            loop {
                let (batch, next) = match source.fetch_playlist_page(&id, cursor).await {
                    Ok(page) => page,
                    Err(e) => {
                        if started {
                            tracing::warn!(error = %e, "discover playlist errored mid-flight");
                            ctrl.playback_error
                                .set(Some(format!("Discover playlist failed mid-load:\n{e}")));
                        }
                        break;
                    }
                };
                let unique: Vec<Track> = batch
                    .into_iter()
                    .filter(|t| seen.insert(t.id.key().into_owned()))
                    .collect();
                if !unique.is_empty() {
                    accumulated.extend(unique.iter().cloned());
                    if started {
                        ctrl.add_to_queue(unique);
                    } else {
                        ctrl.play_queue_linear(unique);
                        started = true;
                    }
                }
                match next {
                    Some(token) => cursor = Some(token),
                    // Only cache when the WHOLE playlist paged in cleanly — a
                    // mid-stream break leaves `accumulated` truncated, and
                    // caching that would poison every future click on this tile.
                    None => {
                        cache_writer.write().insert(id, accumulated);
                        break;
                    }
                }
            }
            if !started {
                fail(&mut ctrl, &mut now_playing);
            }
        }
        .instrument(play_span),
    );
}

#[component]
fn Card(
    title: String,
    subtitle: String,
    thumbnail: Option<String>,
    rounded_full: bool,
    onclick: EventHandler<MouseEvent>,
    on_play: Option<EventHandler<()>>,
    /// The id (playlist_id / MPRE…) this card represents. When set
    /// and equal to DiscoverNowPlaying, the overlay shows pause and
    /// clicking it toggles the player instead of refetching.
    source_id: Option<String>,
) -> Element {
    let img_class = if rounded_full {
        "w-44 h-44 object-cover rounded-full bg-white/5"
    } else {
        "w-44 h-44 object-cover rounded-lg bg-white/5"
    };
    let placeholder_class = if rounded_full {
        "w-44 h-44 rounded-full bg-white/5"
    } else {
        "w-44 h-44 rounded-lg bg-white/5"
    };
    let cover_radius = if rounded_full {
        "rounded-full"
    } else {
        "rounded-lg"
    };
    let now_playing = use_context::<DiscoverNowPlaying>().0;
    let mut cache = use_context::<DiscoverPrefetchCache>().0;
    let active_source = use_context::<Signal<::server::source::ActiveSource>>();
    let mut ctrl = use_context::<hooks::use_player_controller::PlayerController>();
    // Per-tile hover gate that survives across renders so the spawned
    // prefetch task can check whether the cursor is still on the tile
    // after the debounce sleep.
    let mut hover_armed = use_signal(|| false);
    let is_this_source = match (&source_id, now_playing.read().as_ref()) {
        (Some(sid), Some(active)) => sid == active,
        _ => false,
    };
    // Three icon states: play (default), spinner (this tile is fetching
    // / stream is warming up), pause (audio actually playing). The
    // spinner kicks in synchronously because play_playlist_async flips
    // is_loading on the same frame as the click.
    let is_playing = *ctrl.is_playing.read();
    let is_loading = *ctrl.is_loading.read();
    let show_loading = is_this_source && is_loading;
    let show_pause = is_this_source && is_playing && !is_loading;
    let prefetch_id = source_id.clone();
    rsx! {
        div {
            class: "shrink-0 w-44 text-left cursor-pointer transition-transform duration-200 ease-out hover:scale-[1.03] hover:-translate-y-0.5 group",
            onclick: move |e| onclick.call(e),
            onmouseenter: move |_| {
                let Some(id) = prefetch_id.clone() else { return; };
                hover_armed.set(true);
                let prefetch_span = tracing::info_span!("discover.prefetch", id = %id);
                let source = active_source.peek().clone();
                spawn(async move {
                    // Short hover delay so the cursor passing over a
                    // shelf doesn't fire a dozen requests. If the user
                    // moves off the tile inside the delay window,
                    // onmouseleave disarms hover_armed and we skip.
                    tokio::time::sleep(Duration::from_millis(250)).await;
                    if !*hover_armed.peek() {
                        return;
                    }
                    if cache.peek().contains_key(&id) {
                        return;
                    }
                    // Prefetch wants the whole list buffered, so a plain fetch
                    // (no live-batch streaming) is exactly right here.
                    let fetched = if id.starts_with("MPRE") {
                        source.fetch_album_tracks(&id).await
                    } else {
                        source.fetch_playlist_entries(&id).await
                    };
                    if let Ok(tracks) = fetched
                        && !tracks.is_empty()
                    {
                        cache.write().insert(id, tracks);
                    }
                }.instrument(prefetch_span));
            },
            onmouseleave: move |_| {
                hover_armed.set(false);
            },
            div { class: "relative w-44 h-44 mb-3 overflow-hidden {cover_radius}",
                if let Some(url) = thumbnail {
                    img {
                        src: "{url}",
                        class: "{img_class}",
                        loading: "lazy",
                        decoding: "async",
                    }
                } else {
                    div { class: "{placeholder_class}" }
                }
                if let Some(play) = on_play {
                    button {
                        class: "absolute right-3 bottom-3 w-10 h-10 bg-white text-black rounded-full flex items-center justify-center shadow-lg translate-y-4 opacity-0 group-hover:translate-y-0 group-hover:opacity-100 transition-all duration-300 cursor-pointer",
                        onclick: move |e: MouseEvent| {
                            e.stop_propagation();
                            if show_loading {
                                return;
                            }
                            if is_this_source {
                                ctrl.toggle();
                            } else {
                                play.call(());
                            }
                        },
                        i {
                            class: if show_loading {
                                "fa-solid fa-arrows-rotate fa-spin text-sm"
                            } else if show_pause {
                                "fa-solid fa-pause text-sm"
                            } else {
                                "fa-solid fa-play ml-0.5 text-sm"
                            }
                        }
                    }
                }
            }
            div { class: "h-10 flex items-center overflow-hidden",
                p {
                    class: "text-sm font-semibold text-white break-words",
                    style: "display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis;",
                    "{title}"
                }
            }
            p {
                class: "text-xs text-white/50 truncate h-4 mt-1",
                "{subtitle}"
            }
        }
    }
}

#[component]
fn SongCard(track: Track) -> Element {
    let thumbnail = utils::jellyfin_image::resolve_track_cover(
        track.cover.as_deref(),
        &track.id.key(),
        &track.album_id,
        "",
        None,
        320,
        80,
    );
    let title = track.title.clone();
    let artist = track.artist.clone();
    let video_id = track_video_id(&track);

    let active_source = use_context::<Signal<::server::source::ActiveSource>>();
    let mut ctrl = use_context::<hooks::use_player_controller::PlayerController>();
    let now_playing = use_context::<DiscoverNowPlaying>().0;
    let mut cache = use_context::<DiscoverPrefetchCache>().0;

    let source_id = video_id.clone();
    let is_this_source = match (&source_id, now_playing.read().as_ref()) {
        (Some(sid), Some(active)) => sid == active,
        _ => false,
    };
    let is_playing = *ctrl.is_playing.read();
    let is_loading = *ctrl.is_loading.read();
    let show_loading = is_this_source && is_loading;
    let show_pause = is_this_source && is_playing && !is_loading;

    let mut hover_armed = use_signal(|| false);
    let prefetch_id = video_id.clone();

    rsx! {
        div {
            class: "shrink-0 w-44 text-left cursor-pointer transition-transform duration-200 ease-out hover:scale-[1.03] hover:-translate-y-0.5 group",
            onmouseenter: move |_| {
                let Some(id) = prefetch_id.clone() else { return; };
                hover_armed.set(true);
                let mix_span = tracing::info_span!("discover.prefetch_mix", id = %id);
                let source = active_source.peek().clone();
                spawn(async move {
                    tokio::time::sleep(Duration::from_millis(250)).await;
                    if !*hover_armed.peek() {
                        return;
                    }
                    if cache.peek().contains_key(&id) {
                        return;
                    }
                    if let Ok(mix) = source.start_radio(&id).await
                        && !mix.is_empty()
                    {
                        cache.write().insert(id, mix);
                    }
                }.instrument(mix_span));
            },
            onmouseleave: move |_| {
                hover_armed.set(false);
            },
            onclick: {
                let track = track.clone();
                let video_id = video_id.clone();
                move |_| {
                    if show_loading {
                        return;
                    }
                    if is_this_source {
                        ctrl.toggle();
                        return;
                    }
                    if let Some(vid) = video_id.clone() {
                        play_song_with_mix(
                            track.clone(),
                            vid,
                            ctrl,
                            now_playing,
                            cache,
                        );
                    } else {
                        ctrl.play_queue_linear(vec![track.clone()]);
                    }
                }
            },
            div { class: "relative w-44 h-44 mb-3 overflow-hidden rounded-lg",
                if let Some(url) = thumbnail {
                    img {
                        src: "{url}",
                        class: "w-44 h-44 object-cover bg-white/5",
                        loading: "lazy",
                        decoding: "async",
                    }
                } else {
                    div { class: "w-44 h-44 rounded-lg bg-white/5" }
                }
                div { class: "absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 bg-black/40 transition-opacity duration-200",
                    i {
                        class: if show_loading {
                            "fa-solid fa-arrows-rotate fa-spin text-white text-2xl"
                        } else if show_pause {
                            "fa-solid fa-pause text-white text-2xl"
                        } else {
                            "fa-solid fa-play text-white text-2xl"
                        }
                    }
                }
            }
            div { class: "h-10 flex items-center overflow-hidden",
                p {
                    class: "text-sm font-semibold text-white break-words",
                    style: "display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis;",
                    "{title}"
                }
            }
            p {
                class: "text-xs text-white/50 truncate h-4 mt-1",
                "{artist}"
            }
        }
    }
}

/// Pull the YT videoId out of a ytmusic:VIDEOID[:thumb] path. Returns
/// None if the track isn't a YT one (defensive — discover-feed songs
/// should always be).
fn track_video_id(track: &Track) -> Option<String> {
    if track.id.service() != Some(MusicService::YtMusic) {
        return None;
    }
    let id = track.id.key();
    (!id.is_empty()).then(|| id.to_string())
}

/// Click a single Discover song → kick off the YT mix radio so "next"
/// works, with the clicked song as the seed at queue index 0. Same
/// cache + sync-on-hit semantics as play_playlist_async.
fn play_song_with_mix(
    seed: Track,
    video_id: String,
    mut ctrl: hooks::use_player_controller::PlayerController,
    mut now_playing: Signal<Option<String>>,
    cache: Signal<HashMap<String, Vec<Track>>>,
) {
    ctrl.is_loading.set(true);
    now_playing.set(Some(video_id.clone()));
    if let Some(mix) = cache.peek().get(&video_id).cloned()
        && !mix.is_empty()
    {
        let queue = build_song_queue(&seed, mix);
        ctrl.play_queue_linear(queue);
        return;
    }
    let song_span = tracing::info_span!("discover.play_song", video_id = %video_id);
    spawn(
        async move {
            let source = ctrl.active_source.peek().clone();
            match source.start_radio(&video_id).await {
                Ok(mix) if !mix.is_empty() => {
                    let mut cache_writer = cache;
                    cache_writer.write().insert(video_id, mix.clone());
                    let queue = build_song_queue(&seed, mix);
                    ctrl.play_queue_linear(queue);
                }
                _ => {
                    // Mix failed → at least play the seed alone so the user
                    // gets the song they clicked, even if "next" won't work.
                    // now_playing stays as the video_id so the tile shows
                    // pause overlay for the seed song that IS now playing.
                    ctrl.play_queue_linear(vec![seed]);
                }
            }
        }
        .instrument(song_span),
    );
}

/// Put the seed at index 0 and append the rest of the mix. The seed
/// passed in (from the Discover home tile) has duration=0 because the
/// home feed shape doesn't ship one. The mix endpoint DOES ship a
/// duration per row (lengthText), and its first entry is normally the
/// same video as the seed — prefer that version so the player bar
/// gets the right time. Falls back to the caller-provided seed if the
/// mix doesn't contain it.
fn build_song_queue(seed: &Track, mix: Vec<Track>) -> Vec<Track> {
    let seed_vid = track_video_id(seed);
    let (seed_in_queue, rest): (Vec<Track>, Vec<Track>) = mix
        .into_iter()
        .partition(|t| seed_vid.is_some() && track_video_id(t) == seed_vid);
    let mut out = Vec::with_capacity(rest.len() + 1);
    out.push(
        seed_in_queue
            .into_iter()
            .next()
            .unwrap_or_else(|| seed.clone()),
    );
    out.extend(rest);
    out
}

/// Standalone viewer for a YT Music playlist discovered from the home
/// feed. Tracks are pulled directly from YT via get_playlist_entries
/// (which handles continuationItemRenderer pagination internally) —
/// nothing about this view touches `playlist_store`, so a discover
/// playlist never pollutes the user's saved Library Playlists.
#[component]
#[tracing::instrument(name = "render.discover_playlist", skip_all)]
pub fn DiscoverPlaylistDetail(
    selected_playlist_id: Signal<Option<String>>,
    selected_playlist_title: Signal<Option<String>>,
    on_back: EventHandler<()>,
) -> Element {
    let config = use_context::<Signal<AppConfig>>();
    let active_source = use_context::<Signal<::server::source::ActiveSource>>();
    let mut tracks = use_signal(Vec::<Track>::new);
    let mut loading = use_signal(|| true);
    let mut error = use_signal(|| None::<String>);
    let cover_for = hooks::use_db_queries::use_cover_resolver(512);

    let playlist_id = selected_playlist_id.read().clone();
    let header_title = selected_playlist_title
        .read()
        .clone()
        .unwrap_or_else(String::new);

    // Bumped on every effect re-run; spawned fetchers check it before
    // committing their result so a slow fetch for playlist A can't
    // overwrite B's tracks after the user has navigated B → A → B.
    let mut fetch_gen = use_signal(|| 0u64);
    use_effect(move || {
        let Some(pid) = selected_playlist_id.read().clone() else {
            return;
        };
        let my_gen = fetch_gen.with_mut(|g| {
            *g += 1;
            *g
        });
        tracks.set(Vec::new());
        loading.set(true);
        error.set(None);
        // Span created on the render thread, attached to the spawned
        // task via .instrument() so the worker-thread fetch (and its
        // inner yt.* spans) nest under this load instead of orphaning.
        let load_span = tracing::info_span!("playlist.load", playlist_id = %pid);
        let source = active_source.peek().clone();
        spawn(
            async move {
                tracing::debug!("playlist load started");
                let signed_in = config
                    .peek()
                    .server
                    .as_ref()
                    .and_then(|s| s.access_token.as_ref())
                    .is_some();
                if !signed_in {
                    if *fetch_gen.peek() == my_gen {
                        error.set(Some("not signed in".to_string()));
                        loading.set(false);
                    }
                    return;
                }
                // Discover routes both playlists and albums through this viewer;
                // MPRE… ids are albums and need the browse-album endpoint instead.
                let result = if pid.starts_with("MPRE") {
                    source.fetch_album_tracks(&pid).await
                } else {
                    source.fetch_playlist_entries(&pid).await
                };
                if *fetch_gen.peek() != my_gen {
                    return;
                }
                match result {
                    Ok(ts) => {
                        tracing::debug!(tracks = ts.len(), "playlist load complete");
                        tracks.set(ts);
                    }
                    Err(e) => {
                        tracing::warn!(error = %e, "playlist load failed");
                        error.set(Some(e.to_string()));
                    }
                }
                loading.set(false);
            }
            .instrument(load_span),
        );
    });

    if playlist_id.is_none() {
        return rsx! {
            div { class: "flex items-center justify-center h-full text-white/60 p-12",
                p { "{i18n::t(\"playlist_not_found\")}" }
            }
        };
    }

    // Loading / error keep a lightweight header + back button; the loaded state
    // hands off to the shared vaxry TrackListView (same look as the local
    // playlist / album pages) so Discover playlists match everywhere else.
    if *loading.read() {
        return rsx! {
            div { class: "p-6 md:p-10 max-w-[1600px] mx-auto",
                BackButton { on_back }
                div { class: "flex justify-center py-24",
                    i { class: "fa-solid fa-arrows-rotate fa-spin text-2xl text-white/60" }
                }
            }
        };
    }
    if let Some(err) = error.read().clone() {
        return rsx! {
            div { class: "p-6 md:p-10 max-w-[1600px] mx-auto",
                BackButton { on_back }
                div { class: "py-12 text-rose-400 text-sm",
                    "{i18n::t_with(\"discover_failed\", &[(\"error\", err.clone())])}"
                }
            }
        };
    }

    let track_list = tracks.read().clone();
    let cover_url = track_list.first().and_then(&cover_for);

    rsx! {
        div { class: "absolute inset-0 flex flex-col overflow-hidden p-8",
            components::track_list_view::TrackListView {
                name: header_title.clone(),
                description: String::new(),
                cover_url,
                tracks: track_list,
                is_album: false,
                on_close: move |_| on_back.call(()),
            }
        }
    }
}

#[component]
fn BackButton(on_back: EventHandler<()>) -> Element {
    rsx! {
        button {
            class: "inline-flex items-center gap-2 text-white/70 hover:text-white text-sm cursor-pointer mb-6 group",
            onclick: move |_| on_back.call(()),
            i { class: "fa-solid fa-chevron-left text-xs transition-transform group-hover:-translate-x-0.5" }
        }
    }
}

/// YT-backed artist profile. Used wherever YT Music is the active
/// backend — not just inside Discover. Pulls the immersive header
/// (banner + subscribers) and every section shelf from
/// `/browse?browseId=UC…` and hands each one off to the same
/// `ShelfRow` component the Discover home uses, so all sections get
/// hover-play, horizontal scroll, and the existing tile dispatch.
///
/// Callers that already know the channel_id (Discover tiles, mix
/// entries that carry a UC… browseEndpoint) write it into
/// `selected_artist_id`. Callers that only have a name (track row's
/// "go to artist", sidebar Artist tab, NavigationController) leave id
/// at None — the effect kicks off a YT search filtered to artists,
/// takes the top hit's UC… id, then loads the profile. Adds one extra
/// roundtrip but means every artist click in the app lands here.
#[component]
pub fn DiscoverArtistPage(
    selected_artist_id: Signal<Option<String>>,
    selected_artist_name: Signal<String>,
    on_back: EventHandler<()>,
    on_select_album: EventHandler<String>,
    on_select_playlist: EventHandler<(String, String)>,
    on_open_artist: EventHandler<(String, String)>,
    on_search_artist: EventHandler<String>,
) -> Element {
    let config = use_context::<Signal<AppConfig>>();
    let active_source = use_context::<Signal<::server::source::ActiveSource>>();
    let ctrl = use_context::<hooks::use_player_controller::PlayerController>();
    let now_playing = use_context::<DiscoverNowPlaying>().0;
    let cache = use_context::<DiscoverPrefetchCache>().0;
    let mut artist = use_signal(|| None::<YtArtist>);
    let mut loading = use_signal(|| true);
    let mut error = use_signal(|| None::<String>);

    // Generation guard: drop late results when the user navigates to
    // a different artist mid-fetch (both the resolve search AND the
    // browse hit are gated on it).
    let mut fetch_gen = use_signal(|| 0u64);
    use_effect(move || {
        // Effect re-runs when either signal changes. Selection key is
        // (id, name): id wins when set, name is the resolve fallback.
        let cid_opt = selected_artist_id.read().clone();
        let name = selected_artist_name.read().clone();
        if cid_opt.is_none() && name.trim().is_empty() {
            return;
        }
        let my_gen = fetch_gen.with_mut(|g| {
            *g += 1;
            *g
        });
        artist.set(None);
        loading.set(true);
        error.set(None);
        let artist_span = tracing::info_span!("artist.load", artist = %name);
        let source = active_source.peek().clone();
        spawn(
            async move {
                let signed_in = config
                    .peek()
                    .server
                    .as_ref()
                    .and_then(|s| s.access_token.as_ref())
                    .is_some();
                if !signed_in {
                    if *fetch_gen.peek() == my_gen {
                        error.set(Some("not signed in".to_string()));
                        loading.set(false);
                    }
                    return;
                }
                // Resolve cid from name if we didn't get one with the
                // click. Top YT search hit for the artist filter is the
                // first UC… browseId in the response — see
                // search::resolve_artist_channel_id.
                let cid = match cid_opt {
                    Some(c) => c,
                    None => match source.resolve_artist_channel_id(name.trim()).await {
                        Ok(Some(c)) => c,
                        Ok(None) => {
                            if *fetch_gen.peek() == my_gen {
                                error.set(Some(format!(
                                    "No YouTube Music artist found for \"{}\"",
                                    name.trim()
                                )));
                                loading.set(false);
                            }
                            return;
                        }
                        Err(e) => {
                            if *fetch_gen.peek() == my_gen {
                                error.set(Some(e.to_string()));
                                loading.set(false);
                            }
                            return;
                        }
                    },
                };
                if *fetch_gen.peek() != my_gen {
                    return;
                }
                let result = source.fetch_artist(&cid).await;
                if *fetch_gen.peek() != my_gen {
                    return;
                }
                match result {
                    Ok(a) => artist.set(Some(a)),
                    Err(e) => error.set(Some(e.to_string())),
                }
                loading.set(false);
            }
            .instrument(artist_span),
        );
    });

    if selected_artist_id.read().is_none() && selected_artist_name.read().trim().is_empty() {
        return rsx! {
            div { class: "p-12 text-white/60", "No artist selected" }
        };
    }

    rsx! {
        div { class: "max-w-[1600px] mx-auto",
            button {
                class: "inline-flex items-center gap-2 text-white/70 hover:text-white text-sm cursor-pointer mt-6 ml-6 md:ml-10 mb-2 group",
                onclick: move |_| on_back.call(()),
                i { class: "fa-solid fa-chevron-left text-xs transition-transform group-hover:-translate-x-0.5" }
            }

            if *loading.read() {
                div { class: "flex justify-center py-24",
                    i { class: "fa-solid fa-arrows-rotate fa-spin text-2xl text-white/60" }
                }
            } else if let Some(err) = error.read().clone() {
                div { class: "py-12 px-6 md:px-10 text-rose-400 text-sm",
                    "{i18n::t_with(\"discover_failed\", &[(\"error\", err.clone())])}"
                }
            } else if let Some(a) = artist.read().clone() {
                {
                    let banner = a.banner_thumbnail.clone();
                    // Bigger hero — 360px min on desktop. Previous version
                    // sized to content height (≈200px) which felt cramped
                    // for a Spotify-style profile banner.
                    let banner_style = banner
                        .map(|u| format!("background-image: linear-gradient(to bottom, rgba(0,0,0,0.2) 0%, rgba(0,0,0,0.95) 100%), url('{u}'); background-size: cover; background-position: center; min-height: 360px;"))
                        .unwrap_or_else(|| "min-height: 280px;".to_string());
                    let shuffle_pid = a.shuffle_playlist_id.clone();
                    rsx! {
                        div {
                            class: "relative overflow-hidden flex flex-col justify-end",
                            style: "{banner_style}",
                            div { class: "px-6 md:px-10 pt-16 pb-10 flex flex-col gap-4",
                                h1 { class: "text-4xl md:text-6xl font-black text-white break-words drop-shadow-lg", "{a.name}" }
                                if let Some(s) = a.subscribers.clone() {
                                    p { class: "text-sm text-white/70", "{s}" }
                                }
                                if let Some(d) = a.description.clone() {
                                    p { class: "text-sm text-white/60 max-w-3xl line-clamp-3", "{d}" }
                                }
                                div { class: "flex gap-3 mt-2",
                                    if let Some(pid) = shuffle_pid {
                                        button {
                                            class: "inline-flex items-center gap-2 bg-white text-black px-6 py-2.5 rounded-full font-bold hover:scale-105 active:scale-95 transition-transform cursor-pointer",
                                            onclick: move |_| {
                                                play_playlist_async(pid.clone(), ctrl, now_playing, cache);
                                            },
                                            i { class: "fa-solid fa-shuffle text-[11px]" }
                                            span { class: "text-sm", "{i18n::t(\"shuffle\")}" }
                                        }
                                    }
                                }
                            }
                        }
                        div { class: "px-6 md:px-10 pt-8",
                            for (idx, shelf) in a.sections.iter().enumerate() {
                                ShelfRow {
                                    key: "{idx}",
                                    shelf: shelf.clone(),
                                    scroll_id: format!("artist-shelf-{idx}"),
                                    on_select_album: on_select_album,
                                    on_select_playlist: on_select_playlist,
                                    on_open_artist: on_open_artist,
                                    on_search_artist: on_search_artist,
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}