audium 2.0.0

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
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
use anyhow::Result;
use rand::seq::SliceRandom;
use ratatui::DefaultTerminal;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};

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

// -- Terminal color detection -----------------------------------------------

/// Best-effort detection of 24-bit truecolor support.
///
/// No portable query exists, so this uses the agreed heuristics: `NO_COLOR`
/// disables color, `TERM=linux`/`dumb` is 16-color, and `COLORTERM` is the
/// opt-in signal. Misdetection is recoverable from the settings menu.
fn detect_truecolor() -> bool {
    if std::env::var_os("NO_COLOR").is_some() {
        return false;
    }
    if let Ok("linux" | "dumb") = std::env::var("TERM").as_deref() {
        return false;
    }
    matches!(
        std::env::var("COLORTERM").as_deref(),
        Ok("truecolor" | "24bit")
    )
}

/// Resolves the live theme for the current color state. Each mode keeps its
/// own saved choice, and transparency applies only to the RGB themes, whose
/// backgrounds are real colors rather than the terminal default.
fn resolve_theme(
    theme_name: &str,
    console_theme_name: &str,
    transparent: bool,
    truecolor: bool,
) -> Theme {
    if truecolor {
        let mut t = theme_by_name(theme_name).clone();
        t.transparent = transparent;
        t
    } else {
        console_theme_by_name(console_theme_name).clone()
    }
}

// -- Playback speed ---------------------------------------------------------

const SPEED_STEP: f32 = 0.01;
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, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
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 const fn cycle(self) -> Self {
        match self {
            Self::Off => Self::Queue,
            Self::Queue => Self::Track,
            Self::Track => Self::Off,
        }
    }
}

// -- Focus ------------------------------------------------------------------

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

impl Focus {
    /// Tab order, one stop per drawn frame.
    pub const fn cycle(self) -> Self {
        match self {
            Self::Library => Self::Playlists,
            Self::Playlists => Self::TrackList,
            Self::TrackList => Self::Queue,
            Self::Queue => Self::Library,
        }
    }

    /// Shift+Tab: the same ring walked backwards.
    pub const fn cycle_back(self) -> Self {
        match self {
            Self::Library => Self::Queue,
            Self::Playlists => Self::Library,
            Self::TrackList => Self::Playlists,
            Self::Queue => Self::TrackList,
        }
    }

    /// Whether this panel selects what the tracklist shows.
    pub const fn is_sidebar(self) -> bool {
        matches!(self, Self::Library | Self::Playlists)
    }
}

// -- AppState ---------------------------------------------------------------

