ommp 0.1.3

Oh My Music Player — a terminal music player built with ratatui
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use ratatui::layout::Rect;
use std::time::{Duration, Instant};

use crate::app::state::{FocusedPane, Tab};
use crate::app::{App, AppAction};
use crate::ui::layout::LayoutAreas;
use crate::ui::pane::Pane;
use crate::ui::panes::list_pane;
use crate::ui::widgets::{progress_bar, tab_bar};
use crate::ui::widgets::playlist_modal::PlaylistModalMode;
use crate::ui::Ui;

pub const MIN_PANE_WIDTH: u16 = 10;

/// Split the 100% budget left over after `fixed` between the two panes flanking
/// a dragged border, placing the boundary at `boundary_pct`. Returns None when
/// there is not enough room for both.
///
/// Every arm of the drag math used to do this inline with bare `u16`
/// subtraction, which underflows as soon as the pointer leaves the dashboard —
/// dragging the playlist|lyrics border to the left edge panicked outright.
fn split_widths(boundary_pct: u16, fixed: u16, min_w: u16) -> Option<(u16, u16)> {
    let budget = 100u16.checked_sub(fixed)?;
    if budget < min_w * 2 {
        return None;
    }
    let first = boundary_pct.clamp(min_w, budget - min_w);
    Some((first, budget - first))
}

/// True for a plain character keystroke, i.e. one that should be typed into a
/// text field. Without the check, Ctrl+C inside the search box inserted a
/// literal "c" instead of quitting.
fn is_text_input(key: KeyEvent) -> bool {
    !key.modifiers.contains(KeyModifiers::CONTROL)
}

