frame 0.1.5

A markdown task tracker with a terminal UI for humans and a CLI for agents
Documentation
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
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::tui::app::{
    App, AutocompleteKind, AutocompleteState, DetailRegion, EditHistory, EditTarget, FlatItem,
    Mode, StateFilter, View,
};

use super::*;

pub(super) fn handle_navigate(app: &mut App, key: KeyEvent) {
    // Clear recovery notification on any keypress (after 3s minimum display)
    if app.recovery_message.is_some()
        && let Some(at) = app.recovery_message_at
        && at.elapsed() >= std::time::Duration::from_secs(3)
    {
        app.recovery_message = None;
        app.recovery_message_at = None;
    }

    // Conflict popup intercepts Esc
    if app.conflict_text.is_some() {
        if matches!(key.code, KeyCode::Esc) {
            // Log conflict text to recovery log before clearing
            if let Some(ref text) = app.conflict_text {
                crate::io::recovery::log_recovery(
                    &app.project.frame_dir,
                    crate::io::recovery::RecoveryEntry {
                        timestamp: chrono::Utc::now(),
                        category: crate::io::recovery::RecoveryCategory::Conflict,
                        description: "dismissed conflict".to_string(),
                        fields: vec![],
                        body: text.clone(),
                    },
                );
            }
            app.conflict_text = None;
        }
        return;
    }

    // Help overlay intercepts ? and Esc, plus scroll keys
    if app.show_help {
        match key.code {
            KeyCode::Char('?') | KeyCode::Esc => {
                app.show_help = false;
            }
            KeyCode::Char('j') | KeyCode::Down => {
                app.help_scroll = app.help_scroll.saturating_add(1);
            }
            KeyCode::Char('k') | KeyCode::Up => {
                app.help_scroll = app.help_scroll.saturating_sub(1);
            }
            KeyCode::Char('g') => {
                app.help_scroll = 0;
            }
            KeyCode::Char('G') => {
                app.help_scroll = usize::MAX;
            }
            _ => {}
        }
        return;
    }

    // Project picker intercepts all keys
    if app.project_picker.is_some() {
        handle_project_picker_key(app, key);
        return;
    }

    // Tag color popup intercepts all keys
    if app.tag_color_popup.is_some() {
        handle_tag_color_popup_key(app, key);
        return;
    }

    // Dep popup intercepts navigation keys
    if app.dep_popup.is_some() {
        handle_dep_popup_key(app, key);
        return;
    }

    // Prefix rename confirmation popup
    if let Some(ref pr) = app.prefix_rename
        && pr.confirming
    {
        match key.code {
            KeyCode::Enter => {
                execute_prefix_rename(app);
            }
            KeyCode::Esc => {
                // Go back to the prefix editor (not all the way back to Tracks view)
                if let Some(ref mut pr) = app.prefix_rename {
                    let old_prefix = pr.old_prefix.clone();
                    let track_id = pr.track_id.clone();
                    let new_prefix = pr.new_prefix.clone();
                    pr.confirming = false;

                    // Re-enter edit mode with the new_prefix in the buffer
                    app.edit_buffer = new_prefix.clone();
                    app.edit_cursor = new_prefix.len();
                    app.edit_target = Some(EditTarget::ExistingPrefix {
                        track_id,
                        original_prefix: old_prefix,
                    });
                    app.edit_history = Some(EditHistory::new(&new_prefix, new_prefix.len(), 0));
                    app.edit_selection_anchor = None;
                    app.mode = Mode::Edit;
                }
            }
            _ => {}
        }
        return;
    }

    // Filter prefix key: 'f' was pressed, now handle second key
    if app.filter_pending {
        app.filter_pending = false;
        handle_filter_key(app, key);
        return;
    }

    // Clear any transient status message on keypress
    app.status_message = None;
    app.status_is_error = false;

    // Track consecutive Esc presses; show quit hint after 5
    if matches!(key.code, KeyCode::Esc) {
        app.esc_streak = app.esc_streak.saturating_add(1);
        if app.esc_streak >= 5 {
            app.status_message = Some("type QQ to quit".to_string());
        }
    } else {
        app.esc_streak = 0;
    }

    // QQ quit: second Q confirms, any other key cancels
    if app.quit_pending {
        if matches!(
            (key.modifiers, key.code),
            (KeyModifiers::SHIFT, KeyCode::Char('Q'))
        ) {
            app.should_quit = true;
            return;
        } else {
            app.quit_pending = false;
            return;
        }
    }

    match (key.modifiers, key.code) {
        // Quit: Ctrl+Q
        (m, KeyCode::Char('q')) if m.contains(KeyModifiers::CONTROL) => {
            app.should_quit = true;
        }

        // Toggle key debug overlay: Ctrl+D
        (m, KeyCode::Char('d')) if m.contains(KeyModifiers::CONTROL) => {
            app.key_debug = !app.key_debug;
            if !app.key_debug {
                app.last_key_event = None;
            }
        }

        // Quit: Q (first press shows confirmation)
        (KeyModifiers::SHIFT, KeyCode::Char('Q')) => {
            app.quit_pending = true;
            app.status_message = Some("press Q again to quit".to_string());
        }

        // Esc: pop detail stack, close detail view, return to search, or clear search
        (_, KeyCode::Esc) => {
            if let View::Detail { .. } = &app.view {
                if let Some((parent_track, parent_task)) = app.detail_stack.pop() {
                    // Return to parent detail view, focusing on Subtasks region
                    let return_view = app
                        .detail_state
                        .as_ref()
                        .map(|ds| ds.return_view.clone())
                        .unwrap_or(crate::tui::app::ReturnView::Track(0));
                    app.detail_state = None;
                    app.view = View::Detail {
                        track_id: parent_track.clone(),
                        task_id: parent_task.clone(),
                    };
                    // Rebuild regions and focus on Subtasks
                    let regions = if let Some(track) =
                        App::find_track_in_project(&app.project, &parent_track)
                    {
                        if let Some(task) =
                            crate::ops::task_ops::find_task_in_track(track, &parent_task)
                        {
                            App::build_detail_regions(task)
                        } else {
                            vec![DetailRegion::Title]
                        }
                    } else {
                        vec![DetailRegion::Title]
                    };
                    let region = if regions.contains(&DetailRegion::Subtasks) {
                        DetailRegion::Subtasks
                    } else {
                        regions.first().copied().unwrap_or(DetailRegion::Title)
                    };
                    app.detail_state = Some(crate::tui::app::DetailState {
                        region,
                        scroll_offset: 0,
                        regions,
                        return_view,
                        editing: false,
                        edit_buffer: String::new(),
                        edit_cursor_line: 0,
                        edit_cursor_col: 0,
                        edit_original: String::new(),
                        subtask_cursor: 0,
                        flat_subtask_ids: Vec::new(),
                        multiline_selection_anchor: None,
                        note_h_scroll: 0,
                        sticky_col: None,
                        total_lines: 0,
                        note_view_line: None,
                        note_header_line: None,
                        note_content_end: 0,
                        regions_populated: Vec::new(),
                    });
                } else {
                    // Stack empty — return to origin view
                    let return_view = app
                        .detail_state
                        .as_ref()
                        .map(|ds| ds.return_view.clone())
                        .unwrap_or(crate::tui::app::ReturnView::Track(0));
                    match return_view {
                        crate::tui::app::ReturnView::Track(idx) => app.view = View::Track(idx),
                        crate::tui::app::ReturnView::Recent => app.view = View::Recent,
                        crate::tui::app::ReturnView::Board => app.view = View::Board,
                    }
                    app.close_detail_fully();
                }
            } else if app.view == View::Search {
                // Esc from search view: restore return_view, clear results
                if let Some(sr) = app.project_search_results.take() {
                    app.view = sr.return_view;
                }
            } else if app.project_search_results.is_some() {
                // Esc from a jumped-to view with active search: return to Search view
                app.view = View::Search;
            } else if app.last_search.is_some() {
                app.last_search = None;
                app.search_match_idx = 0;
                app.search_wrap_message = None;
                app.search_match_count = None;
                app.search_zero_confirmed = false;
            }
        }

        // Backspace: clear active search in Detail view (where Esc navigates back)
        (_, KeyCode::Backspace)
            if app.last_search.is_some() && matches!(app.view, View::Detail { .. }) =>
        {
            app.last_search = None;
            app.search_match_idx = 0;
            app.search_wrap_message = None;
            app.search_match_count = None;
            app.search_zero_confirmed = false;
        }

        // Help overlay
        (KeyModifiers::NONE, KeyCode::Char('?')) => {
            app.show_help = true;
            app.help_scroll = 0;
        }

        // Search: / (not available in project search results view)
        (KeyModifiers::NONE, KeyCode::Char('/')) if !matches!(app.view, View::Search) => {
            app.mode = Mode::Search;
            app.search_input.clear();
            app.search_draft.clear();
            app.search_history_index = None;
            app.search_wrap_message = None;
            app.search_match_count = None;
            app.search_zero_confirmed = false;
        }

        // n: search next when search active, otherwise note edit (cursor at end) in detail/inbox view
        (KeyModifiers::NONE, KeyCode::Char('n')) => {
            if matches!(app.view, View::Search) {
                move_cursor(app, 1);
            } else if app.last_search.is_some() {
                search_next(app, 1);
            } else if matches!(app.view, View::Detail { .. }) {
                detail_jump_to_region_and_edit(app, DetailRegion::Note, true);
            } else if matches!(app.view, View::Inbox) {
                inbox_edit_note(app, true);
            }
        }
        // N: search prev when search active, otherwise note edit (cursor at start) in detail/inbox view
        (KeyModifiers::SHIFT, KeyCode::Char('N')) => {
            if matches!(app.view, View::Search) {
                move_cursor(app, -1);
            } else if app.last_search.is_some() {
                search_next(app, -1);
            } else if matches!(app.view, View::Detail { .. }) {
                detail_jump_to_region_and_edit(app, DetailRegion::Note, false);
            } else if matches!(app.view, View::Inbox) {
                inbox_edit_note(app, false);
            }
        }

        // Tab switching: 1-9 for active tracks
        (KeyModifiers::NONE, KeyCode::Char(c @ '1'..='9')) => {
            let idx = (c as usize) - ('1' as usize);
            if idx < app.active_track_ids.len() {
                app.close_detail_fully();
                app.project_search_results = None;
                app.view = View::Track(idx);
            }
        }

        // Tab/Shift+Tab: next/prev editable region (detail view) or next/prev tab
        (KeyModifiers::NONE, KeyCode::Tab) => {
            if matches!(app.view, View::Detail { .. }) {
                detail_jump_editable(app, 1);
            } else {
                switch_tab(app, 1);
            }
        }
        (KeyModifiers::SHIFT, KeyCode::BackTab) => {
            if matches!(app.view, View::Detail { .. }) {
                detail_jump_editable(app, -1);
            } else {
                switch_tab(app, -1);
            }
        }

        // View switching
        (KeyModifiers::NONE, KeyCode::Char('i')) => {
            app.close_detail_fully();
            app.project_search_results = None;
            app.view = View::Inbox;
        }
        (KeyModifiers::NONE, KeyCode::Char('r')) => {
            app.close_detail_fully();
            app.project_search_results = None;
            app.view = View::Recent;
        }
        (KeyModifiers::NONE, KeyCode::Char('0') | KeyCode::Char('`')) => {
            app.close_detail_fully();
            app.project_search_results = None;
            app.tracks_name_col_min = 0;
            app.view = View::Tracks;
        }

        // Board view
        (KeyModifiers::SHIFT, KeyCode::Char('K')) => {
            app.close_detail_fully();
            app.project_search_results = None;
            app.view = View::Board;
        }

        // Project-wide search
        (KeyModifiers::SHIFT, KeyCode::Char('S')) => {
            app.project_search_active = true;
            app.project_search_input.clear();
            app.project_search_draft.clear();
            app.project_search_history_index = None;
            app.mode = Mode::Search;
        }

        // Cursor movement: up/down
        (KeyModifiers::NONE, KeyCode::Up | KeyCode::Char('k')) => {
            move_cursor(app, -1);
        }
        (KeyModifiers::NONE, KeyCode::Down | KeyCode::Char('j')) => {
            move_cursor(app, 1);
        }

        // Paragraph movement: Alt+Up/Down — jump between top-level tasks
        (m, KeyCode::Up) if m.contains(KeyModifiers::ALT) => {
            move_paragraph(app, -1);
        }
        (m, KeyCode::Down) if m.contains(KeyModifiers::ALT) => {
            move_paragraph(app, 1);
        }

        // Jump to top: g, Cmd+Up, or Home
        (KeyModifiers::NONE, KeyCode::Char('g')) => {
            jump_to_top(app);
        }
        (m, KeyCode::Up) if m.contains(KeyModifiers::SUPER) => {
            jump_to_top(app);
        }
        (_, KeyCode::Home) => {
            jump_to_top(app);
        }

        // Jump to bottom: G, Cmd+Down, or End
        (KeyModifiers::SHIFT, KeyCode::Char('G')) => {
            jump_to_bottom(app);
        }
        (m, KeyCode::Down) if m.contains(KeyModifiers::SUPER) => {
            jump_to_bottom(app);
        }
        (_, KeyCode::End) => {
            jump_to_bottom(app);
        }

        // Enter: open detail view (track/recent/board view), triage (inbox), or edit region (detail view)
        (KeyModifiers::NONE, KeyCode::Enter) => {
            if matches!(app.view, View::Search) {
                search_result_jump(app);
            } else if matches!(app.view, View::Board) {
                board_open_detail(app);
            } else if matches!(app.view, View::Inbox) {
                inbox_begin_triage(app);
            } else if matches!(app.view, View::Recent) {
                open_recent_detail(app);
            } else {
                handle_enter(app);
            }
        }

        // Expand/collapse (track view) or recent view
        (KeyModifiers::NONE, KeyCode::Right | KeyCode::Char('l')) => {
            if matches!(app.view, View::Board) {
                board_switch_column(app, 1);
            } else if matches!(app.view, View::Recent) {
                expand_recent(app);
            } else {
                expand_or_enter(app);
            }
        }
        (KeyModifiers::NONE, KeyCode::Left | KeyCode::Char('h')) => {
            if matches!(app.view, View::Board) {
                board_switch_column(app, -1);
            } else if matches!(app.view, View::Recent) {
                collapse_recent(app);
            } else {
                collapse_or_parent(app);
            }
        }

        // Task state changes (track view) or reopen (recent view)
        (KeyModifiers::NONE, KeyCode::Char(' ')) => {
            if matches!(app.view, View::Recent) {
                reopen_recent_task(app);
            } else {
                task_state_action(app, StateAction::Cycle);
            }
        }
        (KeyModifiers::NONE, KeyCode::Char('x')) => {
            if matches!(app.view, View::Inbox) {
                inbox_delete_item(app);
            } else {
                task_state_action(app, StateAction::Done);
            }
        }
        (KeyModifiers::NONE, KeyCode::Char('b')) => {
            task_state_action(app, StateAction::ToggleBlocked);
        }
        (KeyModifiers::NONE, KeyCode::Char('~')) => {
            task_state_action(app, StateAction::ToggleParked);
        }

        // Add task (track view), add inbox item (inbox view), or add track (tracks view)
        (KeyModifiers::NONE, KeyCode::Char('a')) => {
            if matches!(app.view, View::Inbox) {
                inbox_add_item(app);
            } else if matches!(app.view, View::Tracks) {
                tracks_add_track(app);
            } else {
                add_task_action(app, AddPosition::Bottom);
            }
        }
        (KeyModifiers::NONE, KeyCode::Char('o')) => {
            task_state_action(app, StateAction::SetTodo);
        }
        (KeyModifiers::NONE, KeyCode::Char('-')) => {
            if matches!(app.view, View::Inbox) {
                inbox_insert_after(app);
            } else if matches!(app.view, View::Tracks) {
                tracks_insert_after(app);
            } else {
                add_task_action(app, AddPosition::AfterCursor);
            }
        }
        (KeyModifiers::NONE, KeyCode::Char('p')) => {
            if matches!(app.view, View::Inbox) {
                inbox_prepend_item(app);
            } else if matches!(app.view, View::Tracks) {
                tracks_prepend(app);
            } else {
                add_task_action(app, AddPosition::Top);
            }
        }
        (KeyModifiers::SHIFT, KeyCode::Char('A')) => {
            add_subtask_action(app);
        }
        (KeyModifiers::NONE, KeyCode::Char('=')) => {
            if matches!(app.view, View::Inbox) {
                inbox_add_item(app);
            } else if matches!(app.view, View::Tracks) {
                tracks_add_track(app);
            } else {
                append_sibling_action(app);
            }
        }

        // Inline title edit (track/board view), edit (inbox view), edit track name (tracks view), or enter edit mode (detail view)
        (KeyModifiers::NONE, KeyCode::Char('e')) => {
            if matches!(app.view, View::Detail { .. }) {
                detail_enter_edit(app, false);
            } else if matches!(app.view, View::Board) {
                board_enter_title_edit(app);
            } else if matches!(app.view, View::Inbox) {
                inbox_edit_title(app);
            } else if matches!(app.view, View::Tracks) {
                tracks_edit_name(app);
            } else {
                enter_title_edit(app);
            }
        }

        // Tag edit: t — detail view jump to tags region, inbox tag edit, or inline tag edit in track/board view
        (KeyModifiers::NONE, KeyCode::Char('t')) => {
            if matches!(app.view, View::Detail { .. }) {
                detail_jump_to_region_and_edit(app, DetailRegion::Tags, false);
            } else if matches!(app.view, View::Board) {
                board_enter_tag_edit(app);
            } else if matches!(app.view, View::Inbox) {
                inbox_edit_tags(app);
            } else {
                enter_tag_edit(app);
            }
        }
        (KeyModifiers::NONE, KeyCode::Char('@')) => {
            if matches!(app.view, View::Detail { .. }) {
                detail_jump_to_region_and_edit(app, DetailRegion::Refs, false);
            }
        }
        (KeyModifiers::NONE, KeyCode::Char('d')) => {
            if matches!(app.view, View::Detail { .. }) {
                detail_jump_to_region_and_edit(app, DetailRegion::Deps, false);
            }
        }

        // Shelve toggle (tracks view only)
        (KeyModifiers::NONE, KeyCode::Char('s')) => {
            if matches!(app.view, View::Tracks) {
                tracks_toggle_shelve(app);
            }
        }

        // Dep popup (track/detail/board view)
        (KeyModifiers::SHIFT, KeyCode::Char('D')) => {
            if matches!(app.view, View::Track(_)) {
                open_dep_popup_from_track_view(app);
            } else if matches!(app.view, View::Board) {
                board_open_dep_popup(app);
            } else if matches!(app.view, View::Detail { .. }) {
                open_dep_popup_from_detail_view(app);
            }
        }

        // Toggle cc tag on task (track/detail), or toggle cc/all mode (board)
        (KeyModifiers::NONE, KeyCode::Char('c')) => {
            if matches!(app.view, View::Board) {
                board_toggle_mode(app);
            } else {
                toggle_cc_tag(app);
            }
        }

        // Set cc-focus to current track
        (KeyModifiers::SHIFT, KeyCode::Char('C')) => {
            set_cc_focus_current(app);
        }

        // Toggle note wrap (detail view only)
        (KeyModifiers::NONE, KeyCode::Char('w')) if matches!(app.view, View::Detail { .. }) => {
            app.toggle_note_wrap();
            app.status_message = Some(
                if app.note_wrap {
                    "wrap: on"
                } else {
                    "wrap: off"
                }
                .into(),
            );
        }

        // Move mode (track, tracks, or inbox view)
        (KeyModifiers::NONE, KeyCode::Char('m')) => {
            if matches!(app.view, View::Inbox) {
                inbox_enter_move_mode(app);
            } else {
                enter_move_mode(app);
            }
        }

        // Cross-track move (track/board/detail view)
        (KeyModifiers::SHIFT, KeyCode::Char('M')) => {
            if matches!(app.view, View::Board) {
                // Resolve board cursor task, then begin cross-track move
                if let Some((track_id, task_id)) = app.board_cursor_task_id() {
                    app.view = View::Track(
                        app.active_track_ids
                            .iter()
                            .position(|id| id == &track_id)
                            .unwrap_or(0),
                    );
                    app.jump_to_task(&task_id);
                    begin_cross_track_move(app);
                }
            } else {
                begin_cross_track_move(app);
            }
        }

        // Redo: Z, Ctrl+Y, Ctrl+Shift+Z, or Super+Shift+Z (must be checked BEFORE undo)
        (m, KeyCode::Char('y')) if m.contains(KeyModifiers::CONTROL) => {
            perform_redo(app);
        }
        (m, KeyCode::Char('z') | KeyCode::Char('Z'))
            if m.contains(KeyModifiers::CONTROL) && m.contains(KeyModifiers::SHIFT) =>
        {
            perform_redo(app);
        }
        (m, KeyCode::Char('z') | KeyCode::Char('Z'))
            if m.contains(KeyModifiers::SUPER) && m.contains(KeyModifiers::SHIFT) =>
        {
            perform_redo(app);
        }
        (KeyModifiers::SHIFT, KeyCode::Char('Z')) => {
            perform_redo(app);
        }

        // Undo: u, z, Ctrl+Z, or Super+Z
        (KeyModifiers::NONE, KeyCode::Char('u') | KeyCode::Char('z')) => {
            perform_undo(app);
        }
        (m, KeyCode::Char('z')) if m.contains(KeyModifiers::CONTROL) => {
            perform_undo(app);
        }
        (m, KeyCode::Char('z')) if m.contains(KeyModifiers::SUPER) => {
            perform_undo(app);
        }

        // Filter prefix key (track view and board view)
        (KeyModifiers::NONE, KeyCode::Char('f')) => {
            if matches!(app.view, View::Track(_) | View::Board) {
                app.filter_pending = true;
            }
        }

        // SELECT mode: v enters select and toggles current task
        (KeyModifiers::NONE, KeyCode::Char('v')) => {
            if matches!(app.view, View::Track(_)) {
                enter_select_mode(app);
            }
        }

        // Range select: V begins range selection mode
        (KeyModifiers::SHIFT, KeyCode::Char('V')) => {
            if matches!(app.view, View::Track(_)) {
                begin_range_select(app);
            }
        }

        // Select all: Ctrl+A
        (m, KeyCode::Char('a')) if m.contains(KeyModifiers::CONTROL) => {
            if matches!(app.view, View::Track(_)) {
                select_all(app);
            }
        }

        // Jump to task by ID: J (available from any view)
        (KeyModifiers::SHIFT, KeyCode::Char('J')) => {
            begin_jump_to(app);
        }

        // Repeat last action: .
        (KeyModifiers::NONE, KeyCode::Char('.')) => {
            repeat_last_action(app);
        }

        // Tag color editor: T (available from any view)
        (KeyModifiers::SHIFT, KeyCode::Char('T')) => {
            app.open_tag_color_popup();
        }

        // Project picker: P (Shift+P, available from any view)
        (KeyModifiers::SHIFT, KeyCode::Char('P')) => {
            open_project_picker(app);
        }

        // Command palette: > (Shift+. reports as NONE or SHIFT depending on terminal)
        (_, KeyCode::Char('>')) => {
            open_command_palette(app);
        }

        _ => {}
    }
}

