soundcloud-tui 0.3.12

A minimalist terminal SoundCloud & YouTube player for Linux in Rust, crafted with @ttype aesthetic.
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
use crate::app::{App, ViewMode};
use crate::storage::VisualStyle;
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::Paragraph,
    Frame,
};

pub fn render(f: &mut Frame, app: &App) {
    let size = f.area();
    if size.width < 30 || size.height < 8 {
        return;
    }

    // Ultra-clean ttype layout: no boxes, pure typography & conveyor lines
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Top status bar
            Constraint::Length(1), // Blank separator
            Constraint::Fill(1),   // Main list content
            Constraint::Length(1), // Blank separator
            Constraint::Length(2), // Center conveyor player tape
            Constraint::Length(1), // Bottom hotkey line
        ])
        .split(size);

    if app.store.config.show_top_status {
        render_top_bar(f, app, chunks[0]);
    }

    match app.view_mode {
        ViewMode::Search => render_search_view(f, app, chunks[2]),
        ViewMode::Queue => render_queue_view(f, app, chunks[2]),
        ViewMode::Playlists => render_playlists_view(f, app, chunks[2]),
        ViewMode::PlaylistDetail => render_playlist_detail_view(f, app, chunks[2]),
        ViewMode::Favorites => render_favorites_view(f, app, chunks[2]),
        ViewMode::History => render_history_view(f, app, chunks[2]),
        ViewMode::UserProfile => render_user_profile_view(f, app, chunks[2]),
        ViewMode::Lyrics => render_lyrics_view(f, app, chunks[2]),
        ViewMode::Settings => render_settings_view(f, app, chunks[2]),
    }

    render_player_tape(f, app, chunks[4]);
    if app.store.config.show_bottom_hints {
        render_bottom_bar(f, app, chunks[5]);
    }

    // Modal overlays (Creating playlist or adding to playlist or artwork URL)
    if let Some(chars) = &app.modal_input {
        render_input_modal(f, app, chars, "New Playlist Name:");
    } else if let Some(chars) = &app.modal_import_input {
        render_input_modal(f, app, chars, "Spotify playlist/album link:");
    } else if let Some((_, chars)) = &app.modal_artwork_input {
        render_artwork_input_modal(f, app, chars);
    } else if let Some(target_track) = &app.modal_target_track {
        render_add_to_playlist_modal(f, app, target_track);
    }
}

pub fn format_duration(seconds: f64) -> String {
    let s = seconds.max(0.0) as u64;
    let m = s / 60;
    let rem_s = s % 60;
    format!("{}:{:02}", m, rem_s)
}

fn render_top_bar(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    let current_view = app.view_mode.name().to_lowercase();
    let history_count = app.store.history.len();
    let mut spans = vec![
        Span::styled(format!("  {} ", current_view), Style::default().fg(accent).add_modifier(Modifier::BOLD)),
        Span::styled("· ", Style::default().fg(Color::Rgb(50, 50, 50))),
        Span::styled(format!("vol {}% ", app.volume), Style::default().fg(Color::Rgb(110, 110, 110))),
        Span::styled("· ", Style::default().fg(Color::Rgb(50, 50, 50))),
    ];

    if app.view_mode == ViewMode::History {
        spans.push(Span::styled(format!("{} tracks ", history_count), Style::default().fg(accent)));
        spans.push(Span::styled("· ", Style::default().fg(Color::Rgb(50, 50, 50))));
    }

    if (app.current_speed - 1.0).abs() > 0.001 {
        let label = if app.current_speed < 1.0 {
            format!("{:.2}x slowed ", app.current_speed)
        } else {
            format!("{:.2}x sped up ", app.current_speed)
        };
        spans.push(Span::styled(label, Style::default().fg(accent).add_modifier(Modifier::BOLD)));
    } else {
        spans.push(Span::styled("1.00x ", Style::default().fg(Color::Rgb(110, 110, 110))));
    }

    if app.shuffle {
        spans.push(Span::styled("· ", Style::default().fg(Color::Rgb(50, 50, 50))));
        spans.push(Span::styled("shuffle ", Style::default().fg(accent)));
    }

    if app.repeat != crate::app::RepeatMode::Off {
        spans.push(Span::styled("· ", Style::default().fg(Color::Rgb(50, 50, 50))));
        spans.push(Span::styled(
            format!("rep:{} ", app.repeat.name().to_lowercase()),
            Style::default().fg(accent),
        ));
    }

    if let Some((msg, _)) = &app.status_message {
        spans.push(Span::styled("· ", Style::default().fg(Color::Rgb(50, 50, 50))));
        spans.push(Span::styled(
            msg.as_str(),
            Style::default().fg(Color::Rgb(120, 120, 120)),
        ));
    }

    let p = Paragraph::new(Line::from(spans)).alignment(Alignment::Left);
    f.render_widget(p, area);
}

