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
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
use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout, Rect},
    style::Style,
    text::{Line, Span},
    widgets::Block,
};
use unicode_width::UnicodeWidthStr;

use crate::app::{App, DiffSource, DiffViewMode, ExpandDirection, GAP_EXPAND_BATCH, InputMode};
use crate::theme::Theme;
use crate::ui::{ai_summary_panel, comment_panel, help_popup, status_bar, styles};

/// Expand `\t` characters in `s` to spaces using vim-style tabstop alignment:
/// each tab advances to the next column that is a multiple of `tab_width`.
/// When the input contains no tabs or `tab_width` is 0, the original string is
/// returned unchanged (cheap fast-path for the common case).
pub(crate) fn expand_tabs(s: &str, tab_width: usize) -> String {
    if !s.contains('\t') || tab_width == 0 {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len());
    let mut col: usize = 0;
    for ch in s.chars() {
        if ch == '\t' {
            let spaces = tab_width - (col % tab_width);
            for _ in 0..spaces {
                out.push(' ');
            }
            col += spaces;
        } else {
            out.push(ch);
            col += unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
        }
    }
    out
}

pub fn render(frame: &mut Frame, app: &mut App) {
    frame.render_widget(
        Block::default().style(styles::panel_style(&app.theme)),
        frame.area(),
    );

    // Special handling for commit selection mode
    if app.nav.input_mode == InputMode::CommitSelect {
        crate::ui::remote_panels::render_commit_select(frame, app);
        return;
    }

    // Clear cursor position before rendering (will be set if in Comment mode)
    app.comment.cursor_screen_pos = None;

    // Tour Guide banner: 1 extra row above the main content, visible only
    // while a tour is active. Gives room for the full agent-authored
    // summary + stop index + date range without truncating to the status
    // bar's ~40-char budget.
    let tour_active = app.tour.plan.is_some();
    let constraints = if tour_active {
        vec![
            Constraint::Length(1), // Header
            Constraint::Length(1), // Tour banner
            Constraint::Min(0),    // Main content
            Constraint::Length(1), // Status bar
        ]
    } else {
        vec![
            Constraint::Length(1), // Header
            Constraint::Min(0),    // Main content
            Constraint::Length(1), // Status bar
        ]
    };
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(frame.area());

    status_bar::render_header(frame, app, chunks[0]);
    let (banner_idx, main_idx, status_idx) = if tour_active {
        (Some(1usize), 2usize, 3usize)
    } else {
        (None, 1usize, 2usize)
    };
    if let Some(i) = banner_idx {
        render_tour_banner(frame, app, chunks[i]);
    }
    render_main_content(frame, app, chunks[main_idx]);
    status_bar::render_status_bar(frame, app, chunks[status_idx]);

    // Render help popup on top if in help mode
    if app.nav.input_mode == InputMode::Help {
        help_popup::render_help(frame, app);
    }

    // Render AI summary popup when toggled on. Drawn after help so it wins if
    // both somehow became active simultaneously — in practice Ctrl+A is not
    // bound in Help mode.
    if app.ai.show_panel {
        ai_summary_panel::render(frame, frame.area(), app);
    }

    // Reaction picker popup. Drawn on top of everything else so the human can
    // always see the 8 emoji while the picker is open.
    if app.nav.input_mode == InputMode::ReactionPicker {
        let app_ref: &App = app;
        crate::ui::reaction_picker::render(frame, frame.area(), app_ref, &app_ref.theme);
    }

    // Mental-model modal (Phase I2). Drawn above everything so the
    // reviewer sees the four prompts while the diff stays clear in
    // the background.
    if app.nav.input_mode == InputMode::MentalModelEdit {
        let app_ref: &App = app;
        crate::ui::mental_model_modal::render(frame, frame.area(), app_ref, &app_ref.theme);
    }

    // Comment input is now rendered inline in the diff view

    // Render confirm dialog if in confirm mode
    if app.nav.input_mode == InputMode::Confirm {
        let message = match app.pending_confirm {
            Some(crate::app::ConfirmAction::Merge) => {
                if let Some(r) = app.remote()
                    && let Some(ref meta) = r.pr_metadata
                {
                    format!("Merge PR #{}: {}? (Y/N)", r.pr_id.number, meta.title)
                } else {
                    "Merge this PR? (Y/N)".to_string()
                }
            }
            Some(crate::app::ConfirmAction::RestartReview) => {
                format!(
                    "Restart review? This marks all {} reviewed file(s) unreviewed. (Y/N)",
                    app.reviewed_file_count()
                )
            }
            _ => "Copy review to clipboard?".to_string(),
        };
        comment_panel::render_confirm_dialog(frame, app, &message);
    }

    // Render review submit dialog
    if app.nav.input_mode == InputMode::ReviewSubmit {
        comment_panel::render_review_submit_dialog(frame, app);
    }

    // Render the agent-forge-write confirmation modal (Phase E final) on
    // top of everything else so the human always sees the pending
    // proposal. Intentionally *not* an InputMode switch — the modal
    // captures `y`/`n`/`Esc` globally in the main event loop so other
    // work (scrolling, reading) stays inspectable while deciding.
    if app.agent_action.has_waiting_pending() {
        comment_panel::render_forge_confirmation_modal(frame, app);
    }

    // Render command palette
    if app.nav.input_mode == InputMode::CommandPalette {
        crate::ui::command_palette::render_command_palette(frame, app);
    }

    // Render comment template picker (Ctrl+T from comment mode)
    if app.nav.input_mode == InputMode::CommentTemplatePicker {
        crate::ui::comment_template_picker::render_comment_template_picker(frame, app);
    }

    // Position terminal cursor for IME when in Comment mode
    // Always set a cursor position to prevent IME from showing at (0,0)
    if app.nav.input_mode == InputMode::Comment {
        let main_area = chunks[main_idx];
        let (col, row) = app.comment.cursor_screen_pos.unwrap_or_else(|| {
            // Fallback: position cursor in the diff area or at a reasonable default
            // Use the diff area if available, otherwise use the main content area
            if let Some(diff_area) = app.ui_layout.diff_area {
                // Position at the start of the diff inner area (after border)
                (diff_area.x + 1, diff_area.y + 1)
            } else {
                // Last resort: position at the main content area
                (main_area.x + 1, main_area.y + 1)
            }
        });
        frame.set_cursor_position(ratatui::layout::Position { x: col, y: row });
    }
}

