revw 0.2.4

A vim-like TUI for managing notes and resources
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
use anyhow::Result;
use crossterm::event::{
    self, Event, KeyCode, KeyEventKind, KeyModifiers, MouseButton, MouseEventKind,
};
use notify::{Event as NotifyEvent, RecursiveMode, Watcher};
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::time::{Duration, Instant};

use crate::app::{App, FileOperation, FormatMode, InputMode, ScrollbarType};

pub fn run_app<B: ratatui::backend::Backend>(
    terminal: &mut ratatui::Terminal<B>,
    mut app: App,
) -> Result<()> {
    // Setup file watcher
    let (tx, mut rx): (std::sync::mpsc::Sender<NotifyEvent>, Receiver<NotifyEvent>) = mpsc::channel();
    let mut watcher =
        notify::recommended_watcher(move |res: Result<NotifyEvent, notify::Error>| {
            if let Ok(event) = res {
                let _ = tx.send(event);
            }
        })?;

    // Watch the file if it exists
    if let Some(ref path) = app.file_path {
        let _ = watcher.watch(path, RecursiveMode::NonRecursive);
    }

    // Watch explorer directory if open
    if app.explorer_open {
        let _ = watcher.watch(&app.explorer_current_dir, RecursiveMode::NonRecursive);
    }

    loop {
        terminal.draw(|f| crate::ui::ui(f, &mut app))?;
        app.update_status();

        // Update watcher if file path or explorer directory changed
        if app.file_path_changed || app.explorer_dir_changed {
            // Unwatch all (recreate watcher to avoid keeping old watches)
            drop(watcher);
            let (new_tx, new_rx): (std::sync::mpsc::Sender<NotifyEvent>, Receiver<NotifyEvent>) = mpsc::channel();
            watcher = notify::recommended_watcher(move |res: Result<NotifyEvent, notify::Error>| {
                if let Ok(event) = res {
                    let _ = new_tx.send(event);
                }
            })?;

            // Watch the new file
            if let Some(ref path) = app.file_path {
                let _ = watcher.watch(path, RecursiveMode::NonRecursive);
            }

            // Watch explorer directory if open
            if app.explorer_open {
                let _ = watcher.watch(&app.explorer_current_dir, RecursiveMode::NonRecursive);
            }

            // Update the receiver to use the new channel
            rx = new_rx;
            app.file_path_changed = false;
            app.explorer_dir_changed = false;
        }

        // Check for file changes
        if app.auto_reload {
            match rx.try_recv() {
                Ok(event) => {
                    // Check if it's a modify event for files
                    if matches!(event.kind, notify::EventKind::Modify(_)) {
                        // Ignore file changes within 1 second after saving (to avoid reloading our own save)
                        let should_reload = if let Some(last_save) = app.last_save_time {
                            last_save.elapsed() > Duration::from_millis(1000)
                        } else {
                            true
                        };

                        // Only reload if not modified by user and not recently saved
                        if !app.is_modified && should_reload && app.file_path.is_some() {
                            app.reload_file();
                        }
                    }
                    // Check for create/delete/modify events in explorer directory
                    if app.explorer_open && (matches!(event.kind, notify::EventKind::Create(_)) || matches!(event.kind, notify::EventKind::Remove(_)) || matches!(event.kind, notify::EventKind::Modify(_))) {
                        // Reload explorer entries
                        app.load_explorer_entries();
                    }
                }
                Err(TryRecvError::Empty) => {}
                Err(TryRecvError::Disconnected) => {}
            }
        }

        if event::poll(Duration::from_millis(100))? {
            match event::read()? {
                Event::Key(key) => {
                    // Filter out key repeat events on Windows to prevent duplicate input
                    #[cfg(target_os = "windows")]
                    if key.kind != KeyEventKind::Press {
                        continue;
                    }
                    if key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('c') {
                        return Ok(());
                    }
                    if key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('r') {
                        app.redo();
                        continue;
                    }

                    // Handle Ctrl+w window commands
                    if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('w') {
                        // Wait for next key (1000ms timeout)
                        loop {
                            if let Ok(true) = event::poll(Duration::from_millis(1000)) {
                                if let Ok(Event::Key(next_key)) = event::read() {
                                    #[cfg(target_os = "windows")]
                                    {
                                        // Skip release events on Windows
                                        if next_key.kind != KeyEventKind::Press {
                                            continue;
                                        }
                                    }

                                    match next_key.code {
                                        KeyCode::Char('w') => {
                                            // Ctrl+w w: cycle between windows (accept with or without Ctrl)
                                            app.switch_window_focus();
                                            let focus_msg = if app.explorer_has_focus {
                                                "Focused explorer"
                                            } else {
                                                "Focused file window"
                                            };
                                            app.set_status(focus_msg);
                                            break;
                                        }
                                        KeyCode::Char('h') => {
                                            // Ctrl+w h: move to left window (explorer)
                                            app.focus_explorer();
                                            app.set_status("Focused explorer");
                                            break;
                                        }
                                        KeyCode::Char('l') => {
                                            // Ctrl+w l: move to right window (file)
                                            app.focus_file();
                                            app.set_status("Focused file window");
                                            break;
                                        }
                                        _ => {
                                            // Any other key - cancel
                                            break;
                                        }
                                    }
                                }
                            } else {
                                // Timeout
                                break;
                            }
                        }
                        continue;
                    }

                    // Handle editing overlay input separately
                    if app.editing_entry {
                        if app.edit_insert_mode {
                            // Insert mode: typing edits current field
                            match key.code {
                                KeyCode::Esc | KeyCode::Char('[') if key.code == KeyCode::Esc || key.modifiers.contains(KeyModifiers::CONTROL) => {
                                    // Exit insert mode
                                    app.edit_insert_mode = false;
                                    // Exit View Edit mode if active and reset scroll
                                    if app.view_edit_mode {
                                        app.view_edit_mode = false;
                                        app.edit_vscroll = 0; // Reset to first line
                                    }
                                    // If entered insert mode directly with 'i' or 'v', skip normal mode and go back to field selection
                                    if app.edit_skip_normal_mode {
                                        app.edit_field_editing_mode = false;
                                        app.edit_skip_normal_mode = false;
                                        // Restore placeholder if field is empty (for :ai/:ao flow)
                                        if app.edit_field_index < app.edit_buffer.len() {
                                            let field = &app.edit_buffer[app.edit_field_index];
                                            if field.is_empty() {
                                                let placeholder = if app.edit_buffer.len() == 3 {
                                                    match app.edit_field_index {
                                                        0 => "date",
                                                        1 => "context",
                                                        _ => "",
                                                    }
                                                } else {
                                                    match app.edit_field_index {
                                                        0 => "name",
                                                        1 => "context",
                                                        2 => "url",
                                                        3 => "percentage",
                                                        _ => "",
                                                    }
                                                };
                                                if !placeholder.is_empty() {
                                                    app.edit_buffer[app.edit_field_index] = placeholder.to_string();
                                                    if app.edit_field_index < app.edit_buffer_is_placeholder.len() {
                                                        app.edit_buffer_is_placeholder[app.edit_field_index] = true;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    // Otherwise stay in field editing mode (normal mode)
                                    // Keep field empty to reflect actual buffer content
                                }
                                KeyCode::Backspace => {
                                    if app.edit_field_index < app.edit_buffer.len() && app.edit_cursor_pos > 0 {
                                        let field = &mut app.edit_buffer[app.edit_field_index];

                                        // In View Edit mode, check if we're deleting \n (2 characters)
                                        if app.view_edit_mode && app.edit_cursor_pos >= 2 {
                                            let char_indices: Vec<_> = field.char_indices().collect();
                                            if app.edit_cursor_pos >= 2 && app.edit_cursor_pos <= char_indices.len() {
                                                // Check if the two characters before cursor are '\' and 'n'
                                                let chars: Vec<char> = field.chars().collect();
                                                if app.edit_cursor_pos >= 2
                                                    && chars[app.edit_cursor_pos - 2] == '\\'
                                                    && chars[app.edit_cursor_pos - 1] == 'n' {
                                                    // Delete both characters of \n
                                                    let byte_pos_1 = char_indices[app.edit_cursor_pos - 2].0;
                                                    field.remove(byte_pos_1);
                                                    field.remove(byte_pos_1); // Remove again at same position (since indices shift)
                                                    app.edit_cursor_pos -= 2;
                                                } else {
                                                    // Normal single character deletion
                                                    let byte_pos = char_indices[app.edit_cursor_pos - 1].0;
                                                    field.remove(byte_pos);
                                                    app.edit_cursor_pos -= 1;
                                                }
                                            }
                                        } else {
                                            // Normal mode or cursor position < 2: normal single character deletion
                                            let char_indices: Vec<_> = field.char_indices().collect();
                                            if app.edit_cursor_pos > 0 && app.edit_cursor_pos <= char_indices.len() {
                                                let byte_pos = char_indices[app.edit_cursor_pos - 1].0;
                                                field.remove(byte_pos);
                                                app.edit_cursor_pos -= 1;
                                            }
                                        }
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Left => {
                                    if app.view_edit_mode {
                                        // In View Edit mode, move cursor like a normal text editor
                                        if app.edit_cursor_pos > 0 && app.edit_field_index < app.edit_buffer.len() {
                                            let field = &app.edit_buffer[app.edit_field_index];
                                            let lines: Vec<&str> = field.split("\\n").collect();

                                            // Find current line and column
                                            let mut char_count = 0;
                                            let mut current_line = 0;
                                            let mut col_in_line = 0;

                                            for (line_idx, line) in lines.iter().enumerate() {
                                                let line_len = line.chars().count();
                                                let separator_len = if line_idx < lines.len() - 1 { 2 } else { 0 };

                                                if app.edit_cursor_pos <= char_count + line_len {
                                                    current_line = line_idx;
                                                    col_in_line = app.edit_cursor_pos - char_count;
                                                    break;
                                                }

                                                char_count += line_len + separator_len;
                                            }

                                            if col_in_line > 0 {
                                                // Move left within current line
                                                app.edit_cursor_pos -= 1;
                                            } else if current_line > 0 {
                                                // Move to end of previous line
                                                let mut new_pos = 0;
                                                for (i, _line) in lines.iter().enumerate().take(current_line - 1) {
                                                    let line_len = lines[i].chars().count();
                                                    let separator_len = if i < lines.len() - 1 { 2 } else { 0 };
                                                    new_pos += line_len + separator_len;
                                                }
                                                new_pos += lines[current_line - 1].chars().count();
                                                app.edit_cursor_pos = new_pos;
                                            }
                                        }
                                    } else if app.edit_cursor_pos > 0 {
                                        app.edit_cursor_pos -= 1;
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Right => {
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        let field_len = field.chars().count();

                                        if app.edit_cursor_pos < field_len {
                                            if app.view_edit_mode {
                                                // In View Edit mode, move cursor like a normal text editor
                                                let lines: Vec<&str> = field.split("\\n").collect();

                                                // Find current line and column
                                                let mut char_count = 0;
                                                let mut current_line = 0;
                                                let mut col_in_line = 0;

                                                for (line_idx, line) in lines.iter().enumerate() {
                                                    let line_len = line.chars().count();
                                                    let separator_len = if line_idx < lines.len() - 1 { 2 } else { 0 };

                                                    if app.edit_cursor_pos <= char_count + line_len {
                                                        current_line = line_idx;
                                                        col_in_line = app.edit_cursor_pos - char_count;
                                                        break;
                                                    }

                                                    char_count += line_len + separator_len;
                                                }

                                                let current_line_len = lines[current_line].chars().count();

                                                if col_in_line < current_line_len {
                                                    // Move right within current line
                                                    app.edit_cursor_pos += 1;
                                                } else if current_line + 1 < lines.len() {
                                                    // Move to start of next line (skip over \n)
                                                    app.edit_cursor_pos += 2; // Skip \n
                                                }
                                            } else {
                                                app.edit_cursor_pos += 1;
                                            }
                                        }
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Enter => {
                                    // In View Edit mode, insert literal \n string
                                    if app.view_edit_mode && app.edit_field_index < app.edit_buffer.len() {
                                        let field = &mut app.edit_buffer[app.edit_field_index];
                                        // Find byte index for character position
                                        let byte_pos = if app.edit_cursor_pos == 0 {
                                            0
                                        } else if app.edit_cursor_pos >= field.chars().count() {
                                            field.len()
                                        } else {
                                            field.char_indices().nth(app.edit_cursor_pos).map(|(i, _)| i).unwrap_or(field.len())
                                        };
                                        // Insert \n as a string (backslash followed by n)
                                        field.insert_str(byte_pos, "\\n");
                                        app.edit_cursor_pos += 2; // Move cursor past \n
                                    }
                                }
                                KeyCode::Up => {
                                    // In View Edit mode, move up one line
                                    if app.view_edit_mode && app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        let lines: Vec<&str> = field.split("\\n").collect();

                                        // Find current line and column
                                        let mut current_pos = 0;
                                        let mut current_line = 0;
                                        let mut col_in_line = 0;

                                        for (line_idx, line) in lines.iter().enumerate() {
                                            let line_len = line.chars().count();
                                            let separator_len = if line_idx < lines.len() - 1 { 2 } else { 0 };

                                            if app.edit_cursor_pos <= current_pos + line_len {
                                                current_line = line_idx;
                                                col_in_line = app.edit_cursor_pos - current_pos;
                                                break;
                                            }

                                            current_pos += line_len + separator_len;
                                        }

                                        // Move to previous line if possible
                                        if current_line > 0 {
                                            let prev_line = lines[current_line - 1];
                                            let prev_line_len = prev_line.chars().count();

                                            // Calculate position in previous line
                                            let mut new_pos = 0;
                                            for (i, _line) in lines.iter().enumerate().take(current_line - 1) {
                                                let line_len = lines[i].chars().count();
                                                let separator_len = if i < lines.len() - 1 { 2 } else { 0 };
                                                new_pos += line_len + separator_len;
                                            }

                                            // Keep same column or go to end of line
                                            new_pos += col_in_line.min(prev_line_len);
                                            app.edit_cursor_pos = new_pos;
                                        }
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Down => {
                                    // In View Edit mode, move down one line
                                    if app.view_edit_mode && app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        let lines: Vec<&str> = field.split("\\n").collect();

                                        // Find current line and column
                                        let mut current_pos = 0;
                                        let mut current_line = 0;
                                        let mut col_in_line = 0;

                                        for (line_idx, line) in lines.iter().enumerate() {
                                            let line_len = line.chars().count();
                                            let separator_len = if line_idx < lines.len() - 1 { 2 } else { 0 };

                                            if app.edit_cursor_pos <= current_pos + line_len {
                                                current_line = line_idx;
                                                col_in_line = app.edit_cursor_pos - current_pos;
                                                break;
                                            }

                                            current_pos += line_len + separator_len;
                                        }

                                        // Move to next line if possible
                                        if current_line + 1 < lines.len() {
                                            let next_line = lines[current_line + 1];
                                            let next_line_len = next_line.chars().count();

                                            // Calculate position in next line
                                            let mut new_pos = 0;
                                            for (i, _line) in lines.iter().enumerate().take(current_line + 1) {
                                                let line_len = lines[i].chars().count();
                                                let separator_len = if i < lines.len() - 1 { 2 } else { 0 };
                                                new_pos += line_len + separator_len;
                                            }

                                            // Keep same column or go to end of line
                                            new_pos += col_in_line.min(next_line_len);
                                            app.edit_cursor_pos = new_pos;
                                        }
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char(c) => {
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &mut app.edit_buffer[app.edit_field_index];
                                        // Find byte index for character position
                                        let byte_pos = if app.edit_cursor_pos == 0 {
                                            0
                                        } else if app.edit_cursor_pos >= field.chars().count() {
                                            field.len()
                                        } else {
                                            field.char_indices().nth(app.edit_cursor_pos).map(|(i, _)| i).unwrap_or(field.len())
                                        };
                                        field.insert(byte_pos, c);
                                        app.edit_cursor_pos += 1;
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                _ => {}
                            }
                        } else if app.edit_field_editing_mode {
                            // Field editing normal mode: cursor navigation within field
                            match key.code {
                                KeyCode::Esc | KeyCode::Char('[') if key.code == KeyCode::Esc || key.modifiers.contains(KeyModifiers::CONTROL) => {
                                    // Exit field editing mode, go back to field selection
                                    app.edit_field_editing_mode = false;
                                    app.edit_cursor_pos = 0;
                                    app.edit_hscroll = 0;
                                    // Exit View Edit mode if active and reset scroll
                                    if app.view_edit_mode {
                                        app.view_edit_mode = false;
                                        app.edit_vscroll = 0; // Reset to first line
                                    }
                                    // Restore placeholder if field is empty
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        if field.is_empty() {
                                            // Determine placeholder based on edit_buffer length
                                            let placeholder = if app.edit_buffer.len() == 3 {
                                                // INSIDE entry: date, context, Exit
                                                match app.edit_field_index {
                                                    0 => "date",
                                                    1 => "context",
                                                    _ => "",
                                                }
                                            } else {
                                                // OUTSIDE entry: name, context, url, percentage, Exit
                                                match app.edit_field_index {
                                                    0 => "name",
                                                    1 => "context",
                                                    2 => "url",
                                                    3 => "percentage",
                                                    _ => "",
                                                }
                                            };
                                            if !placeholder.is_empty() {
                                                app.edit_buffer[app.edit_field_index] = placeholder.to_string();
                                                if app.edit_field_index < app.edit_buffer_is_placeholder.len() {
                                                    app.edit_buffer_is_placeholder[app.edit_field_index] = true;
                                                }
                                            }
                                        }
                                    }
                                }
                                KeyCode::Char('h') | KeyCode::Left => {
                                    if app.edit_cursor_pos > 0 {
                                        app.edit_cursor_pos -= 1;
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('l') | KeyCode::Right => {
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field_len = app.edit_buffer[app.edit_field_index].chars().count();
                                        if app.edit_cursor_pos < field_len {
                                            app.edit_cursor_pos += 1;
                                        }
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('0') => {
                                    app.edit_cursor_pos = 0;
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('$') => {
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field_len = app.edit_buffer[app.edit_field_index].chars().count();
                                        app.edit_cursor_pos = field_len;
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('w') => {
                                    // Move to next word (simplified: skip to next space)
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        let chars: Vec<char> = field.chars().collect();
                                        let mut pos = app.edit_cursor_pos;
                                        // Skip current word
                                        while pos < chars.len() && !chars[pos].is_whitespace() {
                                            pos += 1;
                                        }
                                        // Skip whitespace
                                        while pos < chars.len() && chars[pos].is_whitespace() {
                                            pos += 1;
                                        }
                                        app.edit_cursor_pos = pos;
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('b') => {
                                    // Move to previous word
                                    if app.edit_cursor_pos > 0 {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        let chars: Vec<char> = field.chars().collect();
                                        let mut pos = app.edit_cursor_pos.saturating_sub(1);
                                        // Skip whitespace
                                        while pos > 0 && chars[pos].is_whitespace() {
                                            pos -= 1;
                                        }
                                        // Skip to start of word
                                        while pos > 0 && !chars[pos - 1].is_whitespace() {
                                            pos -= 1;
                                        }
                                        app.edit_cursor_pos = pos;
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('e') => {
                                    // Move to end of current or next word
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        let chars: Vec<char> = field.chars().collect();
                                        if !chars.is_empty() && app.edit_cursor_pos < chars.len() {
                                            let mut pos = app.edit_cursor_pos;

                                            // Skip whitespace if we're on it
                                            while pos < chars.len() && chars[pos].is_whitespace() {
                                                pos += 1;
                                            }

                                            // Move to end of current word
                                            while pos < chars.len() && !chars[pos].is_whitespace() {
                                                pos += 1;
                                            }

                                            // Position on last character of word (not the space after)
                                            if pos > 0 {
                                                app.edit_cursor_pos = pos - 1;
                                            }
                                        }
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('g') => {
                                    // Handle gg (go to start)
                                    app.edit_cursor_pos = 0;
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('G') => {
                                    // Go to end
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field_len = app.edit_buffer[app.edit_field_index].chars().count();
                                        app.edit_cursor_pos = field_len;
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('x') => {
                                    // Delete character at cursor
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &mut app.edit_buffer[app.edit_field_index];
                                        let mut chars: Vec<char> = field.chars().collect();
                                        if app.edit_cursor_pos < chars.len() {
                                            chars.remove(app.edit_cursor_pos);
                                            *field = chars.into_iter().collect();
                                            // Mark as no longer a placeholder if it was
                                            if app.edit_field_index < app.edit_buffer_is_placeholder.len() {
                                                app.edit_buffer_is_placeholder[app.edit_field_index] = false;
                                            }
                                        }
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('X') => {
                                    // Delete character before cursor
                                    if app.edit_field_index < app.edit_buffer.len() && app.edit_cursor_pos > 0 {
                                        let field = &mut app.edit_buffer[app.edit_field_index];
                                        let mut chars: Vec<char> = field.chars().collect();
                                        if app.edit_cursor_pos > 0 && app.edit_cursor_pos <= chars.len() {
                                            chars.remove(app.edit_cursor_pos - 1);
                                            *field = chars.into_iter().collect();
                                            app.edit_cursor_pos -= 1;
                                            // Mark as no longer a placeholder if it was
                                            if app.edit_field_index < app.edit_buffer_is_placeholder.len() {
                                                app.edit_buffer_is_placeholder[app.edit_field_index] = false;
                                            }
                                        }
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('i') => {
                                    // Enter insert mode (from normal mode within field)
                                    app.edit_insert_mode = true;
                                    // edit_skip_normal_mode stays false because we're already in normal mode
                                    // Clear placeholder text when entering insert mode
                                    if app.edit_field_index < app.edit_buffer_is_placeholder.len()
                                        && app.edit_buffer_is_placeholder[app.edit_field_index] {
                                        app.edit_buffer[app.edit_field_index] = String::new();
                                        app.edit_buffer_is_placeholder[app.edit_field_index] = false;
                                        app.edit_cursor_pos = 0;
                                    }
                                }
                                _ => {}
                            }
                        } else {
                            // Field selection mode: navigate between fields
                            match key.code {
                                KeyCode::Esc | KeyCode::Char('q') => {
                                    app.cancel_editing_entry();
                                }
                                KeyCode::Char('w') => {
                                    app.save_edited_entry();
                                }
                                KeyCode::Up | KeyCode::Char('k') => {
                                    if app.edit_field_index > 0 {
                                        app.edit_field_index -= 1;
                                        app.edit_cursor_pos = 0;
                                        app.edit_hscroll = 0;
                                        app.edit_vscroll = 0;
                                    }
                                }
                                KeyCode::Down | KeyCode::Char('j') => {
                                    if app.edit_field_index + 1 < app.edit_buffer.len() {
                                        app.edit_field_index += 1;
                                        app.edit_cursor_pos = 0;
                                        app.edit_hscroll = 0;
                                        app.edit_vscroll = 0;
                                    }
                                }
                                KeyCode::Left | KeyCode::Char('h') => {
                                    // Check if this is context field (index 1)
                                    let is_context_field = (app.edit_buffer.len() == 3 && app.edit_field_index == 1) ||
                                                           (app.edit_buffer.len() == 5 && app.edit_field_index == 1);

                                    if is_context_field {
                                        // Vertical scroll up for context field
                                        app.edit_vscroll = app.edit_vscroll.saturating_sub(1);
                                    } else {
                                        // Horizontal scroll left for other fields
                                        app.edit_hscroll = app.edit_hscroll.saturating_sub(4);
                                    }
                                }
                                KeyCode::Right | KeyCode::Char('l') => {
                                    // Check if this is context field (index 1)
                                    let is_context_field = (app.edit_buffer.len() == 3 && app.edit_field_index == 1) ||
                                                           (app.edit_buffer.len() == 5 && app.edit_field_index == 1);

                                    if is_context_field {
                                        // Vertical scroll down for context field
                                        if app.edit_field_index < app.edit_buffer.len() {
                                            let field = &app.edit_buffer[app.edit_field_index];
                                            let lines: Vec<&str> = field.split("\\n").collect();
                                            // Fixed window size for field selection mode (minimum 5 lines)
                                            let window_height = 5;
                                            let total_lines = lines.len();
                                            // Calculate max scroll: lines - window_height (but at least 0)
                                            let max_scroll = total_lines.saturating_sub(window_height);
                                            // Only scroll if we haven't reached the limit
                                            if (app.edit_vscroll as usize) < max_scroll {
                                                app.edit_vscroll += 1;
                                            }
                                        }
                                    } else {
                                        // Horizontal scroll right for other fields
                                        if app.edit_field_index < app.edit_buffer.len() {
                                            let field_len = app.edit_buffer[app.edit_field_index].chars().count();
                                            // Allow scrolling up to field length
                                            if (app.edit_hscroll as usize) < field_len {
                                                app.edit_hscroll += 4;
                                            }
                                        }
                                    }
                                }
                                KeyCode::Enter => {
                                    // Check if Exit field is selected
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        if field == "Exit" {
                                            // Close overlay without saving
                                            app.cancel_editing_entry();
                                            continue;
                                        }
                                        // Clear placeholder text when entering field editing mode
                                        if app.edit_field_index < app.edit_buffer_is_placeholder.len()
                                            && app.edit_buffer_is_placeholder[app.edit_field_index] {
                                            app.edit_buffer[app.edit_field_index] = String::new();
                                            app.edit_buffer_is_placeholder[app.edit_field_index] = false;
                                        }
                                    }
                                    // Enter field editing mode
                                    app.edit_field_editing_mode = true;
                                    app.edit_cursor_pos = 0;
                                    app.edit_hscroll = 0;
                                }
                                KeyCode::Char('i') => {
                                    // Skip field editing mode, go straight to insert mode with cursor at end
                                    app.edit_field_editing_mode = true;
                                    app.edit_insert_mode = true;
                                    app.edit_skip_normal_mode = true; // Mark that we skipped normal mode
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        // Clear placeholder text when entering insert mode
                                        if app.edit_field_index < app.edit_buffer_is_placeholder.len()
                                            && app.edit_buffer_is_placeholder[app.edit_field_index] {
                                            app.edit_buffer[app.edit_field_index] = String::new();
                                            app.edit_buffer_is_placeholder[app.edit_field_index] = false;
                                            app.edit_cursor_pos = 0;
                                        } else {
                                            // Move cursor to end of text
                                            app.edit_cursor_pos = field.chars().count();
                                        }
                                    }
                                    app.ensure_overlay_cursor_visible();
                                }
                                KeyCode::Char('v') => {
                                    // Enter View Edit mode: render \n as newlines
                                    // ONLY allow View Edit mode for context field (index 1)
                                    if app.edit_field_index != 1 {
                                        // Not on context field, ignore 'v' key
                                        continue;
                                    }

                                    // Check if Exit field is selected
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        if field == "Exit" {
                                            // Don't enter View Edit mode on Exit field
                                            continue;
                                        }
                                        // Clear placeholder text when entering View Edit mode
                                        if app.edit_field_index < app.edit_buffer_is_placeholder.len()
                                            && app.edit_buffer_is_placeholder[app.edit_field_index] {
                                            app.edit_buffer[app.edit_field_index] = String::new();
                                            app.edit_buffer_is_placeholder[app.edit_field_index] = false;
                                            app.edit_cursor_pos = 0;
                                        } else {
                                            // Move cursor to start of field
                                            app.edit_cursor_pos = 0;
                                        }
                                    }
                                    // Enter View Edit mode directly in insert mode (skip normal mode)
                                    app.view_edit_mode = true;
                                    app.edit_field_editing_mode = true;
                                    app.edit_insert_mode = true;
                                    app.edit_skip_normal_mode = true;
                                    // Ensure cursor is visible in the window
                                    app.ensure_overlay_cursor_visible();
                                }
                                _ => {}
                            }
                        }
                        continue;
                    }

                    match app.input_mode {
                        InputMode::Normal => {
                            // Handle file operation confirmation/prompt if active
                            if let Some(ref op) = app.file_op_pending.clone() {
                                match op {
                                    FileOperation::Delete(_) => {
                                        // Waiting for yes/no confirmation
                                        match key.code {
                                            KeyCode::Esc => {
                                                app.cancel_file_operation();
                                                continue;
                                            }
                                            KeyCode::Enter => {
                                                let input = app.file_op_prompt_buffer.trim().to_lowercase();
                                                if input == "yes" {
                                                    app.handle_file_op_confirmation('y');
                                                } else if input == "no" {
                                                    app.handle_file_op_confirmation('n');
                                                } else {
                                                    app.set_status("Invalid input. Type 'yes' or 'no'");
                                                    app.file_op_prompt_buffer.clear();
                                                }
                                                continue;
                                            }
                                            KeyCode::Char(c) => {
                                                app.file_op_prompt_buffer.push(c);
                                                let path_display = if let FileOperation::Delete(path) = op {
                                                    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");
                                                    let item_type = if path.is_dir() { "directory" } else { "file" };
                                                    format!("Delete {} '{}'? (yes/no) {}", item_type, name, app.file_op_prompt_buffer)
                                                } else {
                                                    String::new()
                                                };
                                                app.set_status(&path_display);
                                                continue;
                                            }
                                            KeyCode::Backspace => {
                                                if !app.file_op_prompt_buffer.is_empty() {
                                                    app.file_op_prompt_buffer.pop();
                                                    let path_display = if let FileOperation::Delete(path) = op {
                                                        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");
                                                        let item_type = if path.is_dir() { "directory" } else { "file" };
                                                        format!("Delete {} '{}'? (yes/no) {}", item_type, name, app.file_op_prompt_buffer)
                                                    } else {
                                                        String::new()
                                                    };
                                                    app.set_status(&path_display);
                                                } else {
                                                    app.cancel_file_operation();
                                                }
                                                continue;
                                            }
                                            _ => continue,
                                        }
                                    }
                                    FileOperation::Create | FileOperation::CreateDir | FileOperation::Copy(_) | FileOperation::Rename(_) => {
                                        // Waiting for filename input
                                        match key.code {
                                            KeyCode::Esc => {
                                                app.cancel_file_operation();
                                                continue;
                                            }
                                            KeyCode::Enter => {
                                                app.execute_file_operation();
                                                continue;
                                            }
                                            KeyCode::Char(c) => {
                                                app.file_op_prompt_buffer.push(c);
                                                let prompt_msg = match op {
                                                    FileOperation::Create => "New file name (must end with .json):",
                                                    FileOperation::CreateDir => "New directory name:",
                                                    FileOperation::Copy(src) => {
                                                        let name = src.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");
                                                        &format!("Copy '{}' to (must end with .json):", name)
                                                    }
                                                    FileOperation::Rename(path) => {
                                                        if path.is_dir() {
                                                            "Rename/Move directory to:"
                                                        } else {
                                                            "Rename/Move to (must end with .json):"
                                                        }
                                                    }
                                                    _ => "",
                                                };
                                                app.set_status(&format!("{} {}", prompt_msg, app.file_op_prompt_buffer));
                                                continue;
                                            }
                                            KeyCode::Backspace => {
                                                if !app.file_op_prompt_buffer.is_empty() {
                                                    app.file_op_prompt_buffer.pop();
                                                    let prompt_msg = match op {
                                                        FileOperation::Create => "New file name (must end with .json):",
                                                        FileOperation::CreateDir => "New directory name:",
                                                        FileOperation::Copy(src) => {
                                                            let name = src.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");
                                                            &format!("Copy '{}' to (must end with .json):", name)
                                                        }
                                                        FileOperation::Rename(path) => {
                                                            if path.is_dir() {
                                                                "Rename/Move directory to:"
                                                            } else {
                                                                "Rename/Move to (must end with .json):"
                                                            }
                                                        }
                                                        _ => "",
                                                    };
                                                    app.set_status(&format!("{} {}", prompt_msg, app.file_op_prompt_buffer));
                                                } else {
                                                    app.cancel_file_operation();
                                                }
                                                continue;
                                            }
                                            _ => continue,
                                        }
                                    }
                                }
                            }

                            // Handle substitute confirmation if active
                            if !app.substitute_confirmations.is_empty() {
                                match key.code {
                                    KeyCode::Char('y') | KeyCode::Char('n') | KeyCode::Char('a') | KeyCode::Char('q') => {
                                        if let KeyCode::Char(c) = key.code {
                                            app.handle_substitute_confirmation(c);
                                        }
                                        continue;
                                    }
                                    KeyCode::Esc => {
                                        app.handle_substitute_confirmation('q');
                                        continue;
                                    }
                                    _ => continue,
                                }
                            }

                            // Handle explorer navigation if explorer has focus
                            if app.explorer_open && app.explorer_has_focus {
                                match key.code {
                                    KeyCode::Char('j') | KeyCode::Down => {
                                        app.explorer_move_down();
                                        continue;
                                    }
                                    KeyCode::Char('k') | KeyCode::Up => {
                                        app.explorer_move_up();
                                        continue;
                                    }
                                    KeyCode::Enter => {
                                        // Open file and move focus to right
                                        app.explorer_select_entry();
                                        continue;
                                    }
                                    KeyCode::Char('o') => {
                                        // Check if this might be part of 'go'
                                        if app.vim_buffer == "g" {
                                            // Let handle_vim_input process 'go'
                                            app.handle_vim_input('o');
                                        } else {
                                            // Standalone 'o' - open file
                                            app.explorer_select_entry();
                                        }
                                        continue;
                                    }
                                    KeyCode::Char('q') => {
                                        // Quit program
                                        return Ok(());
                                    }
                                    KeyCode::Char('g') => {
                                        // Start of potential 'go' or 'gg'
                                        app.handle_vim_input('g');
                                        continue;
                                    }
                                    _ => {}
                                }
                            }

                            match key.code {
                            KeyCode::Char('u') => {
                                if !app.showing_help && app.format_mode == FormatMode::Edit {
                                    app.undo();
                                }
                            }
                            KeyCode::Char('v') => {
                                // Enter Visual/Select mode in View mode
                                if !app.showing_help && app.format_mode == FormatMode::View && !app.relf_entries.is_empty() {
                                    app.visual_mode = true;
                                    app.visual_start_index = app.selected_entry_index;
                                    app.visual_end_index = app.selected_entry_index;
                                    app.set_status("-- VISUAL --");
                                }
                            }
                            KeyCode::Char('?') => {
                                // Toggle help
                                app.toggle_help();
                            }
                            KeyCode::Char('q') | KeyCode::Esc | KeyCode::Char('[') => {
                                // Check for Ctrl+[ to exit Visual mode
                                if key.code == KeyCode::Char('[') && !key.modifiers.contains(KeyModifiers::CONTROL) {
                                    // Not Ctrl+[, ignore
                                } else {
                                    // Exit Visual mode if active, otherwise quit
                                    if app.visual_mode {
                                        app.visual_mode = false;
                                        app.set_status("");
                                    } else {
                                        return Ok(());
                                    }
                                }
                            }
                            KeyCode::Char('w') => {
                                // Vim-like: move to start of next word (Edit mode)
                                if !app.showing_help && app.format_mode == FormatMode::Edit {
                                    app.move_to_next_word_start();
                                }
                            }
                            KeyCode::Char('e') => {
                                // Vim-like: move to end of next word (Edit mode)
                                if !app.showing_help && app.format_mode == FormatMode::Edit {
                                    app.move_to_next_word_end();
                                }
                            }
                            KeyCode::Char('b') => {
                                // Vim-like: move to start of previous word (Edit mode)
                                if !app.showing_help && app.format_mode == FormatMode::Edit {
                                    app.move_to_previous_word_start();
                                }
                            }
                            KeyCode::Char('r') => {
                                if !app.showing_help {
                                    // Clear filter when toggling modes
                                    if !app.filter_pattern.is_empty() {
                                        app.filter_pattern.clear();
                                    }

                                    // Toggle between View and Edit only (not Help)
                                    app.format_mode = match app.format_mode {
                                        FormatMode::View => FormatMode::Edit,
                                        FormatMode::Edit => FormatMode::View,
                                        FormatMode::Help => FormatMode::View, // If somehow in Help, go to View
                                    };
                                    let mode_name = match app.format_mode {
                                        FormatMode::View => "View",
                                        FormatMode::Edit => "Edit",
                                        FormatMode::Help => "Help",
                                    };
                                    if app.format_mode == FormatMode::View {
                                        app.hscroll = 0;
                                    }
                                    app.convert_json();
                                    app.set_status(&format!("{} mode", mode_name));
                                }
                            }
                            KeyCode::Char('i') => {
                                if !app.showing_help && app.format_mode == FormatMode::Edit {
                                    app.input_mode = InputMode::Insert;
                                    app.ensure_cursor_visible();
                                    app.set_status("-- INSERT --");
                                }
                            }
                            KeyCode::Char('x') => {
                                if !app.showing_help && app.format_mode == FormatMode::Edit {
                                    app.delete_char();
                                    app.is_modified = true;
                                }
                            }
                            KeyCode::Char('X') => {
                                if !app.showing_help && app.format_mode == FormatMode::Edit {
                                    app.backspace();
                                    app.is_modified = true;
                                }
                            }
                            KeyCode::Char(':') => {
                                // Allow command mode even when showing help (for :h to toggle)
                                app.input_mode = InputMode::Command;
                                app.command_buffer = String::new();
                                app.command_history_index = None;
                                app.set_status(":");
                            }
                            KeyCode::Up | KeyCode::Char('k') => {
                                if app.showing_help {
                                    // Allow scrolling in help mode (takes priority)
                                    app.scroll_up();
                                } else if app.format_mode == FormatMode::Edit {
                                    app.move_cursor_up();
                                } else if !app.relf_entries.is_empty() {
                                    // Move selection up in card view
                                    if app.selected_entry_index > 0 {
                                        app.selected_entry_index -= 1;
                                        // Reset horizontal scroll when changing cards
                                        app.hscroll = 0;
                                        // In Visual mode, extend selection
                                        if app.visual_mode {
                                            app.visual_end_index = app.selected_entry_index;
                                        }
                                    }
                                } else {
                                    app.relf_jump_up();
                                }
                            }
                            KeyCode::Down | KeyCode::Char('j') => {
                                if app.showing_help {
                                    // Allow scrolling in help mode (takes priority)
                                    app.scroll_down();
                                } else if app.format_mode == FormatMode::Edit {
                                    app.move_cursor_down();
                                } else if !app.relf_entries.is_empty() {
                                    // Move selection down in card view
                                    if app.selected_entry_index + 1 < app.relf_entries.len() {
                                        app.selected_entry_index += 1;
                                        // Reset horizontal scroll when changing cards
                                        app.hscroll = 0;
                                        // In Visual mode, extend selection
                                        if app.visual_mode {
                                            app.visual_end_index = app.selected_entry_index;
                                        }
                                    }
                                } else {
                                    app.relf_jump_down();
                                }
                            }
                            KeyCode::Left | KeyCode::Char('h') => {
                                if !app.showing_help {
                                    if app.format_mode == FormatMode::Edit {
                                        app.move_cursor_left();
                                    } else {
                                        // Vertical scroll up in View mode (card context)
                                        app.hscroll = app.hscroll.saturating_sub(1);
                                    }
                                }
                            }
                            KeyCode::Right | KeyCode::Char('l') => {
                                if !app.showing_help {
                                    if app.format_mode == FormatMode::Edit {
                                        app.move_cursor_right();
                                    } else {
                                        // Vertical scroll down in View mode (card context)
                                        // Calculate max scroll based on context field length
                                        if !app.relf_entries.is_empty() && app.selected_entry_index < app.relf_entries.len() {
                                            let entry = &app.relf_entries[app.selected_entry_index];
                                            if let Some(context) = &entry.context {
                                                let context_with_newlines = context.replace("\\n", "\n");
                                                let lines: Vec<&str> = context_with_newlines.lines().collect();
                                                // Estimate visible lines: total height divided by number of visible cards
                                                // Subtract 2 for card borders (top and bottom)
                                                let visible_lines = (app.visible_height as usize / app.max_visible_cards).saturating_sub(2);
                                                let max_scroll = lines.len().saturating_sub(visible_lines);
                                                if (app.hscroll as usize) < max_scroll {
                                                    app.hscroll += 1;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            KeyCode::Char('0') => {
                                if !app.showing_help && app.format_mode == FormatMode::Edit {
                                    app.content_cursor_col = 0;
                                    app.ensure_cursor_visible();
                                }
                            }
                            KeyCode::Char('$') => {
                                if !app.showing_help && app.format_mode == FormatMode::Edit {
                                    let lines = app.get_json_lines();
                                    if app.content_cursor_line < lines.len() {
                                        app.content_cursor_col =
                                            lines[app.content_cursor_line].chars().count();
                                        app.ensure_cursor_visible();
                                    }
                                }
                            }
                            KeyCode::PageUp => app.page_up(),
                            KeyCode::PageDown => app.page_down(),
                            KeyCode::Char('G') => {
                                if app.showing_help {
                                    // Allow scrolling to bottom in help mode (takes priority)
                                    app.scroll_to_bottom();
                                } else if app.format_mode == FormatMode::Edit {
                                    app.scroll_to_bottom();
                                    let lines = app.get_json_lines();
                                    if !lines.is_empty() {
                                        app.content_cursor_line = lines.len() - 1;
                                        app.content_cursor_col = 0;
                                    }
                                } else if !app.relf_entries.is_empty() {
                                    // Jump to last card
                                    app.selected_entry_index = app.relf_entries.len() - 1;
                                } else {
                                    app.scroll_to_bottom();
                                }
                            }
                            KeyCode::Char('/') => {
                                if !app.showing_help {
                                    app.start_search();
                                }
                            }
                            KeyCode::Char('n') => {
                                if !app.showing_help {
                                    app.next_match();
                                }
                            }
                            KeyCode::Char('N') => {
                                if !app.showing_help {
                                    app.prev_match();
                                }
                            }
                            KeyCode::Enter => {
                                // Open edit overlay for selected card
                                if !app.showing_help && !app.relf_entries.is_empty() {
                                    app.start_editing_entry();
                                }
                            }
                            KeyCode::Char(c)
                                if c == 'g'
                                    || c == '-'
                                    || c == '+'
                                    || app.vim_buffer.starts_with('g') =>
                            {
                                // Allow gg in help mode for scrolling to top
                                app.handle_vim_input(c);
                            }
                            _ => {
                                // Reset dd count if any other key is pressed
                                if app.dd_count > 0 {
                                    app.dd_count = 0;
                                    app.vim_buffer.clear();
                                }
                            }
                        }
                        }
                        InputMode::Insert => {
                            // Check for Ctrl+[ to exit insert mode
                            if key.modifiers == KeyModifiers::CONTROL
                                && key.code == KeyCode::Char('[')
                            {
                                app.input_mode = InputMode::Normal;
                                app.set_status("");
                                continue;
                            }

                            match key.code {
                                KeyCode::Esc => {
                                    app.input_mode = InputMode::Normal;
                                    app.set_status("");
                                }
                                KeyCode::Enter => {
                                    app.insert_newline();
                                    app.is_modified = true;
                                }
                                KeyCode::Char(c) => {
                                    app.insert_char(c);
                                    app.is_modified = true;
                                }
                                KeyCode::Backspace => {
                                    app.backspace();
                                    app.is_modified = true;
                                }
                                KeyCode::Left => {
                                    app.move_cursor_left();
                                }
                                KeyCode::Right => {
                                    app.move_cursor_right();
                                }
                                KeyCode::Up => {
                                    app.move_cursor_up();
                                }
                                KeyCode::Down => {
                                    app.move_cursor_down();
                                }
                                KeyCode::Delete => {
                                    app.delete_char();
                                    app.is_modified = true;
                                }
                                _ => {}
                            }
                        }
                        InputMode::Command => match key.code {
                            KeyCode::Esc => {
                                app.input_mode = InputMode::Normal;
                                app.command_buffer.clear();
                                app.command_history_index = None;
                                app.set_status("");
                            }
                            KeyCode::Tab => {
                                // Tab completion for commands
                                app.complete_command();
                            }
                            KeyCode::Enter => {
                                // Add to history before executing
                                app.add_to_command_history(app.command_buffer.clone());

                                if app.execute_command() {
                                    return Ok(()); // Quit the application
                                }
                                app.input_mode = InputMode::Normal;
                                app.command_buffer.clear();
                            }
                            KeyCode::Up => {
                                if let Some(cmd) = app.get_previous_command() {
                                    app.command_buffer = cmd;
                                    app.set_status(&format!(":{}", app.command_buffer));
                                }
                            }
                            KeyCode::Down => {
                                if let Some(cmd) = app.get_next_command() {
                                    app.command_buffer = cmd;
                                    app.set_status(&format!(":{}", app.command_buffer));
                                }
                            }
                            KeyCode::Char(c) => {
                                app.command_buffer.push(c);
                                app.command_history_index = None;
                                app.reset_completion(); // Reset completion on manual input
                                app.set_status(&format!(":{}", app.command_buffer));
                            }
                            KeyCode::Backspace => {
                                if !app.command_buffer.is_empty() {
                                    app.command_buffer.pop();
                                    app.command_history_index = None;
                                    app.reset_completion(); // Reset completion on backspace
                                    app.set_status(&format!(":{}", app.command_buffer));
                                } else {
                                    // Exit command mode when backspace on empty buffer
                                    app.input_mode = InputMode::Normal;
                                    app.command_history_index = None;
                                    app.set_status("");
                                }
                            }
                            _ => {}
                        },
                        InputMode::Search => match key.code {
                            KeyCode::Esc => {
                                app.input_mode = InputMode::Normal;
                                app.search_buffer.clear();
                                app.search_history_index = None;
                                app.set_status("");
                            }
                            KeyCode::Enter => {
                                // Add to history before executing
                                app.add_to_search_history(app.search_buffer.clone());
                                app.execute_search();
                            }
                            KeyCode::Up => {
                                if let Some(search) = app.get_previous_search() {
                                    app.search_buffer = search;
                                    app.set_status(&format!("/{}", app.search_buffer));
                                }
                            }
                            KeyCode::Down => {
                                if let Some(search) = app.get_next_search() {
                                    app.search_buffer = search;
                                    app.set_status(&format!("/{}", app.search_buffer));
                                }
                            }
                            KeyCode::Char(c) => {
                                app.search_buffer.push(c);
                                app.search_history_index = None;
                                app.set_status(&format!("/{}", app.search_buffer));
                            }
                            KeyCode::Backspace => {
                                if !app.search_buffer.is_empty() {
                                    app.search_buffer.pop();
                                    app.search_history_index = None;
                                    app.set_status(&format!("/{}", app.search_buffer));
                                } else {
                                    // Exit search mode when backspace on empty buffer
                                    app.input_mode = InputMode::Normal;
                                    app.search_history_index = None;
                                    app.set_status("");
                                }
                            }
                            _ => {}
                        },
                    }
                }
                Event::Mouse(mouse) => {
                    // Handle overlay mouse events
                    if app.editing_entry {
                        match mouse.kind {
                            MouseEventKind::Down(MouseButton::Left) if mouse.modifiers.is_empty() => {
                                // Check for double-click (clicks within 500ms)
                                let now = Instant::now();
                                let is_double_click = if let Some(last_time) = app.last_click_time {
                                    now.duration_since(last_time).as_millis() < 500
                                } else {
                                    false
                                };

                                if is_double_click {
                                    // Check if Exit field is selected
                                    if app.edit_field_index < app.edit_buffer.len() {
                                        let field = &app.edit_buffer[app.edit_field_index];
                                        if field == "Exit" {
                                            // Close overlay without saving
                                            app.cancel_editing_entry();
                                            app.last_click_time = None;
                                            continue;
                                        }
                                    }

                                    // Double-click: enter insert mode for currently selected field
                                    if !app.edit_insert_mode {
                                        app.edit_field_editing_mode = true;
                                        app.edit_insert_mode = true;
                                        app.edit_skip_normal_mode = true; // Mark that we skipped normal mode

                                        let field = &app.edit_buffer[app.edit_field_index];
                                        // Clear placeholder text when entering insert mode
                                        if app.edit_field_index < app.edit_buffer_is_placeholder.len()
                                            && app.edit_buffer_is_placeholder[app.edit_field_index] {
                                            app.edit_buffer[app.edit_field_index] = String::new();
                                            app.edit_buffer_is_placeholder[app.edit_field_index] = false;
                                            app.edit_cursor_pos = 0;
                                        } else {
                                            // Move cursor to end of text
                                            app.edit_cursor_pos = field.chars().count();
                                        }
                                    }
                                    app.last_click_time = None; // Reset after double-click
                                } else {
                                    // First click: just record the time
                                    app.last_click_time = Some(now);
                                }
                                continue;
                            }
                            // Allow scrolling in overlay (only in field selection mode)
                            MouseEventKind::ScrollUp => {
                                // Block if in field editing mode (normal/insert)
                                if app.edit_field_editing_mode {
                                    continue;
                                }
                                if app.edit_field_index > 0 {
                                    app.edit_field_index -= 1;
                                    app.edit_cursor_pos = 0;
                                    app.edit_hscroll = 0;
                                    app.edit_vscroll = 0;
                                }
                                continue;
                            }
                            MouseEventKind::ScrollDown => {
                                // Block if in field editing mode (normal/insert)
                                if app.edit_field_editing_mode {
                                    continue;
                                }
                                if app.edit_field_index + 1 < app.edit_buffer.len() {
                                    app.edit_field_index += 1;
                                    app.edit_cursor_pos = 0;
                                    app.edit_hscroll = 0;
                                    app.edit_vscroll = 0;
                                }
                                continue;
                            }
                            _ => {
                                // Other mouse events in overlay, ignore
                            }
                        }
                    }

                    match mouse.kind {
                        MouseEventKind::ScrollLeft => {
                            // Horizontal scroll left
                            if app.format_mode == FormatMode::View {
                                app.relf_hscroll_by(-8);
                            } else if app.format_mode == FormatMode::Edit {
                                app.relf_hscroll_by(-8);
                            }
                        }
                        MouseEventKind::ScrollRight => {
                            // Horizontal scroll right
                            if app.format_mode == FormatMode::View {
                                app.relf_hscroll_by(8);
                            } else if app.format_mode == FormatMode::Edit {
                                app.relf_hscroll_by(8);
                            }
                        }
                        MouseEventKind::ScrollUp => {
                            // Don't scroll vertically if horizontal scrollbar is being dragged
                            if app.dragging_scrollbar != Some(ScrollbarType::Horizontal) {
                                // If explorer has focus, scroll explorer
                                if app.explorer_open && app.explorer_has_focus {
                                    app.explorer_move_up();
                                } else if app.format_mode == FormatMode::Edit {
                                    // Scroll and move cursor together
                                    for _ in 0..5 {
                                        if app.content_cursor_line > 0 {
                                            app.move_cursor_up();
                                        } else {
                                            app.scroll_up();
                                        }
                                    }
                                } else if !app.relf_entries.is_empty() {
                                    // Card view: move selection up
                                    if app.selected_entry_index > 0 {
                                        app.selected_entry_index -= 1;
                                    }
                                } else {
                                    // Relf: clamp to content bounds
                                    let dec = 5u16;
                                    app.scroll = app.scroll.saturating_sub(dec);
                                }
                            }
                        }
                        MouseEventKind::ScrollDown => {
                            // Don't scroll vertically if horizontal scrollbar is being dragged
                            if app.dragging_scrollbar != Some(ScrollbarType::Horizontal) {
                                // If explorer has focus, scroll explorer
                                if app.explorer_open && app.explorer_has_focus {
                                    app.explorer_move_down();
                                } else if app.format_mode == FormatMode::Edit {
                                    // Scroll and move cursor together
                                    for _ in 0..5 {
                                        app.move_cursor_down();
                                    }
                                } else if !app.relf_entries.is_empty() {
                                    // Card view: move selection down
                                    if app.selected_entry_index + 1 < app.relf_entries.len() {
                                        app.selected_entry_index += 1;
                                    }
                                } else {
                                    // Relf: clamp to last content page
                                    let inc = 5u16;
                                    let max_off = app.relf_content_max_scroll();
                                    let new_val = app.scroll.saturating_add(inc);
                                    app.scroll = std::cmp::min(new_val, max_off);
                                }
                            }
                        }
                        MouseEventKind::Down(MouseButton::Left) => {
                            // Disable scrollbar dragging in Edit mode
                            if app.format_mode == FormatMode::Edit {
                                continue;
                            }

                            // Handle mouse click on scrollbars
                            let click_x = mouse.column;
                            let click_y = mouse.row;

                            // Check if click is on vertical scrollbar
                            let terminal_width = terminal.size().map(|s| s.width).unwrap_or(80);
                            let terminal_height = terminal.size().map(|s| s.height).unwrap_or(24);

                            // Check horizontal scrollbar first
                            let on_hscrollbar = click_y >= terminal_height.saturating_sub(2)
                                && click_x > 0
                                && click_x < terminal_width - 1;
                            let on_vscrollbar = click_x == terminal_width - 1
                                && click_y > 0
                                && click_y < terminal_height - 1;

                            if on_hscrollbar && app.format_mode == FormatMode::Edit {
                                // Horizontal scrollbar clicked (Edit mode only)
                                app.dragging_scrollbar = Some(ScrollbarType::Horizontal);
                                let max_hscroll = app.relf_max_hscroll();

                                if max_hscroll > 0 {
                                    let scrollbar_width = (terminal_width - 2) as f32;
                                    let click_ratio = (click_x - 1) as f32 / scrollbar_width;
                                    let new_hscroll = (max_hscroll as f32 * click_ratio) as u16;
                                    app.hscroll = new_hscroll.min(max_hscroll);
                                }
                            } else if on_vscrollbar {
                                // Vertical scrollbar clicked
                                app.dragging_scrollbar = Some(ScrollbarType::Vertical);
                                let scrollbar_height = (terminal_height - 2) as f32;
                                let click_ratio = (click_y - 1) as f32 / scrollbar_height;
                                let new_scroll = (app.max_scroll as f32 * click_ratio) as u16;
                                app.scroll = new_scroll.min(app.max_scroll);
                            } else {
                                // Not on any scrollbar - check for double-click
                                // Check for double-click (clicks within 500ms)
                                let now = Instant::now();
                                let is_double_click = if let Some(last_time) = app.last_click_time {
                                    now.duration_since(last_time).as_millis() < 500
                                } else {
                                    false
                                };

                                if is_double_click {
                                    // If explorer has focus, open file and move to file window
                                    if app.explorer_open && app.explorer_has_focus {
                                        app.explorer_select_entry();
                                    } else if app.format_mode == FormatMode::View && !app.relf_entries.is_empty() {
                                        // Double-click: open the overlay for the currently selected entry
                                        app.open_entry_overlay();
                                    }
                                    app.last_click_time = None; // Reset after double-click
                                } else {
                                    // First click: just record the time
                                    app.last_click_time = Some(now);
                                }
                                app.dragging_scrollbar = None;
                            }
                        }
                        MouseEventKind::Up(MouseButton::Left) => {
                            // Disable in Edit mode
                            if app.format_mode == FormatMode::Edit {
                                continue;
                            }
                            // Release scrollbar drag
                            app.dragging_scrollbar = None;
                        }
                        MouseEventKind::Drag(MouseButton::Left) => {
                            // Disable in Edit mode
                            if app.format_mode == FormatMode::Edit {
                                continue;
                            }
                            // Only handle drag if we're already dragging a scrollbar
                            match app.dragging_scrollbar {
                                Some(ScrollbarType::Vertical) => {
                                    // Continue vertical scrollbar drag
                                    let click_y = mouse.row;
                                    let terminal_height =
                                        terminal.size().map(|s| s.height).unwrap_or(24);

                                    if click_y > 0 && click_y < terminal_height - 1 {
                                        let scrollbar_height = (terminal_height - 2) as f32;
                                        let click_ratio = (click_y - 1) as f32 / scrollbar_height;
                                        let new_scroll =
                                            (app.max_scroll as f32 * click_ratio) as u16;
                                        app.scroll = new_scroll.min(app.max_scroll);
                                    }
                                }
                                Some(ScrollbarType::Horizontal) => {
                                    // Continue horizontal scrollbar drag (Edit mode only)
                                    if app.format_mode == FormatMode::Edit {
                                        let click_x = mouse.column;
                                        let terminal_width =
                                            terminal.size().map(|s| s.width).unwrap_or(80);

                                        if click_x > 0 && click_x < terminal_width - 1 {
                                            let max_hscroll = app.relf_max_hscroll();

                                            if max_hscroll > 0 {
                                                let scrollbar_width = (terminal_width - 2) as f32;
                                                let click_ratio =
                                                    (click_x - 1) as f32 / scrollbar_width;
                                                let new_hscroll =
                                                    (max_hscroll as f32 * click_ratio) as u16;
                                                app.hscroll = new_hscroll.min(max_hscroll);
                                            }
                                        }
                                    }
                                }
                                None => {
                                    // Not dragging any scrollbar, ignore
                                }
                            }
                        }
                        _ => {}
                    }
                }
                Event::Paste(_) => {
                    // Paste events not supported - use 'v' key instead
                }
                _ => {}
            }
        }
    }
}