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
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
//! Lightweight markdown renderer for PR descriptions and comment bodies.
//!
//! Parses input with `pulldown-cmark` and maps events onto `ratatui::text::Line`
//! values that reuse the active [`Theme`] palette. This renderer is intentionally
//! conservative: it covers the subset of CommonMark that forge bodies typically
//! use (headers, emphasis, lists, fenced code, links, blockquotes, rules) and
//! falls back to plain text for extreme inputs so the TUI never allocates the
//! world over a misbehaving comment.
//!
//! The output is `Line<'static>` so callers can cache and reuse the rendered
//! paragraphs across frames.

use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use unicode_width::UnicodeWidthStr;

use crate::theme::Theme;

/// Hard upper bound on the input length we will parse as markdown. Larger
/// bodies are rendered as plain text, one `Line` per input line, to keep the
/// rendered output allocation-bounded.
pub const MAX_MARKDOWN_BYTES: usize = 64 * 1024;

/// Render `body` as styled markdown, soft-wrapping paragraphs to `width`.
///
/// The returned `Vec<Line<'static>>` can be cached across frames since every
/// span owns its text.
pub fn render_markdown(body: &str, theme: &Theme, width: usize) -> Vec<Line<'static>> {
    let cleaned = strip_ansi(body);

    // Guardrail: never parse ridiculous inputs — fall back to one line per
    // source line. This keeps allocations proportional to the input and
    // prevents pathological comments from blowing the heap.
    if cleaned.len() > MAX_MARKDOWN_BYTES {
        return cleaned
            .lines()
            .map(|line| Line::from(Span::raw(line.to_string())))
            .collect();
    }

    let width = width.max(1);
    let parser = Parser::new_ext(&cleaned, Options::empty());
    let mut renderer = Renderer::new(theme, width);
    for event in parser {
        renderer.handle_event(event);
    }
    renderer.finish()
}

/// Strip ANSI CSI / OSC escape sequences from `input`.
///
/// This is a simple defensive pass — we don't try to interpret colour codes,
/// just drop them so nothing leaks through to the ratatui renderer.
fn strip_ansi(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch != '\u{1b}' {
            out.push(ch);
            continue;
        }
        match chars.peek() {
            Some('[') => {
                // CSI: ESC [ ... final_byte (0x40..=0x7E)
                chars.next();
                while let Some(&c) = chars.peek() {
                    chars.next();
                    if ('\u{40}'..='\u{7e}').contains(&c) {
                        break;
                    }
                }
            }
            Some(']') => {
                // OSC: ESC ] ... (BEL | ESC \)
                chars.next();
                while let Some(&c) = chars.peek() {
                    chars.next();
                    if c == '\u{07}' {
                        break;
                    }
                    if c == '\u{1b}' {
                        // swallow the following '\\' too
                        if matches!(chars.peek(), Some('\\')) {
                            chars.next();
                        }
                        break;
                    }
                }
            }
            Some(_) => {
                // Two-byte escape (e.g. ESC =). Just drop the next char.
                chars.next();
            }
            None => {}
        }
    }
    out
}

/// Style for strong/emphasis so tests and call sites can agree on what
/// "markdown bold" looks like.
fn strong_style() -> Style {
    Style::default().add_modifier(Modifier::BOLD)
}

fn emphasis_style() -> Style {
    Style::default().add_modifier(Modifier::ITALIC)
}

fn header_style(theme: &Theme) -> Style {
    Style::default()
        .fg(theme.markdown_header)
        .add_modifier(Modifier::BOLD)
}

fn inline_code_style(theme: &Theme) -> Style {
    Style::default()
        .fg(theme.markdown_code)
        .bg(theme.markdown_code_bg)
}

fn code_block_style(theme: &Theme) -> Style {
    Style::default()
        .fg(theme.markdown_code)
        .bg(theme.markdown_code_bg)
}

fn link_style(theme: &Theme) -> Style {
    Style::default()
        .fg(theme.markdown_link)
        .add_modifier(Modifier::UNDERLINED)
}

fn blockquote_style(theme: &Theme) -> Style {
    Style::default()
        .fg(theme.markdown_blockquote)
        .add_modifier(Modifier::ITALIC)
}

fn rule_style(theme: &Theme) -> Style {
    Style::default().fg(theme.markdown_rule)
}

