travelagent 1.11.1

Agent-first TUI code review tool
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
use std::path::PathBuf;

use travelagent_core::model::{Comment, CommentType, LineRange, LineSide};

use super::{AnnotatedLine, App, ConfirmAction, InputMode};

/// Represents a comment location for deletion
enum CommentLocation {
    Review {
        index: usize,
    },
    File {
        path: std::path::PathBuf,
        index: usize,
    },
    Line {
        path: std::path::PathBuf,
        line: u32,
        side: LineSide,
        index: usize,
    },
}

impl App {
    /// Find the comment at the current cursor position
    fn find_comment_at_cursor(&self) -> Option<CommentLocation> {
        let target = self.diff_state.cursor_line;
        match self.line_annotations.get(target) {
            Some(AnnotatedLine::ReviewComment { comment_idx }) => Some(CommentLocation::Review {
                index: *comment_idx,
            }),
            Some(AnnotatedLine::FileComment {
                file_idx,
                comment_idx,
            }) => {
                let path = self.diff_files.get(*file_idx)?.display_path_lossy().clone();
                Some(CommentLocation::File {
                    path,
                    index: *comment_idx,
                })
            }
            Some(AnnotatedLine::LineComment {
                file_idx,
                line,
                side,
                comment_idx,
            }) => {
                let path = self.diff_files.get(*file_idx)?.display_path_lossy().clone();
                Some(CommentLocation::Line {
                    path,
                    line: *line,
                    side: *side,
                    index: *comment_idx,
                })
            }
            _ => None,
        }
    }

    /// Delete the comment at the current cursor position, if any
    /// Returns true if a comment was deleted
    pub fn delete_comment_at_cursor(&mut self) -> bool {
        let location = self.find_comment_at_cursor();

        // Resolve the targeted comment's stable id from its scope+index so we
        // can route the actual deletion through `ReviewEngine::remove_comment`.
        let resolved: Option<(String, String)> = match location {
            Some(CommentLocation::Review { index }) => self
                .engine
                .session()
                .review_comments
                .get(index)
                .map(|c| (c.id.clone(), "Review comment deleted".to_string())),
            Some(CommentLocation::File { path, index }) => self
                .engine
                .session()
                .files
                .get(&path)
                .and_then(|r| r.file_comments.get(index))
                .map(|c| (c.id.clone(), "Comment deleted".to_string())),
            Some(CommentLocation::Line {
                path,
                line,
                side,
                index,
            }) => self
                .engine
                .session()
                .files
                .get(&path)
                .and_then(|r| r.line_comments.get(&line))
                .and_then(|comments| {
                    // Find the actual comment by counting comments with matching side
                    let mut side_idx = 0;
                    for comment in comments {
                        let comment_side = comment.side.unwrap_or(LineSide::New);
                        if comment_side == side {
                            if side_idx == index {
                                return Some((
                                    comment.id.clone(),
                                    format!("Comment on line {line} deleted"),
                                ));
                            }
                            side_idx += 1;
                        }
                    }
                    None
                }),
            None => None,
        };

        let Some((id, message)) = resolved else {
            return false;
        };

        if self.engine.remove_comment(&id) {
            self.dirty = true;
            self.set_message(message);
            self.rebuild_annotations();
            true
        } else {
            false
        }
    }

    pub fn clear_all_comments(&mut self) {
        let (cleared, unreviewed) = self.engine.clear_comments();
        if cleared == 0 && unreviewed == 0 {
            self.set_message("No comments to clear");
            return;
        }

        self.dirty = true;
        self.rebuild_annotations();
        let msg = match (cleared, unreviewed) {
            (0, n) => format!("Unreviewed {n} files"),
            (c, 0) => format!("Cleared {c} comments"),
            (c, n) => format!("Cleared {c} comments, unreviewed {n} files"),
        };
        self.set_message(msg);
    }

