audium 1.2.1

A terminal music app
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
use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use rand::seq::SliceRandom;
use ratatui::DefaultTerminal;
use std::time::{Duration, Instant};

use crate::{
    cli::Cli,
    filepicker::{FilePicker, FilePickerOutcome},
    library::{ALL_TRACKS_ID, Library, PlaylistId, Track, TrackId},
    lyrics,
    modal::{Modal, ModalConfirm, ModalOutcome, RemoveTarget, TextInput, make_lyrics_textarea},
    player::{PlayerEvent, PlayerHandle, resolve_duration, spawn_audio_thread},
    settings::Settings,
    ui,
    ui::layout::{Theme, theme_by_name},
};

// ── Playback speed ─────────────────────────────────────────────────────────

const SPEED_STEP: f32 = 0.05;
const SPEED_MIN: f32 = 0.05;
const SPEED_MAX: f32 = 3.0;

// - LoopMode -

/// Playback loop mode, cycled with `l`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LoopMode {
    #[default]
    Off,
    /// Restart from the first queue entry when the last track finishes.
    Queue,
    /// Replay the current track indefinitely.
    Track,
}

impl LoopMode {
    pub fn cycle(self) -> Self {
        match self {
            Self::Off => Self::Queue,
            Self::Queue => Self::Track,
            Self::Track => Self::Off,
        }
    }
}

// ── Focus ──────────────────────────────────────────────────────────────────

/// Which panel currently owns keyboard focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Focus {
    Sidebar,
    TrackList,
    Queue,
}

impl Focus {
    pub fn cycle(self) -> Self {
        match self {
            Self::Sidebar => Self::TrackList,
            Self::TrackList => Self::Queue,
            Self::Queue => Self::Sidebar,
        }
    }
}

// ── AppState ───────────────────────────────────────────────────────────────

pub struct AppState {
    pub library: Library,
    pub player: PlayerHandle,

    // ── UI ──────────────────────────────────────────────────────────────
    pub focus: Focus,

    /// Which playlist is currently displayed in the tracklist panel.
    pub active_playlist: PlaylistId,

    /// Cursor inside the sidebar (playlist list).
    pub sidebar_cursor: usize,
    /// Cursor inside the tracklist (tracks of `active_playlist`).
    pub tracklist_cursor: usize,
    /// Cursor inside the queue panel.
    pub queue_cursor: usize,

    // ── Playback queue ──────────────────────────────────────────────────
    /// Ephemeral ordered list of tracks waiting to be played.
    pub queue: Vec<Track>,
    /// Index of the currently playing track inside `queue`, if any.
    pub now_playing: Option<usize>,

    // ── Progress tracking ───────────────────────────────────────────────
    pub track_start: Option<Instant>,
    pub seek_offset: Duration,
    pub track_duration: Option<Duration>,

    // ── Overlay state ───────────────────────────────────────────────────
    pub modal: Option<Modal>,
    pub file_picker: Option<FilePicker>,
    pub loop_mode: LoopMode,
    pub theme: Theme,
    pub settings: Settings,
    pub should_quit: bool,

    // ── Tracklist filter ─────────────────────────────────────────────────
    /// Current filter string applied to the active playlist's track list.
    pub tracklist_filter: String,
    /// Whether the filter bar is currently receiving keyboard input.
    pub filter_active: bool,

    // ── Lyrics overlay ───────────────────────────────────────────────────
    /// Whether the lyrics overlay is visible.
    pub show_lyrics: bool,
    /// Manual scroll offset for plain-text (unsynced) lyrics.
    pub lyrics_scroll: usize,
    /// Pre-parsed lyrics for the current track — updated on open/track-change/save.
    pub lyrics_lines: Vec<lyrics::LyricLine>,
    /// Cached track IDs for the active playlist + filter — rebuilt on every mutation.
    filtered_ids: Vec<TrackId>,
}

impl AppState {
    pub fn new(library: Library, player: PlayerHandle, settings: Settings) -> Self {
        let mut theme = theme_by_name(&settings.theme_name).clone();
        theme.transparent = settings.transparent;
        let mut s = Self {
            library,
            player,
            focus: Focus::Sidebar,
            active_playlist: ALL_TRACKS_ID,
            sidebar_cursor: 0,
            tracklist_cursor: 0,
            queue_cursor: 0,
            queue: Vec::new(),
            now_playing: None,
            track_start: None,
            seek_offset: Duration::ZERO,
            track_duration: None,
            modal: None,
            file_picker: None,
            loop_mode: LoopMode::Off,
            theme,
            settings,
            should_quit: false,
            tracklist_filter: String::new(),
            filter_active: false,
            show_lyrics: false,
            lyrics_scroll: 0,
            lyrics_lines: Vec::new(),
            filtered_ids: Vec::new(),
        };
        s.rebuild_filter_cache();
        s
    }