pub fn handle_key_event(key: KeyEvent, app: &App, ui: &mut Ui) -> Vec<AppAction> {
    let mut actions = Vec::new();

    // Quit works from anywhere, including with a modal open.
    if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
        actions.push(AppAction::Quit);
        return actions;
    }

    // About modal: Esc to close, g/s to open URLs
    if ui.show_about_modal {
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') => {
                ui.show_about_modal = false;
            }
            KeyCode::Char('g') => {
                let _ = std::process::Command::new("xdg-open")
                    .arg("https://github.com/sqzer-x/ommp")
                    .stdin(std::process::Stdio::null())
                    .stdout(std::process::Stdio::null())
                    .stderr(std::process::Stdio::null())
                    .spawn();
            }
            KeyCode::Char('s') => {
                let _ = std::process::Command::new("xdg-open")
                    .arg("https://github.com/sponsors/sqzer-x")
                    .stdin(std::process::Stdio::null())
                    .stdout(std::process::Stdio::null())
                    .stderr(std::process::Stdio::null())
                    .spawn();
            }
            _ => {}
        }
        return actions;
    }

    // Help modal: Esc to close
    if ui.show_help_modal {
        if matches!(key.code, KeyCode::Esc | KeyCode::Char('q')) {
            ui.show_help_modal = false;
        }
        return actions;
    }

    // Playlist modal ("b" key) — list, create, rename modes
    if ui.show_playlist_modal {
        match ui.playlist_modal_mode {
            PlaylistModalMode::Create | PlaylistModalMode::Rename => {
                match key.code {
                    KeyCode::Esc => {
                        ui.playlist_modal_mode = PlaylistModalMode::List;
                        ui.playlist_modal_input.clear();
                    }
                    KeyCode::Enter => {
                        let name = ui.playlist_modal_input.trim().to_string();
                        if !name.is_empty() {
                            if ui.playlist_modal_mode == PlaylistModalMode::Create {
                                actions.push(AppAction::CreatePlaylist(name));
                            } else {
                                actions.push(AppAction::RenamePlaylist {
                                    idx: ui.playlist_modal_selected,
                                    name,
                                });
                            }
                        }
                        ui.playlist_modal_mode = PlaylistModalMode::List;
                        ui.playlist_modal_input.clear();
                    }
                    KeyCode::Backspace => {
                        ui.playlist_modal_input.pop();
                    }
                    KeyCode::Char(c) if is_text_input(key) => {
                        ui.playlist_modal_input.push(c);
                    }
                    _ => {}
                }
            }
            PlaylistModalMode::List => {
                match key.code {
                    KeyCode::Esc => {
                        ui.show_playlist_modal = false;
                        ui.playlist_modal_selected = 0;
                    }
                    KeyCode::Up | KeyCode::Char('k') => {
                        if ui.playlist_modal_selected > 0 {
                            ui.playlist_modal_selected -= 1;
                        }
                    }
                    KeyCode::Down | KeyCode::Char('j') => {
                        if !app.playlists.is_empty()
                            && ui.playlist_modal_selected < app.playlists.len() - 1
                        {
                            ui.playlist_modal_selected += 1;
                        }
                    }
                    KeyCode::Enter => {
                        // Toggle track in selected playlist
                        if let Some(track_idx) = app.queue.current_index
                            .and_then(|qi| app.queue.tracks.get(qi).copied())
                        {
                            let pl_idx = ui.playlist_modal_selected;
                            if pl_idx < app.playlists.len() {
                                if app.playlists[pl_idx].tracks.contains(&track_idx) {
                                    actions.push(AppAction::RemoveFromPlaylist {
                                        playlist_idx: pl_idx,
                                        track_idx,
                                    });
                                } else {
                                    actions.push(AppAction::AddToPlaylist {
                                        playlist_idx: pl_idx,
                                        track_idx,
                                    });
                                }
                            }
                        }
                    }
                    KeyCode::Char('a') => {
                        ui.playlist_modal_mode = PlaylistModalMode::Create;
                        ui.playlist_modal_input.clear();
                    }
                    KeyCode::Char('d') => {
                        if !app.playlists.is_empty() {
                            actions.push(AppAction::DeletePlaylist(ui.playlist_modal_selected));
                            if ui.playlist_modal_selected > 0
                                && ui.playlist_modal_selected >= app.playlists.len() - 1
                            {
                                ui.playlist_modal_selected -= 1;
                            }
                        }
                    }
                    KeyCode::Char('r')
                        if !app.playlists.is_empty() => {
                            ui.playlist_modal_mode = PlaylistModalMode::Rename;
                            ui.playlist_modal_input =
                                app.playlists[ui.playlist_modal_selected].name.clone();
                        }
                    _ => {}
                }
            }
        }
        return actions;
    }

    // Search modal: input handling
    if ui.show_search_modal {
        match key.code {
            KeyCode::Esc => {
                ui.show_search_modal = false;
                ui.search_modal_input.clear();
                ui.search_modal_results.clear();
                ui.search_modal_selected = 0;
                ui.search_modal_scroll = 0;
            }
            KeyCode::Enter => {
                if !ui.search_modal_results.is_empty() {
                    let track_idx = ui.search_modal_results[ui.search_modal_selected];
                    actions.push(AppAction::AddToQueue(vec![track_idx]));
                    ui.show_search_modal = false;
                    ui.search_modal_input.clear();
                    ui.search_modal_results.clear();
                    ui.search_modal_selected = 0;
                    ui.search_modal_scroll = 0;
                }
            }
            KeyCode::Up | KeyCode::BackTab => {
                if ui.search_modal_selected > 0 {
                    ui.search_modal_selected -= 1;
                    if ui.search_modal_selected < ui.search_modal_scroll {
                        ui.search_modal_scroll = ui.search_modal_selected;
                    }
                }
            }
            KeyCode::Down | KeyCode::Tab => {
                if !ui.search_modal_results.is_empty()
                    && ui.search_modal_selected < ui.search_modal_results.len() - 1
                {
                    ui.search_modal_selected += 1;
                    let h = ui.search_modal_result_height;
                    if h > 0 && ui.search_modal_selected >= ui.search_modal_scroll + h {
                        ui.search_modal_scroll = ui.search_modal_selected - h + 1;
                    }
                }
            }
            KeyCode::Backspace => {
                ui.search_modal_input.pop();
                ui.search_modal_results = app.library.search(&ui.search_modal_input);
                ui.search_modal_selected = 0;
                ui.search_modal_scroll = 0;
            }
            KeyCode::Char(c) if is_text_input(key) => {
                ui.search_modal_input.push(c);
                ui.search_modal_results = app.library.search(&ui.search_modal_input);
                ui.search_modal_selected = 0;
                ui.search_modal_scroll = 0;
            }
            _ => {}
        }
        return actions;
    }

    // Ctrl-modified commands. These must come before the unmodified bindings
    // below, which match on any modifier — Ctrl+S would otherwise be swallowed
    // by the plain `s` shuffle arm.
    //
    // Ctrl+I and Ctrl+M are deliberately absent: terminals send them as the same
    // bytes as Tab (0x09) and Enter (0x0D), so they cannot be told apart.
    if key.modifiers.contains(KeyModifiers::CONTROL) {
        match key.code {
            KeyCode::Char('s') => ui.show_search_modal = true,
            KeyCode::Char('h') => ui.show_help_modal = true,
            KeyCode::Char('a') => ui.show_about_modal = true,
            KeyCode::Char('l') => actions.push(AppAction::LibrarySync),
            _ => {}
        }
        return actions;
    }

    // Global keybindings first
    match (key.modifiers, key.code) {
        (_, KeyCode::Char('q')) => {
            actions.push(AppAction::Quit);
            return actions;
        }
        (_, KeyCode::Char(' ')) => {
            actions.push(AppAction::PauseResume);
            return actions;
        }
        (_, KeyCode::Char('n')) => {
            actions.push(AppAction::NextTrack);
            return actions;
        }
        (KeyModifiers::SHIFT, KeyCode::Char('N')) => {
            actions.push(AppAction::PrevTrack);
            return actions;
        }
        (_, KeyCode::Char('+')) | (_, KeyCode::Char('=')) => {
            actions.push(AppAction::VolumeUp);
            return actions;
        }
        (_, KeyCode::Char('-')) => {
            actions.push(AppAction::VolumeDown);
            return actions;
        }
        (_, KeyCode::Right) => {
            actions.push(AppAction::SeekForward);
            return actions;
        }
        (_, KeyCode::Left) => {
            actions.push(AppAction::SeekBackward);
            return actions;
        }
        (_, KeyCode::Char('s')) => {
            actions.push(AppAction::ToggleShuffle);
            return actions;
        }
        (_, KeyCode::Char('r')) => {
            actions.push(AppAction::CycleRepeat);
            return actions;
        }
        (_, KeyCode::Char('b')) => {
            // Only open if a track is playing
            if app.queue.current_index.is_some() {
                ui.show_playlist_modal = true;
                ui.playlist_modal_selected = 0;
            }
            return actions;
        }
        (_, KeyCode::Char('p')) => {
            ui.info_view = ui.info_view.next();
            return actions;
        }
        (_, KeyCode::Tab) => {
            actions.push(AppAction::FocusNext);
            return actions;
        }
        (KeyModifiers::SHIFT, KeyCode::BackTab) => {
            actions.push(AppAction::FocusPrev);
            return actions;
        }
        // Tab switching with number keys
        (_, KeyCode::Char('1')) => {
            actions.push(AppAction::SwitchTab(Tab::Queue));
            return actions;
        }
        (_, KeyCode::Char('2')) => {
            actions.push(AppAction::SwitchTab(Tab::Directories));
            return actions;
        }
        (_, KeyCode::Char('3')) => {
            actions.push(AppAction::SwitchTab(Tab::Artists));
            return actions;
        }
        (_, KeyCode::Char('4')) => {
            actions.push(AppAction::SwitchTab(Tab::Albums));
            return actions;
        }
        (_, KeyCode::Char('5')) => {
            actions.push(AppAction::SwitchTab(Tab::Genre));
            return actions;
        }
        (_, KeyCode::Char('6')) => {
            actions.push(AppAction::SwitchTab(Tab::Format));
            return actions;
        }
        (_, KeyCode::Char('7')) => {
            actions.push(AppAction::SwitchTab(Tab::Playlists));
            return actions;
        }
        // h/l for pane focus
        (_, KeyCode::Char('h')) => {
            actions.push(AppAction::FocusPrev);
            return actions;
        }
        (_, KeyCode::Char('l')) => {
            actions.push(AppAction::FocusNext);
            return actions;
        }
        _ => {}
    }

    // Route to focused pane
    let action = match app.focus {
        FocusedPane::Library => library_key(key, app, ui),
        FocusedPane::Playlist => {
            match key.code {
                KeyCode::Char('j') | KeyCode::Down => None,
                KeyCode::Char('k') | KeyCode::Up => None,
                _ => ui.queue_pane.handle_key(key, app),
            }
        }
        FocusedPane::Lyrics => ui.track_info_pane.handle_key(key, app),
    };

    // Auto-focus to Queue pane when adding tracks from Library
    if let Some(ref a) = action {
        if matches!(a, AppAction::AddToQueue(_)) && app.focus == FocusedPane::Library {
            actions.push(AppAction::FocusPane(FocusedPane::Playlist));
        }
    }

    if let Some(a) = action {
        actions.push(a);
    }

    actions
}