    /// Enter edit mode for the comment at the current cursor position
    /// Returns true if a comment was found and edit mode entered
    pub fn enter_edit_mode(&mut self) -> bool {
        let location = self.find_comment_at_cursor();

        match location {
            Some(CommentLocation::Review { index }) => {
                if let Some(comment) = self.engine.session().review_comments.get(index) {
                    self.nav.input_mode = InputMode::Comment;
                    self.comment.buffer = comment.content.clone();
                    self.comment.cursor = self.comment.buffer.len();
                    self.comment.comment_type = comment.comment_type.clone();
                    self.comment.is_review_level = true;
                    self.comment.is_file_level = false;
                    self.comment.line = None;
                    self.comment.editing_id = Some(comment.id.clone());
                    return true;
                }
            }
            Some(CommentLocation::File { path, index }) => {
                if let Some(review) = self.engine.session().files.get(&path)
                    && let Some(comment) = review.file_comments.get(index)
                {
                    self.nav.input_mode = InputMode::Comment;
                    self.comment.buffer = comment.content.clone();
                    self.comment.cursor = self.comment.buffer.len();
                    self.comment.comment_type = comment.comment_type.clone();
                    self.comment.is_review_level = false;
                    self.comment.is_file_level = true;
                    self.comment.line = None;
                    self.comment.editing_id = Some(comment.id.clone());
                    return true;
                }
            }
            Some(CommentLocation::Line {
                path,
                line,
                side,
                index,
            }) => {
                if let Some(review) = self.engine.session().files.get(&path)
                    && let Some(comments) = review.line_comments.get(&line)
                {
                    // Find the actual comment by counting comments with matching side
                    let mut side_idx = 0;
                    for comment in comments {
                        let comment_side = comment.side.unwrap_or(LineSide::New);
                        if comment_side == side {
                            if side_idx == index {
                                self.nav.input_mode = InputMode::Comment;
                                self.comment.buffer = comment.content.clone();
                                self.comment.cursor = self.comment.buffer.len();
                                self.comment.comment_type = comment.comment_type.clone();
                                self.comment.is_review_level = false;
                                self.comment.is_file_level = false;
                                self.comment.line = Some((line, side));
                                self.comment.editing_id = Some(comment.id.clone());
                                return true;
                            }
                            side_idx += 1;
                        }
                    }
                }
            }
            None => {}
        }

        false
    }

    pub fn enter_command_mode(&mut self) {
        // Remember where command mode was launched from so mode-gated
        // commands (e.g. `:tour`, valid only from the commit picker) can
        // check their origin — entering command mode overwrites `input_mode`.
        self.nav.command_origin = self.nav.input_mode;
        if self.ui_layout.command_palette {
            self.nav.input_mode = InputMode::CommandPalette;
        } else {
            self.nav.input_mode = InputMode::Command;
        }
        self.palette.clear();
    }

    pub fn exit_command_mode(&mut self) {
        // Return to wherever command mode was launched from so cancelling
        // the palette / command line doesn't drop the user out of a modal
        // mode (e.g. the CommitSelect picker, where leaving silently to
        // Normal would render an unrelated diff and the picker's selection
        // state would be invisible).
        let restore = match self.nav.command_origin {
            InputMode::CommitSelect => InputMode::CommitSelect,
            // Other modes that have their own enter/exit lifecycle
            // (Comment, Visual, ReviewSubmit, …) shouldn't be restored
            // here because they were never expected to be reached via
            // command mode. Default back to Normal.
            _ => InputMode::Normal,
        };
        self.nav.input_mode = restore;
        self.nav.command_origin = InputMode::Normal;
        self.palette.clear();
    }

    pub fn enter_search_mode(&mut self) {
        self.nav.input_mode = InputMode::Search;
        self.search_buffer.clear();
    }

    pub fn exit_search_mode(&mut self) {
        self.nav.input_mode = InputMode::Normal;
        self.search_buffer.clear();
    }