/// Jump from search results to the selected task/inbox item
fn search_result_jump(app: &mut App) {
    let item = match &app.project_search_results {
        Some(sr) => match sr.items.get(sr.cursor) {
            Some(item) => item.clone(),
            None => return,
        },
        None => return,
    };

    match &item.kind {
        crate::tui::app::SearchResultKind::Track { .. } => {
            if !item.task_id.is_empty() {
                app.jump_to_task(&item.task_id);
            }
        }
        crate::tui::app::SearchResultKind::Inbox { item_index } => {
            let idx = *item_index;
            app.view = View::Inbox;
            let count = app.inbox_count();
            app.inbox_cursor = idx.min(count.saturating_sub(1));
        }
        crate::tui::app::SearchResultKind::Archive { track_id } => {
            app.status_message = Some(format!("Archive task: {} (read-only)", track_id));
        }
    }
}

/// Handle the second key after 'f' prefix for filtering
pub(super) fn handle_filter_key(app: &mut App, key: KeyEvent) {
    let is_board = matches!(app.view, View::Board);
    // Only applies to track view and board view
    if !matches!(app.view, View::Track(_)) && !is_board {
        return;
    }

    // Capture current task ID before changing filter so we can try to stay on it
    let prev_task_id = if is_board {
        None
    } else {
        get_cursor_task_id(app)
    };

    match key.code {
        // State filters: not available in board view (columns are the state filter)
        KeyCode::Char('a') if !is_board => {
            app.filter_state.state_filter = Some(StateFilter::Active);
            reset_cursor_for_filter(app, prev_task_id.as_deref());
        }
        KeyCode::Char('o') if !is_board => {
            app.filter_state.state_filter = Some(StateFilter::Todo);
            reset_cursor_for_filter(app, prev_task_id.as_deref());
        }
        KeyCode::Char('b') if !is_board => {
            app.filter_state.state_filter = Some(StateFilter::Blocked);
            reset_cursor_for_filter(app, prev_task_id.as_deref());
        }
        KeyCode::Char('p') if !is_board => {
            app.filter_state.state_filter = Some(StateFilter::Parked);
            reset_cursor_for_filter(app, prev_task_id.as_deref());
        }
        KeyCode::Char('r') if !is_board => {
            app.filter_state.state_filter = Some(StateFilter::Ready);
            reset_cursor_for_filter(app, prev_task_id.as_deref());
        }
        KeyCode::Char('t') => {
            // Open tag autocomplete for filter tag selection
            begin_filter_tag_select(app);
        }
        KeyCode::Char(' ') if !is_board => {
            // Clear state filter only, keep tag filter
            app.filter_state.clear_state();
            reset_cursor_for_filter(app, prev_task_id.as_deref());
        }
        KeyCode::Char('f') => {
            // Clear all filters
            app.filter_state.clear_all();
            if !is_board {
                reset_cursor_for_filter(app, prev_task_id.as_deref());
            }
        }
        _ => {
            // Unknown second key — ignore silently
        }
    }
}