    // ── Progress ─────────────────────────────────────────────────────────

    pub fn elapsed(&self) -> Duration {
        if self.now_playing.is_none() {
            return Duration::ZERO;
        }
        if self.player.is_paused {
            return self.seek_offset;
        }
        let wall = self
            .track_start
            .map(|s| s.elapsed())
            .unwrap_or(Duration::ZERO);
        self.seek_offset + wall.mul_f32(self.player.playback_speed)
    }

    pub fn progress_ratio(&self) -> f64 {
        let elapsed = self.elapsed().as_secs_f64();
        match self.track_duration {
            Some(d) if d.as_secs_f64() > 0.0 => (elapsed / d.as_secs_f64()).clamp(0.0, 1.0),
            _ => 0.0,
        }
    }

    // ── Queue helpers ─────────────────────────────────────────────────────

    pub fn enqueue(&mut self, track: Track) {
        self.queue.push(track);
    }

    /// Starts playing `queue[idx]`.  The duration is resolved synchronously
    /// from the file headers on the UI thread (fast; just reads a few bytes).
    pub fn play_queue_index(&mut self, idx: usize) {
        if idx >= self.queue.len() {
            return;
        }
        let path = self.queue[idx].path.clone();
        self.player.play(path.clone());
        self.now_playing = Some(idx);
        self.track_start = Some(Instant::now());
        self.seek_offset = Duration::ZERO;
        self.track_duration = resolve_duration(&path);
        if self.show_lyrics {
            self.lyrics_scroll = 0;
            self.refresh_lyrics_cache();
        }
    }

    pub fn play_next(&mut self) {
        match self.loop_mode {
            LoopMode::Track => {
                // Replay the same index; if now_playing is somehow None,
                // fall back to starting from 0.
                let idx = self.now_playing.unwrap_or(0);
                self.play_queue_index(idx);
            }
            LoopMode::Queue => {
                let next = self.now_playing.map(|i| i + 1).unwrap_or(0);
                // Wrap around to the first track instead of halting.
                let idx = if next < self.queue.len() { next } else { 0 };
                if !self.queue.is_empty() {
                    self.play_queue_index(idx);
                }
            }
            LoopMode::Off => {
                let next = self.now_playing.map(|i| i + 1).unwrap_or(0);
                if next < self.queue.len() {
                    self.play_queue_index(next);
                } else {
                    self.halt_playback();
                }
            }
        }
    }

    pub fn play_prev(&mut self) {
        match self.loop_mode {
            LoopMode::Track => {
                let idx = self.now_playing.unwrap_or(0);
                self.play_queue_index(idx);
            }
            LoopMode::Queue => {
                if !self.queue.is_empty() {
                    let idx = match self.now_playing {
                        None | Some(0) => self.queue.len() - 1,
                        Some(i) => i - 1,
                    };
                    self.play_queue_index(idx);
                }
            }
            LoopMode::Off => {
                if let Some(cur) = self.now_playing
                    && cur > 0
                {
                    self.play_queue_index(cur - 1);
                }
            }
        }
    }

    /// Stops playback and resets all progress state to idle.
    /// Use this everywhere a track is forcibly interrupted (removal, queue
    /// exhaustion, etc.) so the player bar always shows a clean 0:00 / -:--.
    fn halt_playback(&mut self) {
        self.now_playing = None;
        self.track_start = None;
        self.seek_offset = Duration::ZERO;
        self.track_duration = None;
        self.player.stop();
    }

    // ── Active playlist helpers ──────────────────────────────────────────