    pub fn enter_comment_mode(&mut self, file_level: bool, line: Option<(u32, LineSide)>) {
        self.nav.input_mode = InputMode::Comment;
        self.comment.buffer.clear();
        self.comment.cursor = 0;
        self.comment.comment_type = self.default_comment_type();
        self.comment.is_review_level = false;
        self.comment.is_file_level = file_level;
        self.comment.line = line;
    }

    pub fn enter_review_comment_mode(&mut self) {
        self.nav.input_mode = InputMode::Comment;
        self.comment.buffer.clear();
        self.comment.cursor = 0;
        self.comment.comment_type = self.default_comment_type();
        self.comment.is_review_level = true;
        self.comment.is_file_level = false;
        self.comment.line = None;
        self.comment.line_range = None;
        self.comment.editing_id = None;
    }

    pub fn exit_comment_mode(&mut self) {
        self.nav.input_mode = InputMode::Normal;
        self.comment.buffer.clear();
        self.comment.cursor = 0;
        self.comment.is_review_level = false;
        self.comment.editing_id = None;
        self.comment.line_range = None;
    }

    /// Enter visual selection mode, anchoring at the current cursor position
    pub fn enter_visual_mode(&mut self, line: u32, side: LineSide) {
        self.nav.input_mode = InputMode::VisualSelect;
        self.comment.visual_anchor = Some((line, side));
    }

    /// Exit visual selection mode and return to normal mode
    pub fn exit_visual_mode(&mut self) {
        self.nav.input_mode = InputMode::Normal;
        self.comment.visual_anchor = None;
    }

    /// Get the current visual selection range (if in visual mode)
    /// Returns None if not in visual mode or if there's no valid selection
    pub fn get_visual_selection(&self) -> Option<(LineRange, LineSide)> {
        if self.nav.input_mode != InputMode::VisualSelect {
            return None;
        }

        let (anchor_line, anchor_side) = self.comment.visual_anchor?;
        let (current_line, current_side) = self.get_line_at_cursor()?;

        // Don't allow selection across sides (old vs new)
        if anchor_side != current_side {
            return None;
        }

        let range = LineRange::new(anchor_line, current_line);
        Some((range, anchor_side))
    }

    /// Check if a given line is within the current visual selection
    pub fn is_line_in_visual_selection(&self, line: u32, side: LineSide) -> bool {
        if let Some((range, sel_side)) = self.get_visual_selection() {
            sel_side == side && range.contains(line)
        } else {
            false
        }
    }

    /// Enter comment mode from visual selection
    pub fn enter_comment_from_visual(&mut self) {
        if let Some((range, side)) = self.get_visual_selection() {
            self.comment.line_range = Some((range, side));
            self.comment.line = Some((range.end, side)); // Key by end line
            self.nav.input_mode = InputMode::Comment;
            self.comment.buffer.clear();
            self.comment.cursor = 0;
            self.comment.comment_type = self.default_comment_type();
            self.comment.is_review_level = false;
            self.comment.is_file_level = false;
            self.comment.visual_anchor = None;
        } else {
            self.set_warning("Invalid visual selection");
            self.exit_visual_mode();
        }
    }