/// What the sidebar cursor can point at. The library is not a playlist, so it
/// gets its own variant instead of a reserved playlist id.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SidebarItem {
    Library,
    Playlist(PlaylistId),
}

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

    // -- UI --------------------------------------------------------------
    pub focus: Focus,

    /// What the tracklist panel is showing.
    pub active_view: SidebarItem,

    /// Cursor inside the playlists frame; indexes `library.playlists`.
    pub playlist_cursor: usize,
    /// Cursor inside the tracklist (tracks of `active_view`).
    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 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 theme = resolve_theme(
            &settings.theme_name,
            &settings.console_theme_name,
            settings.transparent,
            settings.color_mode.truecolor(detect_truecolor()),
        );
        let mut s = Self {
            library,
            player,
            focus: Focus::Library,
            active_view: SidebarItem::Library,
            playlist_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_or(Duration::ZERO, |s| s.elapsed());
        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);
    }

    /// Captures the current playback session for `$XDG_STATE_HOME`.
    pub fn snapshot_state(&self) -> crate::state::PlaybackState {
        crate::state::PlaybackState::new(
            self.queue.iter().map(Track::filename).collect(),
            self.now_playing,
            self.elapsed().as_secs(),
            self.loop_mode,
            self.player.playback_speed,
            self.player.volume,
        )
    }

    /// Restores a saved session, with the current track loaded but *paused* at
    /// its position: launching audium never suddenly makes sound. Entries
    /// whose file is gone are dropped, and `now_playing` follows its track.
    pub fn restore_state(&mut self, saved: &crate::state::PlaybackState) {
        let mut queue = Vec::with_capacity(saved.queue.len());
        let mut now_playing = None;
        for (i, name) in saved.queue.iter().enumerate() {
            if let Some(track) = self.library.track_by_filename(name) {
                if saved.now_playing == Some(i) {
                    now_playing = Some(queue.len());
                }
                queue.push(track.clone());
            }
        }
        self.queue = queue;
        self.queue_cursor = now_playing.unwrap_or(0);
        self.loop_mode = saved.loop_mode;
        self.player.set_speed(saved.speed);
        self.player.set_volume(saved.volume);

        if let Some(idx) = now_playing {
            let track = &self.queue[idx];
            let path = track.path.clone();
            let pos = Duration::from_secs(saved.position_secs);
            self.now_playing = Some(idx);
            self.track_duration = resolve_duration(&path);
            self.seek_offset = pos;
            self.track_start = None; // paused
            self.player.is_paused = true;
            // held paused so Space resumes from here instantly
            self.player.seek(path, pos, true);
        }
    }

    /// Starts playing `queue[idx]`. The duration is resolved on the UI thread,
    /// which is fine: it reads a few header 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 => {
                let idx = self.now_playing.unwrap_or(0);
                self.play_queue_index(idx);
            }
            LoopMode::Queue => {
                let next = self.now_playing.map_or(0, |i| i + 1);
                // wrap 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_or(0, |i| i + 1);
                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 progress to idle. Use wherever a track is
    /// interrupted, 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();
    }

    // -- Sidebar / active view helpers ------------------------------------

    /// The playlist under the playlists-frame cursor.
    fn cursor_playlist_id(&self) -> Option<PlaylistId> {
        self.library
            .playlists
            .get(self.playlist_cursor)
            .map(|pl| pl.id)
    }

    /// The playlist the tracklist is showing, or `None` when it shows the
    /// whole library.
    pub const fn active_playlist_id(&self) -> Option<PlaylistId> {
        match self.active_view {
            SidebarItem::Library => None,
            SidebarItem::Playlist(id) => Some(id),
        }
    }

    /// Name for the tracklist panel. The library view says "All tracks"
    /// rather than "Library", already the sidebar frame's title.
    pub fn active_view_name(&self) -> &str {
        match self.active_view {
            SidebarItem::Library => "All tracks",
            SidebarItem::Playlist(id) => self
                .library
                .playlist(id)
                .map_or("Tracks", |pl| pl.name.as_str()),
        }
    }

    /// Tracks backing the active view, in display order.
    fn view_tracks(&self) -> Vec<&Track> {
        match self.active_view {
            SidebarItem::Library => self.library.tracks.iter().collect(),
            SidebarItem::Playlist(id) => self.library.playlist_tracks(id),
        }
    }

    /// Rebuilds the filtered track ID cache. Call after any change to the
    /// active view, filter string, or library track list.
    pub fn rebuild_filter_cache(&mut self) {
        let all = self.view_tracks();
        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))
            })
            .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.
    /// Returns whether anything changed, so the caller can skip a redraw.
    pub fn tick(&mut self) -> bool {
        let mut changed = false;
        for event in self.player.drain_events() {
            changed = true;
            match event {
                PlayerEvent::TrackFinished => self.play_next(),
                PlayerEvent::Error(msg) => {
                    self.modal = Some(Modal::Notify { message: msg });
                }
            }
        }
        changed
    }

    /// Whether the UI changes on its own right now -- the player bar's elapsed
    /// time and the synced-lyrics overlay both advance without any input.
    const fn is_animating(&self) -> bool {
        self.now_playing.is_some() && !self.player.is_paused
    }

    // -- Input -------------------------------------------------------------

    pub fn handle_key(&mut self, code: KeyCode, modifiers: KeyModifiers) {
        if self.handle_quit_shortcut(code, modifiers) {
            return;
        }
        // Ctrl+C is the only chord audium binds, and every other handler
        // matches the key alone, so without this a chord would land on the
        // same arm as the bare key -- including on destructive actions.
        if modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER) {
            return;
        }
        if self.handle_file_picker_key(code) {
            return;
        }
        if self.handle_modal_key(code, modifiers) {
            return;
        }
        if self.handle_lyrics_overlay_key(code) {
            return;
        }
        if self.handle_filter_key(code) {
            return;
        }
        self.handle_global_key(code);
    }

    // -- Ctrl-C: same as 'q' (ask to quit, confirm on a second press) ------
    fn handle_quit_shortcut(&mut self, code: KeyCode, modifiers: KeyModifiers) -> bool {
        if code != KeyCode::Char('c') || !modifiers.contains(KeyModifiers::CONTROL) {
            return false;
        }
        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);
        }
        true
    }

    // -- File picker takes priority over everything else -------------------
    fn handle_file_picker_key(&mut self, code: KeyCode) -> bool {
        let Some(picker) = &mut self.file_picker else {
            return false;
        };
        match picker.handle_key(code) {
            FilePickerOutcome::Continue => {}
            FilePickerOutcome::Dismissed => self.file_picker = None,
            FilePickerOutcome::Selected(path) => {
                self.file_picker = None;
                self.import_file(&path);
            }
        }
        true
    }

    // -- Modal intercepts next ----------------------------------------------
    fn handle_modal_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> bool {
        let Some(modal) = &mut self.modal else {
            return false;
        };
        match modal.handle_key(code, modifiers) {
            ModalOutcome::Consumed => {}
            ModalOutcome::Dismissed => self.modal = None,
            ModalOutcome::Confirm(c) => {
                if !matches!(c, ModalConfirm::PreviewTheme { .. }) {
                    self.modal = None;
                }
                self.apply_modal_confirm(c);
            }
        }
        true
    }

    // -- Lyrics overlay intercepts when visible, no modal open -------------
    fn handle_lyrics_overlay_key(&mut self, code: KeyCode) -> bool {
        if !self.show_lyrics || self.modal.is_some() || self.file_picker.is_some() {
            return false;
        }
        if let Some(new) = nav::list_move(code, self.lyrics_scroll, self.lyrics_lines.len()) {
            self.lyrics_scroll = new;
            return true;
        }
        match code {
            KeyCode::Esc | KeyCode::Char('y') => {
                self.show_lyrics = false;
                true
            }
            _ => false,
        }
    }

    // -- Filter input (captures printable chars when active) ---------------
    fn handle_filter_key(&mut self, code: KeyCode) -> bool {
        if !self.filter_active {
            return false;
        }
        match code {
            KeyCode::Esc => {
                self.tracklist_filter.clear();
                self.filter_active = false;
                self.tracklist_cursor = 0;
                self.rebuild_filter_cache();
                true
            }
            KeyCode::Backspace => {
                self.tracklist_filter.pop();
                self.tracklist_cursor = 0;
                self.rebuild_filter_cache();
                true
            }
            KeyCode::Char(c) => {
                self.tracklist_filter.push(c);
                self.tracklist_cursor = 0;
                self.rebuild_filter_cache();
                true
            }
            // exits typing mode, then falls through to action_enter
            KeyCode::Enter => {
                self.filter_active = false;
                false
            }
            // navigation and playback shortcuts fall through
            _ => false,
        }
    }

    // -- Global keybindings -------------------------------------------------
    fn handle_global_key(&mut self, code: KeyCode) {
        match code {
            KeyCode::Char('q') => self.modal = Some(Modal::ConfirmQuit),
            KeyCode::Char('?') => self.modal = Some(Modal::Help { scroll: 0 }),

            // 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.cast_signed()),
            KeyCode::Right => self.action_seek(self.settings.seek_step_secs.cast_signed()),
            KeyCode::Char('+' | '=') => self.player.volume_up(),
            KeyCode::Char('-') => self.player.volume_down(),

            // Navigation
            KeyCode::Tab | KeyCode::BackTab => {
                self.focus = if code == KeyCode::BackTab {
                    self.focus.cycle_back()
                } else {
                    self.focus.cycle()
                };
                self.filter_active = false;
                self.tracklist_filter.clear();
                self.tracklist_cursor = 0;
                self.rebuild_filter_cache();
                // landing on a sidebar frame points the tracklist at it
                self.sync_active_view();
            }
            KeyCode::Char('j' | 'k' | 'g' | 'G')
            | KeyCode::Up
            | KeyCode::Down
            | KeyCode::Home
            | KeyCode::End
            | KeyCode::PageUp
            | KeyCode::PageDown => {
                self.move_cursor(code);
            }

            // Context actions
            KeyCode::Enter => self.action_enter(),
            KeyCode::Char('J') => self.action_move_selection(true),
            KeyCode::Char('K') => self.action_move_selection(false),
            KeyCode::Char('a') => self.action_add_to_queue(),
            KeyCode::Char('p') => self.action_add_to_playlist(),
            KeyCode::Char('d') => self.action_remove(),
            KeyCode::Char('D') => self.action_clear_queue(),
            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(),
            KeyCode::Char('y') => self.action_toggle_lyrics(),
            KeyCode::Char('/') if self.focus == Focus::TrackList => {
                self.filter_active = true;
            }

            _ => {}
        }
    }

    // -- Cursor movement ---------------------------------------------------

    /// Moves the focused panel's cursor per the shared list keymap.
    /// Returns `true` if `code` was a navigation key.
    fn move_cursor(&mut self, code: KeyCode) -> bool {
        let (cursor, len) = match self.focus {
            // a single row: nothing to move between
            Focus::Library => (0, 1),
            Focus::Playlists => (self.playlist_cursor, self.library.playlists.len()),
            Focus::TrackList => (self.tracklist_cursor, self.active_tracks().len()),
            Focus::Queue => (self.queue_cursor, self.queue.len()),
        };
        let Some(new) = nav::list_move(code, cursor, len) else {
            return false;
        };
        match self.focus {
            Focus::Library => {}
            Focus::Playlists => {
                self.playlist_cursor = new;
                self.sync_active_view();
            }
            Focus::TrackList => self.tracklist_cursor = new,
            Focus::Queue => self.queue_cursor = new,
        }
        true
    }

    /// Points the tracklist at whichever sidebar frame has focus.
    /// A no-op from the tracklist or queue, which do not choose the view.
    fn sync_active_view(&mut self) {
        let item = match self.focus {
            Focus::Library => SidebarItem::Library,
            Focus::Playlists => match self.cursor_playlist_id() {
                Some(id) => SidebarItem::Playlist(id),
                None => return,
            },
            Focus::TrackList | Focus::Queue => return,
        };

        self.active_view = item;
        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 {
            // paused -> resume
            self.track_start = Some(Instant::now());
            self.player.resume();
        } else {
            // playing -> pause. Snapshot elapsed before setting is_paused, so
            // elapsed() still accumulates track_start 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 Some(idx) = self.now_playing else {
            return;
        };
        let Some(track) = self.queue.get(idx) else {
            return;
        };
        let path = track.path.clone();

        // clamped to [0, duration]
        let current = self.elapsed().as_secs().cast_signed();
        let max_secs = self
            .track_duration
            .map_or(i64::MAX, |d| d.as_secs().saturating_sub(1).cast_signed());
        let target_secs = (current + delta_secs).clamp(0, max_secs).cast_unsigned();
        let target = Duration::from_secs(target_secs);

        // updated UI-side at once, 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())
        };

        // the audio thread reopens, seeks, and continues or stays 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::Library | Focus::Playlists => {
                self.sync_active_view();
                self.focus = Focus::TrackList;
            }
            Focus::TrackList => {
                if let Some(track) = self.selected_track() {
                    let insert_at = self.now_playing.map_or(0, |i| i + 1);
                    self.queue.insert(insert_at, track);
                    self.play_queue_index(insert_at);
                }
            }
            Focus::Queue => {
                let idx = self.queue_cursor;
                self.play_queue_index(idx);
            }
        }
    }

    /// Appends to the queue, scoped to the focused panel: a whole playlist from
    /// the sidebar, the cursor's track from the tracklist. Queue entries are
    /// already queued, so there is nothing to add.
    fn action_add_to_queue(&mut self) {
        match self.focus {
            Focus::Library => {
                let tracks = self.library.tracks.clone();
                self.queue.extend(tracks);
            }
            Focus::Playlists => {
                let Some(id) = self.cursor_playlist_id() else {
                    return;
                };
                let tracks: Vec<Track> = self
                    .library
                    .playlist_tracks(id)
                    .into_iter()
                    .cloned()
                    .collect();
                self.queue.extend(tracks);
            }
            Focus::TrackList => {
                if let Some(track) = self.selected_track() {
                    self.queue.push(track);
                }
            }
            Focus::Queue => {}
        }
    }

    /// `J` / `K`: moves the selected track one place through a playlist or the
    /// queue, carrying the cursor with it.
    ///
    /// A filtered tracklist has no unambiguous order: the row above on screen
    /// may be many places away in the real list, so a swap would fling the
    /// track out of sight. Filtered views are left alone.
    fn action_move_selection(&mut self, down: bool) {
        match self.focus {
            Focus::TrackList => self.move_in_tracklist(down),
            Focus::Playlists => {
                if let Some(new) = self.library.move_playlist(self.playlist_cursor, down) {
                    self.playlist_cursor = new;
                    self.sync_active_view();
                }
            }
            Focus::Queue => self.move_in_queue(down),
            // a single row; nothing to reorder
            Focus::Library => {}
        }
    }

    /// Reorders the focused track list: a playlist's contents, or the whole
    /// library. Filtered views are skipped, see [`Self::action_move_selection`].
    fn move_in_tracklist(&mut self, down: bool) {
        if !self.tracklist_filter.is_empty() {
            return;
        }
        let moved = match self.active_view {
            SidebarItem::Library => self.library.move_track(self.tracklist_cursor, down),
            SidebarItem::Playlist(id) => {
                self.library
                    .playlist_move_track(id, self.tracklist_cursor, down)
            }
        };
        if let Some(new) = moved {
            self.tracklist_cursor = new;
            self.rebuild_filter_cache();
        }
    }

    /// Reorders the queue, keeping `now_playing` pointed at the same track:
    /// it is an index, so any swap that touches it has to move with it or the
    /// bar would start describing a different song.
    fn move_in_queue(&mut self, down: bool) {
        let from = self.queue_cursor;
        let Some(to) = (if down {
            from.checked_add(1).filter(|&i| i < self.queue.len())
        } else {
            from.checked_sub(1)
        }) else {
            return;
        };

        self.queue.swap(from, to);
        self.queue_cursor = to;
        if let Some(np) = self.now_playing {
            if np == from {
                self.now_playing = Some(to);
            } else if np == to {
                self.now_playing = Some(from);
            }
        }
    }

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

            // no playlists yet: skip the empty picker, create one, drop the
            // track into it
            self.modal = Some(if choices.is_empty() {
                Modal::NewPlaylist {
                    input: TextInput::default(),
                    add_track: Some(track.id),
                }
            } else {
                Modal::AddToPlaylist {
                    track_id: track.id,
                    track_name: track.name,
                    choices,
                    cursor: 0,
                }
            });
        }
    }

    fn action_remove(&mut self) {
        match self.focus {
            // only playlists are deletable
            Focus::Library => {}
            Focus::Playlists => {
                if let Some(pl) = self.library.playlists.get(self.playlist_cursor) {
                    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() {
                    // inside a playlist `d` scopes to that playlist
                    let (description, target) = match self.active_playlist_id() {
                        None => (
                            // deletes audium's copy: it has to stick, or the
                            // file re-imports on the next launch
                            format!("Delete \"{}\" from the library?", track.name),
                            RemoveTarget::TrackFromLibrary { track_id: track.id },
                        ),
                        Some(playlist_id) => {
                            let name = self
                                .library
                                .playlist(playlist_id)
                                .map_or_else(String::new, |pl| pl.name.clone());
                            (
                                format!("Remove \"{}\" from \"{name}\"?", track.name),
                                RemoveTarget::TrackFromPlaylist {
                                    playlist_id,
                                    track_id: track.id,
                                },
                            )
                        }
                    };
                    self.modal = Some(Modal::ConfirmRemove {
                        description,
                        target,
                    });
                }
            }
            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_clear_queue(&mut self) {
        if self.queue.is_empty() {
            return;
        }
        self.modal = Some(Modal::ConfirmRemove {
            description: "Clear the entire queue?".into(),
            target: RemoveTarget::Queue,
        });
    }

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

    fn action_open_filepicker(&mut self) {
        let start = std::env::var_os("HOME").map_or_else(|| "/".into(), std::path::PathBuf::from);
        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 = numeric::ratio_to_whole_percent(self.settings.default_volume);
        let preview_theme_idx = themes()
            .iter()
            .position(|t| t.name == self.settings.theme_name.as_str())
            .unwrap_or(0);
        let preview_console_idx = console_themes()
            .iter()
            .position(|t| t.name == self.settings.console_theme_name.as_str())
            .unwrap_or(0);
        self.modal = Some(Modal::Settings(SettingsState {
            cursor: 0,
            volume_pct: vol_pct,
            seek_secs: self.settings.seek_step_secs,
            resume_playback: self.settings.resume_playback,
            preview_theme_idx,
            preview_console_idx,
            transparent: self.settings.transparent,
            color_mode: self.settings.color_mode,
            detected_truecolor: detect_truecolor(),
        }));
    }

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

    /// `z`: prompt to shuffle the active view -- a playlist or the whole
    /// library -- into the queue.
    fn action_shuffle_playlist(&mut self) {
        if self.view_tracks().is_empty() {
            return;
        }
        self.modal = Some(Modal::ShuffleView {
            view_name: self.active_view_name().to_string(),
        });
    }

    // -- 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 the position at the OLD speed first
        let current_pos = if self.now_playing.is_some() {
            Some(self.elapsed())
        } else {
            None
        };
        // rebase on the old speed, then switch: the sink changes in place, so
        // there is no reopen and no gap
        if let Some(pos) = current_pos {
            self.seek_offset = pos;
            self.track_start = if self.player.is_paused {
                None
            } else {
                Some(Instant::now())
            };
        }
        self.player.set_speed(new_speed);
    }

    // -- Metadata / lyrics actions -----------------------------------------

    /// The track under the cursor in the focused panel. The sidebar selects
    /// playlists, not tracks, so it has none.
    fn focused_track(&self) -> Option<Track> {
        match self.focus {
            Focus::TrackList => self.selected_track(),
            Focus::Queue => self.queue.get(self.queue_cursor).cloned(),
            Focus::Library | Focus::Playlists => None,
        }
    }

    /// The one editor key: opens whatever the focused panel has selected.
    /// A playlist's only editable attribute is its name, so the sidebar gets a
    /// single-field dialog; tracks get the full metadata form.
    fn action_edit(&mut self) {
        if self.focus.is_sidebar() {
            self.action_edit_playlist();
            return;
        }
        self.action_edit_metadata();
    }

    /// The library has no editable attributes, so `e` only opens on a playlist.
    fn action_edit_playlist(&mut self) {
        if self.focus == Focus::Playlists
            && let Some(pl) = self.library.playlists.get(self.playlist_cursor)
        {
            self.modal = Some(Modal::EditPlaylist {
                id: pl.id,
                input: TextInput::with_value(&pl.name),
            });
        }
    }

    fn action_edit_metadata(&mut self) {
        if let Some(t) = self.focused_track() {
            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("")),
                ],
                active_field: 0,
                original_name: t.name,
            });
        }
    }

    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_metadata(
        &mut self,
        track_id: TrackId,
        name: &str,
        artist: Option<&String>,
        album: Option<&String>,
    ) {
        for t in &mut self.queue {
            if t.id == track_id {
                t.name = name.to_string();
                t.artist = artist.cloned();
                t.album = album.cloned();
            }
        }
    }

    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_remove(&mut self, target: RemoveTarget) {
        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))
                    .is_some_and(|t| t.id == track_id);
                let removed_before_np = self.now_playing.map_or(0, |np| {
                    self.queue[..np].iter().filter(|t| t.id == track_id).count()
                });

                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::TrackFromPlaylist {
                playlist_id,
                track_id,
            } => {
                let _ = self.library.playlist_remove_track(playlist_id, track_id);
                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.playlist_cursor = self
                    .playlist_cursor
                    .min(self.library.playlists.len().saturating_sub(1));
                self.sync_active_view();
            }

            RemoveTarget::Queue => {
                self.queue.clear();
                self.queue_cursor = 0;
                self.halt_playback();
            }
        }
    }

    /// Tells the user when an edit reached the library but not the file.
    ///
    /// The edit is not lost, being in `audium.json` and on screen, but the
    /// file is the record, so a rescan would revert it. Better to say so now
    /// than let the value quietly change back later.
    fn report_tag_failure(&mut self, result: &Result<()>) {
        if let Err(e) = result {
            self.modal = Some(Modal::Notify {
                message: format!("Saved in audium, but could not write the file's tags: {e}"),
            });
        }
    }

    fn save_metadata(
        &mut self,
        track_id: TrackId,
        name: &str,
        artist: Option<&String>,
        album: Option<&String>,
    ) {
        let written = self.library.update_track_metadata(
            track_id,
            name.to_string(),
            artist.cloned(),
            album.cloned(),
        );
        self.report_tag_failure(&written);
        self.sync_queue_metadata(track_id, name, artist, album);
        self.rebuild_filter_cache();
    }

    fn apply_modal_confirm(&mut self, confirm: ModalConfirm) {
        match confirm {
            ModalConfirm::Remove(target) => self.apply_remove(target),

            ModalConfirm::RenamePlaylist { id, new_name } => {
                let _ = self.library.rename_playlist(id, new_name);
            }

            ModalConfirm::NewPlaylist { name, add_track } => {
                if let Ok(playlist_id) = self.library.create_playlist(name)
                    && let Some(track_id) = add_track
                {
                    let _ = self.library.playlist_add_track(playlist_id, track_id);
                    self.rebuild_filter_cache();
                }
            }

            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(save) => self.apply_save_settings(&save),

            ModalConfirm::PreviewTheme {
                theme_name,
                console_theme_name,
                transparent,
                color_mode,
            } => {
                let truecolor = color_mode.truecolor(detect_truecolor());
                self.theme =
                    resolve_theme(&theme_name, &console_theme_name, transparent, truecolor);
            }

            ModalConfirm::ShuffleView => {
                self.apply_shuffle_view();
            }

            ModalConfirm::SaveMetadata {
                track_id,
                name,
                artist,
                album,
            } => {
                self.save_metadata(track_id, &name, artist.as_ref(), album.as_ref());
            }

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

            ModalConfirm::SaveMetadataAndEditLyrics {
                track_id,
                name,
                artist,
                album,
            } => {
                self.save_metadata(track_id, &name, artist.as_ref(), album.as_ref());
                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}"),
                });
            }
        }
    }

    fn apply_save_settings(&mut self, save: &SettingsSave) {
        self.settings
            .set_default_volume(numeric::whole_percent_to_ratio(save.volume_pct));
        self.settings.set_seek_step_secs(save.seek_secs);
        // forget the session at once, rather than leave a stale file behind
        if !save.resume_playback && self.settings.resume_playback {
            crate::state::PlaybackState::discard();
        }
        self.settings.resume_playback = save.resume_playback;
        self.settings.set_theme(&save.theme_name);
        self.settings.set_console_theme(&save.console_theme_name);
        self.settings.transparent = save.transparent;
        self.settings.color_mode = save.color_mode;
        // applied live, console fallback included
        self.theme = resolve_theme(
            &save.theme_name,
            &save.console_theme_name,
            save.transparent,
            save.color_mode.truecolor(detect_truecolor()),
        );
        let _ = self.settings.save();
    }

    fn apply_shuffle_view(&mut self) {
        // resolve, shuffle in place, replace the queue, start playing
        let mut tracks: Vec<Track> = self.view_tracks().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);
    }
}
// -- 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 {
        // a file argument is an explicit "play this", so it beats the session
        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 });
    } else if !state.settings.resume_playback {
        // resume is off: forget whatever a previous run left behind
        crate::state::PlaybackState::discard();
    } else if let Some(saved) = crate::state::PlaybackState::load() {
        state.restore_state(&saved);
    }

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

    // best effort on the way out: a failure here must not mask the loop's result
    if state.settings.resume_playback {
        let _ = state.snapshot_state().save();
    }
    result
}