    /// Rebuilds the filtered track ID cache. Call after any change to the
    /// active playlist, filter string, or library track list.
    pub fn rebuild_filter_cache(&mut self) {
        let all = self.library.playlist_tracks(self.active_playlist);
        if self.tracklist_filter.is_empty() {
            self.filtered_ids = all.iter().map(|t| t.id).collect();
            return;
        }
        let q = self.tracklist_filter.to_lowercase();
        self.filtered_ids = all
            .iter()
            .filter(|t| {
                t.name.to_lowercase().contains(&q)
                    || t.artist
                        .as_deref()
                        .is_some_and(|s| s.to_lowercase().contains(&q))
                    || t.album
                        .as_deref()
                        .is_some_and(|s| s.to_lowercase().contains(&q))
                    || t.genre
                        .as_deref()
                        .is_some_and(|s| s.to_lowercase().contains(&q))
                    || t.year.is_some_and(|y| y.to_string().contains(&*q))
            })
            .map(|t| t.id)
            .collect();
    }

    /// Returns the filtered tracks for the active playlist from the cached ID list.
    pub fn active_tracks(&self) -> Vec<&Track> {
        self.filtered_ids
            .iter()
            .filter_map(|&id| self.library.track(id))
            .collect()
    }

    fn selected_track(&self) -> Option<Track> {
        self.active_tracks()
            .get(self.tracklist_cursor)
            .map(|t| (*t).clone())
    }

    // ── Tick ─────────────────────────────────────────────────────────────

    /// Processes player events and auto-advances on natural track end.
    pub fn tick(&mut self) {
        for event in self.player.drain_events() {
            match event {
                PlayerEvent::TrackFinished => self.play_next(),
                PlayerEvent::Error(msg) => {
                    self.modal = Some(Modal::Notify { message: msg });
                }
            }
        }
    }

    // ── Input ─────────────────────────────────────────────────────────────

    pub fn handle_key(&mut self, code: KeyCode, modifiers: KeyModifiers) {
        // ── Ctrl-C: same as 'q' (ask to quit, confirm on a second press) ──
        if code == KeyCode::Char('c') && modifiers.contains(KeyModifiers::CONTROL) {
            if matches!(self.modal, Some(Modal::ConfirmQuit)) {
                self.modal = None;
                self.apply_modal_confirm(ModalConfirm::Quit);
            } else {
                self.file_picker = None;
                self.modal = Some(Modal::ConfirmQuit);
            }
            return;
        }

        // ── File picker takes priority ────────────────────────────────
        if let Some(picker) = &mut self.file_picker {
            match picker.handle_key(code) {
                FilePickerOutcome::Continue => return,
                FilePickerOutcome::Dismissed => {
                    self.file_picker = None;
                    return;
                }
                FilePickerOutcome::Selected(path) => {
                    self.file_picker = None;
                    self.import_file(&path);
                    return;
                }
            }
        }

        // ── Modal intercepts next ─────────────────────────────────────
        if let Some(modal) = &mut self.modal {
            match modal.handle_key(code, modifiers) {
                ModalOutcome::Consumed => return,
                ModalOutcome::Dismissed => {
                    self.modal = None;
                    return;
                }
                ModalOutcome::Confirm(c) => {
                    if !matches!(c, ModalConfirm::PreviewTheme { .. }) {
                        self.modal = None;
                    }
                    self.apply_modal_confirm(c);
                    return;
                }
            }
        }

        // ── Lyrics overlay intercepts when visible, no modal open ───────────
        if self.show_lyrics && self.modal.is_none() && self.file_picker.is_none() {
            match code {
                KeyCode::Char('j') | KeyCode::Down => {
                    self.lyrics_scroll = self.lyrics_scroll.saturating_add(1);
                    return;
                }
                KeyCode::Char('k') | KeyCode::Up => {
                    self.lyrics_scroll = self.lyrics_scroll.saturating_sub(1);
                    return;
                }
                KeyCode::Esc | KeyCode::Char('y') => {
                    self.show_lyrics = false;
                    return;
                }
                _ => {}
            }
        }

        // ── Filter input (captures printable chars when active) ───────────
        if self.filter_active {
            match code {
                KeyCode::Esc => {
                    self.tracklist_filter.clear();
                    self.filter_active = false;
                    self.tracklist_cursor = 0;
                    self.rebuild_filter_cache();
                    return;
                }
                KeyCode::Backspace => {
                    self.tracklist_filter.pop();
                    self.tracklist_cursor = 0;
                    self.rebuild_filter_cache();
                    return;
                }
                KeyCode::Char(c) => {
                    self.tracklist_filter.push(c);
                    self.tracklist_cursor = 0;
                    self.rebuild_filter_cache();
                    return;
                }
                // Enter exits typing mode; falls through to action_enter below.
                KeyCode::Enter => {
                    self.filter_active = false;
                }
                // All other keys (navigation, playback shortcuts) fall through.
                _ => {}
            }
        }

        // ── Global keybindings ─────────────────────────────────────────
        match code {
            KeyCode::Char('q') => self.modal = Some(Modal::ConfirmQuit),
            KeyCode::Char('?') => self.modal = Some(Modal::Help),

            // Playback
            KeyCode::Char(' ') => self.action_toggle_play(),
            KeyCode::Char('n') => self.play_next(),
            KeyCode::Char('N') => self.play_prev(),
            KeyCode::Left => self.action_seek(-(self.settings.seek_step_secs as i64)),
            KeyCode::Right => self.action_seek(self.settings.seek_step_secs as i64),
            KeyCode::Char('+') | KeyCode::Char('=') => self.player.volume_up(),
            KeyCode::Char('-') => self.player.volume_down(),

            // Navigation
            KeyCode::Tab => {
                self.focus = self.focus.cycle();
                self.filter_active = false;
                self.tracklist_filter.clear();
                self.tracklist_cursor = 0;
                self.rebuild_filter_cache();
            }
            KeyCode::Char('j') | KeyCode::Down => self.cursor_down(),
            KeyCode::Char('k') | KeyCode::Up => self.cursor_up(),

            // Context actions
            KeyCode::Enter => self.action_enter(),
            KeyCode::Char('a') => self.action_add_to_queue(),
            KeyCode::Char('p') => self.action_add_to_playlist(),
            KeyCode::Char('d') => self.action_remove(),
            KeyCode::Char('r') => self.action_rename(),
            KeyCode::Char('c') => self.action_new_playlist(),
            KeyCode::Char('f') => self.action_open_filepicker(),
            KeyCode::Char('m') => self.action_open_menu(),
            KeyCode::Char('l') => self.loop_mode = self.loop_mode.cycle(),
            KeyCode::Char('z') => self.action_shuffle_playlist(),
            KeyCode::Char('[') => self.action_speed_down(),
            KeyCode::Char(']') => self.action_speed_up(),
            KeyCode::Char('e') => self.action_edit_metadata(),
            KeyCode::Char('y') => self.action_toggle_lyrics(),
            KeyCode::Char('/') if self.focus == Focus::TrackList => {
                self.filter_active = true;
            }

            _ => {}
        }
    }