pub fn handle_mouse_event(
    mouse: MouseEvent,
    app: &App,
    ui: &mut Ui,
    terminal_area: ratatui::layout::Rect,
) -> Vec<AppAction> {
    let mut actions = Vec::new();
    let areas = LayoutAreas::compute(terminal_area, ui.pane_widths, ui.right_split);

    let x = mouse.column;
    let y = mouse.row;

    // Store mouse position for hover tracking across all event types
    ui.mouse_pos = Some((x, y));

    // Search modal mouse handling
    if ui.show_search_modal {
        let ra = ui.search_modal_result_area;
        let in_results = x >= ra.x && x < ra.x + ra.width
            && y >= ra.y && y < ra.y + ra.height;

        // Hover tracking
        if in_results && !ui.search_modal_results.is_empty() {
            let row = ui.search_modal_scroll + (y - ra.y) as usize;
            if row < ui.search_modal_results.len() {
                ui.search_modal_hover_row = Some(row);
            } else {
                ui.search_modal_hover_row = None;
            }
        } else {
            ui.search_modal_hover_row = None;
        }

        match mouse.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                if in_results && !ui.search_modal_results.is_empty() {
                    let clicked = ui.search_modal_scroll + (y - ra.y) as usize;
                    if clicked < ui.search_modal_results.len() {
                        let is_double = is_double_click(ui.last_click, x, y);
                        ui.last_click = if is_double {
                            None
                        } else {
                            Some((Instant::now(), x, y))
                        };

                        if is_double {
                            // Double-click: select and confirm (add to queue)
                            let track_idx = ui.search_modal_results[clicked];
                            actions.push(AppAction::AddToQueue(vec![track_idx]));
                            ui.show_search_modal = false;
                            ui.search_modal_input.clear();
                            ui.search_modal_results.clear();
                            ui.search_modal_selected = 0;
                            ui.search_modal_scroll = 0;
                        } else {
                            // Single click: select
                            ui.search_modal_selected = clicked;
                        }
                    }
                }
            }
            MouseEventKind::ScrollDown => {
                if in_results && !ui.search_modal_results.is_empty() {
                    let max_scroll = ui.search_modal_results.len()
                        .saturating_sub(ui.search_modal_result_height);
                    if ui.search_modal_scroll < max_scroll {
                        ui.search_modal_scroll += 1;
                    }
                }
            }
            MouseEventKind::ScrollUp
                if in_results && ui.search_modal_scroll > 0 => {
                    ui.search_modal_scroll -= 1;
                }
            _ => {}
        }
        return actions;
    }

    // Block all mouse events when any other modal is open
    if ui.show_about_modal || ui.show_help_modal || ui.show_playlist_modal {
        return actions;
    }

    // Determine which pane the mouse is in
    let hit = PaneHit::at(&areas, x, y);
    let in_library = hit.library;
    let in_playlist = hit.playlist;
    let in_lyrics = hit.lyrics;

    // --- Hover tracking (runs on every mouse event including Moved) ---
    update_hover(ui, &areas, app, x, y, in_library, in_playlist);
    update_tab_hover(ui, &areas, x, y);

    // Focus follows the click, not the pointer. Deriving it from hover meant a
    // scroll — or a tick replaying the last known position — immediately undid
    // Tab, and undid the auto-focus after adding to the queue.
    if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {
        if let Some(pane) = hit.pane() {
            if app.focus != pane {
                actions.push(AppAction::FocusPane(pane));
            }
        }
    }

    // --- Border drag resize ---
    let border0_x = areas.library.x + areas.library.width; // lib|playlist boundary
    let border1_x = areas.playlist.x + areas.playlist.width; // playlist|lyrics boundary
    let in_dashboard_y = y >= areas.library.y && y < areas.library.y + areas.library.height;

    // Handle active drag (before normal mouse processing)
    if ui.dragging_border.is_some() {
        match mouse.kind {
            MouseEventKind::Drag(MouseButton::Left) | MouseEventKind::Moved => {
                if let Some(border_idx) = ui.dragging_border {
                    let dashboard_x = areas.library.x;
                    let dashboard_w = areas.library.width + areas.playlist.width + areas.lyrics.width;
                    if dashboard_w > 0 {
                        let rel_x = x.saturating_sub(dashboard_x);
                        let pct = ((rel_x as u32 * 100) / dashboard_w as u32) as u16;
                        let min_w: u16 = MIN_PANE_WIDTH;
                        if border_idx == 0 {
                            // Dragging lib|playlist border
                            if let Some((lib, play)) = split_widths(pct, ui.pane_widths[2], min_w) {
                                ui.pane_widths[0] = lib;
                                ui.pane_widths[1] = play;
                            }
                        } else if border_idx == 1 {
                            // Dragging playlist|lyrics border. `pct` is measured
                            // from the dashboard's left edge, so subtract the
                            // library pane to get the boundary inside the budget.
                            let boundary = pct.saturating_sub(ui.pane_widths[0]);
                            if let Some((play, right)) =
                                split_widths(boundary, ui.pane_widths[0], min_w)
                            {
                                ui.pane_widths[1] = play;
                                ui.pane_widths[2] = right;
                            }
                        } else if border_idx == 2 {
                            // Dragging info|lyrics horizontal border
                            let right_top = areas.info_pane.y;
                            let right_h = areas.info_pane.height + areas.lyrics.height;
                            if right_h > 0 {
                                let rel_y = y.saturating_sub(right_top);
                                let pct_v = ((rel_y as u32 * 100) / right_h as u32).clamp(10, 90) as u16;
                                ui.right_split = pct_v;
                            }
                        }
                    }
                }
                return actions;
            }
            MouseEventKind::Up(MouseButton::Left) => {
                ui.dragging_border = None;
                return actions;
            }
            _ => {
                ui.dragging_border = None;
            }
        }
    }

    // --- Handle specific event kinds ---
    match mouse.kind {
        MouseEventKind::Down(MouseButton::Left) => {
            // Border drag start detection. Ctrl is required so that an ordinary
            // click one column from a border selects a list row instead of
            // silently starting a resize.
            if in_dashboard_y && mouse.modifiers.contains(KeyModifiers::CONTROL) {
                if x.abs_diff(border0_x) <= 1 {
                    ui.dragging_border = Some(0);
                    return actions;
                }
                if x.abs_diff(border1_x) <= 1 {
                    ui.dragging_border = Some(1);
                    return actions;
                }
                // Horizontal border between info_pane and lyrics (within right column)
                let border2_y = areas.info_pane.y + areas.info_pane.height;
                if x >= areas.info_pane.x
                    && x < areas.info_pane.x + areas.info_pane.width
                    && y.abs_diff(border2_y) <= 1
                {
                    ui.dragging_border = Some(2);
                    return actions;
                }
            }

            // Double-click detection. The column has to match too: comparing
            // only the row made a click in the library followed by a click on
            // the same screen row of the queue register as a double-click.
            let is_double_click = is_double_click(ui.last_click, x, y);
            // Cleared once it fires, so three fast clicks are one double-click
            // and one single, not two doubles.
            ui.last_click = if is_double_click {
                None
            } else {
                Some((Instant::now(), x, y))
            };

            // Tab bar click
            if y >= areas.tab_bar.y && y < areas.tab_bar.y + areas.tab_bar.height {
                if let Some(tab_idx) = tab_bar::tab_hit_test(areas.tab_bar, x, y) {
                    actions.push(AppAction::SwitchTab(Tab::from_index(tab_idx)));
                }
                return actions;
            }

            // Progress bar click
            if y >= areas.progress_bar.y && y < areas.progress_bar.y + areas.progress_bar.height {
                let gauge_area = progress_bar::progress_gauge_area(areas.progress_bar);
                if x >= gauge_area.x && x < gauge_area.x + gauge_area.width {
                    let ratio = (x - gauge_area.x) as f64 / gauge_area.width as f64;
                    let seek_pos = ratio * app.playback.duration_secs;
                    actions.push(AppAction::Seek(seek_pos));
                }
                return actions;
            }

            // Double-click in playlist → play that track
            if is_double_click && in_playlist {
                let block = ratatui::widgets::Block::default()
                    .borders(ratatui::widgets::Borders::ALL);
                let inner = block.inner(areas.playlist);
                if y >= inner.y && y < inner.y + inner.height {
                    let clicked = ui.queue_pane.scroll_offset + (y - inner.y) as usize;
                    if clicked < app.queue.tracks.len() {
                        actions.push(AppAction::PlayQueueIndex(clicked));
                        return actions;
                    }
                }
            }

            // Single click in library → select + activate (Enter).
            // Only when the click actually landed on a row: the synthesized
            // Enter is unconditional, so a click on the border or the blank
            // space under a short list used to activate whatever was selected
            // before — which with a queue-replacing activation meant one stray
            // click wiped the queue.
            let clicked_library_row = clicked_row_in(areas.library, y)
                .map(|row| ui.library_pane_scroll(app) + row)
                .filter(|&row| row < library_row_count(app, ui));
            if in_library && clicked_library_row.is_some() {
                // First, route mouse to pane for selection update
                library_mouse(mouse, areas.library, app, ui);
                // Then, trigger Enter action to activate the clicked item
                let enter_key = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
                if let Some(action) = library_key(enter_key, app, ui) {
                    if matches!(action, AppAction::AddToQueue(_)) {
                        actions.push(AppAction::FocusPane(FocusedPane::Playlist));
                    }
                    actions.push(action);
                }
            } else if in_playlist {
                if let Some(a) = ui.queue_pane.handle_mouse(mouse, areas.playlist, app) {
                    actions.push(a);
                }
                // Update queue selection on click
                let block = ratatui::widgets::Block::default()
                    .borders(ratatui::widgets::Borders::ALL);
                let inner = block.inner(areas.playlist);
                if y >= inner.y && y < inner.y + inner.height {
                    let clicked = ui.queue_pane.scroll_offset + (y - inner.y) as usize;
                    if clicked < app.queue.tracks.len() {
                        actions.push(AppAction::SetQueueSelection(clicked));
                    }
                }
            } else if in_lyrics {
                if let Some(a) = ui.track_info_pane.handle_mouse(mouse, areas.lyrics, app) {
                    actions.push(a);
                }
            }
        }
        MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => {
            if in_library {
                if let Some(a) = library_mouse(mouse, areas.library, app, ui) {
                    actions.push(a);
                }
            } else if in_playlist {
                if let Some(a) = ui.queue_pane.handle_mouse(mouse, areas.playlist, app) {
                    actions.push(a);
                }
            } else if in_lyrics {
                if let Some(a) = ui.track_info_pane.handle_mouse(mouse, areas.lyrics, app) {
                    actions.push(a);
                }
            }
        }
        _ => {
            // Moved and other events — hover already handled above
        }
    }

    actions
}

