tnj-tui 0.1.2

TUI Tasks, notes and journals in Notebooks
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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::execute;
// Cursor positioning is now handled by ratatui's Frame::set_cursor_position() inside render
use crossterm::terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, size as terminal_size};
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;
use std::io;
use crate::tui::App;
use crate::tui::error::TuiError;
use crate::tui::widgets::editor::Editor;
use crate::utils::parse_key_binding;

/// Guard that ensures terminal state is restored even on panic
/// This is critical for TUI applications - if the terminal is left in raw mode
/// or alternate screen, the user's terminal will be unusable.
struct TerminalGuard {
    /// Track if we successfully entered raw mode
    raw_mode_enabled: bool,
    /// Track if we successfully entered alternate screen
    alternate_screen_enabled: bool,
}

impl TerminalGuard {
    /// Initialize terminal state and return a guard
    /// The guard will restore terminal state when dropped (even on panic)
    fn new() -> Result<Self, TuiError> {
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen)?;
        
        Ok(Self {
            raw_mode_enabled: true,
            alternate_screen_enabled: true,
        })
    }
    
    /// Manually restore terminal state (called on normal exit)
    /// After calling this, the guard will do nothing on drop
    fn restore(&mut self) -> Result<(), TuiError> {
        if self.raw_mode_enabled {
            disable_raw_mode()?;
            self.raw_mode_enabled = false;
        }
        if self.alternate_screen_enabled {
            execute!(io::stdout(), LeaveAlternateScreen)?;
            self.alternate_screen_enabled = false;
        }
        Ok(())
    }
}

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        // Restore terminal state even if we panic
        // Ignore errors in drop - we're already in a cleanup path
        if self.raw_mode_enabled {
            let _ = disable_raw_mode();
        }
        if self.alternate_screen_enabled {
            let _ = execute!(io::stdout(), LeaveAlternateScreen);
        }
    }
}

pub fn run_event_loop(mut app: App) -> Result<(), TuiError> {
    // Check terminal size before entering alternate screen
    // This allows us to show a helpful error message in the normal terminal
    let (width, height) = terminal_size()
        .map_err(|e| TuiError::IoError(e))?;
    
    use crate::tui::layout::Layout;
    let min_width_with_border = Layout::MIN_WIDTH + 2; // +2 for borders
    let min_height_with_border = Layout::MIN_HEIGHT + 2; // +2 for borders
    
    if width < min_width_with_border || height < min_height_with_border {
        return Err(TuiError::RenderError(format!(
            "Terminal size too small. Current: {}x{}, Minimum required: {}x{}. Please resize your terminal window.",
            width, height, min_width_with_border, min_height_with_border
        )));
    }
    
    // Setup terminal with guard to ensure restoration on panic
    let mut guard = TerminalGuard::new()?;
    
    let backend = CrosstermBackend::new(io::stdout());
    let mut terminal = Terminal::new(backend)?;

    loop {
        // Check if status message should be auto-cleared
        app.check_status_message_timeout();

        // Update form editor scroll before rendering
        if app.ui.mode == crate::tui::app::Mode::Create {
            // Extract values before borrowing editor
            let sidebar_width_percent = app.config.sidebar_width_percent;
            let sidebar_collapsed = app.ui.sidebar_state == crate::tui::app::SidebarState::Collapsed;
            
            // Check if current field is a multi-line field and get form type
            let (is_multi_line, form_type) = if let Some(ref form) = app.form.create_form {
                use crate::tui::widgets::form::FormType;
                let is_multi = match form {
                    crate::tui::app::CreateForm::Task(task_form) => {
                        task_form.current_field == crate::tui::app::TaskField::Description
                    }
                    crate::tui::app::CreateForm::Note(note_form) => {
                        note_form.current_field == crate::tui::app::NoteField::Content
                    }
                    crate::tui::app::CreateForm::Journal(journal_form) => {
                        journal_form.current_field == crate::tui::app::JournalField::Content
                    }
                };
                (is_multi, Some(FormType::from(form)))
            } else {
                (false, None)
            };
            
            if let Some(ref mut editor) = app.get_current_form_editor() {
                use crate::tui::layout::Layout;
                let size = terminal.size()?;
                use ratatui::layout::Rect;
                let rect = Rect::new(0, 0, size.width, size.height);
                let layout = Layout::calculate(
                    rect,
                    sidebar_width_percent,
                    sidebar_collapsed,
                );
                
                // Calculate viewport height for multi-line fields
                let viewport_height = if is_multi_line {
                    // Calculate the actual field area height for the multi-line field
                    if let Some(form_type) = form_type {
                        use crate::tui::widgets::form::{calculate_multi_line_field_height, calculate_field_viewport_height};
                        let field_height = calculate_multi_line_field_height(layout.main_area.height, form_type);
                        calculate_field_viewport_height(field_height)
                    } else {
                        (layout.main_area.height - 2) as usize
                    }
                } else {
                    // For single-line fields, use full height (doesn't matter)
                    (layout.main_area.height - 2) as usize
                };
                
                let viewport_width = layout.main_area.width as usize;
                editor.update_scroll(viewport_height);
                editor.update_horizontal_scroll(viewport_width);
            }
        }

        // Render
        // for edit mode, which handles cursor positioning atomically with rendering
        terminal.draw(|f| {
            use crate::tui::layout::Layout;
            let layout = Layout::calculate(
                f.area(),
                app.config.sidebar_width_percent,
                app.ui.sidebar_state == crate::tui::app::SidebarState::Collapsed,
            );
            crate::tui::render::render(f, &mut app, &layout);
        })?;

        // Handle events - only process Press events to avoid duplicate processing on Windows
        if event::poll(std::time::Duration::from_millis(16))? {
            match event::read()? {
                Event::Key(key_event) => {
                    // Only process Press events (ignore Release events to prevent double-processing on Windows)
                    if key_event.kind == KeyEventKind::Press {
                        if handle_key_event(&mut app, key_event)? {
                            break; // Quit requested
                        }
                    }
                }
                Event::Resize(_, _) => {
                    // Terminal will automatically update on next draw, but we can clear any cached state if needed
                    // The layout is recalculated on each render, so no action needed here
                }
                _ => {
                    // Ignore other event types (mouse, etc.)
                }
            }
        }
    }

    // Restore terminal state explicitly (guard will also restore on drop, but this is cleaner)
    guard.restore()?;

    Ok(())
}