fn render_search_view(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();

    let search_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Clean borderless input line
            Constraint::Length(1), // Spacer
            Constraint::Fill(1),   // Results list
        ])
        .split(area);

    // Borderless minimal prompt: "  ⌕  query▍ "
    let prompt_icon = if app.is_editing_search { "⌕ " } else { "· " };
    let prompt_color = if app.is_editing_search { accent } else { Color::Rgb(90, 90, 90) };

    let mut input_spans = vec![
        Span::styled(format!("  {} ", prompt_icon), Style::default().fg(prompt_color)),
    ];

    if app.query_chars.is_empty() && !app.is_editing_search {
        input_spans.push(Span::styled(
            "press '/' or 'i' to search SoundCloud...",
            Style::default().fg(Color::Rgb(85, 85, 85)),
        ));
    } else if app.query_chars.is_empty() && app.is_editing_search {
        input_spans.push(Span::styled(
            " ",
            Style::default().bg(accent),
        ));
        input_spans.push(Span::styled(
            " type song or artist and press Enter...",
            Style::default().fg(Color::Rgb(75, 75, 75)),
        ));
    } else {
        let cursor_pos = app.input_cursor;
        for (idx, &ch) in app.query_chars.iter().enumerate() {
            if app.is_editing_search && idx == cursor_pos {
                input_spans.push(Span::styled(
                    ch.to_string(),
                    Style::default().fg(Color::Black).bg(accent).add_modifier(Modifier::BOLD),
                ));
            } else {
                input_spans.push(Span::styled(ch.to_string(), Style::default().fg(Color::White)));
            }
        }
        if app.is_editing_search && cursor_pos == app.query_chars.len() {
            input_spans.push(Span::styled(
                " ",
                Style::default().bg(accent),
            ));
        }
        if !app.is_editing_search {
            input_spans.push(Span::styled(
                "   (/ or i to search · Enter to play)",
                Style::default().fg(Color::Rgb(75, 75, 75)),
            ));
        }
    }

    let input_p = Paragraph::new(Line::from(input_spans));
    f.render_widget(input_p, search_layout[0]);

    // Loading / Results
    if app.is_searching {
        let loading = Paragraph::new(Line::from(vec![
            Span::styled("⚡ ", Style::default().fg(accent)),
            Span::styled("searching tracks...", Style::default().fg(Color::Rgb(120, 120, 120))),
        ]))
        .alignment(Alignment::Center);
        f.render_widget(loading, search_layout[2]);
        return;
    }

    if app.search_results.is_empty() {
        let empty_msg = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled(
                "type any song or artist and hit enter",
                Style::default().fg(Color::Rgb(65, 65, 65)),
            )),
        ])
        .alignment(Alignment::Center);
        f.render_widget(empty_msg, search_layout[2]);
        return;
    }

    render_tracks_list(f, &app.search_results, app.search_cursor, accent, search_layout[2], app);
}

fn render_tracks_list(
    f: &mut Frame,
    tracks: &[crate::storage::TrackItem],
    cursor: usize,
    accent: Color,
    area: Rect,
    app: &App,
) {
    let max_lines = area.height as usize;
    if max_lines == 0 {
        return;
    }

    let scroll_offset = if cursor >= max_lines {
        cursor - max_lines + 1
    } else {
        0
    };

    let mut lines = Vec::new();

    for (idx, track) in tracks.iter().enumerate().skip(scroll_offset).take(max_lines) {
        let is_selected = idx == cursor;
        let is_playing = app
            .current_track()
            .map(|t| (!t.id.is_empty() && !track.id.is_empty() && t.id == track.id) || (!t.url.is_empty() && !track.url.is_empty() && t.url == track.url))
            .unwrap_or(false);
        let is_liked = app.store.is_track_liked(track);

        let cursor_glyph = if is_selected {
            match app.store.config.visual {
                VisualStyle::Blocky => "▊ ",
                VisualStyle::Minimal => "· ",
                VisualStyle::Braille => "⣿ ",
                VisualStyle::Neon => "◈ ",
                VisualStyle::Tape => "▸ ",
                VisualStyle::Waveform => "› ",
            }
        } else if is_playing {
            "▶ "
        } else {
            "  "
        };

        let like_icon = if !app.store.config.show_hearts {
            "  "
        } else if is_liked {
            "♥ "
        } else {
            "  "
        };

        let title_style = if is_selected {
            Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
        } else if is_playing {
            Style::default().fg(accent).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::Rgb(140, 140, 140))
        };

        let artist_style = if is_selected {
            Style::default().fg(accent)
        } else {
            Style::default().fg(Color::Rgb(70, 70, 70))
        };

        let dur = if app.store.config.show_durations && track.duration > 0.0 {
            format_duration(track.duration)
        } else {
            "".to_string()
        };

        lines.push(Line::from(vec![
            Span::styled(format!(" {}", cursor_glyph), Style::default().fg(if is_selected { accent } else { Color::Rgb(80, 80, 80) })),
            Span::styled(like_icon, Style::default().fg(if is_liked { Color::Rgb(220, 70, 70) } else { Color::Rgb(40, 40, 40) })),
            Span::styled(format!("{:<42}", truncate_str(&track.title, 40)), title_style),
            Span::styled(format!(" {:<24}", truncate_str(&track.artist, 22)), artist_style),
            Span::styled(format!("{:>7}", dur), Style::default().fg(Color::Rgb(65, 65, 65))),
        ]));
    }

    let p = Paragraph::new(lines);
    f.render_widget(p, area);
}

fn truncate_str(s: &str, max_len: usize) -> String {
    if s.chars().count() > max_len {
        let truncated: String = s.chars().take(max_len.saturating_sub(1)).collect();
        format!("{}…", truncated)
    } else {
        s.to_string()
    }
}

fn render_queue_view(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    if app.queue.is_empty() {
        let empty = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled("queue is empty", Style::default().fg(Color::Rgb(80, 80, 80)))),
            Line::from(Span::styled("press 'a' to enqueue tracks", Style::default().fg(Color::Rgb(50, 50, 50)))),
        ])
        .alignment(Alignment::Center);
        f.render_widget(empty, area);
        return;
    }

    render_tracks_list(f, &app.queue, app.queue_cursor, accent, area, app);
}