/// Render a one-row tour banner above the main content. Shows stop
/// index/count, date range (queried + cached from VCS), commit count,
/// risk-vs-threshold, and the full agent-authored summary — truncated
/// only if it would overflow the terminal width.
fn render_tour_banner(frame: &mut Frame, app: &mut App, area: Rect) {
    let Some(tour) = app.tour.plan.as_ref() else {
        return;
    };
    let Some(stop) = tour.current() else {
        return;
    };
    let total = tour.stops.len();
    let idx = tour.index + 1;
    let commit_count = stop.commit_ids.len();
    let risk = stop.risk.as_u8();
    let threshold = tour.threshold.as_u8();
    let summary = stop.summary.trim().to_string();

    // Date range may be expensive (VCS call), but it's cached on
    // `TourSessionState.date_range_cache` keyed by (first, last) sha so
    // repeated renders at the same stop are ~free.
    let date_range = app.tour_date_range();

    let theme = &app.theme;
    let label_style = Style::default()
        .fg(theme.message_info_fg)
        .bg(theme.message_info_bg)
        .add_modifier(ratatui::style::Modifier::BOLD);
    let body_style = Style::default()
        .fg(theme.message_info_fg)
        .bg(theme.message_info_bg);

    // Compose the banner. `Tour N/M · <date range> · <N commits> · risk=R/T · <summary>`.
    // The summary gets whatever width is left; everything left of it is
    // fixed-size so users always see the orientation info.
    let mut spans: Vec<Span> = vec![
        Span::styled(format!(" Tour {idx}/{total} "), label_style),
        Span::styled("·", body_style),
    ];
    if let Some(dr) = date_range {
        spans.push(Span::styled(format!(" {dr} "), body_style));
        spans.push(Span::styled("·", body_style));
    }
    let commits_str = if commit_count == 1 {
        " 1 commit ".to_string()
    } else {
        format!(" {commit_count} commits ")
    };
    spans.push(Span::styled(commits_str, body_style));
    spans.push(Span::styled("·", body_style));
    spans.push(Span::styled(
        format!(" risk={risk}/{threshold} "),
        body_style,
    ));
    spans.push(Span::styled("·", body_style));
    spans.push(Span::styled(" ", body_style));

    // Compute remaining width for the summary and truncate if needed.
    let prefix_width: usize = spans
        .iter()
        .map(|s| UnicodeWidthStr::width(s.content.as_ref()))
        .sum();
    let total_width = area.width as usize;
    let summary_budget = total_width.saturating_sub(prefix_width).saturating_sub(1);
    let summary_text =
        if UnicodeWidthStr::width(summary.as_str()) > summary_budget && summary_budget > 3 {
            let mut truncated = String::new();
            let mut used = 0usize;
            for ch in summary.chars() {
                let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
                if used + w > summary_budget.saturating_sub(1) {
                    break;
                }
                truncated.push(ch);
                used += w;
            }
            truncated.push('');
            truncated
        } else {
            summary
        };
    spans.push(Span::styled(summary_text, body_style));

    // Background fill for the rest of the row so the banner reads as a
    // solid strip even when the summary is short.
    let line = Line::from(spans);
    frame.render_widget(
        ratatui::widgets::Paragraph::new(line).style(body_style),
        area,
    );
}