/// Tracks what block we're currently inside so list bullets, code fences,
/// and quote prefixes behave.
#[derive(Debug, Clone)]
struct BlockContext {
    kind: BlockKind,
    /// For ordered lists, the next number to emit. None for unordered lists.
    next_ordinal: Option<u64>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BlockKind {
    List,
    BlockQuote,
    CodeBlock,
    Heading,
    Paragraph,
    Item,
}

struct Renderer<'a> {
    theme: &'a Theme,
    width: usize,
    /// Completed lines, ready to hand back to the caller.
    lines: Vec<Line<'static>>,
    /// Spans being accumulated for the "current" line that isn't code-block
    /// content. For code blocks we flush line-by-line instead.
    current: Vec<Span<'static>>,
    /// Inline style modifiers stack (strong/emphasis/link). Each frame records
    /// the delta we applied so we can reverse it when the tag closes.
    style_stack: Vec<Style>,
    /// Block nesting — outer to inner.
    blocks: Vec<BlockContext>,
    /// If we're inside a fenced code block, collect its raw lines and flush
    /// them line-by-line on End(CodeBlock) so the background colour wraps
    /// uniformly.
    code_buffer: String,
    code_lang: Option<String>,
    /// If we're inside a Link tag, remember the destination so we can append
    /// ` (url)` on close.
    link_stack: Vec<String>,
    /// Suppress soft-break -> space conversion when we're building a heading
    /// (headings collapse internally).
    in_heading: Option<HeadingLevel>,
}

impl<'a> Renderer<'a> {
    fn new(theme: &'a Theme, width: usize) -> Self {
        Self {
            theme,
            width,
            lines: Vec::new(),
            current: Vec::new(),
            style_stack: Vec::new(),
            blocks: Vec::new(),
            code_buffer: String::new(),
            code_lang: None,
            link_stack: Vec::new(),
            in_heading: None,
        }
    }