fn event_loop(mut terminal: DefaultTerminal, state: &mut AppState) -> Result<()> {
    /// How long to wait for input before looping again.
    const POLL: Duration = Duration::from_millis(50);
    /// Refresh rate while a track is playing, enough for a smooth elapsed
    /// time without redrawing on every poll.
    const PLAYBACK_REFRESH: Duration = Duration::from_millis(250);
    /// How often the playback session is written out, so an unclean exit (a
    /// crash, a SIGKILL, a closed terminal) loses at most this much position.
    const STATE_SAVE: Duration = Duration::from_secs(5);

    // drawing unconditionally would cost a full render 20 times a second
    // forever, whatever the library size
    let mut dirty = true;
    let mut last_draw = Instant::now();
    let mut last_state_save = Instant::now();
    // the last snapshot actually written, so an idle session is not rewritten
    // every tick. Seeded with the current one so the first tick is a no-op.
    let mut saved_state = Some(state.snapshot_state());

    loop {
        // periodic autosave, but only when it differs from disk. That is what
        // makes it cheap and complete at once: a paused player writes nothing,
        // while a queue edit with nothing playing still counts as a change.
        if state.settings.resume_playback && last_state_save.elapsed() >= STATE_SAVE {
            let snapshot = state.snapshot_state();
            if saved_state.as_ref() != Some(&snapshot) && snapshot.save().is_ok() {
                saved_state = Some(snapshot);
            }
            last_state_save = Instant::now();
        }

        if state.tick() {
            dirty = true;
        }
        if state.is_animating() && last_draw.elapsed() >= PLAYBACK_REFRESH {
            dirty = true;
        }

        if dirty {
            terminal.draw(|frame| ui::render(frame, state))?;
            last_draw = Instant::now();
            dirty = false;
        }

        if event::poll(POLL)? {
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    state.handle_key(key.code, key.modifiers);
                    dirty = true;
                }
                // a resize invalidates the whole frame
                Event::Resize(..) => dirty = true,
                _ => {}
            }
        }

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