fn render_main_content(frame: &mut Frame, app: &mut App, area: Rect) {
    let content_area = if app.has_inline_commit_selector() {
        let selector_height = (app.inline_selector.commits.len() as u16 + 2).min(8); // N items + 2 borders, capped
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(selector_height), Constraint::Min(0)])
            .split(area);
        crate::ui::remote_panels::render_inline_commit_selector(frame, app, chunks[0]);
        chunks[1]
    } else {
        area
    };

    let is_remote = matches!(app.diff_source, DiffSource::Remote { .. });

    if app.ui_layout.show_file_list {
        let file_pct = app.ui_layout.file_list_width_pct();
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(file_pct),
                Constraint::Percentage(100 - file_pct),
            ])
            .split(content_area);

        app.ui_layout.file_list_area = Some(chunks[0]);
        crate::ui::file_list::render_file_list(frame, app, chunks[0]);

        if is_remote {
            crate::ui::remote_panels::render_remote_right_panel(frame, app, chunks[1]);
        } else {
            app.ui_layout.diff_area = Some(chunks[1]);
            render_diff_view(frame, app, chunks[1]);
        }
    } else {
        app.ui_layout.file_list_area = None;

        if is_remote {
            crate::ui::remote_panels::render_remote_right_panel(frame, app, content_area);
        } else {
            app.ui_layout.diff_area = Some(content_area);
            render_diff_view(frame, app, content_area);
        }
    }
}

pub(crate) fn render_diff_view(frame: &mut Frame, app: &mut App, area: Rect) {
    // Viewer pane (`:view` / `t`) takes over the content area when active. We
    // refresh its content cache here; if the current file can't be shown
    // (binary, deleted, remote, IO error) we drop back to the diff and surface
    // the reason — so the toggle never leaves a blank/stuck pane.
    if app.viewer.is_active() {
        match app.refresh_viewer_content() {
            Ok(()) => {
                crate::ui::viewer_pane::render_viewer_pane(frame, app, area);
                return;
            }
            Err(msg) => {
                app.viewer.deactivate();
                app.set_warning(msg);
                // Fall through to the diff renderer below.
            }
        }
    }

    match app.nav.diff_view_mode {
        DiffViewMode::Unified => {
            crate::ui::diff_unified::render_unified_diff(frame, app, area);
        }
        DiffViewMode::SideBySide => {
            crate::ui::diff_side_by_side::render_side_by_side_diff(frame, app, area);
        }
    }
}

/// Build a right-aligned title showing diff stats for the current scope.
/// In overview: total stats across all files. In a file: that file's stats.
pub(crate) fn diff_stat_title(app: &App) -> Line<'static> {
    let (additions, deletions) = if app.is_cursor_in_overview() || app.current_file_path().is_none()
    {
        let (_, a, d) = app.diff_stat();
        (a, d)
    } else {
        app.diff_files[app.diff_state.current_file_idx].stat()
    };

    let theme = &app.theme;
    Line::from(vec![
        Span::styled(
            format!(" +{additions}"),
            Style::default().fg(theme.diff_add),
        ),
        Span::raw(" "),
        Span::styled(
            format!("-{deletions} "),
            Style::default().fg(theme.diff_del),
        ),
    ])
}