fn render_playlists_view(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    if app.store.playlists.is_empty() {
        let empty = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled("no saved playlists", Style::default().fg(Color::Rgb(80, 80, 80)))),
            Line::from(Span::styled("press 'c' to create, 'i' to import from Spotify, or paste any SoundCloud playlist link in search", Style::default().fg(Color::Rgb(50, 50, 50)))),
        ])
        .alignment(Alignment::Center);
        f.render_widget(empty, area);
        return;
    }

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Top hints
            Constraint::Length(1), // Spacer
            Constraint::Fill(1),   // Playlists list
        ])
        .split(area);

    let header = Paragraph::new(Line::from(vec![
        Span::styled("  ≡ ", Style::default().fg(accent).add_modifier(Modifier::BOLD)),
        Span::styled(format!("Your Playlists ({})", app.store.playlists.len()), Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
        Span::styled("  •  'c' create  •  'i' import Spotify  •  'Shift+C' cover  •  'd' delete", Style::default().fg(Color::Rgb(90, 90, 90))),
    ]));
    f.render_widget(header, chunks[0]);

    let max_lines = chunks[2].height as usize;
    if max_lines == 0 {
        return;
    }

    let cursor = app.playlists_cursor;
    let scroll_offset = if cursor >= max_lines {
        cursor - max_lines + 1
    } else {
        0
    };

    let mut lines = Vec::new();
    for (idx, pl) in app.store.playlists.iter().enumerate().skip(scroll_offset).take(max_lines) {
        let is_selected = idx == cursor;
        let prefix = if is_selected { " → " } else { "   " };
        let title_style = if is_selected {
            Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::Rgb(150, 150, 150))
        };

        let cover_icon = if pl.artwork_url.is_some() {
            Span::styled("🖼  ", Style::default().fg(accent))
        } else {
            Span::styled("≡  ", Style::default().fg(Color::Rgb(80, 80, 80)))
        };

        lines.push(Line::from(vec![
            Span::styled(prefix, Style::default().fg(if is_selected { accent } else { Color::Rgb(60, 60, 60) })),
            cover_icon,
            Span::styled(format!("{:<36}", truncate_str(&pl.title, 34)), title_style),
            Span::styled(format!(" {:<22}", truncate_str(&pl.author, 20)), Style::default().fg(Color::Rgb(80, 80, 80))),
            Span::styled(format!("{:>6} tracks", pl.track_count), Style::default().fg(Color::Rgb(65, 65, 65))),
        ]));
    }

    let p = Paragraph::new(lines);
    f.render_widget(p, chunks[2]);
}

fn render_playlist_detail_view(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    let playlist = match app.selected_playlist_idx.and_then(|i| app.store.playlists.get(i)) {
        Some(p) => p,
        None => {
            let empty = Paragraph::new("Playlist not found").alignment(Alignment::Center);
            f.render_widget(empty, area);
            return;
        }
    };

    let total_secs: f64 = playlist.tracks.iter().map(|t| t.duration).sum();
    let duration_str = format_duration(total_secs);

    let has_cover = playlist.artwork_url.is_some();
    let banner_h = if has_cover {
        if area.height >= 34 {
            16
        } else if area.height >= 24 {
            14
        } else {
            10
        }
    } else {
        5
    };
    let cover_w = banner_h * 2; // Perfect visual 1:1 square in terminal fonts

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(banner_h), // Banner with or without cover
            Constraint::Length(1),        // Spacer
            Constraint::Fill(1),          // Tracks
        ])
        .split(area);

    if let Some(ref art) = playlist.artwork_url {
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Length(2),          // Left margin
                Constraint::Length(cover_w),    // High-res square cover
                Constraint::Length(3),          // Gap
                Constraint::Fill(1),            // Info metadata block
            ])
            .split(chunks[0]);

        render_cover(f, art, cols[1], accent);

        let info_lines = vec![
            Line::from(vec![
                Span::styled("╭─ ", Style::default().fg(accent)),
                Span::styled("PLAYLIST", Style::default().fg(accent).add_modifier(Modifier::BOLD)),
                Span::styled(format!("  [{} tracks · {}]", playlist.track_count, duration_str), Style::default().fg(Color::Rgb(130, 130, 130))),
            ]),
            Line::from(vec![
                Span::styled("│  ", Style::default().fg(accent)),
                Span::styled(&playlist.title, Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
            ]),
            Line::from(vec![
                Span::styled("│  ", Style::default().fg(accent)),
                Span::styled("Curated by: ", Style::default().fg(Color::Rgb(100, 100, 100))),
                Span::styled(format!("@{}", playlist.author), Style::default().fg(Color::Rgb(180, 180, 180))),
            ]),
            Line::from(vec![
                Span::styled("│  ", Style::default().fg(accent)),
                Span::styled("Actions: ", Style::default().fg(Color::Rgb(110, 110, 110))),
                Span::styled("Enter ", Style::default().fg(Color::White)),
                Span::styled("play  •  ", Style::default().fg(Color::Rgb(80, 80, 80))),
                Span::styled("Shift+C ", Style::default().fg(Color::White)),
                Span::styled("cover  •  ", Style::default().fg(Color::Rgb(80, 80, 80))),
                Span::styled("d ", Style::default().fg(Color::White)),
                Span::styled("delete  •  ", Style::default().fg(Color::Rgb(80, 80, 80))),
                Span::styled("Esc ", Style::default().fg(Color::White)),
                Span::styled("back", Style::default().fg(Color::Rgb(80, 80, 80))),
            ]),
            Line::from(Span::styled("╰─────────────────────────────────────────────────────────────────────────────", Style::default().fg(Color::Rgb(45, 45, 45)))),
        ];
        f.render_widget(Paragraph::new(info_lines), cols[3]);
    } else {
        let banner_lines = vec![
            Line::from(vec![
                Span::styled("  ╭─ ", Style::default().fg(accent)),
                Span::styled(&playlist.title, Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
                Span::styled(format!("  [{} tracks · {}]", playlist.track_count, duration_str), Style::default().fg(accent)),
            ]),
            Line::from(vec![
                Span::styled("  │  ", Style::default().fg(accent)),
                Span::styled(format!("Curated by: @{}", playlist.author), Style::default().fg(Color::Rgb(150, 150, 150))),
                Span::styled("  •  no cover (press 'Shift+C' to set)", Style::default().fg(Color::Rgb(95, 95, 95))),
            ]),
            Line::from(vec![
                Span::styled("  │  ", Style::default().fg(accent)),
                Span::styled("Actions: ", Style::default().fg(Color::Rgb(110, 110, 110))),
                Span::styled("Enter ", Style::default().fg(Color::White)),
                Span::styled("play track  •  ", Style::default().fg(Color::Rgb(80, 80, 80))),
                Span::styled("Shift+C ", Style::default().fg(Color::White)),
                Span::styled("set/change cover image URL  •  ", Style::default().fg(Color::Rgb(80, 80, 80))),
                Span::styled("d ", Style::default().fg(Color::White)),
                Span::styled("remove track  •  ", Style::default().fg(Color::Rgb(80, 80, 80))),
                Span::styled("Esc ", Style::default().fg(Color::White)),
                Span::styled("back", Style::default().fg(Color::Rgb(80, 80, 80))),
            ]),
            Line::from(Span::styled("  ╰─────────────────────────────────────────────────────────────────────────────", Style::default().fg(Color::Rgb(45, 45, 45)))),
        ];
        f.render_widget(Paragraph::new(banner_lines), chunks[0]);
    }

    if playlist.tracks.is_empty() {
        let empty = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled("This playlist is empty", Style::default().fg(Color::Rgb(80, 80, 80)))),
            Line::from(Span::styled("Press 'm' on any track in Search or Favorites to add it here", Style::default().fg(Color::Rgb(55, 55, 55)))),
        ]).alignment(Alignment::Center);
        f.render_widget(empty, chunks[2]);
        return;
    }

    render_tracks_list(f, &playlist.tracks, app.playlist_detail_cursor, accent, chunks[2], app);
}