    fn finish(mut self) -> Vec<Line<'static>> {
        self.flush_paragraph_line();
        self.lines
    }

    fn in_code_block(&self) -> bool {
        self.blocks
            .last()
            .is_some_and(|b| b.kind == BlockKind::CodeBlock)
    }

    fn is_blockquote(&self) -> bool {
        self.blocks.iter().any(|b| b.kind == BlockKind::BlockQuote)
    }

    fn current_style(&self) -> Style {
        self.style_stack
            .iter()
            .copied()
            .fold(Style::default(), merge_style)
    }

    fn handle_event(&mut self, event: Event<'_>) {
        match event {
            Event::Start(tag) => self.handle_start(tag),
            Event::End(tag) => self.handle_end(tag),
            Event::Text(s) => self.handle_text(&s),
            Event::Code(s) => self.handle_inline_code(&s),
            Event::Html(s) | Event::InlineHtml(s) => self.handle_text(&s),
            Event::SoftBreak => self.handle_soft_break(),
            Event::HardBreak => self.hard_break(),
            Event::Rule => self.handle_rule(),
            Event::FootnoteReference(s) => self.handle_text(&format!("[^{s}]")),
            Event::TaskListMarker(checked) => {
                let marker = if checked { "[x] " } else { "[ ] " };
                self.push_span(Span::raw(marker.to_string()));
            }
            Event::InlineMath(s) => self.handle_text(&format!("${s}$")),
            Event::DisplayMath(s) => self.handle_text(&format!("$${s}$$")),
        }
    }

    fn handle_start(&mut self, tag: Tag<'_>) {
        match tag {
            Tag::Paragraph => {
                self.blocks.push(BlockContext {
                    kind: BlockKind::Paragraph,
                    next_ordinal: None,
                });
            }
            Tag::Heading { level, .. } => {
                self.flush_paragraph_line();
                self.blocks.push(BlockContext {
                    kind: BlockKind::Heading,
                    next_ordinal: None,
                });
                self.in_heading = Some(level);
                let marker = "#".repeat(heading_level(level));
                let style = header_style(self.theme);
                let text = format!("{marker} ");
                self.push_span(Span::styled(text, style));
                self.style_stack.push(style);
            }
            Tag::BlockQuote(_) => {
                self.flush_paragraph_line();
                self.blocks.push(BlockContext {
                    kind: BlockKind::BlockQuote,
                    next_ordinal: None,
                });
            }
            Tag::CodeBlock(kind) => {
                self.flush_paragraph_line();
                self.blocks.push(BlockContext {
                    kind: BlockKind::CodeBlock,
                    next_ordinal: None,
                });
                self.code_buffer.clear();
                self.code_lang = match kind {
                    CodeBlockKind::Fenced(lang) if !lang.is_empty() => Some(lang.to_string()),
                    _ => None,
                };
                // Emit an opener line so fences are visible even in narrow panels.
                let style = code_block_style(self.theme);
                let opener = match &self.code_lang {
                    Some(lang) => format!("``` {lang}"),
                    None => "```".to_string(),
                };
                self.emit_line_with_prefix(vec![Span::styled(opener, style)]);
            }
            Tag::List(start) => {
                self.flush_paragraph_line();
                self.blocks.push(BlockContext {
                    kind: BlockKind::List,
                    next_ordinal: start,
                });
            }
            Tag::Item => {
                self.flush_paragraph_line();
                let (bullet, style) = if let Some(list) = self
                    .blocks
                    .iter_mut()
                    .rev()
                    .find(|b| b.kind == BlockKind::List)
                {
                    match list.next_ordinal.as_mut() {
                        Some(n) => {
                            let s = format!("{n}. ");
                            *n += 1;
                            (s, Style::default())
                        }
                        None => ("- ".to_string(), Style::default()),
                    }
                } else {
                    ("- ".to_string(), Style::default())
                };
                self.blocks.push(BlockContext {
                    kind: BlockKind::Item,
                    next_ordinal: None,
                });
                self.push_span(Span::styled(bullet, style));
            }
            Tag::Emphasis => {
                let style = emphasis_style();
                self.style_stack.push(style);
            }
            Tag::Strong => {
                let style = strong_style();
                self.style_stack.push(style);
            }
            Tag::Strikethrough => {
                let style = Style::default().add_modifier(Modifier::CROSSED_OUT);
                self.style_stack.push(style);
            }
            Tag::Link { dest_url, .. } => {
                self.link_stack.push(dest_url.to_string());
                let style = link_style(self.theme);
                self.style_stack.push(style);
            }
            Tag::Image { dest_url, .. } => {
                // Render as "![alt](url)"-ish — text children will come through
                // and the close tag will append the URL.
                self.link_stack.push(dest_url.to_string());
                let style = link_style(self.theme);
                self.push_span(Span::styled("!".to_string(), style));
                self.style_stack.push(style);
            }
            Tag::HtmlBlock => {
                self.blocks.push(BlockContext {
                    kind: BlockKind::Paragraph,
                    next_ordinal: None,
                });
            }
            _ => {
                // Tables, footnotes, metadata blocks, definition lists —
                // render as a plain paragraph so text inside still shows up.
                self.blocks.push(BlockContext {
                    kind: BlockKind::Paragraph,
                    next_ordinal: None,
                });
            }
        }
    }

    fn handle_end(&mut self, tag: TagEnd) {
        match tag {
            TagEnd::Paragraph => {
                self.flush_paragraph_line();
                self.blocks.pop();
            }
            TagEnd::Heading(_) => {
                // Pop the header style we pushed in start.
                self.style_stack.pop();
                self.flush_paragraph_line();
                self.blocks.pop();
                self.in_heading = None;
            }
            TagEnd::BlockQuote(_) => {
                self.flush_paragraph_line();
                self.blocks.pop();
            }
            TagEnd::CodeBlock => {
                // Flush any accumulated code lines with the code background.
                let style = code_block_style(self.theme);
                let buf = std::mem::take(&mut self.code_buffer);
                for line in buf.split('\n') {
                    // Guard against a trailing newline producing a spurious empty line.
                    if line.is_empty() && buf.ends_with('\n') {
                        continue;
                    }
                    self.emit_line_with_prefix(vec![Span::styled(line.to_string(), style)]);
                }
                self.emit_line_with_prefix(vec![Span::styled("```".to_string(), style)]);
                self.code_lang = None;
                self.blocks.pop();
            }
            TagEnd::List(_) => {
                self.flush_paragraph_line();
                self.blocks.pop();
            }
            TagEnd::Item => {
                self.flush_paragraph_line();
                self.blocks.pop();
            }
            TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough => {
                self.style_stack.pop();
            }
            TagEnd::Link => {
                self.style_stack.pop();
                if let Some(url) = self.link_stack.pop() {
                    let style = link_style(self.theme);
                    self.push_span(Span::styled(format!(" ({url})"), style));
                }
            }
            TagEnd::Image => {
                self.style_stack.pop();
                if let Some(url) = self.link_stack.pop() {
                    let style = link_style(self.theme);
                    self.push_span(Span::styled(format!(" ({url})"), style));
                }
            }
            TagEnd::HtmlBlock => {
                self.flush_paragraph_line();
                self.blocks.pop();
            }
            _ => {
                self.blocks.pop();
            }
        }
    }

    fn handle_text(&mut self, text: &str) {
        if self.in_code_block() {
            self.code_buffer.push_str(text);
            return;
        }
        let style = self.current_style();
        // Soft-wrap the paragraph text across `width` columns.
        for (i, chunk) in split_to_width(text, self.remaining_width())
            .into_iter()
            .enumerate()
        {
            if i > 0 {
                self.flush_paragraph_line();
            }
            if !chunk.is_empty() {
                self.push_span(Span::styled(chunk, style));
            }
        }
    }

    fn handle_inline_code(&mut self, text: &str) {
        let style = inline_code_style(self.theme);
        let combined = merge_style(self.current_style(), style);
        // Treat inline code as atomic text to wrap.
        for (i, chunk) in split_to_width(text, self.remaining_width())
            .into_iter()
            .enumerate()
        {
            if i > 0 {
                self.flush_paragraph_line();
            }
            if !chunk.is_empty() {
                self.push_span(Span::styled(chunk, combined));
            }
        }
    }

    fn handle_soft_break(&mut self) {
        if self.in_heading.is_some() {
            self.push_span(Span::raw(" ".to_string()));
            return;
        }
        // Treat like whitespace so paragraphs reflow.
        self.push_span(Span::raw(" ".to_string()));
    }

    fn hard_break(&mut self) {
        self.flush_paragraph_line();
    }

    fn handle_rule(&mut self) {
        self.flush_paragraph_line();
        let line_width = self.width.max(3);
        let rule = "-".repeat(line_width);
        self.emit_line_with_prefix(vec![Span::styled(rule, rule_style(self.theme))]);
    }

    /// Width still available on the current line after the prefix is applied.
    fn remaining_width(&self) -> usize {
        let prefix = self.compute_prefix();
        let used: usize = self.current.iter().map(|s| s.content.width()).sum();
        self.width
            .saturating_sub(prefix.width())
            .saturating_sub(used)
            .max(1)
    }

    /// Compute the leading indent/quote marker for a freshly-emitted line.
    fn compute_prefix(&self) -> String {
        let mut prefix = String::new();
        let quote_depth = self
            .blocks
            .iter()
            .filter(|b| b.kind == BlockKind::BlockQuote)
            .count();
        for _ in 0..quote_depth {
            prefix.push_str("> ");
        }
        // Item indent: nested items get 2 spaces per enclosing item-or-list pair.
        let list_depth = self
            .blocks
            .iter()
            .filter(|b| b.kind == BlockKind::List)
            .count();
        let item_depth = self
            .blocks
            .iter()
            .filter(|b| b.kind == BlockKind::Item)
            .count();
        // Indent subsequent lines of the same bullet by two spaces per level.
        // Initial bullet line already has the marker attached as a span.
        let wrap_indent = list_depth.saturating_add(item_depth).saturating_sub(1);
        for _ in 0..wrap_indent {
            prefix.push_str("  ");
        }
        prefix
    }

    fn push_span(&mut self, span: Span<'static>) {
        self.current.push(span);
    }

    /// Emit a line that already includes any bullet/code content — attaches
    /// the structural prefix (quote markers, list indent) on the left.
    fn emit_line_with_prefix(&mut self, content: Vec<Span<'static>>) {
        let prefix = self.compute_prefix();
        let mut spans = Vec::with_capacity(content.len() + 1);
        if !prefix.is_empty() {
            let style = if self.is_blockquote() {
                blockquote_style(self.theme)
            } else {
                Style::default()
            };
            spans.push(Span::styled(prefix, style));
        }
        spans.extend(content);
        self.lines.push(Line::from(spans));
    }

    /// Flush the in-progress paragraph / heading / item line into `self.lines`.
    fn flush_paragraph_line(&mut self) {
        if self.current.is_empty() {
            return;
        }
        let spans = std::mem::take(&mut self.current);
        let quote_style = if self.is_blockquote() {
            Some(blockquote_style(self.theme))
        } else {
            None
        };
        let spans = match quote_style {
            Some(q_style) => spans
                .into_iter()
                .map(|s| {
                    // Blend the existing span style with the blockquote tint so
                    // the reader can see the whole quoted paragraph at a glance.
                    Span::styled(s.content, merge_style(q_style, s.style))
                })
                .collect(),
            None => spans,
        };
        self.emit_line_with_prefix(spans);
    }
}