fn handle_delete_confirmation_modal(app: &mut App, key_event: KeyEvent) -> Result<bool, TuiError> {
    match key_event.code {
        KeyCode::Up => {
            // Move selection up (wrapping from Archive to Cancel)
            if app.modals.delete_modal_selection == 0 {
                app.modals.delete_modal_selection = 2; // Wrap to Cancel
            } else {
                app.modals.delete_modal_selection -= 1;
            }
            return Ok(false);
        }
        KeyCode::Down => {
            // Move selection down (wrapping from Cancel to Archive)
            if app.modals.delete_modal_selection == 2 {
                app.modals.delete_modal_selection = 0; // Wrap to Archive
            } else {
                app.modals.delete_modal_selection += 1;
            }
            return Ok(false);
        }
        KeyCode::Enter => {
            // Execute selected action
            if app.modals.delete_modal_selection == 2 {
                // Cancel - just close modal
                app.modals.delete_confirmation = None;
                return Ok(false);
            }
            
            if let Some(ref item) = app.modals.delete_confirmation {
                match item {
                    crate::tui::app::SelectedItem::Task(task) => {
                        if let Some(id) = task.id {
                            if app.modals.delete_modal_selection == 0 {
                                // Archive
                                if let Err(e) = app.database.archive_task(id) {
                                    app.set_status_message(format!("Failed to archive task: {}", e));
                                } else {
                                    if let Err(e) = app.load_data() {
                                        app.set_status_message(format!("Failed to reload data: {}", e));
                                    } else {
                                        app.adjust_selected_index();
                                        app.select_current_item();
                                        app.set_status_message("Task archived".to_string());
                                    }
                                }
                            } else if app.modals.delete_modal_selection == 1 {
                                // Delete
                                if let Err(e) = app.database.delete_task(id) {
                                    app.set_status_message(format!("Failed to delete task: {}", e));
                                } else {
                                    if let Err(e) = app.load_data() {
                                        app.set_status_message(format!("Failed to reload data: {}", e));
                                    } else {
                                        app.adjust_selected_index();
                                        app.select_current_item();
                                        app.set_status_message("Task deleted".to_string());
                                    }
                                }
                            }
                        } else {
                            app.set_status_message("Task has no ID".to_string());
                        }
                    }
                    crate::tui::app::SelectedItem::Note(note) => {
                        if let Some(id) = note.id {
                            if app.modals.delete_modal_selection == 0 {
                                // Archive
                                if let Err(e) = app.database.archive_note(id) {
                                    app.set_status_message(format!("Failed to archive note: {}", e));
                                } else {
                                    if let Err(e) = app.load_data() {
                                        app.set_status_message(format!("Failed to reload data: {}", e));
                                    } else {
                                        app.adjust_selected_index();
                                        app.select_current_item();
                                        app.set_status_message("Note archived".to_string());
                                    }
                                }
                            } else if app.modals.delete_modal_selection == 1 {
                                // Delete
                                if let Err(e) = app.database.delete_note(id) {
                                    app.set_status_message(format!("Failed to delete note: {}", e));
                                } else {
                                    if let Err(e) = app.load_data() {
                                        app.set_status_message(format!("Failed to reload data: {}", e));
                                    } else {
                                        app.adjust_selected_index();
                                        app.select_current_item();
                                        app.set_status_message("Note deleted".to_string());
                                    }
                                }
                            }
                        } else {
                            app.set_status_message("Note has no ID".to_string());
                        }
                    }
                    crate::tui::app::SelectedItem::Journal(journal) => {
                        if let Some(id) = journal.id {
                            if app.modals.delete_modal_selection == 0 {
                                // Archive
                                if let Err(e) = app.database.archive_journal(id) {
                                    app.set_status_message(format!("Failed to archive journal entry: {}", e));
                                } else {
                                    if let Err(e) = app.load_data() {
                                        app.set_status_message(format!("Failed to reload data: {}", e));
                                    } else {
                                        app.adjust_selected_index();
                                        app.select_current_item();
                                        app.set_status_message("Journal archived".to_string());
                                    }
                                }
                            } else if app.modals.delete_modal_selection == 1 {
                                // Delete
                                if let Err(e) = app.database.delete_journal(id) {
                                    app.set_status_message(format!("Failed to delete journal entry: {}", e));
                                } else {
                                    if let Err(e) = app.load_data() {
                                        app.set_status_message(format!("Failed to reload data: {}", e));
                                    } else {
                                        app.adjust_selected_index();
                                        app.select_current_item();
                                        app.set_status_message("Journal deleted".to_string());
                                    }
                                }
                            }
                        } else {
                            app.set_status_message("Journal entry has no ID".to_string());
                        }
                    }
                }
            }
            app.modals.delete_confirmation = None;
            return Ok(false);
        }
        KeyCode::Esc => {
            // Cancel deletion
            app.modals.delete_confirmation = None;
            return Ok(false);
        }
        _ => {
            // Ignore all other keys when confirmation modal is shown
            return Ok(false);
        }
    }
}

fn handle_markdown_help_mode(app: &mut App, key_event: KeyEvent) -> Result<bool, TuiError> {
    match key_event.code {
        KeyCode::Esc => {
            app.exit_markdown_help_mode();
            return Ok(false);
        }
        KeyCode::Up => {
            app.scroll_markdown_help_example_up();
            app.scroll_markdown_help_rendered_up();
            return Ok(false);
        }
        KeyCode::Down => {
            app.scroll_markdown_help_example_down();
            app.scroll_markdown_help_rendered_down();
            return Ok(false);
        }
        KeyCode::PageUp => {
            if let Ok((_, height)) = terminal_size() {
                // Calculate viewport height for markdown help (85% of screen height, minus borders)
                let popup_height = (height as f32 * 0.85) as u16;
                let inner_height = popup_height.saturating_sub(2); // Outer block borders
                let panel_height = inner_height.saturating_sub(2); // Panel borders
                let viewport_height = panel_height as usize;
                
                // Get example text to calculate total lines
                use crate::tui::widgets::markdown_help::get_example_markdown;
                let example_text = get_example_markdown();
                let _example_total_lines = example_text.lines().count();
                
                // Scroll both panels together
                app.scroll_markdown_help_example_page_up(viewport_height);
                app.scroll_markdown_help_rendered_page_up(viewport_height);
            }
            return Ok(false);
        }
        KeyCode::PageDown => {
            if let Ok((_, height)) = terminal_size() {
                // Calculate viewport height for markdown help
                let popup_height = (height as f32 * 0.85) as u16;
                let inner_height = popup_height.saturating_sub(2);
                let panel_height = inner_height.saturating_sub(2);
                let viewport_height = panel_height as usize;
                
                // Get example text to calculate total lines
                use crate::tui::widgets::markdown_help::get_example_markdown;
                let example_text = get_example_markdown();
                let example_total_lines = example_text.lines().count();
                
                // Use example lines as approximation for rendered lines
                app.scroll_markdown_help_example_page_down(viewport_height, example_total_lines);
                app.scroll_markdown_help_rendered_page_down(viewport_height, example_total_lines);
            }
            return Ok(false);
        }
        KeyCode::Home => {
            app.ui.markdown_help_example_scroll = 0;
            app.ui.markdown_help_rendered_scroll = 0;
            return Ok(false);
        }
        KeyCode::End => {
            if let Ok((_, height)) = terminal_size() {
                let popup_height = (height as f32 * 0.85) as u16;
                let inner_height = popup_height.saturating_sub(2);
                let panel_height = inner_height.saturating_sub(2);
                let viewport_height = panel_height as usize;
                
                use crate::tui::widgets::markdown_help::get_example_markdown;
                let example_text = get_example_markdown();
                let example_total_lines = example_text.lines().count();
                
                // Use example lines as approximation for rendered lines
                app.ui.markdown_help_example_scroll = example_total_lines.saturating_sub(viewport_height);
                app.ui.markdown_help_rendered_scroll = example_total_lines.saturating_sub(viewport_height);
            }
            return Ok(false);
        }
        _ => {
            // Check if help binding is pressed again to toggle off
            let help_binding = parse_key_binding(&app.config.key_bindings.help)
                .map_err(|e| TuiError::KeyBindingError(e))?;
            if matches_key_event(key_event, &help_binding) {
                app.exit_markdown_help_mode();
                return Ok(false);
            }
            // Ignore all other keys in markdown help mode
            return Ok(false);
        }
    }
}