    pub fn save_comment(&mut self) {
        if self.comment.buffer.trim().is_empty() {
            self.set_message("Comment cannot be empty");
            return;
        }

        let content = self.comment.buffer.trim().to_string();

        let mut message = "Error: Could not save comment".to_string();

        // Check if we're editing an existing comment
        if let Some(editing_id) = self.comment.editing_id.clone() {
            // Delegate to the engine, which walks every scope (review,
            // file, line, orphaned) and bumps `updated_at`. The pre-save
            // `is_*` / `line` fields were stamped by `enter_edit_mode`
            // from the comment's original location, so we can build the
            // success message without re-probing the session.
            if self.engine.edit_comment(
                &editing_id,
                content.clone(),
                self.comment.comment_type.clone(),
            ) {
                message = if self.comment.is_review_level {
                    "Review comment updated".to_string()
                } else if let Some((line, _)) = self.comment.line {
                    format!("Comment on line {line} updated")
                } else {
                    // File-level, or a line comment whose `line` field
                    // got cleared before save.
                    "Comment updated".to_string()
                };
            } else {
                message = "Error: Comment to edit not found".to_string();
            }
        } else if self.comment.is_review_level {
            let comment = Comment::new(content, self.comment.comment_type.clone(), None);
            self.engine.add_review_comment(comment);
            message = "Review comment added".to_string();
        } else if let Some(path) = self.current_file_path().cloned()
            && self.engine.session().files.contains_key(&path)
        {
            // Create new comment. Use strict engine helpers so an
            // unregistered file would drop the comment (preserving legacy
            // save_comment guarded-drop semantics) — the contains_key
            // check above already filtered those out, so these strict
            // calls always succeed here.
            if self.comment.is_file_level {
                let comment = Comment::new(content, self.comment.comment_type.clone(), None);
                self.engine.try_add_file_comment(&path, comment);
                message = "File comment added".to_string();
            } else if let Some((range, side)) = self.comment.line_range {
                // Range comment from visual selection
                let comment = Comment::new_with_range(
                    content,
                    self.comment.comment_type.clone(),
                    Some(side),
                    range,
                );
                // Store by end line of the range
                self.engine.try_add_line_comment(&path, range.end, comment);
                if range.is_single() {
                    message = format!("Comment added to line {}", range.end);
                } else {
                    message = format!("Comment added to lines {}-{}", range.start, range.end);
                }
            } else if let Some((line, side)) = self.comment.line {
                let comment = Comment::new(content, self.comment.comment_type.clone(), Some(side));
                self.engine.try_add_line_comment(&path, line, comment);
                message = format!("Comment added to line {line}");
            } else {
                // Fallback to file comment if no line specified
                let comment = Comment::new(content, self.comment.comment_type.clone(), None);
                self.engine.try_add_file_comment(&path, comment);
                message = "File comment added".to_string();
            }
        }

        let succeeded = !message.starts_with("Error:");
        if succeeded {
            self.dirty = true;
            // Emit an MCP server-push notification so a connected agent
            // learns about human-authored comments without polling. Skip
            // edits (we notify on add only), review-level comments (they
            // have no file anchor), and file-level fallbacks whose path
            // we can't resolve. Agent-authored MCP comments are recorded
            // through `handle_add_comment` in `mcp_bridge.rs` — that path
            // emits its own notification with `author: "agent"`.
            if self.comment.editing_id.is_none()
                && let Some(path) = self.current_file_path()
            {
                let file = path.to_string_lossy().to_string();
                let line = self
                    .comment
                    .line
                    .map(|(l, _)| l)
                    .or(self.comment.line_range.map(|(r, _)| r.end));
                self.push_notify(super::McpNotify::CommentAdded {
                    file,
                    line,
                    author: "human",
                });
            }
        }

        // Post to remote forge if in remote mode and this is a new line comment.
        if self.has_forge()
            && self.comment.editing_id.is_none()
            && !self.comment.is_file_level
            && !self.comment.is_review_level
            && let Some((line, side)) = self.comment.line
            && let Some(file) = self.diff_files.get(self.diff_state.current_file_idx)
        {
            let path = file.display_path_lossy().to_string_lossy().to_string();
            let body = self.comment.buffer.trim().to_string();
            // TODO(async): This blocks the event loop. Move to background task in Phase 9.
            // Status message won't render until after block_on returns (known limitation).
            match self.post_remote_comment(&path, line, side, &body) {
                Ok(Some(remote_id)) => {
                    // Link local comment to remote ID (#31)
                    if let Some(review) = self
                        .engine
                        .session_mut()
                        .get_file_mut(&PathBuf::from(&path))
                        && let Some(comments) = review.line_comments.get_mut(&line)
                        && let Some(last) = comments.last_mut()
                    {
                        last.remote_id = Some(remote_id);
                    }
                    message = format!("{message} (posted to remote)");
                }
                Ok(None) => {}
                Err(e) => {
                    message = format!("{message} (failed to post to remote: {e})");
                }
            }
        }

        self.set_message(message);
        self.rebuild_annotations();

        self.exit_comment_mode();
    }