/// Post-process rendered markdown lines, splitting any plain spans that contain
/// `@path/to/file` tokens (optionally with `:lineno` suffix) and restyling
/// those tokens with `style`. Spans whose existing style carries the markdown
/// code colour are left untouched — tokens inside fenced code blocks should
/// not be promoted to file references.
///
/// The token regex is effectively `@[A-Za-z0-9_./\-]+(:\d+)?` with the
/// additional rule that the `@` must be at a line boundary or preceded by
/// whitespace — this avoids matching email-like `foo@bar.com` fragments.
pub fn highlight_file_refs(
    lines: Vec<Line<'static>>,
    style: Style,
    code_color: ratatui::style::Color,
) -> Vec<Line<'static>> {
    lines
        .into_iter()
        .map(|line| Line::from(highlight_file_refs_in_spans(line.spans, style, code_color)))
        .collect()
}

fn highlight_file_refs_in_spans(
    spans: Vec<Span<'static>>,
    style: Style,
    code_color: ratatui::style::Color,
) -> Vec<Span<'static>> {
    // Track, across the whole line, the previous character to decide whether
    // a `@` is a valid reference start. This handles the case where one plain
    // span ends with whitespace and the next begins with `@word`.
    let mut out: Vec<Span<'static>> = Vec::with_capacity(spans.len());
    let mut prev_char: Option<char> = None;
    for span in spans {
        // Skip styled spans that look like code (same fg as markdown code
        // colour) — they are inside inline code or fenced blocks.
        if span.style.fg == Some(code_color) {
            // Updating prev_char keeps boundary detection honest for any
            // following plain span.
            prev_char = span.content.chars().last();
            out.push(span);
            continue;
        }
        let original_style = span.style;
        let text = span.content.into_owned();
        let mut idx = 0usize;
        let bytes = text.as_bytes();
        while idx < bytes.len() {
            // Scan forward for a `@` that is at a valid boundary.
            let at_idx = text[idx..].find('@').map(|off| idx + off);
            let Some(at_idx) = at_idx else {
                // No more tokens — push the remainder and break.
                out.push(Span::styled(text[idx..].to_string(), original_style));
                prev_char = text[idx..].chars().last();
                break;
            };
            // Emit the text before the `@` with the original style.
            if at_idx > idx {
                out.push(Span::styled(text[idx..at_idx].to_string(), original_style));
                prev_char = text[idx..at_idx].chars().last();
            }

            // Boundary rule: the character immediately before `@` must be
            // whitespace, a start-of-line, or absent (start of whole line).
            let boundary_ok = match prev_char {
                None => true,
                Some(c) => c.is_whitespace(),
            };
            if !boundary_ok {
                // Not a ref — emit `@` as normal text and continue.
                out.push(Span::styled("@".to_string(), original_style));
                prev_char = Some('@');
                idx = at_idx + 1;
                continue;
            }

            // Consume the path characters after `@`.
            let after = at_idx + 1;
            let mut end = after;
            while end < text.len() {
                let c = text[end..].chars().next().unwrap();
                if is_path_char(c) {
                    end += c.len_utf8();
                } else {
                    break;
                }
            }
            // Optional `:NNNN` line-number suffix.
            if end < text.len()
                && text.as_bytes()[end] == b':'
                && end + 1 < text.len()
                && text.as_bytes()[end + 1].is_ascii_digit()
            {
                end += 1;
                while end < text.len() && text.as_bytes()[end].is_ascii_digit() {
                    end += 1;
                }
            }

            if end == after {
                // `@` not followed by a path char — emit literally.
                out.push(Span::styled("@".to_string(), original_style));
                prev_char = Some('@');
                idx = after;
                continue;
            }

            // Valid token `@...` between at_idx..end.
            out.push(Span::styled(text[at_idx..end].to_string(), style));
            prev_char = text[at_idx..end].chars().last();
            idx = end;
        }
    }
    out
}