fn handle_key_event(app: &mut App, key_event: KeyEvent) -> Result<bool, TuiError> {
    // Handle delete confirmation modal first (before other modes)
    if app.modals.delete_confirmation.is_some() {
        return handle_delete_confirmation_modal(app, key_event);
    }

    // Handle markdown help mode first (before create mode)
    if app.ui.mode == crate::tui::app::Mode::MarkdownHelp {
        return handle_markdown_help_mode(app, key_event);
    }

    // Handle create mode (before edit mode)
    // When in create mode, handle form navigation and editor input
    if app.ui.mode == crate::tui::app::Mode::Create {
        return handle_create_mode(app, key_event);
    }

    // Handle help mode
    if app.ui.mode == crate::tui::app::Mode::Help {
        return handle_help_mode(app, key_event);
    }

    // Handle settings mode
    // Only handle Esc and settings binding here; other keys fall through to global bindings
    if app.ui.mode == crate::tui::app::Mode::Settings {
        match key_event.code {
            KeyCode::Esc => {
                app.exit_settings_mode();
                return Ok(false);
            }
            _ => {
                // Check if settings binding is pressed again to toggle off
                let settings_binding = parse_key_binding(&app.config.key_bindings.settings)
                    .map_err(|e| TuiError::KeyBindingError(e))?;
                if matches_key_event(key_event, &settings_binding) {
                    app.exit_settings_mode();
                    return Ok(false);
                }
                // Allow arrow keys and select in settings mode
                // These will be handled in handle_global_key_bindings
            }
        }
    }

    // Handle notebook modal mode
    if app.ui.mode == crate::tui::app::Mode::NotebookModal {
        return handle_notebook_modal_mode(app, key_event);
    }

    // Handle search mode
    if app.ui.mode == crate::tui::app::Mode::Search {
        return handle_search_mode(app, key_event);
    }

    // Handle filter mode
    if app.ui.mode == crate::tui::app::Mode::Filter {
        return handle_filter_mode(app, key_event);
    }

fn handle_create_mode(app: &mut App, key_event: KeyEvent) -> Result<bool, TuiError> {
    // Check for save binding (Ctrl+s or Alt+s on macOS)
    let save_binding = parse_key_binding(&app.config.key_bindings.save)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    let mut is_save = matches_key_event(key_event, &save_binding);
    
    // On macOS, Option+s may produce a special character (like 'Å›') without ALT modifier
    // Check for this case before the character gets inserted into the editor
    #[cfg(target_os = "macos")]
    {
        if !is_save {
            is_save = match key_event.code {
                KeyCode::Char(c) => {
                    // Option+s on macOS typically produces 'Å›' (U+015B)
                    // Also check for other possible Option+s results depending on keyboard layout
                    c == 'ś' || c == 'Ś' || c == 'ß' || c == '§'
                }
                _ => false,
            };
        }
    }
    
    if is_save {
        // Save with error handling - most errors are already shown via status messages
        // But if there's an unexpected error, show it
        match app.save_create_form() {
            Ok(()) => {
                // Success - status message already set in save_create_form
            }
            Err(e) => {
                // This should rarely happen since save_create_form handles most errors internally
                app.set_status_message(format!("Unexpected error while saving: {}", e));
            }
        }
        return Ok(false);
    }

    // Check for notebook field navigation (up/down arrows)
    // Tab/Shift+Tab should still work to navigate away from notebook field
    if app.is_notebook_field_active() {
        match key_event.code {
            KeyCode::Up => {
                if let Some(ref mut form) = app.form.create_form {
                    match form {
                        crate::tui::app::CreateForm::Task(task_form) => {
                            if task_form.notebook_selected_index > 0 {
                                task_form.notebook_selected_index -= 1;
                                task_form.notebook_id = if task_form.notebook_selected_index == 0 {
                                    None
                                } else {
                                    app.notebooks.notebooks.get(task_form.notebook_selected_index - 1)
                                        .and_then(|n| n.id)
                                };
                            }
                        }
                        crate::tui::app::CreateForm::Note(note_form) => {
                            if note_form.notebook_selected_index > 0 {
                                note_form.notebook_selected_index -= 1;
                                note_form.notebook_id = if note_form.notebook_selected_index == 0 {
                                    None
                                } else {
                                    app.notebooks.notebooks.get(note_form.notebook_selected_index - 1)
                                        .and_then(|n| n.id)
                                };
                            }
                        }
                        crate::tui::app::CreateForm::Journal(journal_form) => {
                            if journal_form.notebook_selected_index > 0 {
                                journal_form.notebook_selected_index -= 1;
                                journal_form.notebook_id = if journal_form.notebook_selected_index == 0 {
                                    None
                                } else {
                                    app.notebooks.notebooks.get(journal_form.notebook_selected_index - 1)
                                        .and_then(|n| n.id)
                                };
                            }
                        }
                    }
                }
                return Ok(false);
            }
            KeyCode::Down => {
                if let Some(ref mut form) = app.form.create_form {
                    // max_valid_index is app.notebooks.len() (the last valid index)
                    // Index 0 = "[None]", indices 1..=len() = notebooks
                    // So if we have 3 notebooks, valid indices are 0, 1, 2, 3
                    // We use len() + 1 for the comparison to allow reaching index len()
                    let max_valid_index = app.notebooks.notebooks.len();
                    let max_index_for_check = app.notebooks.notebooks.len() + 1;
                    match form {
                        crate::tui::app::CreateForm::Task(task_form) => {
                            if task_form.notebook_selected_index < max_index_for_check {
                                task_form.notebook_selected_index += 1;
                                // Clamp to maximum valid index to prevent going out of bounds
                                if task_form.notebook_selected_index > max_valid_index {
                                    task_form.notebook_selected_index = max_valid_index;
                                }
                                task_form.notebook_id = if task_form.notebook_selected_index == 0 {
                                    None
                                } else {
                                    app.notebooks.notebooks.get(task_form.notebook_selected_index - 1)
                                        .and_then(|n| n.id)
                                };
                            }
                        }
                        crate::tui::app::CreateForm::Note(note_form) => {
                            if note_form.notebook_selected_index < max_index_for_check {
                                note_form.notebook_selected_index += 1;
                                // Clamp to maximum valid index to prevent going out of bounds
                                if note_form.notebook_selected_index > max_valid_index {
                                    note_form.notebook_selected_index = max_valid_index;
                                }
                                note_form.notebook_id = if note_form.notebook_selected_index == 0 {
                                    None
                                } else {
                                    app.notebooks.notebooks.get(note_form.notebook_selected_index - 1)
                                        .and_then(|n| n.id)
                                };
                            }
                        }
                        crate::tui::app::CreateForm::Journal(journal_form) => {
                            if journal_form.notebook_selected_index < max_index_for_check {
                                journal_form.notebook_selected_index += 1;
                                // Clamp to maximum valid index to prevent going out of bounds
                                if journal_form.notebook_selected_index > max_valid_index {
                                    journal_form.notebook_selected_index = max_valid_index;
                                }
                                journal_form.notebook_id = if journal_form.notebook_selected_index == 0 {
                                    None
                                } else {
                                    app.notebooks.notebooks.get(journal_form.notebook_selected_index - 1)
                                        .and_then(|n| n.id)
                                };
                            }
                        }
                    }
                }
                return Ok(false);
            }
            // Allow Tab/Shift+Tab to pass through for field navigation
            KeyCode::Tab | KeyCode::BackTab => {
                // Let the Tab handling code below handle this
            }
            _ => {}
        }
    }

    // Check for Tab/Shift+Tab/Enter for field navigation
    // Enter behavior: insert newline if Content field is active, otherwise navigate to next field
    match key_event.code {
        KeyCode::BackTab => {
            // Shift+Tab is sometimes sent as BackTab on some terminals
            app.navigate_form_field(false);
            return Ok(false);
        }
        KeyCode::Tab => {
            let forward = !key_event.modifiers.contains(KeyModifiers::SHIFT);
            app.navigate_form_field(forward);
            return Ok(false);
        }
        KeyCode::Enter => {
            // Check if we're in a Content field - if so, insert newline instead of navigating
            if app.is_content_field_active() {
                // Content field is active - insert newline
                if let Some(ref mut editor) = app.get_current_form_editor() {
                    editor.insert_newline();
                }
                return Ok(false);
            } else {
                // Not in Content field - navigate to next field
                app.navigate_form_field(true);
                return Ok(false);
            }
        }
        KeyCode::Esc => {
            // Cancel creation
            app.exit_create_mode();
            return Ok(false);
        }
        _ => {
            // Check for help binding before default handling
            let help_binding = parse_key_binding(&app.config.key_bindings.help)
                .map_err(|e| TuiError::KeyBindingError(e))?;
            if matches_key_event(key_event, &help_binding) {
                app.enter_markdown_help_mode();
                return Ok(false);
            }
        }
    }

    // Forward all other keys to the current form field's editor
    // Extract config values before borrowing editor
    let undo_binding = parse_key_binding(&app.config.key_bindings.undo)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    let word_left_binding = parse_key_binding(&app.config.key_bindings.word_left)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    let word_right_binding = parse_key_binding(&app.config.key_bindings.word_right)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    
    if let Some(ref mut editor) = app.get_current_form_editor() {
        // Handle undo using config binding
        if matches_key_event(key_event, &undo_binding) {
            editor.undo();
            return Ok(false);
        }
        
        // Handle copy (Ctrl+C or Alt+C on macOS)
        if crate::utils::has_primary_modifier(key_event.modifiers) && 
           (key_event.code == KeyCode::Char('c') || key_event.code == KeyCode::Char('C')) {
            let selected_text = editor.get_selected_text();
            if let Ok(mut clipboard) = arboard::Clipboard::new() {
                if let Err(e) = clipboard.set_text(&selected_text) {
                    app.set_status_message(format!("Failed to copy to clipboard: {}", e));
                } else if !selected_text.is_empty() {
                    app.set_status_message("Copied to clipboard".to_string());
                }
            } else {
                app.set_status_message("Failed to access clipboard".to_string());
            }
            return Ok(false);
        }
        
        // Handle cut (Ctrl+X or Alt+X on macOS)
        if crate::utils::has_primary_modifier(key_event.modifiers) && 
           (key_event.code == KeyCode::Char('x') || key_event.code == KeyCode::Char('X')) {
            let selected_text = editor.get_selected_text();
            if let Ok(mut clipboard) = arboard::Clipboard::new() {
                if let Err(e) = clipboard.set_text(&selected_text) {
                    app.set_status_message(format!("Failed to copy to clipboard: {}", e));
                } else {
                    if !selected_text.is_empty() {
                        editor.delete_selection();
                        app.set_status_message("Cut to clipboard".to_string());
                    }
                }
            } else {
                app.set_status_message("Failed to access clipboard".to_string());
            }
            return Ok(false);
        }
        
        // Handle select all (Ctrl+A or Alt+A on macOS)
        if crate::utils::has_primary_modifier(key_event.modifiers) && 
           (key_event.code == KeyCode::Char('a') || key_event.code == KeyCode::Char('A')) {
            editor.select_all();
            return Ok(false);
        }
        
        // Handle word navigation using config bindings
        
        let extend_selection = key_event.modifiers.contains(KeyModifiers::SHIFT);
        
        match key_event.code {
            KeyCode::Char(c) => {
                // Skip if primary modifier is held (to avoid inserting 'c' or 'x' when copy/cut is intended)
                if crate::utils::has_primary_modifier(key_event.modifiers) {
                    return Ok(false);
                }
                editor.insert_char(c);
                return Ok(false);
            }
            KeyCode::Backspace => {
                editor.delete_char();
                return Ok(false);
            }
            KeyCode::Up => {
                editor.move_cursor_up(extend_selection);
                return Ok(false);
            }
            KeyCode::Down => {
                editor.move_cursor_down(extend_selection);
                return Ok(false);
            }
            KeyCode::Left => {
                if matches_key_event(key_event, &word_left_binding) {
                    editor.move_cursor_word_left(extend_selection);
                } else {
                    editor.move_cursor_left(extend_selection);
                }
                return Ok(false);
            }
            KeyCode::Right => {
                if matches_key_event(key_event, &word_right_binding) {
                    editor.move_cursor_word_right(extend_selection);
                } else {
                    editor.move_cursor_right(extend_selection);
                }
                return Ok(false);
            }
            KeyCode::Home => {
                editor.move_cursor_home(extend_selection);
                return Ok(false);
            }
            KeyCode::End => {
                editor.move_cursor_end(extend_selection);
                return Ok(false);
            }
            _ => {
                // Ignore other keys in create mode
                return Ok(false);
            }
        }
    }
    Ok(false)
}

fn handle_help_mode(app: &mut App, key_event: KeyEvent) -> Result<bool, TuiError> {
    match key_event.code {
        KeyCode::Esc => {
            app.exit_help_mode();
            return Ok(false);
        }
        _ => {
            // Check if help binding is pressed again to toggle off
            let help_binding = parse_key_binding(&app.config.key_bindings.help)
                .map_err(|e| TuiError::KeyBindingError(e))?;
            if matches_key_event(key_event, &help_binding) {
                app.exit_help_mode();
                return Ok(false);
            }
            // Ignore all other keys in help mode
            return Ok(false);
        }
    }
}

fn handle_notebook_modal_mode(app: &mut App, key_event: KeyEvent) -> Result<bool, TuiError> {
    match key_event.code {
        KeyCode::Esc => {
            app.exit_notebook_modal_mode();
            return Ok(false);
        }
        _ => {
            // Check if notebook modal binding is pressed again to toggle off
            let notebook_modal_binding = parse_key_binding(&app.config.key_bindings.notebook_modal)
                .map_err(|e| TuiError::KeyBindingError(e))?;
            let mut is_notebook_modal = matches_key_event(key_event, &notebook_modal_binding);
            
            // On macOS, Option+n may produce a special character (like '˜') without ALT modifier
            // Check for this case before the character gets inserted into the editor
            #[cfg(target_os = "macos")]
            {
                if !is_notebook_modal {
                    is_notebook_modal = match key_event.code {
                        KeyCode::Char(c) => {
                            // Option+n on macOS typically produces '˜' (U+02DC, small tilde)
                            // Also check for regular tilde '~' (U+007E) depending on keyboard layout
                            c == '˜' || c == '~'
                        }
                        _ => false,
                    };
                }
            }
            
            if is_notebook_modal {
                app.exit_notebook_modal_mode();
                return Ok(false);
            }
        }
    }

    if let Some(ref mut state) = app.notebooks.modal_state {
        // Handle field navigation
        match key_event.code {
            KeyCode::Tab | KeyCode::BackTab => {
                app.navigate_notebook_modal();
                return Ok(false);
            }
            KeyCode::Up => {
                match state.current_field {
                    crate::tui::app::NotebookModalField::NotebookList => {
                        app.move_notebook_selection_up();
                    }
                    crate::tui::app::NotebookModalField::ActionsList => {
                        app.move_actions_selection_up();
                    }
                }
                return Ok(false);
            }
            KeyCode::Down => {
                match state.current_field {
                    crate::tui::app::NotebookModalField::NotebookList => {
                        app.move_notebook_selection_down();
                    }
                    crate::tui::app::NotebookModalField::ActionsList => {
                        app.move_actions_selection_down();
                    }
                }
                return Ok(false);
            }
            KeyCode::Enter => {
                // If in Add or Rename mode, save the notebook
                if matches!(state.mode, crate::tui::app::NotebookModalMode::Add | crate::tui::app::NotebookModalMode::Rename) {
                    let name = if state.name_editor.lines.is_empty() {
                        String::new()
                    } else {
                        state.name_editor.lines[0].clone()
                    };
                    
                    let selected_idx = state.selected_index;
                    let mode = state.mode.clone();
                    let notebook_id_opt = if selected_idx > 0 {
                        app.notebooks.notebooks.get(selected_idx - 1).and_then(|n| n.id)
                    } else {
                        None
                    };
                    
                    // Release the borrow on state by ending the if let block
                    // We'll re-borrow after calling methods
                    
                    match mode {
                        crate::tui::app::NotebookModalMode::Add => {
                            if let Err(e) = app.add_notebook(name) {
                                app.set_status_message(format!("Failed to add notebook: {}", e));
                            } else {
                                // Reload notebooks
                                app.notebooks.notebooks = app.database.get_all_notebooks().unwrap_or_default();
                                if let Some(ref mut new_state) = app.notebooks.modal_state {
                                    new_state.mode = crate::tui::app::NotebookModalMode::View;
                                    new_state.name_editor = Editor::new();
                                }
                            }
                        }
                        crate::tui::app::NotebookModalMode::Rename => {
                            if let Some(id) = notebook_id_opt {
                                if let Err(e) = app.rename_notebook(id, name) {
                                    app.set_status_message(format!("Failed to rename notebook: {}", e));
                                } else {
                                    // Reload notebooks
                                    app.notebooks.notebooks = app.database.get_all_notebooks().unwrap_or_default();
                                    if let Some(ref mut new_state) = app.notebooks.modal_state {
                                        new_state.mode = crate::tui::app::NotebookModalMode::View;
                                        new_state.name_editor = Editor::new();
                                    }
                                }
                            }
                        }
                        _ => {}
                    }
                    return Ok(false);
                }
                
                // Otherwise, handle field actions
                match state.current_field {
                    crate::tui::app::NotebookModalField::ActionsList => {
                        // Handle action based on actions_selected_index
                        // 0 = Add, 1 = Rename, 2 = Delete, 3 = Switch
                        match state.actions_selected_index {
                            0 => {
                                // Add
                                state.mode = crate::tui::app::NotebookModalMode::Add;
                                state.name_editor = Editor::new();
                            }
                            1 => {
                                // Rename
                                if state.selected_index > 0 {
                                    // Can't rename "[None]"
                                    let notebook_id = app.notebooks.notebooks.get(state.selected_index - 1)
                                        .and_then(|n| n.id);
                                    if let Some(id) = notebook_id {
                                        state.mode = crate::tui::app::NotebookModalMode::Rename;
                                        state.name_editor = Editor::from_string(
                                            app.notebooks.notebooks.iter()
                                                .find(|n| n.id == Some(id))
                                                .map(|n| n.name.clone())
                                                .unwrap_or_default()
                                        );
                                    }
                                }
                            }
                            2 => {
                                // Delete
                                if state.selected_index > 0 {
                                    // Can't delete "[None]"
                                    let notebook_id = app.notebooks.notebooks.get(state.selected_index - 1)
                                        .and_then(|n| n.id);
                                    if let Some(id) = notebook_id {
                                        let selected_idx = state.selected_index;
                                        
                                        // Release the borrow on state by ending the if let block
                                        
                                        if let Err(e) = app.delete_notebook(id) {
                                            app.set_status_message(format!("Failed to delete notebook: {}", e));
                                        } else {
                                            // Reload notebooks and reset selection
                                            app.notebooks.notebooks = app.database.get_all_notebooks().unwrap_or_default();
                                            if let Some(ref mut new_state) = app.notebooks.modal_state {
                                                if selected_idx > app.notebooks.notebooks.len() {
                                                    new_state.selected_index = app.notebooks.notebooks.len();
                                                }
                                                new_state.list_state.select(Some(new_state.selected_index));
                                            }
                                        }
                                    }
                                }
                            }
                            3 => {
                                // Switch
                                let notebook_id = if state.selected_index == 0 {
                                    None // "[None]"
                                } else {
                                    app.notebooks.notebooks.get(state.selected_index - 1)
                                        .and_then(|n| n.id)
                                };
                                if let Err(e) = app.switch_notebook(notebook_id) {
                                    app.set_status_message(format!("Failed to switch notebook: {}", e));
                                } else {
                                    app.exit_notebook_modal_mode();
                                }
                                return Ok(false);
                            }
                            _ => {}
                        }
                    }
                    crate::tui::app::NotebookModalField::NotebookList => {
                        // Switch to the selected notebook
                        let notebook_id = if state.selected_index == 0 {
                            None // "[None]"
                        } else {
                            app.notebooks.notebooks.get(state.selected_index - 1)
                                .and_then(|n| n.id)
                        };
                        if let Err(e) = app.switch_notebook(notebook_id) {
                            app.set_status_message(format!("Failed to switch notebook: {}", e));
                        } else {
                            app.exit_notebook_modal_mode();
                        }
                        return Ok(false);
                    }
                }
                return Ok(false);
            }
            _ => {
                // Handle text input for add/rename mode
                if matches!(state.mode, crate::tui::app::NotebookModalMode::Add | crate::tui::app::NotebookModalMode::Rename) {
                    let undo_binding = parse_key_binding(&app.config.key_bindings.undo)
                        .map_err(|e| TuiError::KeyBindingError(e))?;
                    
                    if let Some(ref mut editor) = app.get_notebook_modal_editor() {
                        if matches_key_event(key_event, &undo_binding) {
                            editor.undo();
                            return Ok(false);
                        }
                        
                        let extend_selection = key_event.modifiers.contains(KeyModifiers::SHIFT);
                        
                        match key_event.code {
                            KeyCode::Char(c) => {
                                if crate::utils::has_primary_modifier(key_event.modifiers) {
                                    return Ok(false);
                                }
                                editor.insert_char(c);
                                return Ok(false);
                            }
                            KeyCode::Backspace => {
                                editor.delete_char();
                                return Ok(false);
                            }
                            KeyCode::Left => {
                                editor.move_cursor_left(extend_selection);
                                return Ok(false);
                            }
                            KeyCode::Right => {
                                editor.move_cursor_right(extend_selection);
                                return Ok(false);
                            }
                            KeyCode::Home => {
                                editor.move_cursor_home(extend_selection);
                                return Ok(false);
                            }
                            KeyCode::End => {
                                editor.move_cursor_end(extend_selection);
                                return Ok(false);
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
    }
    Ok(false)
}

fn handle_search_mode(app: &mut App, key_event: KeyEvent) -> Result<bool, TuiError> {
    match key_event.code {
        KeyCode::Esc => {
            app.exit_search_mode();
            return Ok(false);
        }
        KeyCode::Enter => {
            app.exit_search_mode();
            return Ok(false);
        }
        KeyCode::Char(c) => {
            app.add_to_search(c);
            return Ok(false);
        }
        KeyCode::Backspace => {
            app.remove_from_search();
            return Ok(false);
        }
        _ => Ok(false)
    }
}

fn handle_filter_mode(app: &mut App, key_event: KeyEvent) -> Result<bool, TuiError> {
    match key_event.code {
        KeyCode::Esc => {
            app.exit_filter_mode();
            return Ok(false);
        }
        KeyCode::BackTab => {
            app.navigate_filter_field(false);
            return Ok(false);
        }
        KeyCode::Tab => {
            let forward = !key_event.modifiers.contains(KeyModifiers::SHIFT);
            app.navigate_filter_field(forward);
            return Ok(false);
        }
        KeyCode::Enter => {
            // Check which field is active
            if let Some(ref state) = app.filter.form_state {
                match state.current_field {
                    crate::tui::app::FilterFormField::Apply => {
                        app.apply_filters();
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Clear => {
                        app.clear_filters();
                        app.exit_filter_mode();
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Cancel => {
                        app.exit_filter_mode();
                        return Ok(false);
                    }
                    _ => {
                        // Navigate to next field
                        app.navigate_filter_field(true);
                        return Ok(false);
                    }
                }
            } else {
                // No form state available, ignore the Enter key
                return Ok(false);
            }
        }
        KeyCode::Up => {
            if let Some(ref mut state) = app.filter.form_state {
                match state.current_field {
                    crate::tui::app::FilterFormField::Archived => {
                        app.move_filter_archived_up();
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Status => {
                        app.move_filter_status_up();
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::TagLogic => {
                        app.move_filter_tag_logic_up();
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Apply => {
                        // Wrap to Cancel
                        state.current_field = crate::tui::app::FilterFormField::Cancel;
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Clear => {
                        // Move to Apply
                        state.current_field = crate::tui::app::FilterFormField::Apply;
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Cancel => {
                        // Move to Clear
                        state.current_field = crate::tui::app::FilterFormField::Clear;
                        return Ok(false);
                    }
                    _ => {}
                }
            }
        }
        KeyCode::Down => {
            if let Some(ref mut state) = app.filter.form_state {
                match state.current_field {
                    crate::tui::app::FilterFormField::Archived => {
                        app.move_filter_archived_down();
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Status => {
                        app.move_filter_status_down();
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::TagLogic => {
                        app.move_filter_tag_logic_down();
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Apply => {
                        // Move to Clear
                        state.current_field = crate::tui::app::FilterFormField::Clear;
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Clear => {
                        // Move to Cancel
                        state.current_field = crate::tui::app::FilterFormField::Cancel;
                        return Ok(false);
                    }
                    crate::tui::app::FilterFormField::Cancel => {
                        // Wrap to Apply
                        state.current_field = crate::tui::app::FilterFormField::Apply;
                        return Ok(false);
                    }
                    _ => {}
                }
            }
        }
        _ => {
            // Handle text input for tags field
            if app.is_filter_tags_field_active() {
                let undo_binding = parse_key_binding(&app.config.key_bindings.undo)
                    .map_err(|e| TuiError::KeyBindingError(e))?;
                let word_left_binding = parse_key_binding(&app.config.key_bindings.word_left)
                    .map_err(|e| TuiError::KeyBindingError(e))?;
                let word_right_binding = parse_key_binding(&app.config.key_bindings.word_right)
                    .map_err(|e| TuiError::KeyBindingError(e))?;
                
                if let Some(ref mut editor) = app.get_current_filter_editor() {
                    if matches_key_event(key_event, &undo_binding) {
                        editor.undo();
                        return Ok(false);
                    }
                    
                    // Handle copy (Ctrl+C or Alt+C on macOS)
                    if crate::utils::has_primary_modifier(key_event.modifiers) && 
                       (key_event.code == KeyCode::Char('c') || key_event.code == KeyCode::Char('C')) {
                        let selected_text = editor.get_selected_text();
                        if let Ok(mut clipboard) = arboard::Clipboard::new() {
                            if let Err(e) = clipboard.set_text(&selected_text) {
                                app.set_status_message(format!("Failed to copy to clipboard: {}", e));
                            } else if !selected_text.is_empty() {
                                app.set_status_message("Copied to clipboard".to_string());
                            }
                        } else {
                            app.set_status_message("Failed to access clipboard".to_string());
                        }
                        return Ok(false);
                    }
                    
                    // Handle cut (Ctrl+X or Alt+X on macOS)
                    if crate::utils::has_primary_modifier(key_event.modifiers) && 
                       (key_event.code == KeyCode::Char('x') || key_event.code == KeyCode::Char('X')) {
                        let selected_text = editor.get_selected_text();
                        if let Ok(mut clipboard) = arboard::Clipboard::new() {
                            if let Err(e) = clipboard.set_text(&selected_text) {
                                app.set_status_message(format!("Failed to copy to clipboard: {}", e));
                            } else {
                                if !selected_text.is_empty() {
                                    editor.delete_selection();
                                    app.set_status_message("Cut to clipboard".to_string());
                                }
                            }
                        } else {
                            app.set_status_message("Failed to access clipboard".to_string());
                        }
                        return Ok(false);
                    }
                    
                    // Handle select all (Ctrl+A or Alt+A on macOS)
                    if crate::utils::has_primary_modifier(key_event.modifiers) && 
                       (key_event.code == KeyCode::Char('a') || key_event.code == KeyCode::Char('A')) {
                        editor.select_all();
                        return Ok(false);
                    }
                    
                    let extend_selection = key_event.modifiers.contains(KeyModifiers::SHIFT);
                    
                    match key_event.code {
                        KeyCode::Char(c) => {
                            // Skip if primary modifier is held (to avoid inserting 'c' or 'x' when copy/cut is intended)
                            if crate::utils::has_primary_modifier(key_event.modifiers) {
                                return Ok(false);
                            }
                            editor.insert_char(c);
                            return Ok(false);
                        }
                        KeyCode::Backspace => {
                            editor.delete_char();
                            return Ok(false);
                        }
                        KeyCode::Up => {
                            editor.move_cursor_up(extend_selection);
                            return Ok(false);
                        }
                        KeyCode::Down => {
                            editor.move_cursor_down(extend_selection);
                            return Ok(false);
                        }
                        KeyCode::Left => {
                            if matches_key_event(key_event, &word_left_binding) {
                                editor.move_cursor_word_left(extend_selection);
                            } else {
                                editor.move_cursor_left(extend_selection);
                            }
                            return Ok(false);
                        }
                        KeyCode::Right => {
                            if matches_key_event(key_event, &word_right_binding) {
                                editor.move_cursor_word_right(extend_selection);
                            } else {
                                editor.move_cursor_right(extend_selection);
                            }
                            return Ok(false);
                        }
                        KeyCode::Home => {
                            editor.move_cursor_home(extend_selection);
                            return Ok(false);
                        }
                        KeyCode::End => {
                            editor.move_cursor_end(extend_selection);
                            return Ok(false);
                        }
                        _ => {}
                    }
                }
            }
        }
    }
    Ok(false)
}

    // Handle global key bindings (work across all modes)
    return handle_global_key_bindings(app, key_event);
}

fn handle_global_key_bindings(app: &mut App, key_event: KeyEvent) -> Result<bool, TuiError> {
    // Check for quit key
    let quit_binding = parse_key_binding(&app.config.key_bindings.quit)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &quit_binding) {
        return Ok(true); // Quit
    }

    // Check for toggle sidebar (Ctrl+b or Alt+b on macOS)
    let toggle_binding = parse_key_binding(&app.config.key_bindings.toggle_sidebar)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &toggle_binding) {
        app.toggle_sidebar();
        return Ok(false);
    }

    // Check for notebook modal binding - process early to catch Option+n before other handlers
    let notebook_modal_binding = parse_key_binding(&app.config.key_bindings.notebook_modal)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    let mut is_notebook_modal = matches_key_event(key_event, &notebook_modal_binding);
    
    // On macOS, Option+n may produce a special character (like '˜') without ALT modifier
    // Check for this case before the character gets inserted into the editor
    #[cfg(target_os = "macos")]
    {
        if !is_notebook_modal {
            is_notebook_modal = match key_event.code {
                KeyCode::Char(c) => {
                    // Option+n on macOS typically produces '˜' (U+02DC, small tilde)
                    // Also check for regular tilde '~' (U+007E) depending on keyboard layout
                    c == '˜' || c == '~'
                }
                _ => false,
            };
        }
    }
    
    if is_notebook_modal {
        if app.ui.mode == crate::tui::app::Mode::NotebookModal {
            app.exit_notebook_modal_mode();
        } else {
            app.enter_notebook_modal_mode();
        }
        return Ok(false);
    }

    // Check for tab navigation - process these early and return to prevent double-processing
    let tab_left_binding = parse_key_binding(&app.config.key_bindings.tab_left)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &tab_left_binding) {
        match app.ui.current_tab {
            crate::tui::app::Tab::Tasks => {
                // Already at first tab, do nothing
            }
            crate::tui::app::Tab::Notes => {
                app.switch_tab(crate::tui::app::Tab::Tasks);
            }
            crate::tui::app::Tab::Journal => {
                app.switch_tab(crate::tui::app::Tab::Notes);
            }
        }
        return Ok(false);
    }

    let tab_right_binding = parse_key_binding(&app.config.key_bindings.tab_right)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &tab_right_binding) {
        match app.ui.current_tab {
            crate::tui::app::Tab::Tasks => {
                app.switch_tab(crate::tui::app::Tab::Notes);
            }
            crate::tui::app::Tab::Notes => {
                app.switch_tab(crate::tui::app::Tab::Journal);
            }
            crate::tui::app::Tab::Journal => {
                // Already at last tab, do nothing
            }
        }
        return Ok(false);
    }

    // Check for task reordering (Ctrl+Up/Down or Alt+Up/Down on macOS) - only on Tasks tab in View mode
    if app.ui.mode == crate::tui::app::Mode::View 
        && app.ui.current_tab == crate::tui::app::Tab::Tasks
        && crate::utils::has_primary_modifier(key_event.modifiers) {
        match key_event.code {
            KeyCode::Up => {
                if let Err(e) = app.reorder_task_up() {
                    app.set_status_message(format!("Failed to reorder task: {}", e));
                }
                return Ok(false);
            }
            KeyCode::Down => {
                if let Err(e) = app.reorder_task_down() {
                    app.set_status_message(format!("Failed to reorder task: {}", e));
                }
                return Ok(false);
            }
            _ => {}
        }
    }

    // Check for arrow key navigation (when not in create mode)
    // Arrow keys work as an alternative to configured bindings
    // In Settings mode, Up/Down arrows navigate between categories
    if app.ui.mode != crate::tui::app::Mode::Create {
        match key_event.code {
            KeyCode::Up => {
                if app.ui.mode == crate::tui::app::Mode::Settings {
                    // Up/Down arrows navigate between settings categories
                    app.move_settings_category_up();
                } else {
                    app.move_selection_up();
                }
                return Ok(false);
            }
            KeyCode::Down => {
                if app.ui.mode == crate::tui::app::Mode::Settings {
                    // Up/Down arrows navigate between settings categories
                    app.move_settings_category_down();
                } else {
                    app.move_selection_down();
                }
                return Ok(false);
            }
            KeyCode::PageUp => {
                // Scroll item view page up if in View mode with selected item
                if app.ui.mode == crate::tui::app::Mode::View && app.ui.selected_item.is_some() {
                    if let Ok((_, height)) = terminal_size() {
                        use crate::tui::layout::Layout;
                        use ratatui::layout::Rect;
                        let rect = Rect::new(0, 0, 80, height); // Width doesn't matter for height calculation
                        let layout = Layout::calculate(
                            rect,
                            app.config.sidebar_width_percent,
                            app.ui.sidebar_state == crate::tui::app::SidebarState::Collapsed,
                        );
                        let viewport_height = (layout.main_area.height - 2) as usize;
                        app.scroll_item_view_page_up(viewport_height);
                    }
                }
                return Ok(false);
            }
            KeyCode::PageDown => {
                // Scroll item view page down if in View mode with selected item
                if app.ui.mode == crate::tui::app::Mode::View && app.ui.selected_item.is_some() {
                    if let Ok((_, height)) = terminal_size() {
                        use crate::tui::layout::Layout;
                        use ratatui::layout::Rect;
                        let rect = Rect::new(0, 0, 80, height); // Width doesn't matter for height calculation
                        let layout = Layout::calculate(
                            rect,
                            app.config.sidebar_width_percent,
                            app.ui.sidebar_state == crate::tui::app::SidebarState::Collapsed,
                        );
                        let viewport_height = (layout.main_area.height - 2) as usize;
                        app.scroll_item_view_page_down(viewport_height);
                    }
                }
                return Ok(false);
            }
            KeyCode::Home => {
                // Scroll item view to top if in View mode with selected item
                if app.ui.mode == crate::tui::app::Mode::View && app.ui.selected_item.is_some() {
                    app.scroll_item_view_to_top();
                }
                return Ok(false);
            }
            KeyCode::End => {
                // Scroll item view to bottom if in View mode with selected item
                if app.ui.mode == crate::tui::app::Mode::View && app.ui.selected_item.is_some() {
                    if let Ok((_, height)) = terminal_size() {
                        use crate::tui::layout::Layout;
                        use ratatui::layout::Rect;
                        let rect = Rect::new(0, 0, 80, height); // Width doesn't matter for height calculation
                        let layout = Layout::calculate(
                            rect,
                            app.config.sidebar_width_percent,
                            app.ui.sidebar_state == crate::tui::app::SidebarState::Collapsed,
                        );
                        let viewport_height = (layout.main_area.height - 2) as usize;
                        app.scroll_item_view_to_bottom(viewport_height);
                    }
                }
                return Ok(false);
            }
            _ => {}
        }
    }

    // Check for list navigation bindings
    // In Settings mode, j/k navigate within the current settings form
    let list_down_binding = parse_key_binding(&app.config.key_bindings.list_down)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &list_down_binding) {
        if app.ui.mode == crate::tui::app::Mode::Settings {
            // Navigate within current settings category
            let categories = app.get_settings_categories();
            if let Some(category) = categories.get(app.settings.category_index) {
                if category == "Theme Settings" {
                    app.move_settings_theme_selection_down();
                } else if category == "Appearance Settings" {
                    app.move_settings_sidebar_width_down();
                } else if category == "Display Settings" {
                    app.move_settings_display_mode_down();
                }
            }
        } else {
            app.move_selection_down();
        }
        return Ok(false);
    }

    let list_up_binding = parse_key_binding(&app.config.key_bindings.list_up)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &list_up_binding) {
        if app.ui.mode == crate::tui::app::Mode::Settings {
            // Navigate within current settings category
            let categories = app.get_settings_categories();
            if let Some(category) = categories.get(app.settings.category_index) {
                if category == "Theme Settings" {
                    app.move_settings_theme_selection_up();
                } else if category == "Appearance Settings" {
                    app.move_settings_sidebar_width_up();
                } else if category == "Display Settings" {
                    app.move_settings_display_mode_up();
                }
            }
        } else {
            app.move_selection_up();
        }
        return Ok(false);
    }

    // Check for tab number bindings
    let tab_1_binding = parse_key_binding(&app.config.key_bindings.tab_1)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &tab_1_binding) {
        app.switch_tab(crate::tui::app::Tab::Tasks);
        return Ok(false);
    }

    let tab_2_binding = parse_key_binding(&app.config.key_bindings.tab_2)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &tab_2_binding) {
        app.switch_tab(crate::tui::app::Tab::Notes);
        return Ok(false);
    }

    let tab_3_binding = parse_key_binding(&app.config.key_bindings.tab_3)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &tab_3_binding) {
        app.switch_tab(crate::tui::app::Tab::Journal);
        return Ok(false);
    }

    // Check for settings binding
    let settings_binding = parse_key_binding(&app.config.key_bindings.settings)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &settings_binding) {
        if app.ui.mode == crate::tui::app::Mode::Settings {
            app.exit_settings_mode();
        } else {
            app.enter_settings_mode();
        }
        return Ok(false);
    }

    // Check for select binding
    let select_binding = parse_key_binding(&app.config.key_bindings.select)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &select_binding) {
        // In Settings mode, Enter applies selected setting based on category
        if app.ui.mode == crate::tui::app::Mode::Settings {
            let categories = app.get_settings_categories();
            if let Some(category) = categories.get(app.settings.category_index) {
                if category == "Theme Settings" {
                    let themes = app.get_available_themes();
                    if let Some(theme_name) = themes.get(app.settings.theme_index) {
                        if let Err(e) = app.select_theme(theme_name) {
                            app.set_status_message(format!("Failed to change theme: {}", e));
                        }
                    }
                } else if category == "Appearance Settings" {
                    if let Err(e) = app.apply_sidebar_width() {
                        app.set_status_message(format!("Failed to change sidebar width: {}", e));
                    }
                } else if category == "Display Settings" {
                    if let Err(e) = app.apply_display_mode() {
                        app.set_status_message(format!("Failed to change display mode: {}", e));
                    }
                }
            }
        } else {
            app.select_current_item();
        }
        return Ok(false);
    }

    // Check for new binding
    let new_binding = parse_key_binding(&app.config.key_bindings.new)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &new_binding) {
        // New item - enter create mode
        app.enter_create_mode();
        return Ok(false);
    }

    // Check for edit binding
    let edit_binding = parse_key_binding(&app.config.key_bindings.edit)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &edit_binding) {
        // Edit item
        app.enter_edit_mode();
        return Ok(false);
    }

    // Check for delete binding
    let delete_binding = parse_key_binding(&app.config.key_bindings.delete)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &delete_binding) {
        // Show confirmation modal instead of deleting immediately
        if let Some(ref item) = app.ui.selected_item {
            app.modals.delete_confirmation = Some(item.clone());
            app.modals.delete_modal_selection = 0; // Initialize to Archive option
        } else {
            app.set_status_message("No item selected".to_string());
        }
        return Ok(false);
    }

    // Check for toggle task status binding
    let toggle_task_status_binding = parse_key_binding(&app.config.key_bindings.toggle_task_status)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &toggle_task_status_binding) {
        // Toggle task status (only works on Tasks tab)
        match app.toggle_task_status() {
            Ok(()) => {
                // Success - status message already set in toggle_task_status
            }
            Err(e) => {
                app.set_status_message(format!("Failed to toggle task status: {}", e));
            }
        }
        return Ok(false);
    }

    // Check for help binding
    let help_binding = parse_key_binding(&app.config.key_bindings.help)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &help_binding) {
        // If in Create mode, show markdown help; otherwise show regular help
        if app.ui.mode == crate::tui::app::Mode::Create {
            app.enter_markdown_help_mode();
        } else {
            app.enter_help_mode();
        }
        return Ok(false);
    }

    // Check for search binding
    let search_binding = parse_key_binding(&app.config.key_bindings.search)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &search_binding) {
        app.enter_search_mode();
        return Ok(false);
    }

    // Check for filter binding
    let filter_binding = parse_key_binding(&app.config.key_bindings.filter)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &filter_binding) {
        app.enter_filter_mode();
        return Ok(false);
    }

    // Check for toggle list view binding
    let toggle_list_view_binding = parse_key_binding(&app.config.key_bindings.toggle_list_view)
        .map_err(|e| TuiError::KeyBindingError(e))?;
    if matches_key_event(key_event, &toggle_list_view_binding) {
        app.toggle_list_view_mode();
        return Ok(false);
    }

    Ok(false)
}

fn matches_key_event(key_event: KeyEvent, binding: &crate::utils::ParsedKeyBinding) -> bool {
    // Check modifiers
    // Use primary modifier check (Ctrl on Windows/Linux, Option/Alt on macOS)
    // This follows cross-platform TUI best practices
    let has_primary_mod = crate::utils::has_primary_modifier(key_event.modifiers);
    if binding.requires_ctrl != has_primary_mod {
        return false;
    }

    // Check key code
    binding.key_code == key_event.code
}