/// Get cursor indicator (single character for inline content)
pub(crate) fn cursor_indicator(line_idx: usize, current_line_idx: usize) -> &'static str {
    if line_idx == current_line_idx {
        ""
    } else {
        " "
    }
}

/// Get cursor indicator with spacing (two characters for line prefixes)
pub(crate) fn cursor_indicator_spaced(line_idx: usize, current_line_idx: usize) -> &'static str {
    if line_idx == current_line_idx {
        ""
    } else {
        "  "
    }
}

/// Render a single expanded context line (shared by unified + side-by-side via unified path)
pub(crate) fn render_expanded_context_line(
    lines: &mut Vec<Line<'_>>,
    line_idx: &mut usize,
    current_line_idx: usize,
    expanded_line: &travelagent_core::model::DiffLine,
    theme: &Theme,
) {
    let indicator = cursor_indicator(*line_idx, current_line_idx);
    let line_num = expanded_line
        .new_lineno
        .map_or_else(|| "     ".to_string(), |n| format!("{n:>4} "));
    let line_spans = vec![
        Span::styled(indicator, styles::current_line_indicator_style(theme)),
        Span::styled(line_num, styles::gutter_expanded_style(theme)),
        Span::styled("  ", styles::expanded_context_style(theme)),
        Span::styled(
            expanded_line.content.clone(),
            styles::expanded_context_style(theme),
        ),
    ];
    lines.push(Line::from(line_spans));
    *line_idx += 1;
}

/// Render an expander line with direction arrow
pub(crate) fn render_expander_line(
    lines: &mut Vec<Line<'_>>,
    line_idx: &mut usize,
    current_line_idx: usize,
    direction: ExpandDirection,
    remaining: usize,
    theme: &Theme,
) {
    let arrow = match direction {
        ExpandDirection::Down => "",
        ExpandDirection::Up => "",
        ExpandDirection::Both => "",
    };
    let count = remaining.min(GAP_EXPAND_BATCH);
    let indicator = cursor_indicator_spaced(*line_idx, current_line_idx);
    lines.push(Line::from(vec![
        Span::styled(indicator, styles::current_line_indicator_style(theme)),
        Span::styled(
            format!("       ... {arrow} expand ({count} lines) ..."),
            styles::dim_style(theme),
        ),
    ]));
    *line_idx += 1;
}

/// Render a single expanded context line in side-by-side mode
pub(crate) fn render_hidden_lines(
    lines: &mut Vec<Line<'_>>,
    line_idx: &mut usize,
    current_line_idx: usize,
    count: usize,
    theme: &Theme,
) {
    let indicator = cursor_indicator_spaced(*line_idx, current_line_idx);
    lines.push(Line::from(vec![
        Span::styled(indicator, styles::current_line_indicator_style(theme)),
        Span::styled(
            format!("       ... {count} lines hidden ..."),
            styles::dim_style(theme),
        ),
    ]));
    *line_idx += 1;
}

/// Render a single placeholder line used in place of a collapsed file's diff
/// body. Format matches GitHub's collapsed-file teaser:
///
///   "File collapsed — {N} lines, {reason}. Press `z` to expand."
///
/// `reason` is `"lockfile-like"` when the path matched an auto-collapse glob,
/// `"over threshold"` when the line count put it over `line_threshold`, and
/// `"manual"` when the auto rule wouldn't fire but the user explicitly
/// collapsed via `z`.
pub(crate) fn render_collapsed_placeholder(
    lines: &mut Vec<Line<'_>>,
    line_idx: &mut usize,
    current_line_idx: usize,
    app: &App,
    file: &travelagent_core::model::DiffFile,
) {
    let (additions, deletions) = file.stat();
    let changed = additions + deletions;
    let file_idx = app
        .diff_files
        .iter()
        .position(|f| std::ptr::eq(f, file))
        .unwrap_or(0);
    let reason_label = match app.auto_collapse_reason_for(file_idx) {
        Some(reason) => reason.label(),
        None => "manual",
    };
    let indicator = cursor_indicator_spaced(*line_idx, current_line_idx);
    lines.push(Line::from(vec![
        Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
        Span::styled(
            format!(
                "    File collapsed \u{2014} {changed} lines, {reason_label}. Press `z` to expand."
            ),
            styles::dim_style(&app.theme),
        ),
    ]));
    *line_idx += 1;
}