const DOUBLE_CLICK: Duration = Duration::from_millis(400);

/// Row index under `y` inside a bordered pane, or None for the border itself.
fn clicked_row_in(area: ratatui::layout::Rect, y: u16) -> Option<usize> {
    let inner = ratatui::widgets::Block::default()
        .borders(ratatui::widgets::Borders::ALL)
        .inner(area);
    (y >= inner.y && y < inner.y + inner.height).then(|| (y - inner.y) as usize)
}

/// How many rows the library pane is currently showing, so a click below the
/// last one can be ignored instead of activating whatever was selected before.
fn library_row_count(app: &App, ui: &Ui) -> usize {
    match app.tab {
        Tab::Queue => ui.library_pane.row_count(app),
        Tab::Directories => ui.dir_browser_pane.entries.len(),
        tab => list_pane::row_count(app, tab),
    }
}

/// Route a key to whichever pane the library column is showing.
fn library_key(key: KeyEvent, app: &App, ui: &mut Ui) -> Option<AppAction> {
    match app.tab {
        Tab::Queue => ui.library_pane.handle_key(key, app),
        Tab::Directories => ui.dir_browser_pane.handle_key(key, app),
        tab => {
            let count = list_pane::row_count(app, tab);
            let pane = ui.list_pane_mut(tab);
            pane.handle_key(key, count)
                .then(|| list_pane::activate(app, tab, pane.selected))
                .flatten()
        }
    }
}