fn render_favorites_view(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    if app.store.liked.is_empty() {
        let empty = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled("no favorites", Style::default().fg(Color::Rgb(80, 80, 80)))),
            Line::from(Span::styled("press 'l' while playing to add", Style::default().fg(Color::Rgb(50, 50, 50)))),
        ])
        .alignment(Alignment::Center);
        f.render_widget(empty, area);
        return;
    }

    render_tracks_list(f, &app.store.liked, app.favorites_cursor, accent, area, app);
}

fn render_history_view(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    if app.store.history.is_empty() {
        let empty = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled("no history", Style::default().fg(Color::Rgb(80, 80, 80)))),
        ])
        .alignment(Alignment::Center);
        f.render_widget(empty, area);
        return;
    }

    let tracks: Vec<_> = app.store.history.iter().map(|h| h.track.clone()).collect();
    render_tracks_list(f, &tracks, app.history_cursor, accent, area, app);
}

fn render_settings_view(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    if area.height == 0 {
        return;
    }

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Header
            Constraint::Length(1), // Blank separator
            Constraint::Fill(1),   // List
        ])
        .split(area);

    let categories = [
        ("1. Appearance & UI", "theme · player style · bar width · top/bottom bars · icons", 7usize),
        ("2. Audio & Speed Engine", "volume · pitch mode · slowed/sped-up presets · DSP filter", 6usize),
        ("3. Playback & Radio", "auto-wave · resume pos · seek step · shuffle · repeat · mouse", 6usize),
        ("4. Discord RPC & System", "rich presence · activity type · button · timestamps · MPRIS", 6usize),
        ("5. Storage & Maintenance", "gapless disk prefetch · history limit · clear cache/history", 4usize),
    ];

    let Some(cat_idx) = app.selected_settings_category else {
        // Render top-level categories list (just like Playlists view)
        let header = Paragraph::new(Line::from(vec![
            Span::styled("  ⚙  ", Style::default().fg(accent)),
            Span::styled("settings categories", Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
            Span::styled("  (enter / → to open · config: ~/.config/sctui/config.json)", Style::default().fg(Color::Rgb(70, 70, 70))),
        ]));
        f.render_widget(header, chunks[0]);

        let mut lines = Vec::new();
        for (idx, (title, desc, count)) in categories.iter().enumerate() {
            let is_selected = idx == app.settings_category_cursor;
            let prefix = if is_selected { " → " } else { "   " };
            let title_style = if is_selected {
                Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::Rgb(150, 150, 150))
            };
            let desc_style = if is_selected {
                Style::default().fg(accent)
            } else {
                Style::default().fg(Color::Rgb(80, 80, 80))
            };

            lines.push(Line::from(vec![
                Span::styled(prefix, Style::default().fg(if is_selected { accent } else { Color::Rgb(60, 60, 60) })),
                Span::styled("≡ ", Style::default().fg(accent)),
                Span::styled(format!("{:<26}", title), title_style),
                Span::styled(format!(" {:<58}", desc), desc_style),
                Span::styled(format!("{:>2} options", count), Style::default().fg(Color::Rgb(65, 65, 65))),
            ]));
        }

        let p = Paragraph::new(lines);
        f.render_widget(p, chunks[2]);
        return;
    };

    // Inside a specific category
    let (cat_title, _, _) = categories.get(cat_idx).copied().unwrap_or(("Settings", "", 0));
    let header = Paragraph::new(Line::from(vec![
        Span::styled("  ⚙  ", Style::default().fg(accent)),
        Span::styled(cat_title, Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
        Span::styled("  (enter / ← → to change · esc / backspace to back)", Style::default().fg(Color::Rgb(70, 70, 70))),
    ]));
    f.render_widget(header, chunks[0]);

    let items: Vec<(&str, String)> = match cat_idx {
        0 => vec![
            ("color theme", app.store.config.theme.name().to_string()),
            ("player style", app.store.config.visual.name().to_string()),
            ("progress bar width", format!("{} cols", app.store.config.progress_bar_width)),
            (
                "bottom hints bar",
                if app.store.config.show_bottom_hints {
                    "visible".to_string()
                } else {
                    "hidden".to_string()
                },
            ),
            (
                "top status bar",
                if app.store.config.show_top_status {
                    "visible".to_string()
                } else {
                    "hidden".to_string()
                },
            ),
            (
                "track durations",
                if app.store.config.show_durations {
                    "shown".to_string()
                } else {
                    "hidden".to_string()
                },
            ),
            (
                "favorite heart icons",
                if app.store.config.show_hearts {
                    "shown (♥)".to_string()
                } else {
                    "hidden".to_string()
                },
            ),
        ],
        1 => vec![
            ("default volume", format!("{}%", app.store.config.default_volume)),
            ("volume step (+/-)", format!("{}%", app.store.config.volume_step)),
            ("speed pitch mode", app.store.config.pitch_mode.name().to_string()),
            ("slowed preset (< / [)", format!("{:.2}x", app.store.config.slowed_preset)),
            ("sped up preset (> / ])", format!("{:.2}x", app.store.config.speedup_preset)),
            ("audio DSP filter (EQ)", app.store.config.audio_filter.name().to_string()),
        ],
        2 => vec![
            (
                "auto-wave radio",
                if app.store.config.auto_wave {
                    "enabled (infinite related tracks)".to_string()
                } else {
                    "disabled".to_string()
                },
            ),
            (
                "resume position & speed",
                if app.store.config.resume_playback {
                    "remember per track".to_string()
                } else {
                    "always start at 0:00".to_string()
                },
            ),
            ("seek step (←/→)", format!("{} sec", app.store.config.seek_step)),
            (
                "default shuffle on start",
                if app.store.config.default_shuffle {
                    "on".to_string()
                } else {
                    "off".to_string()
                },
            ),
            ("default repeat mode", app.store.config.default_repeat.clone()),
            (
                "terminal mouse support",
                if app.store.config.mouse_support {
                    "enabled (click to play/seek)".to_string()
                } else {
                    "disabled (keyboard only)".to_string()
                },
            ),
        ],
        3 => vec![
            (
                "discord rich presence",
                if app.store.config.discord_rpc {
                    "on".to_string()
                } else {
                    "off".to_string()
                },
            ),
            ("discord activity type", app.store.config.rpc_activity_type.name().to_string()),
            (
                "discord button link",
                if app.store.config.discord_buttons {
                    "on (visible to others)".to_string()
                } else {
                    "off (visible to self & others)".to_string()
                },
            ),
            (
                "discord elapsed timer",
                if app.store.config.discord_timestamps {
                    "shown".to_string()
                } else {
                    "hidden".to_string()
                },
            ),
            (
                "system media keys (MPRIS2)",
                if app.store.config.mpris_enabled {
                    "enabled".to_string()
                } else {
                    "disabled".to_string()
                },
            ),
            (
                "auto-fetch synced lyrics",
                if app.store.config.auto_lyrics {
                    "enabled (LRCLIB)".to_string()
                } else {
                    "disabled".to_string()
                },
            ),
        ],
        4 => vec![
            (
                "gapless disk prefetch",
                if app.store.config.gapless_prefetch {
                    "enabled (at 70% track pos)".to_string()
                } else {
                    "disabled".to_string()
                },
            ),
            ("max history entries", format!("{} tracks", app.store.config.history_limit)),
            ("clear audio cache", crate::storage::DataStore::cache_size_label()),
            ("clear listening history", format!("{} tracks saved", app.store.history.len())),
        ],
        _ => Vec::new(),
    };

    let mut lines = Vec::new();
    for (idx, (label, val)) in items.iter().enumerate() {
        let is_selected = idx == app.settings_cursor;
        let prefix = if is_selected { " → " } else { "   " };
        let style_label = if is_selected {
            Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::Rgb(140, 140, 140))
        };
        let style_val = if is_selected {
            Style::default().fg(accent).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::Rgb(95, 95, 95))
        };

        lines.push(Line::from(vec![
            Span::styled(prefix, Style::default().fg(if is_selected { accent } else { Color::Rgb(60, 60, 60) })),
            Span::styled(format!("{:<28}", label), style_label),
            Span::styled(format!("‹ {} ›", val), style_val),
        ]));
    }

    let p = Paragraph::new(lines);
    f.render_widget(p, chunks[2]);
}