pub(crate) fn comment_type_presentation(
    app: &App,
    comment_type: &travelagent_core::model::CommentType,
) -> comment_panel::CommentTypePresentation {
    comment_panel::CommentTypePresentation {
        label: app.comment_type_label(comment_type),
        color: app.comment_type_color(comment_type),
    }
}

/// L3: render the orphaned-comments section for one review bucket.
///
/// `header_label` is e.g. `"── Orphaned comments (3) ──"` for a per-file
/// section, or `"── Orphaned comments (removed files) (5) ──"` for the
/// session-level bucket rendered above the file list.
///
/// Mirrors the visual shape of [`render_collapsed_placeholder`] — one
/// section header, one comment box per orphan (with a "was line N" line
/// above the box), and a trailing spacing line. The row count here must
/// stay in lock-step with [`App::file_orphans_render_height`] and
/// [`App::session_orphans_render_height`] in `app/layout.rs`, otherwise
/// the cursor math used by `calculate_file_scroll_offset` drifts.
///
/// TODO(live-mode): collapse after N > 10 — see `docs/design/live-review-mode.md`
/// "Risks + open questions".
pub(crate) fn render_orphans_section(
    lines: &mut Vec<Line<'_>>,
    line_idx: &mut usize,
    current_line_idx: usize,
    app: &App,
    header_label: String,
    orphans: &[travelagent_core::model::Comment],
) {
    use travelagent_core::model::AnchorState;
    let theme = &app.theme;

    let indicator = cursor_indicator_spaced(*line_idx, current_line_idx);
    lines.push(Line::from(vec![
        Span::styled(indicator, styles::current_line_indicator_style(theme)),
        Span::styled(header_label, styles::dim_style(theme)),
    ]));
    *line_idx += 1;

    for comment in orphans {
        // Per-orphan "was line N: <snippet>" line, mimicking the design
        // doc's `[ORPHANED was line N] "..."` shape.
        let (was_line, last_seen) = match comment.anchor.as_ref() {
            Some(AnchorState::Orphaned {
                was_line,
                last_seen_content,
                ..
            }) => (*was_line, last_seen_content.clone()),
            _ => (0, String::new()),
        };
        // Truncate long content for the preview; full content shows in the
        // body below.
        let preview: String = last_seen.chars().take(60).collect();
        let hdr_indicator = cursor_indicator(*line_idx, current_line_idx);
        lines.push(Line::from(vec![
            Span::styled(hdr_indicator, styles::current_line_indicator_style(theme)),
            Span::styled(
                format!("  [ORPHANED was line {was_line}] "),
                styles::dim_style(theme),
            ),
            Span::styled(format!("\"{preview}\""), styles::dim_style(theme)),
        ]));
        *line_idx += 1;

        let comment_lines = comment_panel::format_comment_lines(
            theme,
            comment_type_presentation(app, &comment.comment_type),
            &comment.content,
            None,
        );
        for mut cl in comment_lines {
            let ind = cursor_indicator(*line_idx, current_line_idx);
            cl.spans.insert(
                0,
                Span::styled(ind, styles::current_line_indicator_style(theme)),
            );
            lines.push(cl);
            *line_idx += 1;
        }
    }

    // Trailing spacing line.
    let ind = cursor_indicator(*line_idx, current_line_idx);
    lines.push(Line::from(Span::styled(
        ind,
        styles::current_line_indicator_style(theme),
    )));
    *line_idx += 1;
}