    // ── Cursor movement ───────────────────────────────────────────────────

    fn cursor_down(&mut self) {
        match self.focus {
            Focus::Sidebar => {
                let len = self.library.playlists.len();
                if len > 0 {
                    self.sidebar_cursor = (self.sidebar_cursor + 1).min(len - 1);
                    self.sync_active_playlist();
                }
            }
            Focus::TrackList => {
                let len = self.active_tracks().len();
                if len > 0 {
                    self.tracklist_cursor = (self.tracklist_cursor + 1).min(len - 1);
                }
            }
            Focus::Queue => {
                let len = self.queue.len();
                if len > 0 {
                    self.queue_cursor = (self.queue_cursor + 1).min(len - 1);
                }
            }
        }
    }

    fn cursor_up(&mut self) {
        match self.focus {
            Focus::Sidebar => {
                self.sidebar_cursor = self.sidebar_cursor.saturating_sub(1);
                self.sync_active_playlist();
            }
            Focus::TrackList => {
                self.tracklist_cursor = self.tracklist_cursor.saturating_sub(1);
            }
            Focus::Queue => {
                self.queue_cursor = self.queue_cursor.saturating_sub(1);
            }
        }
    }

    /// Keeps `active_playlist` in sync with `sidebar_cursor`.
    fn sync_active_playlist(&mut self) {
        if let Some(pl) = self.library.playlists.get(self.sidebar_cursor) {
            self.active_playlist = pl.id;
            self.tracklist_cursor = 0;
            self.tracklist_filter.clear();
            self.filter_active = false;
            self.rebuild_filter_cache();
        }
    }

    // ── Actions ───────────────────────────────────────────────────────────

    fn action_toggle_play(&mut self) {
        if self.now_playing.is_none() {
            if !self.queue.is_empty() {
                self.play_queue_index(0);
            }
        } else if self.player.is_paused {
            // Currently paused → resume.
            self.track_start = Some(Instant::now());
            self.player.resume();
        } else {
            // Currently playing → pause.
            // Snapshot elapsed before setting is_paused so elapsed() still
            // accumulates track_start.elapsed() during this call.
            self.seek_offset = self.elapsed();
            self.track_start = None;
            self.player.pause();
        }
    }