fn render_player_tape(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    let width = area.width as usize;
    if width < 20 {
        return;
    }

    let track_title = app
        .current_track()
        .map(|t| format!("{}  ·  {}", t.title, t.artist))
        .unwrap_or_else(|| "idle".to_string());

    let state_icon = if app.current_track().is_none() {
        "◼"
    } else if app.is_paused {
        "⏸"
    } else {
        "▶"
    };

    let (cur_str, tot_str, progress_ratio) = if app.total_duration > 0.0 {
        let ratio = (app.current_pos / app.total_duration).clamp(0.0, 1.0);
        (
            format_duration(app.current_pos),
            format_duration(app.total_duration),
            ratio,
        )
    } else if app.current_pos > 0.0 {
        (format_duration(app.current_pos), "--:--".to_string(), 0.0)
    } else {
        ("0:00".to_string(), "0:00".to_string(), 0.0)
    };

    // Dynamic waveform / visual style tape rendering
    let max_bar = app.store.config.progress_bar_width.clamp(20, 120);
    let bar_width = width.saturating_sub(24).clamp(12, max_bar);
    let filled_len = (bar_width as f64 * progress_ratio) as usize;

    let mut tape_spans = Vec::new();
    tape_spans.push(Span::styled(format!("{:>5} ", cur_str), Style::default().fg(Color::Rgb(90, 90, 90))));

    match app.store.config.visual {
        VisualStyle::Waveform => {
            let waveform_blocks = ['▂', '▃', '▄', '▅', '▆', '▇', '█'];
            let total_samples = app.current_waveform.len();
            for i in 0..bar_width {
                let glyph = if total_samples > 0 {
                    let sample_idx = (i * total_samples) / bar_width;
                    let val = app.current_waveform.get(sample_idx).copied().unwrap_or(0) as usize;
                    let glyph_idx = (val * (waveform_blocks.len() - 1)) / 100;
                    waveform_blocks[glyph_idx.min(waveform_blocks.len() - 1)]
                } else {
                    waveform_blocks[(i * 3 + 2) % waveform_blocks.len()]
                };
                let style = if i < filled_len {
                    Style::default().fg(accent).add_modifier(Modifier::BOLD)
                } else if i == filled_len {
                    Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(Color::Rgb(55, 55, 55))
                };
                tape_spans.push(Span::styled(glyph.to_string(), style));
            }
        }
        VisualStyle::Braille => {
            let braille_blocks = ['⣀', '⣤', '⣶', '⣿'];
            let total_samples = app.current_waveform.len();
            for i in 0..bar_width {
                let glyph = if total_samples > 0 {
                    let sample_idx = (i * total_samples) / bar_width;
                    let val = app.current_waveform.get(sample_idx).copied().unwrap_or(0) as usize;
                    let glyph_idx = (val * (braille_blocks.len() - 1)) / 100;
                    braille_blocks[glyph_idx.min(braille_blocks.len() - 1)]
                } else {
                    braille_blocks[(i * 2 + 1) % braille_blocks.len()]
                };
                let style = if i < filled_len {
                    Style::default().fg(accent).add_modifier(Modifier::BOLD)
                } else if i == filled_len {
                    Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(Color::Rgb(55, 55, 55))
                };
                tape_spans.push(Span::styled(glyph.to_string(), style));
            }
        }
        VisualStyle::Tape => {
            for i in 0..bar_width {
                let (ch, style) = if i < filled_len {
                    ('━', Style::default().fg(accent).add_modifier(Modifier::BOLD))
                } else if i == filled_len {
                    ('●', Style::default().fg(Color::White).add_modifier(Modifier::BOLD))
                } else {
                    ('─', Style::default().fg(Color::Rgb(55, 55, 55)))
                };
                tape_spans.push(Span::styled(ch.to_string(), style));
            }
        }
        VisualStyle::Blocky => {
            for i in 0..bar_width {
                let (ch, style) = if i < filled_len {
                    ('█', Style::default().fg(accent))
                } else if i == filled_len {
                    ('▓', Style::default().fg(Color::White).add_modifier(Modifier::BOLD))
                } else {
                    ('░', Style::default().fg(Color::Rgb(55, 55, 55)))
                };
                tape_spans.push(Span::styled(ch.to_string(), style));
            }
        }
        VisualStyle::Minimal => {
            for i in 0..bar_width {
                let (ch, style) = if i < filled_len {
                    ('·', Style::default().fg(accent).add_modifier(Modifier::BOLD))
                } else if i == filled_len {
                    ('◆', Style::default().fg(Color::White).add_modifier(Modifier::BOLD))
                } else {
                    ('·', Style::default().fg(Color::Rgb(45, 45, 45)))
                };
                tape_spans.push(Span::styled(ch.to_string(), style));
            }
        }
        VisualStyle::Neon => {
            for i in 0..bar_width {
                let (ch, style) = if i < filled_len {
                    ('═', Style::default().fg(accent).add_modifier(Modifier::BOLD))
                } else if i == filled_len {
                    ('◈', Style::default().fg(Color::White).add_modifier(Modifier::BOLD))
                } else {
                    ('─', Style::default().fg(Color::Rgb(45, 45, 45)))
                };
                tape_spans.push(Span::styled(ch.to_string(), style));
            }
        }
    }

    tape_spans.push(Span::styled(format!(" {:<5}", tot_str), Style::default().fg(Color::Rgb(90, 90, 90))));

    let line1 = Line::from(vec![
        Span::styled(format!("{} ", state_icon), Style::default().fg(accent)),
        Span::styled(
            truncate_str(&track_title, width.saturating_sub(10)),
            Style::default().fg(Color::White).add_modifier(Modifier::BOLD),
        ),
    ]);

    let line2 = Line::from(tape_spans);

    let p = Paragraph::new(vec![line1, line2]).alignment(Alignment::Center);
    f.render_widget(p, area);
}