fn is_path_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '/' | '-')
}

fn heading_level(level: HeadingLevel) -> usize {
    match level {
        HeadingLevel::H1 => 1,
        HeadingLevel::H2 => 2,
        HeadingLevel::H3 => 3,
        HeadingLevel::H4 => 4,
        HeadingLevel::H5 => 5,
        HeadingLevel::H6 => 6,
    }
}

/// Merge two styles. `layer` is applied on top of `base`, i.e. explicitly set
/// fields on `layer` win.
fn merge_style(base: Style, layer: Style) -> Style {
    let mut out = base;
    if let Some(fg) = layer.fg {
        out = out.fg(fg);
    }
    if let Some(bg) = layer.bg {
        out = out.bg(bg);
    }
    out = out.add_modifier(layer.add_modifier);
    if !layer.sub_modifier.is_empty() {
        out = out.remove_modifier(layer.sub_modifier);
    }
    if let Some(color) = layer.underline_color {
        out = out.underline_color(color);
    }
    out
}

/// Split `text` into chunks that each fit within `width` columns without
/// splitting in the middle of a word when possible. Falls back to hard-breaking
/// words that are themselves wider than the available width.
fn split_to_width(text: &str, width: usize) -> Vec<String> {
    let width = width.max(1);
    if text.is_empty() {
        return vec![String::new()];
    }
    if text.width() <= width {
        return vec![text.to_string()];
    }

    let mut out = Vec::new();
    let mut current = String::new();
    let mut current_width = 0usize;

    let words = split_preserving_whitespace(text);
    for word in words {
        let w_width = word.width();
        if current_width == 0 && w_width > width {
            // Hard-break the oversized word.
            let mut remaining = word.as_str();
            while !remaining.is_empty() {
                let (chunk, rest) = take_up_to_width(remaining, width);
                out.push(chunk);
                remaining = rest;
            }
            continue;
        }
        if current_width + w_width > width {
            out.push(std::mem::take(&mut current));
            current_width = 0;
            // Drop leading whitespace on new line.
            if word.chars().all(char::is_whitespace) {
                continue;
            }
        }
        current.push_str(&word);
        current_width += w_width;
    }
    if !current.is_empty() {
        out.push(current);
    }
    if out.is_empty() {
        out.push(String::new());
    }
    out
}