/// Begin tag filter selection using tag autocomplete
pub(super) fn begin_filter_tag_select(app: &mut App) {
    let candidates = app.collect_all_tags();
    if candidates.is_empty() {
        return;
    }
    // Enter Edit mode with a special edit target for filter tag selection
    app.mode = Mode::Edit;
    app.edit_buffer = String::new();
    app.edit_cursor = 0;
    app.edit_selection_anchor = None;
    app.edit_target = Some(EditTarget::FilterTag);
    app.edit_history = Some(EditHistory::new("", 0, 0));

    let mut ac = AutocompleteState::new(AutocompleteKind::Tag, candidates);
    ac.filter("");
    app.autocomplete = Some(ac);
}

/// Begin jump-to-task prompt: enter Edit mode with task ID autocomplete
pub(super) fn begin_jump_to(app: &mut App) {
    let candidates = app.collect_active_track_task_ids();
    if candidates.is_empty() {
        app.status_message = Some("no tasks to jump to".to_string());
        return;
    }
    app.mode = Mode::Edit;
    app.edit_buffer = String::new();
    app.edit_cursor = 0;
    app.edit_selection_anchor = None;
    app.edit_target = Some(EditTarget::JumpTo);
    app.edit_history = Some(EditHistory::new("", 0, 0));

    let mut ac = AutocompleteState::new(AutocompleteKind::JumpTaskId, candidates);
    ac.filter("");
    app.autocomplete = Some(ac);
}