fn render_user_profile_view(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    let profile = match &app.current_user_profile {
        Some(p) => p,
        None => {
            let empty = Paragraph::new("No profile loaded. Press 'u' on any track to view author").alignment(Alignment::Center);
            f.render_widget(empty, area);
            return;
        }
    };

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Header
            Constraint::Length(1), // Blank
            Constraint::Fill(1),   // Tracks
        ])
        .split(area);

    let desc = profile.description.as_deref().unwrap_or("SoundCloud Artist");
    let header = Paragraph::new(Line::from(vec![
        Span::styled("@", Style::default().fg(accent).add_modifier(Modifier::BOLD)),
        Span::styled(&profile.username, Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
        Span::styled(format!("  •  {} followers  •  {} tracks", profile.followers_count, profile.track_count), Style::default().fg(Color::Rgb(100, 100, 100))),
        Span::styled(format!("  •  {}", truncate_str(desc, 30)), Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("  (esc to back)", Style::default().fg(Color::Rgb(50, 50, 50))),
    ]));
    f.render_widget(header, chunks[0]);

    render_tracks_list(f, &profile.tracks, app.user_profile_cursor, accent, chunks[2], app);
}

fn render_lyrics_view(f: &mut Frame, app: &App, area: Rect) {
    let accent = app.theme_accent();
    let current_track = match app.current_track() {
        Some(t) => t,
        None => {
            let empty = Paragraph::new("No track playing").alignment(Alignment::Center);
            f.render_widget(empty, area);
            return;
        }
    };

    let lyrics = match &app.current_lyrics {
        Some(l) if l.track_id == current_track.id => l,
        _ => {
            let loading = Paragraph::new(vec![
                Line::from(""),
                Line::from(Span::styled("♪ searching lyrics on LRCLIB...", Style::default().fg(Color::Rgb(100, 100, 100)))),
                Line::from(""),
                Line::from(Span::styled(format!("{} - {}", current_track.artist, current_track.title), Style::default().fg(Color::Rgb(60, 60, 60)))),
            ]).alignment(Alignment::Center);
            f.render_widget(loading, area);
            return;
        }
    };

    let cur_time = app.current_pos;
    let max_lines = area.height as usize;
    if max_lines == 0 {
        return;
    }

    if !lyrics.lines.is_empty() {
        // Find current synced line
        let current_line_idx = lyrics
            .lines
            .iter()
            .rposition(|line| line.time_secs <= cur_time)
            .unwrap_or(0);

        let half_screen = max_lines / 2;
        let start_idx = current_line_idx.saturating_sub(half_screen);

        let mut lines = Vec::new();
        for (idx, line) in lyrics.lines.iter().enumerate().skip(start_idx).take(max_lines) {
            let is_current = idx == current_line_idx;
            if is_current {
                lines.push(Line::from(Span::styled(
                    format!("▶  {}", line.text),
                    Style::default().fg(accent).add_modifier(Modifier::BOLD),
                )));
            } else {
                let diff = (idx as isize - current_line_idx as isize).abs();
                let dim_val = match diff {
                    1 => 130,
                    2 => 100,
                    3 => 70,
                    _ => 45,
                };
                lines.push(Line::from(Span::styled(
                    format!("   {}", line.text),
                    Style::default().fg(Color::Rgb(dim_val, dim_val, dim_val)),
                )));
            }
        }
        let p = Paragraph::new(lines).alignment(Alignment::Center);
        f.render_widget(p, area);
    } else if let Some(plain) = &lyrics.plain_lyrics {
        let lines: Vec<Line> = plain.lines().take(max_lines).map(|l| Line::from(Span::styled(l, Style::default().fg(Color::Rgb(140, 140, 140))))).collect();
        let p = Paragraph::new(lines).alignment(Alignment::Center);
        f.render_widget(p, area);
    } else {
        let empty = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled("No lyrics found for this track", Style::default().fg(Color::Rgb(80, 80, 80)))),
        ]).alignment(Alignment::Center);
        f.render_widget(empty, area);
    }
}