    pub fn cycle_comment_type(&mut self) {
        if self.comment.types.is_empty() {
            return;
        }

        let current_id = self.comment.comment_type.id();
        let current_index = self
            .comment
            .types
            .iter()
            .position(|comment_type| comment_type.id == current_id)
            .unwrap_or(0);
        let next_index = (current_index + 1) % self.comment.types.len();
        self.comment.comment_type = CommentType::from_id(&self.comment.types[next_index].id);
    }

    pub fn cycle_comment_type_reverse(&mut self) {
        if self.comment.types.is_empty() {
            return;
        }

        let current_id = self.comment.comment_type.id();
        let current_index = self
            .comment
            .types
            .iter()
            .position(|comment_type| comment_type.id == current_id)
            .unwrap_or(0);
        let prev_index = if current_index == 0 {
            self.comment.types.len() - 1
        } else {
            current_index - 1
        };
        self.comment.comment_type = CommentType::from_id(&self.comment.types[prev_index].id);
    }

    pub fn toggle_help(&mut self) {
        if self.nav.input_mode == InputMode::Help {
            self.nav.input_mode = InputMode::Normal;
        } else {
            self.nav.input_mode = InputMode::Help;
            self.help_state.scroll_offset = 0;
        }
    }

    pub fn help_scroll_down(&mut self, lines: usize) {
        let max_offset = self
            .help_state
            .total_lines
            .saturating_sub(self.help_state.viewport_height);
        self.help_state.scroll_offset = (self.help_state.scroll_offset + lines).min(max_offset);
    }

    pub fn help_scroll_up(&mut self, lines: usize) {
        self.help_state.scroll_offset = self.help_state.scroll_offset.saturating_sub(lines);
    }

    pub fn help_scroll_to_top(&mut self) {
        self.help_state.scroll_offset = 0;
    }

    pub fn help_scroll_to_bottom(&mut self) {
        let max_offset = self
            .help_state
            .total_lines
            .saturating_sub(self.help_state.viewport_height);
        self.help_state.scroll_offset = max_offset;
    }

    pub fn enter_confirm_mode(&mut self, action: ConfirmAction) {
        self.nav.input_mode = InputMode::Confirm;
        self.pending_confirm = Some(action);
    }

    pub fn exit_confirm_mode(&mut self) {
        self.nav.input_mode = InputMode::Normal;
        self.pending_confirm = None;
    }

    /// Enter the reaction picker popup targeting the given thread id.
    ///
    /// The thread id is stored on `RemoteSessionState`; in local mode
    /// this call is a no-op because the reaction picker is only reachable
    /// from the Conversation panel (remote-only).
    pub fn enter_reaction_picker(&mut self, thread_id: String) {
        self.nav.input_mode = InputMode::ReactionPicker;
        self.reaction_picker_cursor = 0;
        if let Some(r) = self.remote_mut() {
            r.reaction_picker_target_thread = Some(thread_id);
        }
    }

    /// Open the reusable-template picker from comment mode. When no
    /// templates are configured, flashes a pointer to the config file
    /// via `set_warning` instead of opening an empty popup so the user
    /// gets actionable feedback on the first `Ctrl+T`.
    pub fn enter_comment_template_picker(&mut self) {
        if self.comment_templates.is_empty() {
            self.set_warning(
                "No comment templates configured — see ~/.config/travelagent/config.toml",
            );
            return;
        }
        self.nav.input_mode = InputMode::CommentTemplatePicker;
        self.ui_layout.reset_template_picker();
    }

    /// Close the template picker without inserting anything, returning
    /// to comment mode with the buffer untouched.
    pub fn exit_comment_template_picker(&mut self) {
        self.nav.input_mode = InputMode::Comment;
        self.ui_layout.reset_template_picker();
    }