/// Route a mouse event to whichever pane the library column is showing.
fn library_mouse(mouse: MouseEvent, area: Rect, app: &App, ui: &mut Ui) -> Option<AppAction> {
    match app.tab {
        Tab::Queue => ui.library_pane.handle_mouse(mouse, area, app),
        Tab::Directories => ui.dir_browser_pane.handle_mouse(mouse, area, app),
        tab => {
            let count = list_pane::row_count(app, tab);
            ui.list_pane_mut(tab).handle_mouse(mouse, area, count);
            None
        }
    }
}

/// A second click counts only if it lands on the same cell in time. Matching on
/// the row alone let a click in one pane pair up with a click in another.
fn is_double_click(last: Option<(Instant, u16, u16)>, x: u16, y: u16) -> bool {
    last.is_some_and(|(at, lx, ly)| lx == x && ly == y && at.elapsed() < DOUBLE_CLICK)
}

/// Which dashboard pane a point lands in. Both the mouse handler and the tick
/// refresh need this; they used to carry byte-identical copies of the maths.
struct PaneHit {
    library: bool,
    playlist: bool,
    lyrics: bool,
}

impl PaneHit {
    fn at(areas: &LayoutAreas, x: u16, y: u16) -> Self {
        let inside = |r: ratatui::layout::Rect| {
            x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height
        };
        Self {
            library: inside(areas.library),
            playlist: inside(areas.playlist),
            lyrics: inside(areas.lyrics),
        }
    }