fn render_input_modal(f: &mut Frame, app: &App, input_chars: &[char], prompt: &str) {
    let size = f.area();
    let accent = app.theme_accent();
    let text: String = input_chars.iter().collect();

    let area = centered_rect(50, 20, size);
    f.render_widget(ratatui::widgets::Clear, area);

    let block = ratatui::widgets::Block::default()
        .borders(ratatui::widgets::Borders::ALL)
        .border_style(Style::default().fg(accent))
        .title(Span::styled(" Create Playlist ", Style::default().fg(accent).add_modifier(Modifier::BOLD)));
    f.render_widget(block, area);

    let inner = area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 1 });
    let p = Paragraph::new(vec![
        Line::from(Span::styled(prompt, Style::default().fg(Color::Rgb(140, 140, 140)))),
        Line::from(""),
        Line::from(vec![
            Span::styled("▸ ", Style::default().fg(accent)),
            Span::styled(&text, Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
            Span::styled("▍", Style::default().fg(accent)),
        ]),
        Line::from(""),
        Line::from(Span::styled("Enter: Confirm  •  Esc: Cancel", Style::default().fg(Color::Rgb(80, 80, 80)))),
    ]);
    f.render_widget(p, inner);
}

fn render_artwork_input_modal(f: &mut Frame, app: &App, input_chars: &[char]) {
    let size = f.area();
    let accent = app.theme_accent();
    let text: String = input_chars.iter().collect();

    let area = centered_rect(65, 24, size);
    f.render_widget(ratatui::widgets::Clear, area);

    let block = ratatui::widgets::Block::default()
        .borders(ratatui::widgets::Borders::ALL)
        .border_style(Style::default().fg(accent))
        .title(Span::styled(" Set Playlist Cover Image URL ", Style::default().fg(accent).add_modifier(Modifier::BOLD)));
    f.render_widget(block, area);

    let inner = area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 1 });
    let p = Paragraph::new(vec![
        Line::from(Span::styled("Paste direct image link (e.g. https://.../cover.jpg or i.imgur.com/...):", Style::default().fg(Color::Rgb(140, 140, 140)))),
        Line::from(""),
        Line::from(vec![
            Span::styled("🖼  ", Style::default().fg(accent)),
            Span::styled(if text.is_empty() { "https://" } else { &text }, Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
            Span::styled("▍", Style::default().fg(accent)),
        ]),
        Line::from(""),
        Line::from(Span::styled("Tip: Leave blank and press Enter to remove cover image", Style::default().fg(Color::Rgb(95, 95, 95)))),
        Line::from(Span::styled("Enter: Save  •  Esc: Cancel", Style::default().fg(Color::Rgb(80, 80, 80)))),
    ]);
    f.render_widget(p, inner);
}

fn render_add_to_playlist_modal(f: &mut Frame, app: &App, target_track: &crate::storage::TrackItem) {
    let size = f.area();
    let accent = app.theme_accent();

    let area = centered_rect(55, 40, size);
    f.render_widget(ratatui::widgets::Clear, area);

    let title_str = format!(" Add to Playlist: {} ", truncate_str(&target_track.title, 25));
    let block = ratatui::widgets::Block::default()
        .borders(ratatui::widgets::Borders::ALL)
        .border_style(Style::default().fg(accent))
        .title(Span::styled(title_str, Style::default().fg(accent).add_modifier(Modifier::BOLD)));
    f.render_widget(block, area);

    let inner = area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 1 });
    let mut lines = Vec::new();
    lines.push(Line::from(Span::styled("Select target playlist:", Style::default().fg(Color::Rgb(120, 120, 120)))));
    lines.push(Line::from(""));

    for (idx, pl) in app.store.playlists.iter().enumerate() {
        let is_sel = idx == app.modal_playlist_cursor;
        let prefix = if is_sel { " ▸ " } else { "   " };
        let style = if is_sel {
            Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::Rgb(130, 130, 130))
        };
        lines.push(Line::from(vec![
            Span::styled(prefix, Style::default().fg(if is_sel { accent } else { Color::Rgb(50, 50, 50) })),
            Span::styled(format!("{:<28}", truncate_str(&pl.title, 26)), style),
            Span::styled(format!("({} tracks)", pl.track_count), Style::default().fg(Color::Rgb(70, 70, 70))),
        ]));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled("Enter: Add  •  Esc: Cancel", Style::default().fg(Color::Rgb(80, 80, 80)))));

    let p = Paragraph::new(lines);
    f.render_widget(p, inner);
}

fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(r);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}

fn render_bottom_bar(f: &mut Frame, _app: &App, area: Rect) {
    let hints = vec![
        Span::styled("  / ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("search ", Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("· ", Style::default().fg(Color::Rgb(40, 40, 40))),
        Span::styled("enter ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("play ", Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("· ", Style::default().fg(Color::Rgb(40, 40, 40))),
        Span::styled("space ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("pause ", Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("· ", Style::default().fg(Color::Rgb(40, 40, 40))),
        Span::styled("tab/1-7 ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("views ", Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("· ", Style::default().fg(Color::Rgb(40, 40, 40))),
        Span::styled("w ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("wave ", Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("· ", Style::default().fg(Color::Rgb(40, 40, 40))),
        Span::styled("o ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("link ", Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("· ", Style::default().fg(Color::Rgb(40, 40, 40))),
        Span::styled("< > ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("slow/fast ", Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("· ", Style::default().fg(Color::Rgb(40, 40, 40))),
        Span::styled("0 ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("norm ", Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("· ", Style::default().fg(Color::Rgb(40, 40, 40))),
        Span::styled("y ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("lyrics ", Style::default().fg(Color::Rgb(70, 70, 70))),
        Span::styled("· ", Style::default().fg(Color::Rgb(40, 40, 40))),
        Span::styled("q ", Style::default().fg(Color::Rgb(120, 120, 120))),
        Span::styled("quit", Style::default().fg(Color::Rgb(70, 70, 70))),
    ];
    let p = Paragraph::new(Line::from(hints)).alignment(Alignment::Left);
    f.render_widget(p, area);
}

// ---- Cover image rendering (high-res Lanczos3 half-block truecolor) ----
struct CoverData {
    img: image::RgbImage,
    scaled_w: u16,
    scaled_h: u16,
    lines: Vec<Line<'static>>,
}

enum CoverState {
    Loading,
    Failed,
    Ready(CoverData),
}

static COVER_CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, CoverState>>> =
    std::sync::OnceLock::new();

fn cover_cache() -> &'static std::sync::Mutex<std::collections::HashMap<String, CoverState>> {
    COVER_CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
}

fn render_cover(f: &mut Frame, url: &str, area: Rect, accent: Color) {
    if area.width == 0 || area.height == 0 {
        return;
    }
    let mut spawn = false;
    let lines_to_draw: Option<Vec<Line<'static>>> = {
        let mut cache = cover_cache().lock().unwrap_or_else(|e| e.into_inner());
        if !cache.contains_key(url) {
            cache.insert(url.to_string(), CoverState::Loading);
            spawn = true;
        }
        match cache.get_mut(url) {
            Some(CoverState::Ready(data)) => {
                let target_w = area.width;
                let target_h = area.height;
                if data.scaled_w != target_w || data.scaled_h != target_h {
                    let px_w = target_w as u32;
                    let px_h = (target_h as u32) * 2;
                    let thumb = image::imageops::resize(&data.img, px_w, px_h, image::imageops::FilterType::Lanczos3);
                    let mut lines = Vec::with_capacity(target_h as usize);
                    for row in 0..target_h {
                        let mut spans = Vec::with_capacity(target_w as usize);
                        let y_top = (row as u32) * 2;
                        let y_bot = y_top + 1;
                        for col in 0..target_w {
                            let p_top = thumb.get_pixel(col as u32, y_top);
                            let p_bot = thumb.get_pixel(col as u32, y_bot);
                            spans.push(Span::styled(
                                "▀",
                                Style::default()
                                    .fg(Color::Rgb(p_top[0], p_top[1], p_top[2]))
                                    .bg(Color::Rgb(p_bot[0], p_bot[1], p_bot[2])),
                            ));
                        }
                        lines.push(Line::from(spans));
                    }
                    data.scaled_w = target_w;
                    data.scaled_h = target_h;
                    data.lines = lines;
                }
                Some(data.lines.clone())
            }
            _ => None,
        }
    };

    if spawn {
        let u = url.to_string();
        std::thread::spawn(move || {
            let res = std::process::Command::new("curl")
                .args(["-s", "-L", "-m", "10", "-A", "Mozilla/5.0", &u])
                .output()
                .ok()
                .filter(|o| o.status.success())
                .and_then(|o| image::load_from_memory(&o.stdout).ok())
                .map(|img| img.to_rgb8());

            let mut cache = cover_cache().lock().unwrap_or_else(|e| e.into_inner());
            match res {
                Some(img) => {
                    cache.insert(u, CoverState::Ready(CoverData {
                        img,
                        scaled_w: 0,
                        scaled_h: 0,
                        lines: Vec::new(),
                    }));
                }
                None => {
                    cache.insert(u, CoverState::Failed);
                }
            }
        });
    }

    if let Some(lines) = lines_to_draw {
        f.render_widget(Paragraph::new(lines), area);
    } else {
        let is_failed = {
            let cache = cover_cache().lock().unwrap_or_else(|e| e.into_inner());
            matches!(cache.get(url), Some(CoverState::Failed))
        };
        let label = if is_failed { "No Cover" } else { "◌ Loading..." };
        let border_color = if is_failed { Color::Rgb(60, 60, 60) } else { accent };
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL)
            .border_style(Style::default().fg(border_color));
        let p = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled(label, Style::default().fg(border_color))),
        ])
        .block(block)
        .alignment(Alignment::Center);
        f.render_widget(p, area);
    }
}