// ---------------------------------------------------------------------------
// SELECT mode (bulk operations)

/// Expand current node or move to first child (track view)
pub(super) fn expand_or_enter(app: &mut App) {
    if let View::Track(idx) = &app.view {
        let track_id = match app.active_track_ids.get(*idx) {
            Some(id) => id.clone(),
            None => return,
        };
        let flat_items = app.build_flat_items(&track_id);
        let cursor = app.track_states.get(&track_id).map_or(0, |s| s.cursor);

        if cursor >= flat_items.len() {
            return;
        }

        if let FlatItem::Task {
            has_children,
            is_expanded,
            section,
            path,
            ..
        } = &flat_items[cursor]
        {
            if *has_children && !is_expanded {
                // Expand this node
                let track = match app.current_track() {
                    Some(t) => t,
                    None => return,
                };
                if let Some(task) = resolve_task_from_track(track, *section, path) {
                    let key = crate::tui::app::task_expand_key(task, *section, path);
                    let state = app.get_track_state(&track_id);
                    state.expanded.insert(key);
                }
            } else if *has_children && *is_expanded && cursor + 1 < flat_items.len() {
                // Already expanded: move to first child, skipping non-selectable items
                let target = super::common::skip_non_selectable(&flat_items, cursor + 1, 1);
                let state = app.get_track_state(&track_id);
                state.cursor = target;
            }
        }
    }
}