    fn pane(&self) -> Option<FocusedPane> {
        if self.library {
            Some(FocusedPane::Library)
        } else if self.playlist {
            Some(FocusedPane::Playlist)
        } else if self.lyrics {
            Some(FocusedPane::Lyrics)
        } else {
            None
        }
    }
}

fn update_tab_hover(ui: &mut Ui, areas: &LayoutAreas, x: u16, y: u16) {
    ui.hovered_tab = if y >= areas.tab_bar.y && y < areas.tab_bar.y + areas.tab_bar.height {
        tab_bar::tab_hit_test(areas.tab_bar, x, y)
    } else {
        None
    };
}

/// Clear all hover_row state across all panes
fn clear_all_hovers(ui: &mut Ui) {
    ui.queue_pane.hover_row = None;
    ui.library_pane.hover_row = None;
    ui.dir_browser_pane.hover_row = None;
    for pane in &mut ui.list_panes {
        pane.hover_row = None;
    }
}

/// Update hover_row state for panes based on mouse position
fn update_hover(
    ui: &mut Ui,
    areas: &LayoutAreas,
    app: &App,
    x: u16,
    y: u16,
    in_library: bool,
    in_playlist: bool,
) {
    clear_all_hovers(ui);

    if in_playlist {
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL);
        let inner = block.inner(areas.playlist);
        if x >= inner.x && x < inner.x + inner.width
            && y >= inner.y && y < inner.y + inner.height
        {
            let row = ui.queue_pane.scroll_offset + (y - inner.y) as usize;
            if row < app.queue.tracks.len() {
                ui.queue_pane.hover_row = Some(row);
            }
        }
    } else if in_library {
        let block = ratatui::widgets::Block::default()
            .borders(ratatui::widgets::Borders::ALL);
        let inner = block.inner(areas.library);
        // Bounded like the queue branch above: hovering the blank space below a
        // short list used to light up a row that isn't there.
        let row_count = library_row_count(app, ui);
        let scroll = ui.library_pane_scroll(app);
        if x >= inner.x && x < inner.x + inner.width
            && y >= inner.y && y < inner.y + inner.height
            && (scroll + (y - inner.y) as usize) < row_count
        {
            let row = scroll + (y - inner.y) as usize;
            match app.tab {
                Tab::Queue => ui.library_pane.hover_row = Some(row),
                Tab::Directories => ui.dir_browser_pane.hover_row = Some(row),
                tab => ui.list_pane_mut(tab).hover_row = Some(row),
            }
        }
    }
}