    /// Seek by `delta_secs` seconds (negative = rewind, positive = forward).
    /// No-op if nothing is playing or the track path is unavailable.
    fn action_seek(&mut self, delta_secs: i64) {
        let idx = match self.now_playing {
            Some(i) => i,
            None => return,
        };
        let path = match self.queue.get(idx) {
            Some(t) => t.path.clone(),
            None => return,
        };

        // Compute new position, clamped to [0, duration].
        let current = self.elapsed().as_secs() as i64;
        let max_secs = self
            .track_duration
            .map(|d| d.as_secs().saturating_sub(1) as i64)
            .unwrap_or(i64::MAX);
        let target_secs = (current + delta_secs).clamp(0, max_secs) as u64;
        let target = Duration::from_secs(target_secs);

        // Update UI-side clock immediately so the bar moves on the next frame.
        self.seek_offset = target;
        self.track_start = if self.player.is_paused {
            None
        } else {
            Some(Instant::now())
        };

        // Tell the audio thread to reopen, seek, and continue (or stay paused).
        self.player.seek(path, target, self.player.is_paused);
    }

    /// Enter on tracklist  →  play immediately (inserts after current).
    /// Enter on queue      →  play that queue entry immediately.
    fn action_enter(&mut self) {
        match self.focus {
            Focus::Sidebar => {
                self.sync_active_playlist();
                self.focus = Focus::TrackList;
            }
            Focus::TrackList => {
                if let Some(track) = self.selected_track() {
                    let insert_at = self.now_playing.map(|i| i + 1).unwrap_or(0);
                    self.queue.insert(insert_at, track);
                    self.play_queue_index(insert_at);
                }
            }
            Focus::Queue => {
                let idx = self.queue_cursor;
                self.play_queue_index(idx);
            }
        }
    }

    fn action_add_to_queue(&mut self) {
        if let Some(track) = self.selected_track() {
            self.queue.push(track);
        }
    }

    fn action_add_to_playlist(&mut self) {
        if let Some(track) = self.selected_track() {
            let choices: Vec<(u64, String)> = self
                .library
                .playlists
                .iter()
                .filter(|p| p.id != ALL_TRACKS_ID)
                .map(|p| (p.id, p.name.clone()))
                .collect();

            self.modal = Some(Modal::AddToPlaylist {
                track_id: track.id,
                track_name: track.name,
                choices,
                cursor: 0,
            });
        }
    }

    fn action_remove(&mut self) {
        match self.focus {
            Focus::Sidebar => {
                if let Some(pl) = self.library.playlists.get(self.sidebar_cursor) {
                    if pl.id == ALL_TRACKS_ID {
                        return; // cannot delete "All Tracks"
                    }
                    self.modal = Some(Modal::ConfirmRemove {
                        description: format!("Delete playlist \"{}\"?", pl.name),
                        target: RemoveTarget::Playlist { playlist_id: pl.id },
                    });
                }
            }
            Focus::TrackList => {
                if let Some(track) = self.selected_track() {
                    self.modal = Some(Modal::ConfirmRemove {
                        description: format!("Remove \"{}\" from library?", track.name),
                        target: RemoveTarget::TrackFromLibrary { track_id: track.id },
                    });
                }
            }
            Focus::Queue => {
                if self.queue_cursor < self.queue.len() {
                    self.modal = Some(Modal::ConfirmRemove {
                        description: "Remove this track from the queue?".into(),
                        target: RemoveTarget::TrackFromQueue {
                            queue_idx: self.queue_cursor,
                        },
                    });
                }
            }
        }
    }

    fn action_rename(&mut self) {
        match self.focus {
            Focus::Sidebar => {
                if let Some(pl) = self.library.playlists.get(self.sidebar_cursor) {
                    if pl.id == ALL_TRACKS_ID {
                        return;
                    }
                    self.modal = Some(Modal::Rename {
                        kind: "Playlist".into(),
                        id: pl.id,
                        input: TextInput::with_value(&pl.name),
                    });
                }
            }
            Focus::TrackList => {
                if let Some(t) = self.selected_track() {
                    self.modal = Some(Modal::Rename {
                        kind: "Track".into(),
                        id: t.id,
                        input: TextInput::with_value(&t.name),
                    });
                }
            }
            Focus::Queue => {
                if let Some(t) = self.queue.get(self.queue_cursor).cloned() {
                    self.modal = Some(Modal::Rename {
                        kind: "Track".into(),
                        id: t.id,
                        input: TextInput::with_value(&t.name),
                    });
                }
            }
        }
    }