/// Collapse current node or move to parent (track view)
pub(super) fn collapse_or_parent(app: &mut App) {
    if let View::Track(idx) = &app.view {
        let track_id = match app.active_track_ids.get(*idx) {
            Some(id) => id.clone(),
            None => return,
        };
        let flat_items = app.build_flat_items(&track_id);
        let cursor = app.track_states.get(&track_id).map_or(0, |s| s.cursor);

        if cursor >= flat_items.len() {
            return;
        }

        if let FlatItem::Task {
            has_children: _,
            is_expanded,
            section,
            path,
            depth,
            ..
        } = &flat_items[cursor]
        {
            if *is_expanded {
                // Collapse this node
                let track = match app.current_track() {
                    Some(t) => t,
                    None => return,
                };
                if let Some(task) = resolve_task_from_track(track, *section, path) {
                    let key = crate::tui::app::task_expand_key(task, *section, path);
                    let state = app.get_track_state(&track_id);
                    state.expanded.remove(&key);
                }
            } else if *depth > 0 {
                // Move to parent: find the previous item at depth - 1
                let parent_depth = depth - 1;
                for i in (0..cursor).rev() {
                    if let FlatItem::Task { depth: d, .. } = &flat_items[i]
                        && *d == parent_depth
                    {
                        app.get_track_state(&track_id).cursor = i;
                        break;
                    }
                }
            }
        }
    }
}