/// Break `text` into words and whitespace runs so we can wrap on word
/// boundaries. Returns an iterator of owned strings for convenience.
fn split_preserving_whitespace(text: &str) -> std::vec::IntoIter<String> {
    let mut out = Vec::new();
    let mut buf = String::new();
    let mut in_ws = false;
    for ch in text.chars() {
        let ws = ch.is_whitespace();
        if buf.is_empty() {
            in_ws = ws;
            buf.push(ch);
            continue;
        }
        if ws == in_ws {
            buf.push(ch);
        } else {
            out.push(std::mem::take(&mut buf));
            in_ws = ws;
            buf.push(ch);
        }
    }
    if !buf.is_empty() {
        out.push(buf);
    }
    out.into_iter()
}

/// Take at most `width` columns from the front of `text`, returning the chunk
/// and the remainder. Splits on char boundaries.
fn take_up_to_width(text: &str, width: usize) -> (String, &str) {
    let mut end = 0usize;
    let mut used = 0usize;
    for (i, ch) in text.char_indices() {
        let cw = UnicodeWidthStr::width(ch.to_string().as_str());
        if used + cw > width && used > 0 {
            break;
        }
        used += cw;
        end = i + ch.len_utf8();
    }
    (text[..end].to_string(), &text[end..])
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::theme::Theme;

    fn theme() -> Theme {
        Theme::dark()
    }

    /// Collapse all spans on a line into a single string for readability.
    fn line_text(line: &Line<'_>) -> String {
        line.spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn headers_are_bold_and_prefixed_with_hashes() {
        let theme = theme();
        let lines = render_markdown("# Hello\n## World\n### Sub", &theme, 80);
        assert_eq!(lines.len(), 3, "should produce one line per header");
        assert_eq!(line_text(&lines[0]), "# Hello");
        assert_eq!(line_text(&lines[1]), "## World");
        assert_eq!(line_text(&lines[2]), "### Sub");
        // First span on the header carries the markdown_header colour + BOLD.
        let style = lines[0].spans[0].style;
        assert_eq!(style.fg, Some(theme.markdown_header));
        assert!(style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn emphasis_spans_carry_italic_and_bold_modifiers() {
        let theme = theme();
        let lines = render_markdown("Regular **bold** and *italic* text.", &theme, 80);
        assert_eq!(lines.len(), 1);
        let line = &lines[0];
        // Find the span whose content is "bold"
        let bold = line
            .spans
            .iter()
            .find(|s| s.content.as_ref() == "bold")
            .expect("bold span present");
        assert!(bold.style.add_modifier.contains(Modifier::BOLD));
        let italic = line
            .spans
            .iter()
            .find(|s| s.content.as_ref() == "italic")
            .expect("italic span present");
        assert!(italic.style.add_modifier.contains(Modifier::ITALIC));
    }

    #[test]
    fn inline_code_gets_code_colours() {
        let theme = theme();
        let lines = render_markdown("call `foo()` here", &theme, 80);
        let line = &lines[0];
        let code = line
            .spans
            .iter()
            .find(|s| s.content.as_ref() == "foo()")
            .expect("inline code span present");
        assert_eq!(code.style.fg, Some(theme.markdown_code));
        assert_eq!(code.style.bg, Some(theme.markdown_code_bg));
    }

    #[test]
    fn fenced_code_block_preserves_lines_and_wraps_in_fences() {
        let theme = theme();
        let body = "```rust\nfn main() {\n    println!(\"hi\");\n}\n```";
        let lines = render_markdown(body, &theme, 80);
        // Opener, three content lines, closer = 5.
        assert!(
            lines.len() >= 5,
            "expected at least 5 lines, got {}",
            lines.len()
        );
        let opener = line_text(&lines[0]);
        assert!(opener.contains("```"), "opener: {opener:?}");
        assert!(opener.contains("rust"));
        // Middle line should carry code foreground.
        let mid = &lines[1];
        let content_span = mid.spans.last().expect("content span on code line");
        assert_eq!(content_span.style.fg, Some(theme.markdown_code));
        assert_eq!(content_span.style.bg, Some(theme.markdown_code_bg));
        let closer = line_text(&lines[lines.len() - 1]);
        assert_eq!(closer, "```");
    }

    #[test]
    fn nested_lists_indent_wrapped_bullet_text() {
        let theme = theme();
        let body = "- Outer\n  - Inner one\n  - Inner two\n- Second";
        let lines = render_markdown(body, &theme, 80);
        let texts: Vec<_> = lines.iter().map(line_text).collect();
        assert!(
            texts.iter().any(|t| t.contains("- Outer")),
            "expected outer bullet line, got {texts:?}"
        );
        // Inner items should have more leading space than outer items.
        let inner_one_leading = texts
            .iter()
            .find(|t| t.contains("Inner one"))
            .map(|t| t.chars().take_while(|c| *c == ' ').count())
            .expect("inner one line");
        let outer_leading = texts
            .iter()
            .find(|t| t.contains("Outer"))
            .map(|t| t.chars().take_while(|c| *c == ' ').count())
            .expect("outer line");
        assert!(
            inner_one_leading > outer_leading,
            "expected inner bullet to be more indented: inner={inner_one_leading} outer={outer_leading} lines={texts:?}"
        );
        let second_leading = texts
            .iter()
            .find(|t| t.contains("Second"))
            .map(|t| t.chars().take_while(|c| *c == ' ').count())
            .expect("second line");
        assert_eq!(
            second_leading, outer_leading,
            "top-level bullets should share indent; lines={texts:?}"
        );
    }

    #[test]
    fn ordered_lists_number_each_item() {
        let theme = theme();
        let body = "1. first\n2. second\n3. third";
        let lines = render_markdown(body, &theme, 80);
        let texts: Vec<_> = lines.iter().map(line_text).collect();
        assert!(
            texts.iter().any(|t| t.contains("1. first")),
            "expected ordered item 1, got {texts:?}"
        );
        assert!(
            texts.iter().any(|t| t.contains("2. second")),
            "expected ordered item 2, got {texts:?}"
        );
        assert!(
            texts.iter().any(|t| t.contains("3. third")),
            "expected ordered item 3, got {texts:?}"
        );
    }

    #[test]
    fn links_render_text_followed_by_url_in_link_style() {
        let theme = theme();
        let lines = render_markdown("see [docs](https://example.com/docs) for more", &theme, 80);
        let spans = &lines[0].spans;
        // Find the span for 'docs'
        let label = spans
            .iter()
            .find(|s| s.content.as_ref() == "docs")
            .expect("link label span");
        assert_eq!(label.style.fg, Some(theme.markdown_link));
        assert!(
            label.style.add_modifier.contains(Modifier::UNDERLINED),
            "link label should be underlined"
        );
        // URL should appear as "( ... )" after the label.
        let url = spans
            .iter()
            .find(|s| s.content.contains("https://example.com/docs"))
            .expect("url span present");
        assert_eq!(url.style.fg, Some(theme.markdown_link));
    }

    #[test]
    fn blockquote_lines_are_prefixed_with_gt_and_italicised() {
        let theme = theme();
        let body = "> quoted\n> second line";
        let lines = render_markdown(body, &theme, 80);
        assert!(!lines.is_empty());
        let quoted_line = &lines[0];
        assert!(quoted_line.spans[0].content.starts_with("> "));
        // The quote prefix should use the blockquote colour.
        assert_eq!(
            quoted_line.spans[0].style.fg,
            Some(theme.markdown_blockquote)
        );
        // Subsequent span should carry italic.
        let italic = quoted_line
            .spans
            .iter()
            .find(|s| s.content.as_ref() == "quoted second line")
            .or_else(|| {
                quoted_line
                    .spans
                    .iter()
                    .find(|s| s.content.contains("quoted"))
            })
            .expect("quote body span");
        assert!(italic.style.add_modifier.contains(Modifier::ITALIC));
    }

    #[test]
    fn thematic_break_renders_as_dashes_line() {
        let theme = theme();
        let lines = render_markdown("before\n\n---\n\nafter", &theme, 12);
        let texts: Vec<_> = lines.iter().map(line_text).collect();
        assert!(
            texts
                .iter()
                .any(|t| t.chars().all(|c| c == '-') && !t.is_empty()),
            "expected a dashes-only line in {texts:?}"
        );
    }

    #[test]
    fn ansi_escape_sequences_are_stripped() {
        let theme = theme();
        // Red + reset wrapping "danger"
        let body = "plain \u{1b}[31mdanger\u{1b}[0m after";
        let lines = render_markdown(body, &theme, 80);
        let text = line_text(&lines[0]);
        assert_eq!(text, "plain danger after");
        // And also the OSC form shouldn't leak into output.
        let body = "x\u{1b}]0;title\u{07}y";
        let lines = render_markdown(body, &theme, 80);
        assert_eq!(line_text(&lines[0]), "xy");
    }

    #[test]
    fn oversized_body_falls_back_to_plain_text() {
        let theme = theme();
        let chunk = "line of plain text\n";
        let body: String = chunk.repeat((MAX_MARKDOWN_BYTES / chunk.len()) + 10);
        assert!(body.len() > MAX_MARKDOWN_BYTES);
        let lines = render_markdown(&body, &theme, 80);
        // Every line should be a plain Span with no markdown styling.
        assert!(lines.len() > 100);
        for l in &lines {
            assert_eq!(l.spans.len(), 1, "plain fallback should be single span");
            assert_eq!(l.spans[0].style, Style::default());
        }
    }

    #[test]
    fn paragraphs_wrap_to_requested_width() {
        let theme = theme();
        let body = "alpha beta gamma delta epsilon";
        let lines = render_markdown(body, &theme, 10);
        assert!(
            lines.len() >= 2,
            "expected wrap across >=2 lines, got {lines:?}"
        );
        for line in &lines {
            let w: usize = line.spans.iter().map(|s| s.content.as_ref().width()).sum();
            assert!(w <= 12, "line too wide: {w} ({:?})", line_text(line));
        }
    }

    #[test]
    fn html_passes_through_literally() {
        let theme = theme();
        let body = "<b>hi</b>";
        let lines = render_markdown(body, &theme, 80);
        let joined: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
        assert!(joined.contains("<b>") && joined.contains("</b>"));
    }

    #[test]
    fn urls_are_preserved_verbatim() {
        let theme = theme();
        let body = "[x](https://a.example/path?q=1&r=2#frag)";
        let lines = render_markdown(body, &theme, 200);
        let joined: String = lines.iter().map(line_text).collect::<String>();
        assert!(
            joined.contains("https://a.example/path?q=1&r=2#frag"),
            "url not preserved: {joined:?}"
        );
    }

    #[test]
    fn strip_ansi_leaves_plain_text_alone() {
        assert_eq!(strip_ansi("no escapes here"), "no escapes here");
    }

    #[test]
    fn strip_ansi_handles_common_csi_sequences() {
        assert_eq!(strip_ansi("\u{1b}[1;31mred\u{1b}[0m ok"), "red ok");
    }

    // ── highlight_file_refs tests ──

    fn highlight_style() -> Style {
        Style::default().fg(ratatui::style::Color::Cyan)
    }

    fn code_color() -> ratatui::style::Color {
        // A distinctive colour that won't clash with the highlight style so
        // tests can reliably separate the two buckets.
        ratatui::style::Color::Rgb(220, 220, 140)
    }

    fn highlight_spans(text: &str) -> Vec<Span<'static>> {
        let input = vec![Line::from(Span::raw(text.to_string()))];
        let out = highlight_file_refs(input, highlight_style(), code_color());
        out.into_iter().next().unwrap().spans
    }

    #[test]
    fn highlights_at_file_token() {
        let spans = highlight_spans("see @src/foo.rs for context");
        let hit = spans
            .iter()
            .find(|s| s.content.as_ref() == "@src/foo.rs")
            .expect("file-ref span present");
        assert_eq!(hit.style.fg, Some(ratatui::style::Color::Cyan));
    }

    #[test]
    fn highlights_at_file_with_line() {
        let spans = highlight_spans("check @src/main.rs:42");
        let hit = spans
            .iter()
            .find(|s| s.content.as_ref() == "@src/main.rs:42")
            .expect("file-ref with line span present");
        assert_eq!(hit.style.fg, Some(ratatui::style::Color::Cyan));
    }

    #[test]
    fn does_not_highlight_email_like_at_symbol() {
        // `foo@bar.com` — the `@` is attached to alphanumeric, so the
        // `@bar.com` fragment must NOT become a file reference.
        let spans = highlight_spans("ping foo@bar.com today");
        for span in &spans {
            // Any span that begins with `@` would only exist if we mistakenly
            // split the email; the whole "foo@bar.com today" should stay
            // together or at least never produce a cyan-styled `@bar.com`.
            if span.content.starts_with('@') {
                assert_ne!(
                    span.style.fg,
                    Some(ratatui::style::Color::Cyan),
                    "email fragment {:?} was promoted to a file reference",
                    span.content
                );
            }
        }
    }

    #[test]
    fn handles_multiple_refs_in_one_line() {
        let spans = highlight_spans("edit @a/b.rs and @c.rs:7 plus text");
        let refs: Vec<&str> = spans
            .iter()
            .filter(|s| s.style.fg == Some(ratatui::style::Color::Cyan))
            .map(|s| s.content.as_ref())
            .collect();
        assert!(refs.contains(&"@a/b.rs"), "first ref missing: {refs:?}");
        assert!(refs.contains(&"@c.rs:7"), "second ref missing: {refs:?}");
    }

    #[test]
    fn preserves_existing_span_styles_for_non_matching_text() {
        let body = "call `foo()` here";
        let lines = render_markdown(body, &theme(), 80);
        let out = highlight_file_refs(lines, highlight_style(), theme().markdown_code);
        // The inline-code span should still carry the original code colour and
        // must NOT have been rewritten to the file-ref cyan.
        let code = out[0]
            .spans
            .iter()
            .find(|s| s.content.as_ref() == "foo()")
            .expect("inline code span preserved");
        assert_eq!(code.style.fg, Some(theme().markdown_code));
    }
}