    fn action_new_playlist(&mut self) {
        self.modal = Some(Modal::NewPlaylist {
            input: TextInput::default(),
        });
    }

    fn action_open_filepicker(&mut self) {
        let start = std::env::var_os("HOME")
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|| "/".into());
        self.file_picker = Some(FilePicker::new(start));
    }

    fn action_open_menu(&mut self) {
        self.modal = Some(Modal::Menu { cursor: 0 });
    }

    fn open_settings(&mut self) {
        let vol_pct = (self.settings.default_volume * 100.0).round() as u32;
        let preview_theme_idx = crate::ui::layout::themes()
            .iter()
            .position(|t| t.name == self.settings.theme_name.as_str())
            .unwrap_or(0);
        self.modal = Some(Modal::Settings {
            cursor: 0,
            volume_pct: vol_pct,
            seek_secs: self.settings.seek_step_secs,
            preview_theme_idx,
            transparent: self.settings.transparent,
        });
    }

    fn open_about(&mut self) {
        self.modal = Some(Modal::About);
    }

    /// `z` — prompt to shuffle the active playlist into the queue.
    fn action_shuffle_playlist(&mut self) {
        if let Some(pl) = self.library.playlist(self.active_playlist) {
            if pl.tracks.is_empty() {
                return;
            }
            self.modal = Some(Modal::ShufflePlaylist {
                playlist_id: pl.id,
                playlist_name: pl.name.clone(),
            });
        }
    }

    // ── Playback speed ────────────────────────────────────────────────────

    fn action_speed_up(&mut self) {
        let new = ((self.player.playback_speed + SPEED_STEP) * 100.0).round() / 100.0;
        self.change_speed(new.min(SPEED_MAX));
    }

    fn action_speed_down(&mut self) {
        let new = ((self.player.playback_speed - SPEED_STEP) * 100.0).round() / 100.0;
        self.change_speed(new.max(SPEED_MIN));
    }

    fn change_speed(&mut self, new_speed: f32) {
        if (new_speed - self.player.playback_speed).abs() < 0.001 {
            return;
        }
        // Snapshot track position with the OLD speed before changing.
        let current_pos = if self.now_playing.is_some() {
            Some(self.elapsed())
        } else {
            None
        };
        self.player.playback_speed = new_speed;
        // Re-seek to the same position so the new speed takes effect immediately.
        if let Some(pos) = current_pos
            && let Some(np) = self.now_playing
            && let Some(track) = self.queue.get(np)
        {
            let path = track.path.clone();
            let paused = self.player.is_paused;
            self.seek_offset = pos;
            self.track_start = if paused { None } else { Some(Instant::now()) };
            self.player.seek(path, pos, paused);
        }
    }

    // ── Metadata / lyrics actions ─────────────────────────────────────────

    fn selected_track_for_edit(&self) -> Option<Track> {
        match self.focus {
            Focus::TrackList => self.selected_track(),
            Focus::Queue => self.queue.get(self.queue_cursor).cloned(),
            Focus::Sidebar => None,
        }
    }

    fn action_edit_metadata(&mut self) {
        if let Some(t) = self.selected_track_for_edit() {
            self.modal = Some(Modal::EditMetadata {
                track_id: t.id,
                fields: [
                    TextInput::with_value(&t.name),
                    TextInput::with_value(t.artist.as_deref().unwrap_or("")),
                    TextInput::with_value(t.album.as_deref().unwrap_or("")),
                    TextInput::with_value(t.year.map(|y| y.to_string()).unwrap_or_default()),
                    TextInput::with_value(t.genre.as_deref().unwrap_or("")),
                ],
                active_field: 0,
                year_error: false,
            });
        }
    }

    fn refresh_lyrics_cache(&mut self) {
        self.lyrics_lines = self
            .now_playing
            .and_then(|i| self.queue.get(i))
            .and_then(|t| self.library.track(t.id))
            .and_then(|t| t.lyrics.as_ref())
            .map(|raw| lyrics::parse_lrc(raw))
            .unwrap_or_default();
    }

    fn sync_queue_name(&mut self, track_id: TrackId, name: &str) {
        for t in &mut self.queue {
            if t.id == track_id {
                t.name = name.to_string();
            }
        }
    }

    fn sync_queue_metadata(
        &mut self,
        track_id: TrackId,
        name: &str,
        artist: &Option<String>,
        album: &Option<String>,
        year: Option<u32>,
        genre: &Option<String>,
    ) {
        for t in &mut self.queue {
            if t.id == track_id {
                t.name = name.to_string();
                t.artist = artist.clone();
                t.album = album.clone();
                t.year = year;
                t.genre = genre.clone();
            }
        }
    }

    fn action_edit_lyrics(&mut self, track_id: TrackId) {
        let raw = self
            .library
            .track(track_id)
            .and_then(|t| t.lyrics.as_deref())
            .unwrap_or("")
            .to_string();
        self.modal = Some(Modal::EditLyrics {
            track_id,
            textarea: make_lyrics_textarea(&raw),
        });
    }

    fn action_toggle_lyrics(&mut self) {
        if let Some(np) = self.now_playing.and_then(|i| self.queue.get(i)) {
            let has_lyrics = self
                .library
                .track(np.id)
                .and_then(|t| t.lyrics.as_ref())
                .is_some();
            if has_lyrics {
                self.show_lyrics = !self.show_lyrics;
                if self.show_lyrics {
                    self.lyrics_scroll = 0;
                    self.refresh_lyrics_cache();
                }
            } else {
                self.show_lyrics = false;
                self.modal = Some(Modal::Notify {
                    message: "No lyrics for this track — press e to edit metadata and add them."
                        .into(),
                });
            }
        } else {
            self.show_lyrics = false;
            self.modal = Some(Modal::Notify {
                message: "Nothing is playing.".into(),
            });
        }
    }

    // ── Modal confirm handler ─────────────────────────────────────────────

    fn apply_modal_confirm(&mut self, confirm: ModalConfirm) {
        match confirm {
            ModalConfirm::Remove(target) => match target {
                RemoveTarget::TrackFromQueue { queue_idx } => {
                    if queue_idx < self.queue.len() {
                        self.queue.remove(queue_idx);
                        if let Some(np) = self.now_playing {
                            if queue_idx < np {
                                self.now_playing = Some(np - 1);
                            } else if queue_idx == np {
                                self.halt_playback();
                            }
                        }

                        self.queue_cursor =
                            self.queue_cursor.min(self.queue.len().saturating_sub(1));
                    }
                }

                RemoveTarget::TrackFromLibrary { track_id } => {
                    let _ = self.library.remove_track(track_id);

                    let playing_removed = self
                        .now_playing
                        .and_then(|np| self.queue.get(np))
                        .map(|t| t.id == track_id)
                        .unwrap_or(false);
                    let removed_before_np = self
                        .now_playing
                        .map(|np| self.queue[..np].iter().filter(|t| t.id == track_id).count())
                        .unwrap_or(0);

                    self.queue.retain(|t| t.id != track_id);

                    if playing_removed {
                        self.halt_playback();
                    } else if removed_before_np > 0
                        && let Some(np) = self.now_playing.as_mut()
                    {
                        *np -= removed_before_np;
                    }

                    self.queue_cursor = self.queue_cursor.min(self.queue.len().saturating_sub(1));
                    self.rebuild_filter_cache();
                    self.tracklist_cursor = self
                        .tracklist_cursor
                        .min(self.active_tracks().len().saturating_sub(1));
                }

                RemoveTarget::Playlist { playlist_id } => {
                    let _ = self.library.delete_playlist(playlist_id);
                    self.sidebar_cursor = self
                        .sidebar_cursor
                        .min(self.library.playlists.len().saturating_sub(1));
                    self.sync_active_playlist();
                }
            },

            ModalConfirm::Rename { kind, id, new_name } => {
                if kind == "Track" {
                    let _ = self.library.rename_track(id, &new_name);
                    self.sync_queue_name(id, &new_name);
                    self.rebuild_filter_cache();
                } else {
                    let _ = self.library.rename_playlist(id, new_name);
                }
            }

            ModalConfirm::NewPlaylist { name } => {
                let _ = self.library.create_playlist(name);
            }

            ModalConfirm::AddToPlaylist {
                track_id,
                playlist_id,
            } => {
                let _ = self.library.playlist_add_track(playlist_id, track_id);
                self.rebuild_filter_cache();
            }

            ModalConfirm::OpenSettings => {
                self.open_settings();
            }

            ModalConfirm::OpenAbout => {
                self.open_about();
            }

            ModalConfirm::Quit => {
                self.should_quit = true;
            }

            ModalConfirm::SaveSettings {
                volume_pct,
                seek_secs,
                theme_name,
                transparent,
            } => {
                self.settings.set_default_volume(volume_pct as f32 / 100.0);
                self.settings.set_seek_step_secs(seek_secs);
                self.settings.set_theme(&theme_name);
                self.settings.transparent = transparent;
                // Apply theme and transparency live.
                let mut t = theme_by_name(&theme_name).clone();
                t.transparent = transparent;
                self.theme = t;
                let _ = self.settings.save();
            }

            ModalConfirm::PreviewTheme {
                theme_name,
                transparent,
            } => {
                let mut t = theme_by_name(&theme_name).clone();
                t.transparent = transparent;
                self.theme = t;
            }

            ModalConfirm::ShufflePlaylist { playlist_id } => {
                // Resolve tracks, shuffle in place, replace queue, start playing.
                let mut tracks: Vec<Track> = self
                    .library
                    .playlist_tracks(playlist_id)
                    .into_iter()
                    .cloned()
                    .collect();

                if tracks.is_empty() {
                    return;
                }

                tracks.shuffle(&mut rand::rng());

                self.halt_playback();
                self.queue = tracks;
                self.queue_cursor = 0;
                self.play_queue_index(0);
            }

            ModalConfirm::SaveMetadata {
                track_id,
                name,
                artist,
                album,
                year,
                genre,
            } => {
                let _ = self.library.update_track_metadata(
                    track_id,
                    name.clone(),
                    artist.clone(),
                    album.clone(),
                    year,
                    genre.clone(),
                );
                self.sync_queue_metadata(track_id, &name, &artist, &album, year, &genre);
                self.rebuild_filter_cache();
            }

            ModalConfirm::SaveLyrics { track_id, lyrics } => {
                let _ = self.library.set_track_lyrics(track_id, lyrics);
                if self.show_lyrics {
                    self.refresh_lyrics_cache();
                }
            }

            ModalConfirm::SaveMetadataAndEditLyrics {
                track_id,
                name,
                artist,
                album,
                year,
                genre,
            } => {
                let _ = self.library.update_track_metadata(
                    track_id,
                    name.clone(),
                    artist.clone(),
                    album.clone(),
                    year,
                    genre.clone(),
                );
                self.sync_queue_metadata(track_id, &name, &artist, &album, year, &genre);
                self.rebuild_filter_cache();
                self.action_edit_lyrics(track_id);
            }
        }
    }

    // ── File import ───────────────────────────────────────────────────────

    fn import_file(&mut self, path: &std::path::Path) {
        match self.library.add_file(path) {
            Ok((track, is_new)) => {
                self.rebuild_filter_cache();
                self.modal = Some(Modal::Notify {
                    message: if is_new {
                        format!("\"{}\" added to library.", track.name)
                    } else {
                        format!("\"{}\" is already in the library.", track.name)
                    },
                });
            }
            Err(e) => {
                self.modal = Some(Modal::Notify {
                    message: format!("Error importing file: {e}"),
                });
            }
        }
    }
}
// ── Entry point ────────────────────────────────────────────────────────────

