gitlab-tracker 0.3.2

A fast terminal TUI dashboard for tracking GitLab Merge Requests across branches
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
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crossterm::event::{KeyCode, KeyEvent, MouseEvent, MouseEventKind};
use tokio::sync::{mpsc::UnboundedSender, Semaphore};

use crate::app::{ActivePane, App, InputMode, InspectorView, LogTimeField, LogTimeForm};
use crate::gitlab::{spawn_milestone_mrs_fetch, spawn_mr_fetch, CachedMrData, FetchContext};
use crate::models::{AppEvent, MrStatus, TrackedMr};
use crate::storage::{save_config_async, save_state_async};
use crate::utils::parse_duration_to_hours;

/// Handles a mouse event and updates the application state accordingly.
///
/// Returns `true` when the selected dashboard row changed (scroll in the table pane),
/// so the caller can trigger a time-entries re-fetch when the TimeLog view is active.
pub fn handle_mouse_event(
    mouse: MouseEvent,
    term_width: u16,
    app: &mut App,
    tx: &UnboundedSender<AppEvent>,
) {
    // The inspector occupies the right 35% of the terminal width.
    let inspector_start_col = term_width * 65 / 100;

    match mouse.kind {
        // Update focus based on where the cursor is.
        MouseEventKind::Moved | MouseEventKind::Drag(_) => {
            if mouse.column >= inspector_start_col {
                app.active_pane = ActivePane::Inspector;
            } else {
                app.active_pane = ActivePane::Dashboard;
            }
        }
        // Route scroll to the pane under the cursor.
        MouseEventKind::ScrollDown => {
            if mouse.column >= inspector_start_col {
                app.inspector_scroll_down(3);
            } else {
                app.next_row();
                // When the TimeLog view is active, re-fetch time entries for the newly
                // selected MR's linked ticket — mirrors the keyboard ↓ / j handler.
                if app.inspector_view == InspectorView::TimeLog {
                    if let Some(provider) = app.tracker.as_ref().map(Arc::clone) {
                        let ticket_id = app
                            .table_state
                            .selected()
                            .and_then(|i| app.visible_mrs().nth(i))
                            .and_then(|mr| mr.linked_ticket.as_ref())
                            .map(|t| t.id.clone());

                        if let Some(tid) = ticket_id {
                            let tx2 = tx.clone();
                            tokio::spawn(async move {
                                let entries = provider.fetch_time_entries(&tid).await;
                                let _ = tx2
                                    .send(crate::models::AppEvent::TimeEntriesLoaded { entries });
                            });
                        }
                    }
                }
            }
        }
        MouseEventKind::ScrollUp => {
            if mouse.column >= inspector_start_col {
                app.inspector_scroll_up(3);
            } else {
                app.prev_row();
                // When the TimeLog view is active, re-fetch time entries for the newly
                // selected MR's linked ticket — mirrors the keyboard ↑ / k handler.
                if app.inspector_view == InspectorView::TimeLog {
                    if let Some(provider) = app.tracker.as_ref().map(Arc::clone) {
                        let ticket_id = app
                            .table_state
                            .selected()
                            .and_then(|i| app.visible_mrs().nth(i))
                            .and_then(|mr| mr.linked_ticket.as_ref())
                            .map(|t| t.id.clone());

                        if let Some(tid) = ticket_id {
                            let tx2 = tx.clone();
                            tokio::spawn(async move {
                                let entries = provider.fetch_time_entries(&tid).await;
                                let _ = tx2
                                    .send(crate::models::AppEvent::TimeEntriesLoaded { entries });
                            });
                        }
                    }
                }
            }
        }
        _ => {}
    }
}