/// L3: render the session-level "removed files" orphan section above the
/// per-file diffs. `app` is borrowed immutably here; we collect the
/// orphans into owned `Comment`s to satisfy the borrow checker (the
/// renderer walks both `app.engine.session().files` and
/// `comment_panel::format_comment_lines` which takes `&Theme`, so holding
/// a borrow on `session` while calling back into `app` methods would
/// overlap).
pub(crate) fn render_session_orphans(
    lines: &mut Vec<Line<'_>>,
    line_idx: &mut usize,
    current_line_idx: usize,
    app: &App,
) {
    use std::collections::HashSet;
    let diff_paths: HashSet<_> = app
        .diff_files
        .iter()
        .map(|f| f.display_path_lossy().clone())
        .collect();
    let mut gone: Vec<_> = app
        .engine
        .session()
        .files
        .iter()
        .filter(|(p, _)| !diff_paths.contains(*p))
        .filter(|(_, r)| !r.orphaned_comments.is_empty())
        .collect();
    gone.sort_by(|a, b| a.0.cmp(b.0));
    let total: usize = gone.iter().map(|(_, r)| r.orphaned_comments.len()).sum();
    if total == 0 {
        return;
    }
    let mut flat: Vec<travelagent_core::model::Comment> = Vec::with_capacity(total);
    for (_, r) in &gone {
        for c in &r.orphaned_comments {
            flat.push(c.clone());
        }
    }
    let label = format!("── Orphaned comments (removed files) ({total}) ──");
    render_orphans_section(lines, line_idx, current_line_idx, app, label, &flat);
}

/// Adjust scroll_offset so the comment input box is visible in the viewport.
///
/// The input box is rendered inline in the diff view, so without this
/// adjustment it can end up below (or above) the visible area when a
/// comment is started near the viewport edge or when typing a multi-line
/// comment grows the box past the bottom. If the box is taller than the
/// viewport we fall back to keeping just the text cursor line visible.
pub(crate) fn scroll_comment_input_into_view(
    scroll_offset: &mut usize,
    box_range: Option<(usize, usize)>,
    cursor_line: Option<usize>,
    viewport_height: usize,
    total_lines: usize,
) {
    let Some((box_start, box_end)) = box_range else {
        return;
    };
    if viewport_height == 0 {
        return;
    }

    let box_height = box_end.saturating_sub(box_start) + 1;

    if box_height <= viewport_height {
        if box_start < *scroll_offset {
            *scroll_offset = box_start;
        } else if box_end >= *scroll_offset + viewport_height {
            *scroll_offset = box_end + 1 - viewport_height;
        }
    } else if let Some(cursor) = cursor_line {
        // Box too tall for viewport: keep the text cursor line visible.
        if cursor < *scroll_offset {
            *scroll_offset = cursor;
        } else if cursor >= *scroll_offset + viewport_height {
            *scroll_offset = cursor + 1 - viewport_height;
        }
    }

    // Clamp so we never scroll past the last line.
    let max_scroll = total_lines.saturating_sub(viewport_height);
    if *scroll_offset > max_scroll {
        *scroll_offset = max_scroll;
    }
}

/// Truncate or pad a string to a specific width
pub(crate) fn truncate_or_pad(s: &str, width: usize) -> String {
    let char_count = s.chars().count();
    if char_count > width {
        s.chars().take(width.saturating_sub(3)).collect::<String>() + "..."
    } else {
        format!("{s:width$}")
    }
}

/// Truncate or pad highlighted spans to a specific display width
/// Uses unicode width to properly handle wide characters (CJK, emoji, etc.)
/// Returns a vector of spans that fits exactly within the width
pub(crate) fn truncate_or_pad_spans(
    spans: &[(travelagent_core::style::StyleHint, String)],
    width: usize,
    base_style: Style,
) -> Vec<Span<'static>> {
    // Count total display width
    let total_width: usize = spans.iter().map(|(_, text)| text.width()).sum();

    if total_width > width {
        // Need to truncate
        let mut result = Vec::new();
        let mut remaining = width.saturating_sub(3); // Reserve space for "..."

        for (hint, text) in spans {
            if remaining == 0 {
                break;
            }
            let style = styles::style_hint_to_ratatui(*hint);

            let text_width = text.width();
            if text_width <= remaining {
                result.push(Span::styled(text.clone(), style));
                remaining -= text_width;
            } else {
                // Truncate this span character by character to fit remaining width
                let mut truncated = String::new();
                let mut current_width = 0;
                for c in text.chars() {
                    let char_width = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
                    if current_width + char_width > remaining {
                        break;
                    }
                    truncated.push(c);
                    current_width += char_width;
                }
                if !truncated.is_empty() {
                    result.push(Span::styled(truncated, style));
                }
                remaining = 0;
            }
        }

        // Add ellipsis
        result.push(Span::styled("...".to_string(), base_style));
        result
    } else if total_width < width {
        // Need to pad
        let mut result: Vec<Span> = spans
            .iter()
            .map(|(hint, text)| Span::styled(text.clone(), styles::style_hint_to_ratatui(*hint)))
            .collect();

        // Add padding
        let padding = " ".repeat(width - total_width);
        result.push(Span::styled(padding, base_style));
        result
    } else {
        // Perfect fit
        spans
            .iter()
            .map(|(hint, text)| Span::styled(text.clone(), styles::style_hint_to_ratatui(*hint)))
            .collect()
    }
}