pub(super) fn resolve_task_from_track<'a>(
    track: &'a crate::model::Track,
    section: crate::model::SectionKind,
    path: &[usize],
) -> Option<&'a crate::model::Task> {
    let tasks = track.section_tasks(section);
    if path.is_empty() {
        return None;
    }
    let mut current = tasks.get(path[0])?;
    for &idx in &path[1..] {
        current = current.subtasks.get(idx)?;
    }
    Some(current)
}

/// Count total tracks (for cursor navigation in tracks view)
pub(super) fn count_tracks(app: &App) -> usize {
    app.project.config.tracks.len()
}

/// Count total recent entries (done tasks + archived tasks) across all tracks
pub(super) fn count_recent_tasks(app: &App) -> usize {
    super::build_recent_entries(app).len()
}

// ---------------------------------------------------------------------------
// Board view helpers
// ---------------------------------------------------------------------------

/// Switch to adjacent board column (direction: -1 = left, 1 = right)
fn board_switch_column(app: &mut App, direction: i32) {
    use crate::tui::app::BoardColumn;

    let max_col = (app.board_state.visible_columns as i32 - 1).max(0);
    let cur = app.board_state.focus_column.index() as i32;
    let new = (cur + direction).clamp(0, max_col);
    app.board_state.focus_column = BoardColumn::from_index(new as usize);
}