    /// Insert the currently-selected template's body at the cursor
    /// position in the comment buffer, then return to comment mode.
    /// No-op when the filter eliminated every entry.
    pub fn select_comment_template(&mut self) {
        use crate::ui::comment_template_picker::filter_templates;
        let filtered = filter_templates(&self.comment_templates, self.ui_layout.template_filter());
        let Some(&entry_idx) = filtered.get(self.ui_layout.template_cursor()) else {
            // Nothing to insert; treat as cancel.
            self.exit_comment_template_picker();
            return;
        };
        let body = self.comment_templates[entry_idx].1.clone();
        // Defensive: cursor should always be a char boundary, but clamp
        // to the buffer length so a stale cursor doesn't panic on insert.
        let cursor = self.comment.cursor.min(self.comment.buffer.len());
        self.comment.buffer.insert_str(cursor, &body);
        self.comment.cursor = cursor + body.len();
        self.exit_comment_template_picker();
    }

    /// Close the reaction picker popup and return to Normal mode.
    pub fn exit_reaction_picker(&mut self) {
        self.nav.input_mode = InputMode::Normal;
        self.reaction_picker_cursor = 0;
        if let Some(r) = self.remote_mut() {
            r.reaction_picker_target_thread = None;
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::app::{App, InputMode};
    use crate::test_support::cwd_lock;
    use crate::theme::Theme;
    use tempfile::TempDir;

    fn build_test_app() -> (App, TempDir) {
        let _lock = cwd_lock();
        let dir = TempDir::new().unwrap();

        let repo = git2::Repository::init(dir.path()).unwrap();
        let sig = git2::Signature::now("test", "test@test.com").unwrap();
        let tree_id = repo.index().unwrap().write_tree().unwrap();
        let tree = repo.find_tree(tree_id).unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
            .unwrap();
        std::fs::write(dir.path().join("test.txt"), "hello\n").unwrap();

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(dir.path()).unwrap();

        let theme = Theme::dark();
        let app = App::new(
            theme,
            None,
            false,
            None,
            true,
            None,
            None,
            crate::test_support::runtime_handle(),
        )
        .unwrap();

        std::env::set_current_dir(original_dir).unwrap();
        (app, dir)
    }

    #[test]
    fn enter_reaction_picker_sets_mode_and_target() {
        // Reaction picker target lives on RemoteSessionState; this test
        // exercises the remote-mode path via `make_remote_app`. The local
        // build_test_app path is a no-op for the target field.
        let (mut app, _dir) = build_test_app();
        // Put cursor at a nonzero index to verify reset-to-zero semantics.
        app.reaction_picker_cursor = 5;

        app.enter_reaction_picker("thread-abc".to_string());

        assert_eq!(app.nav.input_mode, InputMode::ReactionPicker);
        // Local mode: no RemoteSessionState, so the target is not stored.
        // The mode flip and cursor reset still apply.
        assert!(app.remote().is_none());
        assert_eq!(app.reaction_picker_cursor, 0);
    }

    #[test]
    fn exit_reaction_picker_resets_mode() {
        let (mut app, _dir) = build_test_app();
        app.enter_reaction_picker("thread-xyz".to_string());
        app.reaction_picker_cursor = 3;

        app.exit_reaction_picker();

        assert_eq!(app.nav.input_mode, InputMode::Normal);
        // Local mode: no RemoteSessionState, so no target to clear.
        assert!(app.remote().is_none());
        assert_eq!(app.reaction_picker_cursor, 0);
    }

    // ── comment template picker (Phase F) ──

    #[test]
    fn open_picker_with_no_templates_shows_friendly_error_and_does_not_open_popup() {
        let (mut app, _dir) = build_test_app();
        // Pretend the user is in comment mode already.
        app.nav.input_mode = InputMode::Comment;
        assert!(app.comment_templates.is_empty());

        app.enter_comment_template_picker();

        // Popup must not open — mode stays Comment.
        assert_eq!(app.nav.input_mode, InputMode::Comment);
        // And the warning is surfaced through the normal status-bar channel.
        let msg = app.message.as_ref().expect("warning message should be set");
        assert!(
            msg.content.contains("No comment templates configured"),
            "expected friendly warning, got {:?}",
            msg.content
        );
        assert!(
            msg.content.contains("config.toml"),
            "warning should mention the config file path"
        );
    }

    #[test]
    fn open_picker_with_templates_shows_all_sorted_alphabetically() {
        let (mut app, _dir) = build_test_app();
        // Seed templates out of order; `set_comment_templates` must sort.
        let mut map = std::collections::HashMap::new();
        map.insert("style".to_string(), "Nit (style): ".to_string());
        map.insert("nit".to_string(), "nit: ".to_string());
        map.insert("q".to_string(), "Question: ".to_string());
        app.set_comment_templates(Some(map));

        // Order is deterministic and alphabetic.
        let names: Vec<&str> = app
            .comment_templates
            .iter()
            .map(|(n, _)| n.as_str())
            .collect();
        assert_eq!(names, vec!["nit", "q", "style"]);

        app.nav.input_mode = InputMode::Comment;
        app.enter_comment_template_picker();
        assert_eq!(app.nav.input_mode, InputMode::CommentTemplatePicker);
        assert_eq!(app.ui_layout.template_cursor(), 0);
        assert!(app.ui_layout.template_filter().is_empty());
    }

    #[test]
    fn selecting_template_inserts_text_at_cursor_position() {
        let (mut app, _dir) = build_test_app();
        let mut map = std::collections::HashMap::new();
        map.insert("nit".to_string(), "nit: ".to_string());
        map.insert("q".to_string(), "Question: ".to_string());
        app.set_comment_templates(Some(map));

        // Start with a partial comment buffer, cursor in the middle.
        app.comment.buffer = "hello world".to_string();
        app.comment.cursor = 5; // between "hello" and " world"
        app.nav.input_mode = InputMode::Comment;

        app.enter_comment_template_picker();
        assert_eq!(app.nav.input_mode, InputMode::CommentTemplatePicker);
        // Templates are sorted: [("nit", "nit: "), ("q", "Question: ")].
        // Cursor defaults to 0, so selecting inserts "nit: " at position 5.
        app.select_comment_template();

        assert_eq!(app.comment.buffer, "hellonit:  world");
        assert_eq!(app.comment.cursor, 5 + "nit: ".len());
        // Picker closes back to comment mode.
        assert_eq!(app.nav.input_mode, InputMode::Comment);
        // Filter/cursor reset.
        assert_eq!(app.ui_layout.template_cursor(), 0);
        assert!(app.ui_layout.template_filter().is_empty());
    }

    // ── save_comment ────────────────────────────────────────────────────
    //
    // `save_comment` is a 28-CC junction that branches on
    // editing/review-level/file-level/line-level/range-comment, plus
    // the remote-post tail. These tests lock the major branches.

    #[test]
    fn save_comment_review_level_pushes_and_emits_message() {
        // Happy path: review-level comment with non-empty trimmed content
        // is added to the engine and the success message is set.
        let (mut app, _dir) = build_test_app();
        app.enter_review_comment_mode();
        app.comment.buffer = "  important review note  ".to_string();
        app.comment.cursor = app.comment.buffer.len();

        app.save_comment();

        // Trimmed content stored on the engine session.
        let comments = &app.engine.session().review_comments;
        assert_eq!(comments.len(), 1);
        assert_eq!(comments[0].content, "important review note");
        // Status message matches the "added" branch (not edit / not error).
        let msg = app.message.as_ref().expect("status set");
        assert!(
            msg.content.contains("Review comment added"),
            "expected review-level success message, got: {}",
            msg.content
        );
        // Side-effects: dirty flag flipped, comment mode exited.
        assert!(app.dirty);
        assert_eq!(app.nav.input_mode, InputMode::Normal);
        // Buffer cleared by exit_comment_mode.
        assert!(app.comment.buffer.is_empty());
    }

    #[test]
    fn save_comment_with_empty_buffer_is_noop_with_message() {
        // Empty / whitespace-only buffer must short-circuit without
        // mutating the session, without setting `dirty`, and must
        // surface a "cannot be empty" status message.
        let (mut app, _dir) = build_test_app();
        app.enter_review_comment_mode();
        app.comment.buffer = "   \t  ".to_string();
        let dirty_before = app.dirty;
        let count_before = app.engine.session().review_comments.len();

        app.save_comment();

        assert_eq!(
            app.engine.session().review_comments.len(),
            count_before,
            "no comment may be appended for an empty buffer"
        );
        assert_eq!(app.dirty, dirty_before, "dirty flag must not flip");
        let msg = app.message.as_ref().expect("status set");
        assert!(
            msg.content.contains("Comment cannot be empty"),
            "expected empty-buffer warning, got: {}",
            msg.content
        );
        // `save_comment` short-circuits before exit_comment_mode for
        // empty buffers — buffer/state preserved so the user can edit.
        assert_eq!(app.nav.input_mode, InputMode::Comment);
    }

    #[test]
    fn save_comment_edit_path_updates_existing_review_comment() {
        // Edit branch: enter_edit_mode stamps `editing_id`; save_comment
        // routes through `engine.edit_comment` and uses the "updated"
        // message instead of "added".
        use travelagent_core::model::{Comment, CommentType};

        let (mut app, _dir) = build_test_app();
        // Seed an existing review comment, then route through edit.
        let existing = Comment::new("old content".into(), CommentType::Note, None);
        let edit_id = existing.id.clone();
        app.engine.session_mut().review_comments.push(existing);

        // Mimic `enter_edit_mode`'s state stamping for a review comment.
        app.nav.input_mode = InputMode::Comment;
        app.comment.is_review_level = true;
        app.comment.is_file_level = false;
        app.comment.line = None;
        app.comment.editing_id = Some(edit_id.clone());
        app.comment.buffer = "new content".to_string();
        app.comment.cursor = app.comment.buffer.len();

        app.save_comment();

        // Content updated in place; the comment id is preserved.
        let comments = &app.engine.session().review_comments;
        assert_eq!(comments.len(), 1, "edit must not append a new comment");
        assert_eq!(comments[0].id, edit_id);
        assert_eq!(comments[0].content, "new content");
        let msg = app.message.as_ref().expect("status set");
        assert!(
            msg.content.contains("Review comment updated"),
            "expected edit-path message, got: {}",
            msg.content
        );
        assert!(app.dirty);
        assert_eq!(app.nav.input_mode, InputMode::Normal);
    }

    #[test]
    fn exit_command_mode_returns_to_commit_select_when_launched_from_picker() {
        // Regression: opening the palette from the CommitSelect picker
        // and then cancelling used to drop the user to Normal, which
        // rendered an unrelated diff and made the picker's selection
        // state invisible. exit_command_mode now restores CommitSelect
        // when command_origin says we came from the picker.
        let (mut app, _dir) = build_test_app();
        app.nav.input_mode = InputMode::CommitSelect;

        app.enter_command_mode();
        assert_eq!(app.nav.command_origin, InputMode::CommitSelect);
        assert!(matches!(
            app.nav.input_mode,
            InputMode::Command | InputMode::CommandPalette
        ));

        app.exit_command_mode();
        assert_eq!(app.nav.input_mode, InputMode::CommitSelect);
        // command_origin resets so a future palette open gets a clean slate.
        assert_eq!(app.nav.command_origin, InputMode::Normal);
    }

    #[test]
    fn exit_command_mode_returns_to_normal_for_normal_origin() {
        // Default case: palette opened from Normal mode lands back in Normal.
        let (mut app, _dir) = build_test_app();
        app.nav.input_mode = InputMode::Normal;

        app.enter_command_mode();
        app.exit_command_mode();

        assert_eq!(app.nav.input_mode, InputMode::Normal);
        assert_eq!(app.nav.command_origin, InputMode::Normal);
    }
}