jiq 2.21.1

Interactive JSON query tool with real-time output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
//! Global key handlers
//!
//! This module handles keys that work regardless of which pane has focus,
//! including help popup navigation, quit commands, output mode selection,
//! focus switching, and error overlay toggle.

use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use super::super::app_state::{App, Focus, OutputMode};

/// Accept autocomplete suggestion when visible in input field
/// Returns true if autocomplete was handled, false otherwise
fn accept_autocomplete_suggestion(app: &mut App) -> bool {
    if app.focus == Focus::InputField && app.autocomplete.is_visible() {
        if let Some(suggestion) = app.autocomplete.selected() {
            let suggestion_clone = suggestion.clone();
            app.insert_autocomplete_suggestion(&suggestion_clone);
            app.debouncer.mark_executed();
            app.update_tooltip();
        }
        return true;
    }
    false
}

/// Handle global keys that work regardless of focus
/// Returns true if key was handled, false otherwise
pub fn handle_global_keys(app: &mut App, key: KeyEvent) -> bool {
    // Don't intercept keys when history popup is visible (except BackTab for focus switch)
    // (Enter, Tab need to be handled by history handler)
    if app.history.is_visible() && key.code != KeyCode::BackTab {
        return false;
    }

    // Handle help popup when visible (must be first to block other keys)
    if app.help.visible {
        match key.code {
            // Close help
            KeyCode::Esc | KeyCode::F(1) => {
                app.help.visible = false;
                app.help.scroll.reset();
                return true;
            }
            KeyCode::Char('q') if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                app.help.visible = false;
                app.help.scroll.reset();
                return true;
            }
            KeyCode::Char('?') => {
                app.help.visible = false;
                app.help.scroll.reset();
                return true;
            }
            // Scroll down (j, J, Down, Ctrl+D)
            KeyCode::Char('j') | KeyCode::Down => {
                app.help.scroll.scroll_down(1);
                return true;
            }
            KeyCode::Char('J') => {
                app.help.scroll.scroll_down(10);
                return true;
            }
            KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                app.help.scroll.scroll_down(10);
                return true;
            }
            KeyCode::PageDown => {
                app.help.scroll.scroll_down(10);
                return true;
            }
            // Scroll up (k, K, Up, Ctrl+U, PageUp)
            KeyCode::Char('k') | KeyCode::Up => {
                app.help.scroll.scroll_up(1);
                return true;
            }
            KeyCode::Char('K') => {
                app.help.scroll.scroll_up(10);
                return true;
            }
            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                app.help.scroll.scroll_up(10);
                return true;
            }
            KeyCode::PageUp => {
                app.help.scroll.scroll_up(10);
                return true;
            }
            // Jump to top/bottom
            KeyCode::Char('g') | KeyCode::Home => {
                app.help.scroll.jump_to_top();
                return true;
            }
            KeyCode::Char('G') | KeyCode::End => {
                app.help.scroll.jump_to_bottom();
                return true;
            }
            _ => {
                // Help popup blocks other keys
                return true;
            }
        }
    }

    // Global keys (work even when help is not visible)
    match key.code {
        // Quit (Ctrl+C always works)
        KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            app.should_quit = true;
            true
        }
        // Quit with 'q' in Normal mode (but not in Insert mode input field)
        KeyCode::Char('q') if !key.modifiers.contains(KeyModifiers::CONTROL) => {
            // Only quit in Normal mode or when results pane is focused
            match app.focus {
                Focus::ResultsPane => {
                    app.should_quit = true;
                    true
                }
                Focus::InputField => {
                    // Check editor mode - only quit in Normal mode
                    if app.input.editor_mode == crate::editor::EditorMode::Normal {
                        app.should_quit = true;
                        true
                    } else {
                        false // 'q' in Insert mode is just typing
                    }
                }
            }
        }

        // Output query string: Ctrl+Q (primary), Shift+Enter, or Alt+Enter
        KeyCode::Char('q') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            // Execute any pending debounced query immediately (bypass debounce)
            if app.debouncer.has_pending() {
                crate::editor::editor_events::execute_query(app);
                app.debouncer.mark_executed();
            }
            // Save successful queries to history
            if app.query.result.is_ok() && !app.query().is_empty() {
                let query = app.query().to_string();
                app.history.add_entry(&query);
            }
            app.output_mode = Some(OutputMode::Query);
            app.should_quit = true;
            true
        }
        KeyCode::Enter if key.modifiers.contains(KeyModifiers::SHIFT) => {
            // Execute any pending debounced query immediately (bypass debounce)
            if app.debouncer.has_pending() {
                crate::editor::editor_events::execute_query(app);
                app.debouncer.mark_executed();
            }
            // Save successful queries to history
            if app.query.result.is_ok() && !app.query().is_empty() {
                let query = app.query().to_string();
                app.history.add_entry(&query);
            }
            app.output_mode = Some(OutputMode::Query);
            app.should_quit = true;
            true
        }
        KeyCode::Enter if key.modifiers.contains(KeyModifiers::ALT) => {
            // Execute any pending debounced query immediately (bypass debounce)
            if app.debouncer.has_pending() {
                crate::editor::editor_events::execute_query(app);
                app.debouncer.mark_executed();
            }
            // Save successful queries to history
            if app.query.result.is_ok() && !app.query().is_empty() {
                let query = app.query().to_string();
                app.history.add_entry(&query);
            }
            app.output_mode = Some(OutputMode::Query);
            app.should_quit = true;
            true
        }
        KeyCode::Enter => {
            // Accept autocomplete suggestion if visible (same behavior as Tab)
            // Requirements: 1.1, 1.2, 1.3, 1.4, 3.1
            if accept_autocomplete_suggestion(app) {
                return true;
            }

            // Fall through to existing exit behavior when autocomplete not visible
            // Requirements: 2.1, 2.2, 2.3
            // Execute any pending debounced query immediately (bypass debounce)
            if app.debouncer.has_pending() {
                crate::editor::editor_events::execute_query(app);
                app.debouncer.mark_executed();
            }
            // Save successful queries to history
            if app.query.result.is_ok() && !app.query().is_empty() {
                let query = app.query().to_string();
                app.history.add_entry(&query);
            }
            app.output_mode = Some(OutputMode::Results);
            app.should_quit = true;
            true
        }

        // Accept autocomplete with Tab (only if visible in input field)
        KeyCode::Tab if !key.modifiers.contains(KeyModifiers::CONTROL) => {
            accept_autocomplete_suggestion(app)
        }

        // Switch focus with Shift+Tab
        KeyCode::BackTab => {
            // Close history popup if it's open
            if app.history.is_visible() {
                app.history.close();
            }

            app.focus = match app.focus {
                Focus::InputField => Focus::ResultsPane,
                Focus::ResultsPane => Focus::InputField,
            };
            true
        }

        // Toggle help popup (F1 or ?)
        KeyCode::F(1) => {
            app.help.visible = !app.help.visible;
            true
        }
        KeyCode::Char('?') => {
            // Only toggle help in Normal mode (Insert mode needs '?' for typing)
            if app.input.editor_mode == crate::editor::EditorMode::Normal
                || app.focus == Focus::ResultsPane
            {
                app.help.visible = !app.help.visible;
                true
            } else {
                false
            }
        }

        // Toggle error overlay with Ctrl+E
        KeyCode::Char('e') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            // Only toggle if there's an error to show
            if app.query.result.is_err() {
                app.error_overlay_visible = !app.error_overlay_visible;
            }
            true
        }

        // Toggle tooltip with Ctrl+T (T for Tooltip)
        // Requirements 2.1, 2.2, 2.3: Toggle tooltip state on/off
        KeyCode::Char('t') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            crate::tooltip::tooltip_events::handle_tooltip_toggle(&mut app.tooltip);
            true
        }

        // Open search with Ctrl+F (works from any pane)
        // Requirements 1.1: Ctrl+F opens search from any pane
        KeyCode::Char('f') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            crate::search::search_events::open_search(app);
            true
        }

        _ => false, // Key not handled
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::editor::EditorMode;
    use crate::history::HistoryState;
    use crate::test_utils::test_helpers::{
        TEST_JSON, app_with_query, key, key_with_mods, test_app,
    };
    use tui_textarea::CursorMove;

    // Helper to execute any pending debounced query
    // In tests, we need to manually trigger execution since there's no event loop
    fn flush_debounced_query(app: &mut App) {
        if app.debouncer.has_pending() {
            crate::editor::editor_events::execute_query(app);
            app.debouncer.mark_executed();
        }
    }

    // ========== Error Overlay Tests ==========

    #[test]
    fn test_error_overlay_initializes_hidden() {
        let app = test_app(TEST_JSON);
        assert!(!app.error_overlay_visible);
    }

    #[test]
    fn test_ctrl_e_toggles_error_overlay_when_error_exists() {
        let mut app = test_app(TEST_JSON);
        app.input.editor_mode = EditorMode::Insert;

        // Type an invalid query (| is invalid jq syntax)
        app.handle_key_event(key(KeyCode::Char('|')));
        // Flush debounced query to execute immediately (simulates debounce period passing)
        flush_debounced_query(&mut app);

        // Should have an error now
        assert!(app.query.result.is_err());
        assert!(!app.error_overlay_visible); // Initially hidden

        // Press Ctrl+E to show overlay
        app.handle_key_event(key_with_mods(KeyCode::Char('e'), KeyModifiers::CONTROL));
        assert!(app.error_overlay_visible);

        // Press Ctrl+E again to hide overlay
        app.handle_key_event(key_with_mods(KeyCode::Char('e'), KeyModifiers::CONTROL));
        assert!(!app.error_overlay_visible);
    }

    #[test]
    fn test_ctrl_e_does_nothing_when_no_error() {
        let mut app = test_app(TEST_JSON);
        // Initial query "." should succeed
        assert!(app.query.result.is_ok());
        assert!(!app.error_overlay_visible);

        // Press Ctrl+E (should do nothing since no error)
        app.handle_key_event(key_with_mods(KeyCode::Char('e'), KeyModifiers::CONTROL));
        assert!(!app.error_overlay_visible); // Should remain hidden
    }

    #[test]
    fn test_error_overlay_hides_on_query_change() {
        let mut app = test_app(TEST_JSON);
        app.input.editor_mode = EditorMode::Insert;

        // Type invalid query
        app.handle_key_event(key(KeyCode::Char('|')));
        // Flush debounced query to execute immediately
        flush_debounced_query(&mut app);
        assert!(app.query.result.is_err());

        // Show error overlay
        app.handle_key_event(key_with_mods(KeyCode::Char('e'), KeyModifiers::CONTROL));
        assert!(app.error_overlay_visible);

        // Change query by pressing backspace to delete the invalid character
        app.handle_key_event(key(KeyCode::Backspace));

        // Overlay should auto-hide after query change
        assert!(!app.error_overlay_visible);
    }

    #[test]
    fn test_error_overlay_hides_on_query_change_in_normal_mode() {
        let mut app = test_app(TEST_JSON);
        app.input.editor_mode = EditorMode::Insert;

        // Type invalid query
        app.handle_key_event(key(KeyCode::Char('|')));
        // Flush debounced query to execute immediately
        flush_debounced_query(&mut app);
        assert!(app.query.result.is_err());

        // Show error overlay
        app.handle_key_event(key_with_mods(KeyCode::Char('e'), KeyModifiers::CONTROL));
        assert!(app.error_overlay_visible);

        // Switch to Normal mode and delete the character
        app.handle_key_event(key(KeyCode::Esc));
        app.input.textarea.move_cursor(CursorMove::Head);
        app.handle_key_event(key(KeyCode::Char('x')));

        // Overlay should auto-hide after query change
        assert!(!app.error_overlay_visible);
    }

    #[test]
    fn test_ctrl_e_works_in_normal_mode() {
        let mut app = test_app(TEST_JSON);
        app.input.editor_mode = EditorMode::Insert;

        // Type invalid query
        app.handle_key_event(key(KeyCode::Char('|')));
        // Flush debounced query to execute immediately
        flush_debounced_query(&mut app);
        assert!(app.query.result.is_err());

        // Switch to Normal mode
        app.handle_key_event(key(KeyCode::Esc));
        assert_eq!(app.input.editor_mode, EditorMode::Normal);

        // Press Ctrl+E in Normal mode
        app.handle_key_event(key_with_mods(KeyCode::Char('e'), KeyModifiers::CONTROL));
        assert!(app.error_overlay_visible);
    }

    #[test]
    fn test_ctrl_e_works_when_results_pane_focused() {
        let mut app = test_app(TEST_JSON);
        app.input.editor_mode = EditorMode::Insert;

        // Type invalid query
        app.handle_key_event(key(KeyCode::Char('|')));
        // Flush debounced query to execute immediately
        flush_debounced_query(&mut app);
        assert!(app.query.result.is_err());

        // Switch focus to results pane
        app.handle_key_event(key(KeyCode::BackTab));
        assert_eq!(app.focus, Focus::ResultsPane);

        // Press Ctrl+E while results pane is focused
        app.handle_key_event(key_with_mods(KeyCode::Char('e'), KeyModifiers::CONTROL));
        assert!(app.error_overlay_visible);
    }

    // ========== Global Key Handler Tests ==========

    #[test]
    fn test_ctrl_c_sets_quit_flag() {
        let mut app = app_with_query(".");

        app.handle_key_event(key_with_mods(KeyCode::Char('c'), KeyModifiers::CONTROL));

        assert!(app.should_quit);
    }

    #[test]
    fn test_q_sets_quit_flag_in_normal_mode() {
        let mut app = app_with_query(".");
        app.input.editor_mode = EditorMode::Normal;

        app.handle_key_event(key(KeyCode::Char('q')));

        assert!(app.should_quit);
    }

    #[test]
    fn test_q_does_not_quit_in_insert_mode() {
        let mut app = app_with_query(".");
        app.input.editor_mode = EditorMode::Insert;

        app.handle_key_event(key(KeyCode::Char('q')));

        // Should NOT quit - 'q' should be typed instead
        assert!(!app.should_quit);
        assert_eq!(app.query(), ".q");
    }

    #[test]
    fn test_enter_sets_results_output_mode() {
        let mut app = app_with_query(".");

        app.handle_key_event(key(KeyCode::Enter));

        assert_eq!(app.output_mode, Some(OutputMode::Results));
        assert!(app.should_quit);
    }

    #[test]
    fn test_enter_saves_successful_query_to_history() {
        // CRITICAL: Enter should save query to history before exiting
        let mut app = app_with_query(".name");
        let initial_count = app.history.total_count();

        // Ensure query is successful
        assert!(app.query.result.is_ok());

        app.handle_key_event(key(KeyCode::Enter));

        // History should have one more entry
        assert_eq!(app.history.total_count(), initial_count + 1);
        assert!(app.should_quit);
    }

    #[test]
    fn test_enter_does_not_save_failed_query_to_history() {
        // Failed queries should NOT be saved to history
        let mut app = test_app(r#"{"name": "test"}"#);
        app.input.editor_mode = EditorMode::Insert;

        // Type invalid query
        app.handle_key_event(key(KeyCode::Char('|')));
        // Flush debounced query to execute immediately
        flush_debounced_query(&mut app);
        let initial_count = app.history.total_count();

        // Ensure query failed
        assert!(app.query.result.is_err());

        app.handle_key_event(key(KeyCode::Enter));

        // History should NOT have changed
        assert_eq!(app.history.total_count(), initial_count);
        assert!(app.should_quit);
    }

    #[test]
    fn test_enter_does_not_save_empty_query_to_history() {
        // Empty queries should NOT be saved to history
        let mut app = app_with_query("");
        let initial_count = app.history.total_count();

        app.handle_key_event(key(KeyCode::Enter));

        // History should NOT have changed
        assert_eq!(app.history.total_count(), initial_count);
        assert!(app.should_quit);
    }

    // ========== Ctrl+Q Tests ==========

    #[test]
    fn test_ctrl_q_outputs_query_and_saves_successful_query() {
        let mut app = app_with_query(".name");
        let initial_count = app.history.total_count();

        app.handle_key_event(key_with_mods(KeyCode::Char('q'), KeyModifiers::CONTROL));

        assert_eq!(app.history.total_count(), initial_count + 1);
        assert_eq!(app.output_mode, Some(OutputMode::Query));
        assert!(app.should_quit);
    }

    #[test]
    fn test_ctrl_q_does_not_save_failed_query() {
        let mut app = test_app(TEST_JSON);
        app.input.editor_mode = EditorMode::Insert;
        app.history = HistoryState::empty();

        // Type invalid query
        app.handle_key_event(key(KeyCode::Char('|')));
        // Flush debounced query to execute immediately
        flush_debounced_query(&mut app);
        let initial_count = app.history.total_count();

        // Ensure query failed
        assert!(app.query.result.is_err());

        app.handle_key_event(key_with_mods(KeyCode::Char('q'), KeyModifiers::CONTROL));

        // Should NOT save to history
        assert_eq!(app.history.total_count(), initial_count);
        // But should still exit with query output mode
        assert_eq!(app.output_mode, Some(OutputMode::Query));
        assert!(app.should_quit);
    }

    // ========== Shift+Enter Tests ==========

    #[test]
    fn test_shift_enter_outputs_query_and_saves_successful_query() {
        let mut app = app_with_query(".name");
        let initial_count = app.history.total_count();

        app.handle_key_event(key_with_mods(KeyCode::Enter, KeyModifiers::SHIFT));

        assert_eq!(app.history.total_count(), initial_count + 1);
        assert_eq!(app.output_mode, Some(OutputMode::Query));
        assert!(app.should_quit);
    }

    #[test]
    fn test_shift_enter_does_not_save_failed_query() {
        let mut app = test_app(TEST_JSON);
        app.input.editor_mode = EditorMode::Insert;
        app.history = HistoryState::empty();

        // Type invalid query
        app.handle_key_event(key(KeyCode::Char('|')));
        // Flush debounced query to execute immediately
        flush_debounced_query(&mut app);
        let initial_count = app.history.total_count();

        // Ensure query failed
        assert!(app.query.result.is_err());

        app.handle_key_event(key_with_mods(KeyCode::Enter, KeyModifiers::SHIFT));

        // Should NOT save to history
        assert_eq!(app.history.total_count(), initial_count);
        // But should still exit with query output mode
        assert_eq!(app.output_mode, Some(OutputMode::Query));
        assert!(app.should_quit);
    }

    // ========== Alt+Enter Tests ==========

    #[test]
    fn test_alt_enter_outputs_query_and_saves_successful_query() {
        let mut app = app_with_query(".name");
        let initial_count = app.history.total_count();

        app.handle_key_event(key_with_mods(KeyCode::Enter, KeyModifiers::ALT));

        assert_eq!(app.history.total_count(), initial_count + 1);
        assert_eq!(app.output_mode, Some(OutputMode::Query));
        assert!(app.should_quit);
    }

    #[test]
    fn test_alt_enter_does_not_save_failed_query() {
        let mut app = test_app(TEST_JSON);
        app.input.editor_mode = EditorMode::Insert;
        app.history = HistoryState::empty();

        // Type invalid query
        app.handle_key_event(key(KeyCode::Char('|')));
        // Flush debounced query to execute immediately
        flush_debounced_query(&mut app);
        let initial_count = app.history.total_count();

        // Ensure query failed
        assert!(app.query.result.is_err());

        app.handle_key_event(key_with_mods(KeyCode::Enter, KeyModifiers::ALT));

        // Should NOT save to history
        assert_eq!(app.history.total_count(), initial_count);
        // But should still exit with query output mode
        assert_eq!(app.output_mode, Some(OutputMode::Query));
        assert!(app.should_quit);
    }

    #[test]
    fn test_shift_tab_switches_focus_to_results() {
        let mut app = app_with_query(".");
        app.focus = Focus::InputField;

        app.handle_key_event(key(KeyCode::BackTab));

        assert_eq!(app.focus, Focus::ResultsPane);
    }

    #[test]
    fn test_shift_tab_switches_focus_to_input() {
        let mut app = app_with_query(".");
        app.focus = Focus::ResultsPane;

        app.handle_key_event(key(KeyCode::BackTab));

        assert_eq!(app.focus, Focus::InputField);
    }

    #[test]
    fn test_global_keys_work_regardless_of_focus() {
        let mut app = app_with_query(".");
        app.focus = Focus::ResultsPane;

        app.handle_key_event(key_with_mods(KeyCode::Char('c'), KeyModifiers::CONTROL));

        // Ctrl+C should work even when results pane is focused
        assert!(app.should_quit);
    }

    #[test]
    fn test_insert_mode_text_input_updates_query() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;

        // Simulate typing a character
        app.handle_key_event(key(KeyCode::Char('.')));

        assert_eq!(app.query(), ".");
    }

    #[test]
    fn test_query_execution_resets_scroll() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;
        app.results_scroll.offset = 50;

        // Insert text which should trigger query execution
        app.handle_key_event(key(KeyCode::Char('.')));

        // Scroll should be reset when query changes
        assert_eq!(app.results_scroll.offset, 0);
    }

    // ========== UTF-8 Edge Case Tests ==========

    #[test]
    fn test_history_with_emoji() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;

        app.history.add_entry_in_memory(".emoji_field 🚀");

        app.handle_key_event(key_with_mods(KeyCode::Char('p'), KeyModifiers::CONTROL));
        assert_eq!(app.query(), ".emoji_field 🚀");
    }

    #[test]
    fn test_history_with_multibyte_chars() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;

        app.history.add_entry_in_memory(".café | .naïve");

        app.handle_key_event(key_with_mods(KeyCode::Char('p'), KeyModifiers::CONTROL));
        assert_eq!(app.query(), ".café | .naïve");
    }

    #[test]
    fn test_history_search_with_unicode() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;

        app.history.add_entry_in_memory(".café");
        app.history.add_entry_in_memory(".coffee");

        app.handle_key_event(key_with_mods(KeyCode::Char('r'), KeyModifiers::CONTROL));

        // Search for unicode
        app.handle_key_event(key(KeyCode::Char('c')));
        app.handle_key_event(key(KeyCode::Char('a')));
        app.handle_key_event(key(KeyCode::Char('f')));

        // Should filter to .café
        assert_eq!(app.history.filtered_count(), 1);
    }

    // ========== Boundary Condition Tests ==========

    #[test]
    fn test_cycling_stops_at_oldest() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;

        app.history.add_entry_in_memory(".first");

        // Cycle to first entry
        app.handle_key_event(key_with_mods(KeyCode::Char('p'), KeyModifiers::CONTROL));
        assert_eq!(app.query(), ".first");

        // Spam Ctrl+P - should stay at .first
        app.handle_key_event(key_with_mods(KeyCode::Char('p'), KeyModifiers::CONTROL));
        app.handle_key_event(key_with_mods(KeyCode::Char('p'), KeyModifiers::CONTROL));
        assert_eq!(app.query(), ".first");
    }

    #[test]
    fn test_history_popup_with_single_entry() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;

        app.history.add_entry_in_memory(".single");

        app.handle_key_event(key_with_mods(KeyCode::Char('r'), KeyModifiers::CONTROL));
        assert!(app.history.is_visible());

        // Should wrap on navigation
        app.handle_key_event(key(KeyCode::Up));
        assert_eq!(app.history.selected_index(), 0);

        app.handle_key_event(key(KeyCode::Down));
        assert_eq!(app.history.selected_index(), 0);
    }

    #[test]
    fn test_filter_with_no_matches() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;

        app.history.add_entry_in_memory(".foo");
        app.history.add_entry_in_memory(".bar");

        app.handle_key_event(key_with_mods(KeyCode::Char('r'), KeyModifiers::CONTROL));

        // Search for something that doesn't match
        app.handle_key_event(key(KeyCode::Char('x')));
        app.handle_key_event(key(KeyCode::Char('y')));
        app.handle_key_event(key(KeyCode::Char('z')));

        // Should have zero matches
        assert_eq!(app.history.filtered_count(), 0);
    }

    #[test]
    fn test_backspace_on_empty_search() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;

        app.history.add_entry_in_memory(".test");

        app.handle_key_event(key_with_mods(KeyCode::Char('r'), KeyModifiers::CONTROL));

        // Search is empty initially
        assert_eq!(app.history.search_query(), "");

        // Press backspace - should not crash
        app.handle_key_event(key(KeyCode::Backspace));
        assert_eq!(app.history.search_query(), "");
    }

    // ========== 'q' key behavior tests ==========

    #[test]
    fn test_q_quits_in_results_pane_insert_mode() {
        let mut app = app_with_query("");
        app.focus = Focus::ResultsPane;
        app.input.editor_mode = EditorMode::Insert;

        // 'q' should quit even when editor is in Insert mode
        // because we're in ResultsPane (not editing text)
        app.handle_key_event(key(KeyCode::Char('q')));

        assert!(app.should_quit);
    }

    #[test]
    fn test_q_does_not_quit_in_input_field_insert_mode() {
        let mut app = app_with_query("");
        app.focus = Focus::InputField;
        app.input.editor_mode = EditorMode::Insert;

        // 'q' should NOT quit when in InputField with Insert mode
        // (user is typing)
        app.handle_key_event(key(KeyCode::Char('q')));

        assert!(!app.should_quit);
        // The 'q' should be inserted into the query
        assert!(app.query().contains('q'));
    }

    #[test]
    fn test_q_quits_in_input_field_normal_mode() {
        let mut app = app_with_query("");
        app.focus = Focus::InputField;
        app.input.editor_mode = EditorMode::Normal;

        // 'q' should quit when in Normal mode
        app.handle_key_event(key(KeyCode::Char('q')));

        assert!(app.should_quit);
    }

    #[test]
    fn test_q_quits_in_results_pane_normal_mode() {
        let mut app = app_with_query("");
        app.focus = Focus::ResultsPane;
        app.input.editor_mode = EditorMode::Normal;

        // 'q' should quit when in ResultsPane Normal mode
        app.handle_key_event(key(KeyCode::Char('q')));

        assert!(app.should_quit);
    }

    #[test]
    fn test_focus_switch_preserves_editor_mode() {
        let mut app = app_with_query("");
        app.focus = Focus::InputField;
        app.input.editor_mode = EditorMode::Insert;

        // Switch to ResultsPane
        app.handle_key_event(key(KeyCode::BackTab));

        // Editor mode should still be Insert
        assert_eq!(app.focus, Focus::ResultsPane);
        assert_eq!(app.input.editor_mode, EditorMode::Insert);

        // 'q' should quit in ResultsPane even with Insert mode
        app.handle_key_event(key(KeyCode::Char('q')));
        assert!(app.should_quit);
    }

    // ========== Help Popup Tests ==========

    #[test]
    fn test_help_popup_initializes_hidden() {
        let app = test_app(TEST_JSON);
        assert!(!app.help.visible);
    }

    #[test]
    fn test_f1_toggles_help_popup() {
        let mut app = app_with_query(".");
        assert!(!app.help.visible);

        app.handle_key_event(key(KeyCode::F(1)));
        assert!(app.help.visible);

        app.handle_key_event(key(KeyCode::F(1)));
        assert!(!app.help.visible);
    }

    #[test]
    fn test_question_mark_toggles_help_in_normal_mode() {
        let mut app = app_with_query(".");
        app.input.editor_mode = EditorMode::Normal;
        app.focus = Focus::InputField;

        app.handle_key_event(key(KeyCode::Char('?')));
        assert!(app.help.visible);

        app.handle_key_event(key(KeyCode::Char('?')));
        assert!(!app.help.visible);
    }

    #[test]
    fn test_question_mark_does_not_toggle_help_in_insert_mode() {
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        app.handle_key_event(key(KeyCode::Char('?')));
        // Should type '?' not toggle help
        assert!(!app.help.visible);
        assert!(app.query().contains('?'));
    }

    #[test]
    fn test_esc_closes_help_popup() {
        let mut app = app_with_query(".");
        app.help.visible = true;

        app.handle_key_event(key(KeyCode::Esc));
        assert!(!app.help.visible);
    }

    #[test]
    fn test_q_closes_help_popup() {
        let mut app = app_with_query(".");
        app.help.visible = true;

        app.handle_key_event(key(KeyCode::Char('q')));
        assert!(!app.help.visible);
    }

    #[test]
    fn test_help_popup_blocks_other_keys() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.input.editor_mode = EditorMode::Insert;

        // Try to type - should be blocked
        app.handle_key_event(key(KeyCode::Char('x')));
        assert!(!app.query().contains('x'));
        assert!(app.help.visible);
    }

    #[test]
    fn test_f1_works_in_insert_mode() {
        let mut app = app_with_query(".");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        app.handle_key_event(key(KeyCode::F(1)));
        assert!(app.help.visible);
    }

    #[test]
    fn test_help_popup_scroll_j_scrolls_down() {
        let mut app = app_with_query(".");
        app.help.visible = true;

        // Set up bounds for help content (48 lines + padding, viewport 20)
        app.help.scroll.update_bounds(60, 20);
        app.help.scroll.offset = 0;

        app.handle_key_event(key(KeyCode::Char('j')));
        assert_eq!(app.help.scroll.offset, 1);
    }

    #[test]
    fn test_help_popup_scroll_k_scrolls_up() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.help.scroll.offset = 5;

        app.handle_key_event(key(KeyCode::Char('k')));
        assert_eq!(app.help.scroll.offset, 4);
    }

    #[test]
    fn test_help_popup_scroll_down_arrow() {
        let mut app = app_with_query(".");
        app.help.visible = true;

        // Set up bounds for help content
        app.help.scroll.update_bounds(60, 20);
        app.help.scroll.offset = 0;

        app.handle_key_event(key(KeyCode::Down));
        assert_eq!(app.help.scroll.offset, 1);
    }

    #[test]
    fn test_help_popup_scroll_up_arrow() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.help.scroll.offset = 5;

        app.handle_key_event(key(KeyCode::Up));
        assert_eq!(app.help.scroll.offset, 4);
    }

    #[test]
    fn test_help_popup_scroll_capital_j_scrolls_10() {
        let mut app = app_with_query(".");
        app.help.visible = true;

        // Set up bounds for help content
        app.help.scroll.update_bounds(60, 20);
        app.help.scroll.offset = 0;

        app.handle_key_event(key(KeyCode::Char('J')));
        assert_eq!(app.help.scroll.offset, 10);
    }

    #[test]
    fn test_help_popup_scroll_capital_k_scrolls_10() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.help.scroll.offset = 15;

        app.handle_key_event(key(KeyCode::Char('K')));
        assert_eq!(app.help.scroll.offset, 5);
    }

    #[test]
    fn test_help_popup_scroll_ctrl_d() {
        let mut app = app_with_query(".");
        app.help.visible = true;

        // Set up bounds for help content
        app.help.scroll.update_bounds(60, 20);
        app.help.scroll.offset = 0;

        app.handle_key_event(key_with_mods(KeyCode::Char('d'), KeyModifiers::CONTROL));
        assert_eq!(app.help.scroll.offset, 10);
    }

    #[test]
    fn test_help_popup_scroll_ctrl_u() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.help.scroll.offset = 15;

        app.handle_key_event(key_with_mods(KeyCode::Char('u'), KeyModifiers::CONTROL));
        assert_eq!(app.help.scroll.offset, 5);
    }

    #[test]
    fn test_help_popup_scroll_g_jumps_to_top() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.help.scroll.offset = 20;

        app.handle_key_event(key(KeyCode::Char('g')));
        assert_eq!(app.help.scroll.offset, 0);
    }

    #[test]
    fn test_help_popup_scroll_capital_g_jumps_to_bottom() {
        let mut app = app_with_query(".");
        app.help.visible = true;

        // Set up bounds for help content
        app.help.scroll.update_bounds(60, 20);
        app.help.scroll.offset = 0;

        app.handle_key_event(key(KeyCode::Char('G')));
        assert_eq!(app.help.scroll.offset, app.help.scroll.max_offset);
    }

    #[test]
    fn test_help_popup_scroll_k_saturates_at_zero() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.help.scroll.offset = 0;

        app.handle_key_event(key(KeyCode::Char('k')));
        assert_eq!(app.help.scroll.offset, 0);
    }

    #[test]
    fn test_help_popup_close_resets_scroll() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.help.scroll.offset = 10;

        app.handle_key_event(key(KeyCode::Esc));
        assert!(!app.help.visible);
        assert_eq!(app.help.scroll.offset, 0);
    }

    #[test]
    fn test_help_popup_scroll_page_down() {
        let mut app = app_with_query(".");
        app.help.visible = true;

        // Set up bounds for help content
        app.help.scroll.update_bounds(60, 20);
        app.help.scroll.offset = 0;

        app.handle_key_event(key(KeyCode::PageDown));
        assert_eq!(app.help.scroll.offset, 10);
    }

    #[test]
    fn test_help_popup_scroll_page_up() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.help.scroll.offset = 15;

        app.handle_key_event(key(KeyCode::PageUp));
        assert_eq!(app.help.scroll.offset, 5);
    }

    #[test]
    fn test_help_popup_scroll_home_jumps_to_top() {
        let mut app = app_with_query(".");
        app.help.visible = true;
        app.help.scroll.offset = 20;

        app.handle_key_event(key(KeyCode::Home));
        assert_eq!(app.help.scroll.offset, 0);
    }

    #[test]
    fn test_help_popup_scroll_end_jumps_to_bottom() {
        let mut app = app_with_query(".");
        app.help.visible = true;

        // Set up bounds for help content
        app.help.scroll.update_bounds(60, 20);
        app.help.scroll.offset = 0;

        app.handle_key_event(key(KeyCode::End));
        assert_eq!(app.help.scroll.offset, app.help.scroll.max_offset);
    }

    // ========== Tab Autocomplete Acceptance Tests ==========

    // ========== Dispatch Order and Focus Tests ==========

    #[test]
    fn test_tab_does_not_accept_autocomplete_in_results_pane() {
        // Critical: Tab should only accept autocomplete when InputField is focused
        let mut app = app_with_query(".na");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::ResultsPane; // Focus on RESULTS, not input

        let suggestions = vec![crate::autocomplete::Suggestion::new(
            ".name",
            crate::autocomplete::SuggestionType::Field,
        )];
        app.autocomplete.update_suggestions(suggestions);
        assert!(app.autocomplete.is_visible());

        // Press Tab while results pane is focused
        app.handle_key_event(key(KeyCode::Tab));

        // Should NOT accept autocomplete (focus check prevents it)
        assert_eq!(app.query(), ".na"); // Query unchanged
        assert!(app.autocomplete.is_visible()); // Still visible
    }

    #[test]
    fn test_vim_navigation_blocked_when_help_visible() {
        // Critical: VIM navigation should be blocked when help popup is open
        let mut app = app_with_query(".test");
        app.input.editor_mode = EditorMode::Normal;
        app.focus = Focus::InputField;
        app.help.visible = true;

        // Try VIM navigation - should be blocked by help popup
        app.handle_key_event(key(KeyCode::Char('h'))); // Move left
        app.handle_key_event(key(KeyCode::Char('l'))); // Move right
        app.handle_key_event(key(KeyCode::Char('w'))); // Word forward
        app.handle_key_event(key(KeyCode::Char('x'))); // Delete char

        // Query should be unchanged (all keys blocked by help)
        assert_eq!(app.query(), ".test");
        assert!(app.help.visible);
    }

    #[test]
    fn test_history_popup_enter_not_intercepted_by_global() {
        // Critical: Enter in history popup should select entry, not output mode
        let mut app = app_with_query("");
        app.input.editor_mode = EditorMode::Insert;

        app.history.add_entry_in_memory(".selected");

        // Open history popup
        app.handle_key_event(key_with_mods(KeyCode::Char('r'), KeyModifiers::CONTROL));
        assert!(app.history.is_visible());

        // Press Enter - should select from history, NOT set output mode
        app.handle_key_event(key(KeyCode::Enter));

        // History should be closed and query should be selected entry
        assert!(!app.history.is_visible());
        assert_eq!(app.query(), ".selected");
        assert!(app.output_mode.is_none()); // Should NOT set output mode
        assert!(!app.should_quit); // Should NOT quit
    }

    #[test]
    fn test_tab_accepts_field_suggestion_replaces_from_dot() {
        // Field suggestions should replace from the last dot
        let mut app = app_with_query(".na");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        // Validate base state
        // .na returns null, so base_query stays at "." (from App::new())
        use crate::query::ResultType;
        assert_eq!(
            app.query.base_query_for_suggestions,
            Some(".".to_string()),
            "base_query should remain '.' since .na returns null"
        );
        assert_eq!(
            app.query.base_type_for_suggestions,
            Some(ResultType::Object),
            "base_type should be Object (root object)"
        );

        // Suggestion should be "name" (no leading dot) since after Dot (CharType::Dot)
        let suggestions = vec![crate::autocomplete::Suggestion::new(
            "name",
            crate::autocomplete::SuggestionType::Field,
        )];
        app.autocomplete.update_suggestions(suggestions);

        app.handle_key_event(key(KeyCode::Tab));

        // Formula for Dot: base + suggestion = "." + "name" = ".name" ✅
        assert_eq!(app.query(), ".name");
        assert!(!app.autocomplete.is_visible());
    }

    #[test]
    fn test_tab_accepts_array_suggestion_appends() {
        // Array suggestions should APPEND when no partial exists
        let mut app = app_with_query(".services");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        // Validate base state was set up by app_with_query
        use crate::query::ResultType;
        assert_eq!(
            app.query.base_query_for_suggestions,
            Some(".services".to_string()),
            "base_query should be '.services'"
        );
        assert_eq!(
            app.query.base_type_for_suggestions,
            Some(ResultType::ArrayOfObjects),
            "base_type should be ArrayOfObjects"
        );

        // Verify cursor is at end
        assert_eq!(app.input.textarea.cursor().1, 9); // After ".services"

        let suggestions = vec![crate::autocomplete::Suggestion::new(
            "[].name",
            crate::autocomplete::SuggestionType::Field,
        )];
        app.autocomplete.update_suggestions(suggestions);

        app.handle_key_event(key(KeyCode::Tab));

        // Should append: .services → .services[].name
        assert_eq!(app.query(), ".services[].name");
        assert!(!app.autocomplete.is_visible());
    }

    #[test]
    fn test_tab_accepts_array_suggestion_replaces_short_partial() {
        // Array suggestions should replace short partials (1-3 chars)
        // First execute base query to set up state
        let mut app = app_with_query(".services");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        // Validate base state
        use crate::query::ResultType;
        assert_eq!(
            app.query.base_query_for_suggestions,
            Some(".services".to_string())
        );
        assert_eq!(
            app.query.base_type_for_suggestions,
            Some(ResultType::ArrayOfObjects)
        );

        // Now add the partial to textarea
        app.input.textarea.insert_str(".s");

        let suggestions = vec![crate::autocomplete::Suggestion::new(
            "[].serviceArn",
            crate::autocomplete::SuggestionType::Field,
        )];
        app.autocomplete.update_suggestions(suggestions);

        app.handle_key_event(key(KeyCode::Tab));

        // Should replace: base + suggestion = ".services" + "[].serviceArn"
        assert_eq!(app.query(), ".services[].serviceArn");
        assert!(!app.autocomplete.is_visible());
    }

    #[test]
    fn test_tab_accepts_nested_array_suggestion() {
        // Nested array access: user types dot after .items[].tags to trigger autocomplete
        let mut app = app_with_query(".items[].tags");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        // Validate base state
        use crate::query::ResultType;
        assert_eq!(
            app.query.base_query_for_suggestions,
            Some(".items[].tags".to_string()),
            "base_query should be '.items[].tags'"
        );
        assert_eq!(
            app.query.base_type_for_suggestions,
            Some(ResultType::ArrayOfObjects),
            "base_type should be ArrayOfObjects"
        );

        // User types "." to trigger autocomplete
        app.input.textarea.insert_char('.');

        // Suggestion is "[].name" (no leading dot since after NoOp 's')
        let suggestions = vec![crate::autocomplete::Suggestion::new(
            "[].name",
            crate::autocomplete::SuggestionType::Field,
        )];
        app.autocomplete.update_suggestions(suggestions);

        app.handle_key_event(key(KeyCode::Tab));

        // Formula for NoOp: base + suggestion
        // ".items[].tags" + "[].name" = ".items[].tags[].name" ✅
        assert_eq!(app.query(), ".items[].tags[].name");
        assert!(!app.autocomplete.is_visible());
    }

    // ========== Tooltip Toggle Tests (Ctrl+T) ==========

    #[test]
    fn test_tooltip_initializes_enabled() {
        let app = test_app(TEST_JSON);
        assert!(app.tooltip.enabled);
    }

    #[test]
    fn test_ctrl_t_toggles_tooltip_from_enabled() {
        let mut app = app_with_query(".");
        assert!(app.tooltip.enabled);

        app.handle_key_event(key_with_mods(KeyCode::Char('t'), KeyModifiers::CONTROL));
        assert!(!app.tooltip.enabled);
    }

    #[test]
    fn test_ctrl_t_toggles_tooltip_from_disabled() {
        let mut app = app_with_query(".");
        app.tooltip.toggle(); // disable first
        assert!(!app.tooltip.enabled);

        app.handle_key_event(key_with_mods(KeyCode::Char('t'), KeyModifiers::CONTROL));
        assert!(app.tooltip.enabled);
    }

    #[test]
    fn test_ctrl_t_works_in_insert_mode() {
        let mut app = app_with_query(".");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;
        assert!(app.tooltip.enabled);

        app.handle_key_event(key_with_mods(KeyCode::Char('t'), KeyModifiers::CONTROL));
        assert!(!app.tooltip.enabled);
    }

    #[test]
    fn test_ctrl_t_works_in_normal_mode() {
        let mut app = app_with_query(".");
        app.input.editor_mode = EditorMode::Normal;
        app.focus = Focus::InputField;
        assert!(app.tooltip.enabled);

        app.handle_key_event(key_with_mods(KeyCode::Char('t'), KeyModifiers::CONTROL));
        assert!(!app.tooltip.enabled);
    }

    #[test]
    fn test_ctrl_t_works_when_results_pane_focused() {
        let mut app = app_with_query(".");
        app.focus = Focus::ResultsPane;
        assert!(app.tooltip.enabled);

        app.handle_key_event(key_with_mods(KeyCode::Char('t'), KeyModifiers::CONTROL));
        assert!(!app.tooltip.enabled);
    }

    #[test]
    fn test_ctrl_t_preserves_current_function() {
        let mut app = app_with_query("select(.x)");
        app.tooltip.set_current_function(Some("select".to_string()));
        assert!(app.tooltip.enabled);

        app.handle_key_event(key_with_mods(KeyCode::Char('t'), KeyModifiers::CONTROL));

        // Should toggle enabled but preserve current_function
        assert!(!app.tooltip.enabled);
        assert_eq!(app.tooltip.current_function, Some("select".to_string()));
    }

    #[test]
    fn test_ctrl_t_round_trip() {
        let mut app = app_with_query(".");
        let initial_enabled = app.tooltip.enabled;

        // Toggle twice should return to original state
        app.handle_key_event(key_with_mods(KeyCode::Char('t'), KeyModifiers::CONTROL));
        app.handle_key_event(key_with_mods(KeyCode::Char('t'), KeyModifiers::CONTROL));

        assert_eq!(app.tooltip.enabled, initial_enabled);
    }

    // ========== Enter Key Autocomplete Tests ==========

    #[test]
    fn test_enter_accepts_suggestion_when_autocomplete_visible() {
        // Test Enter accepts suggestion when autocomplete visible
        // Requirements: 1.1
        let mut app = app_with_query(".na");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        let suggestions = vec![crate::autocomplete::Suggestion::new(
            "name",
            crate::autocomplete::SuggestionType::Field,
        )];
        app.autocomplete.update_suggestions(suggestions);
        assert!(app.autocomplete.is_visible());

        app.handle_key_event(key(KeyCode::Enter));

        // Should accept suggestion, not exit
        assert!(!app.should_quit);
        assert!(app.output_mode.is_none());
        assert_eq!(app.query(), ".name");
    }

    #[test]
    fn test_enter_closes_autocomplete_popup_after_selection() {
        // Test Enter closes autocomplete popup after selection
        // Requirements: 1.2
        let mut app = app_with_query(".na");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        let suggestions = vec![crate::autocomplete::Suggestion::new(
            "name",
            crate::autocomplete::SuggestionType::Field,
        )];
        app.autocomplete.update_suggestions(suggestions);
        assert!(app.autocomplete.is_visible());

        app.handle_key_event(key(KeyCode::Enter));

        // Autocomplete should be hidden after selection
        assert!(!app.autocomplete.is_visible());
    }

    #[test]
    fn test_enter_exits_application_when_autocomplete_not_visible() {
        // Test Enter exits application when autocomplete not visible
        // Requirements: 2.1
        let mut app = app_with_query(".");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        // Ensure autocomplete is not visible
        assert!(!app.autocomplete.is_visible());

        app.handle_key_event(key(KeyCode::Enter));

        // Should exit with results
        assert!(app.should_quit);
        assert_eq!(app.output_mode, Some(OutputMode::Results));
    }

    #[test]
    fn test_enter_with_shift_modifier_bypasses_autocomplete_check() {
        // Test Enter with Shift modifier bypasses autocomplete check
        // Requirements: 2.2
        let mut app = app_with_query(".na");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        let suggestions = vec![crate::autocomplete::Suggestion::new(
            "name",
            crate::autocomplete::SuggestionType::Field,
        )];
        app.autocomplete.update_suggestions(suggestions);
        assert!(app.autocomplete.is_visible());

        // Shift+Enter should output query, not accept autocomplete
        app.handle_key_event(key_with_mods(KeyCode::Enter, KeyModifiers::SHIFT));

        // Should exit with query output mode (bypassing autocomplete)
        assert!(app.should_quit);
        assert_eq!(app.output_mode, Some(OutputMode::Query));
    }

    #[test]
    fn test_enter_with_alt_modifier_bypasses_autocomplete_check() {
        // Test Enter with Alt modifier bypasses autocomplete check
        // Requirements: 2.3
        let mut app = app_with_query(".na");
        app.input.editor_mode = EditorMode::Insert;
        app.focus = Focus::InputField;

        let suggestions = vec![crate::autocomplete::Suggestion::new(
            "name",
            crate::autocomplete::SuggestionType::Field,
        )];
        app.autocomplete.update_suggestions(suggestions);
        assert!(app.autocomplete.is_visible());

        // Alt+Enter should output query, not accept autocomplete
        app.handle_key_event(key_with_mods(KeyCode::Enter, KeyModifiers::ALT));

        // Should exit with query output mode (bypassing autocomplete)
        assert!(app.should_quit);
        assert_eq!(app.output_mode, Some(OutputMode::Query));
    }

    // ========== Property-Based Tests for Enter Key Autocomplete ==========

    use proptest::prelude::*;

    // Feature: enter-key-autocomplete, Property 1: Enter and Tab equivalence for autocomplete selection
    // *For any* application state where the autocomplete popup is visible with at least one suggestion,
    // pressing Enter should produce the exact same query string as pressing Tab.
    // **Validates: Requirements 3.1**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_enter_tab_equivalence_for_autocomplete(
            // Generate different suggestion types
            suggestion_type in prop_oneof![
                Just(crate::autocomplete::SuggestionType::Field),
                Just(crate::autocomplete::SuggestionType::Function),
            ],
            // Generate different suggestion texts
            suggestion_text in prop_oneof![
                Just("name"),
                Just("age"),
                Just("city"),
                Just("length"),
                Just("keys"),
            ],
        ) {
            // Create two identical app instances
            let mut app_enter = app_with_query(".");
            app_enter.input.editor_mode = EditorMode::Insert;
            app_enter.focus = Focus::InputField;

            let mut app_tab = app_with_query(".");
            app_tab.input.editor_mode = EditorMode::Insert;
            app_tab.focus = Focus::InputField;

            // Set up identical autocomplete suggestions
            let suggestion = crate::autocomplete::Suggestion::new(suggestion_text, suggestion_type.clone());
            app_enter.autocomplete.update_suggestions(vec![suggestion.clone()]);
            app_tab.autocomplete.update_suggestions(vec![suggestion]);

            // Verify both have visible autocomplete
            prop_assert!(app_enter.autocomplete.is_visible());
            prop_assert!(app_tab.autocomplete.is_visible());

            // Press Enter on one, Tab on the other
            app_enter.handle_key_event(key(KeyCode::Enter));
            app_tab.handle_key_event(key(KeyCode::Tab));

            // Both should produce the same query string
            prop_assert_eq!(
                app_enter.query(),
                app_tab.query(),
                "Enter and Tab should produce identical query strings"
            );

            // Both should have autocomplete hidden
            prop_assert!(
                !app_enter.autocomplete.is_visible(),
                "Autocomplete should be hidden after Enter"
            );
            prop_assert!(
                !app_tab.autocomplete.is_visible(),
                "Autocomplete should be hidden after Tab"
            );
        }
    }

    // Feature: enter-key-autocomplete, Property 2: Enter accepts autocomplete and closes popup
    // *For any* application state where the autocomplete popup is visible,
    // pressing Enter should result in the autocomplete popup being hidden
    // and the selected suggestion text appearing in the query.
    // **Validates: Requirements 1.1, 1.2**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_enter_accepts_autocomplete_and_closes_popup(
            // Generate different suggestion texts
            suggestion_text in prop_oneof![
                Just("name"),
                Just("age"),
                Just("city"),
                Just("services"),
                Just("items"),
            ],
        ) {
            let mut app = app_with_query(".");
            app.input.editor_mode = EditorMode::Insert;
            app.focus = Focus::InputField;

            // Set up autocomplete with a suggestion
            let suggestion = crate::autocomplete::Suggestion::new(
                suggestion_text,
                crate::autocomplete::SuggestionType::Field,
            );
            app.autocomplete.update_suggestions(vec![suggestion]);

            // Verify autocomplete is visible
            prop_assert!(app.autocomplete.is_visible());

            // Press Enter
            app.handle_key_event(key(KeyCode::Enter));

            // Autocomplete should be hidden
            prop_assert!(
                !app.autocomplete.is_visible(),
                "Autocomplete should be hidden after Enter"
            );

            // Query should contain the suggestion text
            prop_assert!(
                app.query().contains(suggestion_text),
                "Query '{}' should contain suggestion text '{}'",
                app.query(),
                suggestion_text
            );

            // Should NOT have quit (autocomplete acceptance, not exit)
            prop_assert!(
                !app.should_quit,
                "Should not quit when accepting autocomplete"
            );
        }
    }

    // Feature: enter-key-autocomplete, Property 3: Enter exits when autocomplete not visible
    // *For any* application state where the autocomplete popup is not visible,
    // pressing Enter should set the should_quit flag to true and output_mode to Results.
    // **Validates: Requirements 2.1**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_enter_exits_when_autocomplete_not_visible(
            // Test with different focus states
            focus_on_input in any::<bool>(),
            // Test with different editor modes
            insert_mode in any::<bool>(),
        ) {
            let mut app = app_with_query(".");
            app.focus = if focus_on_input {
                Focus::InputField
            } else {
                Focus::ResultsPane
            };
            app.input.editor_mode = if insert_mode {
                EditorMode::Insert
            } else {
                EditorMode::Normal
            };

            // Ensure autocomplete is NOT visible
            app.autocomplete.hide();
            prop_assert!(!app.autocomplete.is_visible());

            // Press Enter
            app.handle_key_event(key(KeyCode::Enter));

            // Should quit with Results output mode
            prop_assert!(
                app.should_quit,
                "Should quit when Enter pressed without autocomplete"
            );
            prop_assert_eq!(
                app.output_mode,
                Some(OutputMode::Results),
                "Output mode should be Results"
            );
        }
    }
}