/// Toggle board mode between CC and All
fn board_toggle_mode(app: &mut App) {
    use crate::tui::app::BoardMode;
    app.board_state.mode = match app.board_state.mode {
        BoardMode::Cc => BoardMode::All,
        BoardMode::All => BoardMode::Cc,
    };
    // Reset cursors since the lists change
    app.board_state.cursor = [0; 3];
    app.board_state.scroll = [0; 3];
}

/// Open detail view from board cursor
fn board_open_detail(app: &mut App) {
    if let Some((track_id, task_id)) = app.board_cursor_task_id() {
        app.open_detail(track_id, task_id);
    }
}

/// Open dep popup from board cursor
fn board_open_dep_popup(app: &mut App) {
    if let Some((track_id, task_id)) = app.board_cursor_task_id() {
        // Jump to track view, navigate to task, then open popup
        if let Some(idx) = app.active_track_ids.iter().position(|id| id == &track_id) {
            let prev_view = app.view.clone();
            app.view = View::Track(idx);
            app.jump_to_task(&task_id);
            open_dep_popup_from_track_view(app);
            // If popup didn't open (task not found), restore view
            if app.dep_popup.is_none() {
                app.view = prev_view;
            }
        }
    }
}

/// Enter title edit mode from board cursor
fn board_enter_title_edit(app: &mut App) {
    if let Some((track_id, task_id)) = app.board_cursor_task_id() {
        // Jump to track view and enter edit mode
        if let Some(idx) = app.active_track_ids.iter().position(|id| id == &track_id) {
            app.view = View::Track(idx);
            app.jump_to_task(&task_id);
            enter_title_edit(app);
        }
    }
}

/// Enter tag edit mode from board cursor
fn board_enter_tag_edit(app: &mut App) {
    if let Some((track_id, task_id)) = app.board_cursor_task_id()
        && let Some(idx) = app.active_track_ids.iter().position(|id| id == &track_id)
    {
        app.view = View::Track(idx);
        app.jump_to_task(&task_id);
        enter_tag_edit(app);
    }
}