/// Handles a keyboard event and updates the application state accordingly.
///
/// Returns `true` if the main loop should exit (e.g. Esc was pressed).
pub async fn handle_key_event(
    key: KeyEvent,
    app: &mut App,
    api_semaphore: &Arc<Semaphore>,
    tx: &UnboundedSender<AppEvent>,
    last_known_branches: &mut HashMap<String, HashSet<String>>,
) -> bool {
    match app.input_mode {
        // ------------------------------------------------------------------
        // Editing mode: the input field has exclusive focus.
        // Only Esc, Enter, Backspace and printable chars are handled here.
        // ------------------------------------------------------------------
        InputMode::Editing => match key.code {
            // Esc closes autocomplete if open, otherwise cancels editing.
            KeyCode::Esc => {
                if !app.milestone_suggestions.is_empty() {
                    app.milestone_suggestions.clear();
                } else {
                    app.input.clear();
                    app.input_mode = InputMode::Normal;
                }
            }

            KeyCode::Enter => {
                // If an autocomplete suggestion is highlighted, confirm it and
                // immediately dispatch a bulk-add fetch for that milestone's MRs.
                if !app.milestone_suggestions.is_empty() {
                    if let Some(title) = app.confirm_milestone_suggestion() {
                        let ctx = build_fetch_context(app);
                        // Filter by milestone title — the GitLab MRs API uses the title,
                        // not the numeric milestone ID, for the `milestone` query parameter.
                        spawn_milestone_mrs_fetch(ctx, title, tx.clone());
                        app.input.clear();
                        app.input_mode = InputMode::Normal;
                    }
                } else {
                    handle_enter(app, api_semaphore, tx, last_known_branches).await;
                    // Return to Normal after submitting so shortcuts are available again.
                    app.input_mode = InputMode::Normal;
                }
            }

            // Navigate autocomplete suggestions with Tab / Shift+Tab.
            KeyCode::Tab => {
                if !app.milestone_suggestions.is_empty() {
                    app.milestone_suggestion_next();
                }
            }
            KeyCode::BackTab => {
                if !app.milestone_suggestions.is_empty() {
                    app.milestone_suggestion_prev();
                }
            }

            // Up/Down also navigate autocomplete when it is open.
            KeyCode::Down => {
                if !app.milestone_suggestions.is_empty() {
                    app.milestone_suggestion_next();
                }
            }
            KeyCode::Up => {
                if !app.milestone_suggestions.is_empty() {
                    app.milestone_suggestion_prev();
                }
            }

            KeyCode::Backspace => {
                app.input.pop();
                app.update_milestone_suggestions();
            }

            KeyCode::Char(c) => {
                app.input.push(c);
                app.update_milestone_suggestions();
            }

            _ => {}
        },

        // ------------------------------------------------------------------
        // Column-picker mode: the popup is open.
        // Up/Down move the cursor; Space toggles; Esc closes and persists.
        // ------------------------------------------------------------------
        InputMode::ColumnPicker => {
            // Column count: 5 fixed columns + 1 tracker column when a provider is configured.
            let column_count = if app.tracker.is_some() { 6 } else { 5 };

            match key.code {
                KeyCode::Up | KeyCode::Char('k') => {
                    if app.column_picker_cursor > 0 {
                        app.column_picker_cursor -= 1;
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    if app.column_picker_cursor < column_count - 1 {
                        app.column_picker_cursor += 1;
                    }
                }
                KeyCode::Char(' ') => {
                    // Toggle the column at the current cursor position.
                    // Order must mirror `VisibleColumns` field declaration order
                    // and the entries array in `render_column_picker`.
                    match app.column_picker_cursor {
                        0 => {
                            app.config.visible_columns.activity =
                                !app.config.visible_columns.activity
                        }
                        1 => {
                            app.config.visible_columns.target_branch =
                                !app.config.visible_columns.target_branch
                        }
                        2 => app.config.visible_columns.labels = !app.config.visible_columns.labels,
                        3 => {
                            app.config.visible_columns.milestone =
                                !app.config.visible_columns.milestone
                        }
                        4 => app.config.visible_columns.notes = !app.config.visible_columns.notes,
                        // Entry 5 — only reachable when a tracker provider is configured.
                        5 => {
                            app.config.visible_columns.tracker_ticket =
                                !app.config.visible_columns.tracker_ticket
                        }
                        _ => {}
                    }
                }
                KeyCode::Esc | KeyCode::Enter => {
                    // Close the popup and persist the new column visibility to config.json.
                    app.input_mode = InputMode::Normal;
                    save_config_async(&app.config).await;
                }
                _ => {}
            }
        }

        // ------------------------------------------------------------------
        // Log Time popup mode — only reachable when a tracker provider is configured.
        // Tab/Shift+Tab cycle fields; Up/Down navigate activities; Enter submits.
        // ------------------------------------------------------------------
        InputMode::LogTime => {
            match key.code {
                KeyCode::Esc => {
                    // Close popup without submitting — reset the form.
                    app.input_mode = InputMode::Normal;
                    app.log_time_form = LogTimeForm::default();
                }

                // Tab / Shift+Tab cycle through fields: Duration → Activity → Comment → wrap.
                KeyCode::Tab => {
                    app.log_time_form.focused_field = match app.log_time_form.focused_field {
                        LogTimeField::Duration => LogTimeField::Activity,
                        LogTimeField::Activity => LogTimeField::Comment,
                        LogTimeField::Comment => LogTimeField::Duration,
                    };
                    app.log_time_form.error = None;
                }
                KeyCode::BackTab => {
                    app.log_time_form.focused_field = match app.log_time_form.focused_field {
                        LogTimeField::Duration => LogTimeField::Comment,
                        LogTimeField::Activity => LogTimeField::Duration,
                        LogTimeField::Comment => LogTimeField::Activity,
                    };
                    app.log_time_form.error = None;
                }

                // Up/Down navigate the activity list when that field is focused.
                KeyCode::Up | KeyCode::Char('k') => {
                    if app.log_time_form.focused_field == LogTimeField::Activity
                        && !app.activities.is_empty()
                    {
                        let len = app.activities.len();
                        app.log_time_form.selected_activity_idx =
                            (app.log_time_form.selected_activity_idx + len - 1) % len;
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    if app.log_time_form.focused_field == LogTimeField::Activity
                        && !app.activities.is_empty()
                    {
                        let len = app.activities.len();
                        app.log_time_form.selected_activity_idx =
                            (app.log_time_form.selected_activity_idx + 1) % len;
                    }
                }

                // Enter: validate and submit when on Comment field, else advance field.
                KeyCode::Enter => {
                    match app.log_time_form.focused_field {
                        LogTimeField::Duration | LogTimeField::Activity => {
                            app.log_time_form.focused_field = match app.log_time_form.focused_field
                            {
                                LogTimeField::Duration => LogTimeField::Activity,
                                _ => LogTimeField::Comment,
                            };
                            app.log_time_form.error = None;
                        }
                        LogTimeField::Comment => {
                            // Validate duration before submitting.
                            let hours = parse_duration_to_hours(&app.log_time_form.duration_input);
                            match hours {
                                Err(e) => {
                                    app.log_time_form.error = Some(e);
                                    app.log_time_form.focused_field = LogTimeField::Duration;
                                }
                                Ok(h) => {
                                    if app.activities.is_empty() {
                                        app.log_time_form.error =
                                            Some("No activities loaded".into());
                                    } else if app.log_time_form.submitting {
                                        // Already in flight — ignore double-Enter.
                                    } else {
                                        // Resolve the selected activity, the Redmine ticket id,
                                        // and the parent MR id (needed to route the refresh).
                                        let activity = app
                                            .activities
                                            .get(app.log_time_form.selected_activity_idx)
                                            .cloned();
                                        let selected_mr = app
                                            .table_state
                                            .selected()
                                            .and_then(|i| app.visible_mrs().nth(i));
                                        let mr_id = selected_mr.map(|mr| mr.id.clone());
                                        let ticket_id = selected_mr
                                            .and_then(|mr| mr.linked_ticket.as_ref())
                                            .map(|t| t.id.clone());

                                        if let (Some(activity), Some(mr_id), Some(ticket_id)) =
                                            (activity, mr_id, ticket_id)
                                        {
                                            app.log_time_form.submitting = true;
                                            app.log_time_form.error = None;

                                            let provider = app.tracker.as_ref().map(Arc::clone);
                                            let comment = app.log_time_form.comment_input.clone();
                                            let spent_on =
                                                chrono::Utc::now().format("%Y-%m-%d").to_string();
                                            let tx2 = tx.clone();
                                            let tid = ticket_id.clone();

                                            if let Some(provider) = provider {
                                                tokio::spawn(async move {
                                                    let entry =
                                                        gitlab_tracker_core::TimeEntryRequest {
                                                            hours: h,
                                                            activity_id: activity.id,
                                                            comment,
                                                            spent_on,
                                                        };
                                                    match provider.log_time(&tid, entry).await {
                                                        Ok(()) => {
                                                            let _ = tx2.send(
                                                                crate::models::AppEvent::TimeLogSubmitted {
                                                                    mr_id,
                                                                    ticket_id: tid,
                                                                },
                                                            );
                                                        }
                                                        Err(e) => {
                                                            let _ = tx2.send(
                                                                crate::models::AppEvent::TimeLogFailed {
                                                                    error: e,
                                                                },
                                                            );
                                                        }
                                                    }
                                                });
                                            }
                                        } else {
                                            app.log_time_form.error =
                                                Some("No linked ticket selected".into());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Backspace edits the focused text field.
                KeyCode::Backspace => match app.log_time_form.focused_field {
                    LogTimeField::Duration => {
                        app.log_time_form.duration_input.pop();
                    }
                    LogTimeField::Comment => {
                        app.log_time_form.comment_input.pop();
                    }
                    LogTimeField::Activity => {}
                },

                // Printable chars feed the focused text field.
                KeyCode::Char(c) => match app.log_time_form.focused_field {
                    LogTimeField::Duration => {
                        app.log_time_form.duration_input.push(c);
                    }
                    LogTimeField::Comment => {
                        app.log_time_form.comment_input.push(c);
                    }
                    LogTimeField::Activity => {}
                },

                _ => {}
            }
        }

        // ------------------------------------------------------------------
        // Normal mode: shortcuts are active; input field is passive.
        // '/' or 'i' enters Editing mode (vim-style focus).
        // ------------------------------------------------------------------
        InputMode::Normal => match key.code {
            // Quit the application.
            KeyCode::Esc => return true,

            // Enter Editing mode — the input field now has exclusive focus.
            KeyCode::Char('/') | KeyCode::Char('i') => {
                app.input_mode = InputMode::Editing;
            }

            // Tab cycles focus between panes.
            KeyCode::Tab => {
                app.active_pane = app.active_pane.next();
            }

            // Arrow keys and j/k are routed based on the active pane.
            KeyCode::Down | KeyCode::Char('j') => match app.active_pane {
                ActivePane::Inspector => app.inspector_scroll_down(1),
                ActivePane::Dashboard => {
                    app.next_row();
                    // When navigating rows while the TimeLog view is active, re-fetch
                    // time entries for the newly selected MR's linked ticket.
                    if app.inspector_view == InspectorView::TimeLog {
                        if let Some(provider) = app.tracker.as_ref().map(Arc::clone) {
                            let ticket_id = app
                                .table_state
                                .selected()
                                .and_then(|i| app.visible_mrs().nth(i))
                                .and_then(|mr| mr.linked_ticket.as_ref())
                                .map(|t| t.id.clone());

                            if let Some(tid) = ticket_id {
                                let tx2 = tx.clone();
                                tokio::spawn(async move {
                                    let entries = provider.fetch_time_entries(&tid).await;
                                    let _ = tx2.send(crate::models::AppEvent::TimeEntriesLoaded {
                                        entries,
                                    });
                                });
                            }
                        }
                    }
                }
            },
            KeyCode::Up | KeyCode::Char('k') => match app.active_pane {
                ActivePane::Inspector => app.inspector_scroll_up(1),
                ActivePane::Dashboard => {
                    app.prev_row();
                    // When navigating rows while the TimeLog view is active, re-fetch
                    // time entries for the newly selected MR's linked ticket.
                    if app.inspector_view == InspectorView::TimeLog {
                        if let Some(provider) = app.tracker.as_ref().map(Arc::clone) {
                            let ticket_id = app
                                .table_state
                                .selected()
                                .and_then(|i| app.visible_mrs().nth(i))
                                .and_then(|mr| mr.linked_ticket.as_ref())
                                .map(|t| t.id.clone());

                            if let Some(tid) = ticket_id {
                                let tx2 = tx.clone();
                                tokio::spawn(async move {
                                    let entries = provider.fetch_time_entries(&tid).await;
                                    let _ = tx2.send(crate::models::AppEvent::TimeEntriesLoaded {
                                        entries,
                                    });
                                });
                            }
                        }
                    }
                }
            },

            // Open the MR URL in the default browser.
            KeyCode::Char('o') | KeyCode::Char('O') => {
                if let Some(selected) = app.table_state.selected() {
                    if let Some(mr) = app.mrs.get(selected) {
                        let target_url = if !mr.web_url.is_empty() {
                            mr.web_url.clone()
                        } else {
                            format!(
                                "{}/projects/{}/merge_requests/{}",
                                app.base_url, app.project_id, mr.id
                            )
                        };
                        let _ = open::that(target_url);
                    }
                }
            }

            // [Y]ank — copy the git clone command for the MR source branch to clipboard.
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                if let Some(selected) = app.table_state.selected() {
                    if let Some(mr) = app.mrs.get(selected) {
                        let ssh_url = mr
                            .web_url
                            .split("/-/")
                            .next()
                            .unwrap_or("")
                            .replacen("https://", "git@", 1)
                            .replacen('/', ":", 1);
                        let cmd = format!("git clone -b {} {}.git", mr.source_branch, ssh_url);
                        if let Ok(mut ctx) = arboard::Clipboard::new() {
                            let _ = ctx.set_text(cmd);
                        }
                    }
                }
            }

            // Force a full refresh of all MRs (GitLab + Redmine tickets).
            KeyCode::Char('r') | KeyCode::Char('R') => {
                app.time_left = app.refresh_interval_secs;
                let ctx = build_fetch_context(app);

                for mr in &mut app.mrs {
                    mr.status = MrStatus::Loading;
                    let cached = cached_from_mr(mr);
                    spawn_mr_fetch(
                        ctx.clone(),
                        mr.id.clone(),
                        cached,
                        api_semaphore.clone(),
                        tx.clone(),
                    );

                    // Re-fetch the tracker ticket so that spent_hours and time entries
                    // reflect any change logged since the last refresh, regardless of
                    // whether the GitLab MR itself was updated.
                    if let Some(provider) = app.tracker.as_ref().map(Arc::clone) {
                        if let Some(ticket_id) = mr.linked_ticket.as_ref().map(|t| t.id.clone()) {
                            let mr_id = mr.id.clone();
                            let tx2 = tx.clone();
                            tokio::spawn(async move {
                                if let Some(ticket) = provider.fetch_ticket(&ticket_id).await {
                                    let _ =
                                        tx2.send(crate::models::AppEvent::TrackerTicketLoaded {
                                            mr_id,
                                            ticket,
                                        });
                                }
                            });
                        }
                    }
                }
            }

            // [P] cycles the Inspector view: MrInfo → Pipelines → TimeLog → MrInfo.
            // TimeLog is skipped when no tracker provider is configured.
            KeyCode::Char('p') | KeyCode::Char('P') => {
                let next = app.inspector_view.next_for(app.tracker.is_some());
                app.inspector_view = next;
                app.reset_inspector_scroll();

                // When entering the TimeLog view, fetch time entries for the selected ticket.
                if app.inspector_view == InspectorView::TimeLog {
                    let has_provider = app.tracker.is_some();
                    let selected_idx = app.table_state.selected();
                    let ticket_id = selected_idx
                        .and_then(|i| app.visible_mrs().nth(i))
                        .and_then(|mr| mr.linked_ticket.as_ref())
                        .map(|t| t.id.clone());

                    tracing::debug!(
                        has_provider,
                        selected_idx = ?selected_idx,
                        ticket_id = ?ticket_id,
                        "TimeLog view entered — attempting time entries fetch"
                    );

                    if let Some(provider) = app.tracker.as_ref().map(Arc::clone) {
                        if let Some(tid) = ticket_id {
                            let tx2 = tx.clone();
                            tokio::spawn(async move {
                                tracing::debug!(ticket_id = %tid, "Spawning fetch_time_entries");
                                let entries = provider.fetch_time_entries(&tid).await;
                                tracing::debug!(
                                    count = entries.len(),
                                    "fetch_time_entries returned"
                                );
                                let _ = tx2
                                    .send(crate::models::AppEvent::TimeEntriesLoaded { entries });
                            });
                        }
                    }
                }
            }

            // [L] opens the Log Time popup for the selected MR's linked tracker ticket.
            // Only active when a tracker provider is configured and a ticket is linked.
            KeyCode::Char('l') | KeyCode::Char('L') => {
                let has_ticket = app
                    .table_state
                    .selected()
                    .and_then(|i| app.visible_mrs().nth(i))
                    .and_then(|mr| mr.linked_ticket.as_ref())
                    .is_some();

                if has_ticket {
                    app.log_time_form = LogTimeForm::default();
                    app.input_mode = InputMode::LogTime;

                    // Fetch activities lazily if not yet loaded.
                    if app.activities.is_empty() {
                        if let Some(provider) = app.tracker.as_ref().map(Arc::clone) {
                            let tx2 = tx.clone();
                            tokio::spawn(async move {
                                let activities = provider.fetch_activities().await;
                                let _ =
                                    tx2.send(crate::models::AppEvent::ActivitiesLoaded(activities));
                            });
                        }
                    }
                }
            }

            KeyCode::Char('s') => app.cycle_sort_column(),
            KeyCode::Char('S') => app.toggle_sort_order(),

            // [F] cycles the active filter (All → Flagged → All → …).
            KeyCode::Char('f') | KeyCode::Char('F') => {
                app.cycle_filter();
            }

            // Space toggles the flagged state of the selected MR and persists immediately.
            KeyCode::Char(' ') => {
                if app.toggle_flag_selected().is_some() {
                    save_state_async(&app.mrs, &app.branches, last_known_branches).await;
                }
            }

            // [C] opens the column-picker popup.
            KeyCode::Char('c') | KeyCode::Char('C') => {
                app.column_picker_cursor = 0;
                app.input_mode = InputMode::ColumnPicker;
            }

            // [T] opens the tracker ticket linked to the selected MR in the browser.
            // Only active when a tracker provider is configured and a ticket is linked.
            KeyCode::Char('t') | KeyCode::Char('T') => {
                if let Some(selected) = app.table_state.selected() {
                    if let Some(mr) = app.visible_mrs().nth(selected) {
                        if let Some(ticket) = &mr.linked_ticket {
                            let _ = open::that(&ticket.url);
                        }
                    }
                }
            }

            // Delete: remove the selected MR from the list.
            KeyCode::Delete => {
                if let Some(selected) = app.table_state.selected() {
                    if selected < app.mrs.len() {
                        app.mrs.remove(selected);
                        if app.mrs.is_empty() {
                            app.table_state.select(None);
                        } else if selected >= app.mrs.len() {
                            app.table_state.select(Some(app.mrs.len() - 1));
                        }
                        save_state_async(&app.mrs, &app.branches, last_known_branches).await;
                    }
                }
            }

            _ => {}
        },
    }

    false
}

/// Handles the Enter key: parses the input field and dispatches the appropriate action
/// (add/remove MR, add/remove branch).
async fn handle_enter(
    app: &mut App,
    api_semaphore: &Arc<Semaphore>,
    tx: &UnboundedSender<AppEvent>,
    last_known_branches: &mut HashMap<String, HashSet<String>>,
) {
    let value = app.input.trim().to_string();
    if value.is_empty() {
        return;
    }

    if value.starts_with('-') {
        // Remove an MR (numeric) or a branch (text).
        let to_remove = value.trim_start_matches('-').to_string();
        if to_remove.chars().all(|c| c.is_numeric()) {
            app.mrs.retain(|m| m.id != to_remove);
        } else {
            app.branches.retain(|b| b != &to_remove);
        }
        save_state_async(&app.mrs, &app.branches, last_known_branches).await;
        if app.mrs.is_empty() {
            app.table_state.select(None);
        }
    } else if value.chars().all(|c| c.is_numeric()) {
        // Add a new MR to track.
        if !app.mrs.iter().any(|m| m.id == value) {
            app.mrs.push(TrackedMr {
                id: value.clone(),
                title: "Loading...".to_string(),
                status: MrStatus::Loading,
                state: crate::models::GitlabMrState::Opened,
                // Mergeability is fetched live — start as Unknown until the first API response.
                mergeability: crate::models::MergeabilityStatus::Unknown,
                sha: None,
                description: String::new(),
                author: "Loading".to_string(),
                assignee: "Loading".to_string(),
                reviewers: vec![],
                milestone: "Loading".to_string(),
                milestone_due_date: None,
                web_url: String::new(),
                labels: vec![],
                updated_at: None,
                source_branch: "unknown".to_string(),
                target_branch: "unknown".to_string(),
                merged_by: None,
                merged_at: None,
                // Pipelines are fetched on demand when the user presses [P].
                pipelines: vec![],
                // New MRs are not highlighted on first load.
                recently_updated: false,
                // Notes count is unknown until the first API response.
                user_notes_count: 0,
                // New MRs start unflagged.
                flagged: false,
                // Ticket resolved live after the first MR fetch — not pre-populated.
                linked_ticket: None,
            });
            app.table_state.select(Some(app.mrs.len() - 1));
            save_state_async(&app.mrs, &app.branches, last_known_branches).await;

            let ctx = build_fetch_context(app);
            spawn_mr_fetch(
                ctx,
                value,
                CachedMrData::default(),
                api_semaphore.clone(),
                tx.clone(),
            );
        }
    } else {
        // Add a new branch to track.
        if !app.branches.contains(&value) {
            app.branches.push(value.clone());
            save_state_async(&app.mrs, &app.branches, last_known_branches).await;

            let ctx = build_fetch_context(app);
            for mr in &mut app.mrs {
                if mr.status != MrStatus::Loading {
                    mr.status = MrStatus::Loading;
                    let cached = cached_from_mr(mr);
                    spawn_mr_fetch(
                        ctx.clone(),
                        mr.id.clone(),
                        cached,
                        api_semaphore.clone(),
                        tx.clone(),
                    );
                }
            }
        }
    }

    app.input.clear();
}

/// Handles a keyboard event in demo mode (no network, no input field, no mutations).
///
/// Accepts both `Press` and `Repeat` kinds so held keys scroll smoothly.
/// Returns `true` if the main loop should exit (Esc was pressed).
pub fn handle_key_event_demo(key: KeyEvent, app: &mut App) -> bool {
    // Column-picker popup intercepts all keys when open.
    if app.input_mode == InputMode::ColumnPicker {
        const COLUMN_COUNT: usize = 5;
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                if app.column_picker_cursor > 0 {
                    app.column_picker_cursor -= 1;
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if app.column_picker_cursor < COLUMN_COUNT - 1 {
                    app.column_picker_cursor += 1;
                }
            }
            KeyCode::Char(' ') => match app.column_picker_cursor {
                0 => app.config.visible_columns.activity = !app.config.visible_columns.activity,
                1 => {
                    app.config.visible_columns.target_branch =
                        !app.config.visible_columns.target_branch
                }
                2 => app.config.visible_columns.labels = !app.config.visible_columns.labels,
                3 => app.config.visible_columns.milestone = !app.config.visible_columns.milestone,
                4 => app.config.visible_columns.notes = !app.config.visible_columns.notes,
                _ => {}
            },
            // Close the popup — no disk write in demo mode.
            // Enter is used in the demo tape instead of Esc because VHS may fire
            // the Escape sequence before the column picker frame is rendered, causing
            // it to be received in Normal mode and quitting the app instead.
            KeyCode::Enter => {
                app.input_mode = InputMode::Normal;
            }
            _ => {}
        }
        return false;
    }

    match key.code {
        KeyCode::Esc => return true,

        KeyCode::Tab => {
            app.active_pane = app.active_pane.next();
        }

        KeyCode::Down | KeyCode::Char('j') => match app.active_pane {
            ActivePane::Inspector => app.inspector_scroll_down(1),
            ActivePane::Dashboard => app.next_row(),
        },
        KeyCode::Up | KeyCode::Char('k') => match app.active_pane {
            ActivePane::Inspector => app.inspector_scroll_up(1),
            ActivePane::Dashboard => app.prev_row(),
        },

        // Open the MR URL in the default browser (useful even in demo mode).
        KeyCode::Char('o') | KeyCode::Char('O') => {
            if let Some(selected) = app.table_state.selected() {
                if let Some(mr) = app.mrs.get(selected) {
                    let target_url = if !mr.web_url.is_empty() {
                        mr.web_url.clone()
                    } else {
                        format!(
                            "{}/projects/{}/merge_requests/{}",
                            app.base_url, app.project_id, mr.id
                        )
                    };
                    let _ = open::that(target_url);
                }
            }
        }

        // [Y]ank — copy the git clone command for the MR source branch to clipboard.
        KeyCode::Char('y') | KeyCode::Char('Y') => {
            if let Some(selected) = app.table_state.selected() {
                if let Some(mr) = app.mrs.get(selected) {
                    let ssh_url = mr
                        .web_url
                        .split("/-/")
                        .next()
                        .unwrap_or("")
                        .replacen("https://", "git@", 1)
                        .replacen('/', ":", 1);
                    let cmd = format!("git clone -b {} {}.git", mr.source_branch, ssh_url);
                    if let Ok(mut ctx) = arboard::Clipboard::new() {
                        let _ = ctx.set_text(cmd);
                    }
                }
            }
        }

        // Reset the refresh timer display only (no actual network fetch in demo mode).
        KeyCode::Char('r') | KeyCode::Char('R') => {
            app.time_left = app.refresh_interval_secs;
        }

        KeyCode::Char('s') => app.cycle_sort_column(),
        KeyCode::Char('S') => app.toggle_sort_order(),

        // [F] cycles the active filter in demo mode.
        KeyCode::Char('f') | KeyCode::Char('F') => {
            app.cycle_filter();
        }

        // Space toggles the flagged state of the selected MR in demo mode (no persistence).
        KeyCode::Char(' ') => {
            app.toggle_flag_selected();
        }

        // [P] cycles the Inspector view in demo mode (no network fetch).
        KeyCode::Char('p') | KeyCode::Char('P') => {
            app.inspector_view = app.inspector_view.next_for(app.tracker.is_some());
            app.reset_inspector_scroll();
        }

        _ => {}
    }

    false
}

/// Builds a `FetchContext` from the current application state.
fn build_fetch_context(app: &App) -> FetchContext {
    FetchContext {
        base_url: app.base_url.clone(),
        token: app.token.clone(),
        project_id: app.project_id.clone(),
        branches: app.branches.clone(),
    }
}

/// Builds a `CachedMrData` snapshot from a `TrackedMr` for use in fetch requests.
///
/// Includes `updated_at` and the current `pipelines` so the fetcher can skip
/// pipeline re-fetching when the MR has not changed since the last cycle.
fn cached_from_mr(mr: &TrackedMr) -> CachedMrData {
    CachedMrData {
        title: Some(mr.title.clone()),
        sha: mr.sha.clone(),
        description: Some(mr.description.clone()),
        author: Some(mr.author.clone()),
        assignee: Some(mr.assignee.clone()),
        web_url: Some(mr.web_url.clone()),
        labels: Some(mr.labels.clone()),
        updated_at: mr.updated_at.clone(),
        pipelines: mr.pipelines.clone(),
    }
}