/// Refresh row highlighting from the stored mouse position, so hover stays
/// current on terminals that only report motion sporadically.
///
/// This deliberately does not touch focus. It used to re-derive focus from
/// `ui.mouse_pos` on every 200ms tick, and since that position is latched on the
/// first mouse event and never cleared, pressing Tab moved focus for one frame
/// before the next tick dragged it back under the pointer.
pub fn refresh_hover(app: &App, ui: &mut Ui, terminal_area: ratatui::layout::Rect) {
    // Skip hover updates when any modal is open
    if ui.show_about_modal || ui.show_help_modal || ui.show_search_modal || ui.show_playlist_modal {
        return;
    }
    let Some((x, y)) = ui.mouse_pos else { return };
    let areas = LayoutAreas::compute(terminal_area, ui.pane_widths, ui.right_split);
    let hit = PaneHit::at(&areas, x, y);
    update_hover(ui, &areas, app, x, y, hit.library, hit.playlist);
    update_tab_hover(ui, &areas, x, y);
}

/// Update queue selection based on keyboard in playlist focus
pub fn update_queue_selection(app: &mut App, key: KeyEvent) {
    let count = app.queue.tracks.len();
    if count == 0 {
        return;
    }

    match key.code {
        KeyCode::Char('j') | KeyCode::Down => {
            if app.queue.selected_index < count - 1 {
                app.queue.selected_index += 1;
            }
        }
        KeyCode::Char('k') | KeyCode::Up
            if app.queue.selected_index > 0 => {
                app.queue.selected_index -= 1;
            }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn new_ui() -> Ui {
        Ui::new(
            PathBuf::from("."),
            ratatui_image::picker::Picker::from_fontsize((8, 16)),
        )
    }

    fn ctrl(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL)
    }

    fn plain(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
    }

    #[test]
    fn ctrl_commands_open_their_modals() {
        let app = App::new(PathBuf::from("."));

        let mut ui = new_ui();
        handle_key_event(ctrl('s'), &app, &mut ui);
        assert!(ui.show_search_modal);

        let mut ui = new_ui();
        handle_key_event(ctrl('h'), &app, &mut ui);
        assert!(ui.show_help_modal);

        let mut ui = new_ui();
        handle_key_event(ctrl('a'), &app, &mut ui);
        assert!(ui.show_about_modal);

        let mut ui = new_ui();
        let actions = handle_key_event(ctrl('l'), &app, &mut ui);
        assert!(matches!(actions.as_slice(), [AppAction::LibrarySync]));
    }

    #[test]
    fn ctrl_shortcuts_do_not_fall_through_to_the_unmodified_binding() {
        let app = App::new(PathBuf::from("."));
        let mut ui = new_ui();

        // The plain-`s` arm matches any modifier, so without ordering the Ctrl
        // block first, Ctrl+S would toggle shuffle instead of opening search.
        let actions = handle_key_event(ctrl('s'), &app, &mut ui);
        assert!(actions.is_empty(), "Ctrl+S must not emit ToggleShuffle");
        assert!(ui.show_search_modal);

        // Unmodified keys are untouched.
        let mut ui = new_ui();
        let actions = handle_key_event(plain('s'), &app, &mut ui);
        assert!(matches!(actions.as_slice(), [AppAction::ToggleShuffle]));
        assert!(!ui.show_search_modal);
    }

    #[test]
    fn ctrl_c_quits_even_from_inside_a_text_field() {
        let app = App::new(PathBuf::from("."));
        let mut ui = new_ui();
        ui.show_search_modal = true;

        let actions = handle_key_event(ctrl('c'), &app, &mut ui);

        assert!(matches!(actions.as_slice(), [AppAction::Quit]));
        // It used to be typed into the query as a literal "c".
        assert!(ui.search_modal_input.is_empty());
    }

    #[test]
    fn split_widths_keeps_the_total_at_100_and_both_panes_above_the_minimum() {
        let (a, b) = split_widths(50, 20, MIN_PANE_WIDTH).unwrap();
        assert_eq!((a, b), (50, 30));
        assert_eq!(a + b + 20, 100);
    }

    #[test]
    fn split_widths_survives_dragging_past_either_edge() {
        // Pointer at or left of the dashboard: used to underflow `100 - fixed - 100`.
        let (a, b) = split_widths(0, 20, MIN_PANE_WIDTH).unwrap();
        assert_eq!((a, b), (MIN_PANE_WIDTH, 80 - MIN_PANE_WIDTH));
        // Pointer dragged far past the right edge.
        let (a, b) = split_widths(500, 20, MIN_PANE_WIDTH).unwrap();
        assert_eq!((a, b), (80 - MIN_PANE_WIDTH, MIN_PANE_WIDTH));
    }

    #[test]
    fn split_widths_refuses_when_the_third_pane_leaves_no_room() {
        // 85 fixed leaves 15, which cannot hold two 10% panes. The old code
        // called clamp(10, 5) here, and `Ord::clamp` panics when min > max.
        assert_eq!(split_widths(50, 85, MIN_PANE_WIDTH), None);
        assert_eq!(split_widths(50, 120, MIN_PANE_WIDTH), None);
        // Exactly enough room is allowed.
        assert_eq!(split_widths(50, 80, MIN_PANE_WIDTH), Some((10, 10)));
    }
}