/// Per-row add/del metadata for side-by-side diff background painting.
///
/// Apply horizontal scroll to a line while preserving the first span (cursor indicator)
pub(crate) fn apply_horizontal_scroll(line: Line, scroll_x: usize) -> Line {
    if scroll_x == 0 || line.spans.is_empty() {
        return line;
    }

    let mut spans: Vec<Span> = line.spans.into_iter().collect();

    // Preserve the first span (indicator)
    let indicator = spans.remove(0);

    // Skip scroll_x characters from the remaining spans
    let mut chars_to_skip = scroll_x;
    let mut new_spans = vec![indicator];

    for span in spans {
        let content = span.content.to_string();
        let char_count = content.chars().count();
        if chars_to_skip >= char_count {
            chars_to_skip -= char_count;
            // Skip this span entirely
        } else if chars_to_skip > 0 {
            // Partially skip this span
            let new_content: String = content.chars().skip(chars_to_skip).collect();
            chars_to_skip = 0;
            new_spans.push(Span::styled(new_content, span.style));
        } else {
            // Keep this span as-is
            new_spans.push(Span::styled(content, span.style));
        }
    }

    Line::from(new_spans)
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn should_not_scroll_when_comment_box_already_visible() {
        // given: box at lines 5-7, viewport shows lines 0-9
        let mut scroll = 0;
        // when
        scroll_comment_input_into_view(&mut scroll, Some((5, 7)), Some(6), 10, 100);
        // then
        assert_eq!(scroll, 0);
    }

    #[test]
    fn should_scroll_down_when_comment_box_below_viewport() {
        // given: box at lines 20-22, viewport shows lines 0-9
        let mut scroll = 0;
        // when
        scroll_comment_input_into_view(&mut scroll, Some((20, 22)), Some(21), 10, 100);
        // then: scroll so box_end (22) is the last visible line => scroll = 22 - 10 + 1 = 13
        assert_eq!(scroll, 13);
    }

    #[test]
    fn should_scroll_up_when_comment_box_above_viewport() {
        // given: box at lines 5-7, viewport shows lines 20-29
        let mut scroll = 20;
        // when
        scroll_comment_input_into_view(&mut scroll, Some((5, 7)), Some(6), 10, 100);
        // then: scroll so box_start (5) is the first visible line
        assert_eq!(scroll, 5);
    }

    #[test]
    fn should_scroll_to_cursor_when_box_taller_than_viewport() {
        // given: box spans 20 lines, viewport only 10 lines
        let mut scroll = 0;
        // when
        scroll_comment_input_into_view(&mut scroll, Some((30, 49)), Some(45), 10, 100);
        // then: scroll so cursor (45) is the last visible line => scroll = 45 - 10 + 1 = 36
        assert_eq!(scroll, 36);
    }

    #[test]
    fn should_not_scroll_past_end_of_content() {
        // given: scroll already past max (e.g., content shrank)
        let mut scroll = 200;
        // when
        scroll_comment_input_into_view(&mut scroll, Some((95, 97)), Some(96), 10, 100);
        // then: clamped to max_scroll = 100 - 10 = 90
        assert_eq!(scroll, 90);
    }

    #[test]
    fn should_not_scroll_when_no_comment_box() {
        // given
        let mut scroll = 42;
        // when
        scroll_comment_input_into_view(&mut scroll, None, None, 10, 100);
        // then
        assert_eq!(scroll, 42);
    }

    #[test]
    fn should_handle_box_partially_below_viewport() {
        // given: viewport shows 0-9, box starts at 8 and ends at 10 (footer off-screen)
        let mut scroll = 0;
        // when
        scroll_comment_input_into_view(&mut scroll, Some((8, 10)), Some(9), 10, 100);
        // then: scroll so box_end (10) is visible => scroll = 10 - 10 + 1 = 1
        assert_eq!(scroll, 1);
    }

    #[test]
    fn expand_tabs_leaves_plain_text_unchanged() {
        assert_eq!(expand_tabs("hello world", 4), "hello world");
        assert_eq!(expand_tabs("", 4), "");
    }

    #[test]
    fn expand_tabs_leading_tab_becomes_tab_width_spaces() {
        assert_eq!(expand_tabs("\tfoo", 4), "    foo");
        assert_eq!(expand_tabs("\tfoo", 8), "        foo");
    }

    #[test]
    fn expand_tabs_mid_string_tab_aligns_to_next_column() {
        // "ab\tc" with tab_width=4: col=2 after "ab"; tab fills 2 spaces to
        // land on col 4.
        assert_eq!(expand_tabs("ab\tc", 4), "ab  c");
        // With tab_width=8 the same string fills 6 spaces.
        assert_eq!(expand_tabs("ab\tc", 8), "ab      c");
    }

    #[test]
    fn expand_tabs_multiple_tabs_on_one_line() {
        // "\t\tx" with tab_width=4: first tab -> 4 spaces (col 4), second
        // tab -> 4 more spaces (col 8), then x.
        assert_eq!(expand_tabs("\t\tx", 4), "        x");
        // Mixed: "a\tb\tc" with tab_width=2: col0 a, col1 tab->1sp (col2),
        // b (col3), tab->1sp (col4), c.
        assert_eq!(expand_tabs("a\tb\tc", 2), "a b c");
    }

    #[test]
    fn expand_tabs_zero_width_returns_input_unchanged() {
        // Zero tab width is the documented "disabled" case.
        assert_eq!(expand_tabs("a\tb", 0), "a\tb");
    }

    #[test]
    fn truncate_or_pad_spans_respects_unicode_display_width() {
        // Regression (Phase A): wide characters (CJK, emoji) are 2 display
        // columns each; truncate/pad math must count columns, not chars
        // or bytes, or SBS columns misalign. Caps the input to the exact
        // column budget to lock the contract in.
        use travelagent_core::style::StyleHint;
        let hint = StyleHint::default();

        // CJK (2-col each): "日本語" = 6 display cols, "テスト" = 6.
        let spans = vec![(hint, "日本語テスト".to_string())];
        let out = truncate_or_pad_spans(&spans, 12, ratatui::style::Style::default());
        let total_cols: usize = out
            .iter()
            .map(|s| UnicodeWidthStr::width(s.content.as_ref()))
            .sum();
        assert_eq!(total_cols, 12, "CJK-exact-fit must preserve both tokens");

        // Emoji are also 2-col each under Unicode wcwidth. A 4-emoji string
        // (8 cols) truncated to 6 cols yields "...", taking 3 cols, plus
        // at most 3 cols of content — total ≤ 6.
        let emojis = "🙂🙃🚀🎯";
        let spans = vec![(hint, emojis.to_string())];
        let out = truncate_or_pad_spans(&spans, 6, ratatui::style::Style::default());
        let total_cols: usize = out
            .iter()
            .map(|s| UnicodeWidthStr::width(s.content.as_ref()))
            .sum();
        assert!(total_cols <= 6, "truncate must not exceed column budget");
        let joined: String = out.iter().map(|s| s.content.as_ref()).collect();
        assert!(
            joined.ends_with("..."),
            "truncated output must end with ellipsis, got {joined:?}"
        );

        // 80-column viewport with mixed ASCII + CJK: assert the pad branch
        // adds the right number of space columns (not chars).
        let mixed = "hello 日本";
        let spans = vec![(hint, mixed.to_string())];
        let mixed_cols = UnicodeWidthStr::width(mixed); // 6 + 4 = 10 cols
        let out = truncate_or_pad_spans(&spans, 80, ratatui::style::Style::default());
        let total_cols: usize = out
            .iter()
            .map(|s| UnicodeWidthStr::width(s.content.as_ref()))
            .sum();
        assert_eq!(
            total_cols, 80,
            "pad must land on exact column width (input was {mixed_cols} cols)"
        );
    }
}