pub fn run(cli: Cli) -> Result<()> {
    let mut library = Library::load()?;
    let settings = Settings::load();

    let initial_track: Option<(Track, bool)> = if let Some(file) = cli.file {
        let result = library.add_file(&file)?;
        Some(result)
    } else {
        None
    };

    let player = spawn_audio_thread(settings.default_volume)?;

    let mut state = AppState::new(library, player, settings);

    if let Some((track, is_new)) = initial_track {
        let msg = if is_new {
            format!("\"{}\" added to library.", track.name)
        } else {
            format!("\"{}\" is already in the library.", track.name)
        };
        state.enqueue(track);
        state.play_queue_index(0);
        state.modal = Some(Modal::Notify { message: msg });
    }

    let terminal = ratatui::init();
    let result = event_loop(terminal, &mut state);
    ratatui::restore();
    result
}

fn event_loop(mut terminal: DefaultTerminal, state: &mut AppState) -> Result<()> {
    loop {
        state.tick();
        terminal.draw(|frame| ui::render(frame, state))?;

        if event::poll(Duration::from_millis(50))?
            && let Event::Key(key) = event::read()?
            && key.kind == KeyEventKind::Press
        {
            state.handle_key(key.code, key.modifiers);
        }

        if state.should_quit {
            break;
        }
    }
    Ok(())
}