lazyllama 0.5.2

A lightweight TUI client for Ollama with markdown support and smart scrolling.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
/*
 *  _                      _      _
 * | |    __ _  ______  __| |    | | __ _ _ __ ___   __ _
 * | |   / _` ||_  /\ \/ /| |    | |/ _` | '_ ` _ \ / _` |
 * | |__| (_| | / /  \  / | |___ | | (_| | | | | | | (_| |
 * |_____\__,_|/___| /_/  |_____||_|\__,_|_| |_| |_|\__,_|
 *
 * Copyright (C) 2026 Raimo Geisel
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

//! Terminal User Interface rendering and layout functions.
//!
//! This module handles all aspects of the visual presentation including:
//! - Widget rendering and layout management
//! - Markdown parsing and syntax highlighting
//! - Scroll position calculation and management
//! - Real-time UI updates during AI response streaming
//!
//! The UI is built with Ratatui and features:
//! - Responsive layout that adapts to terminal size
//! - Code block highlighting with language detection
//! - Smart scrolling with autoscroll and manual modes
//! - Model status indicators and selection highlighting
//! - Animated loading indicators

use crate::app::App;
use pulldown_cmark::{Event, Parser, Tag, TagEnd};
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout},
    style::{Color, Modifier, Style},
    text::{Line, Span, Text},
    widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Wrap},
    Frame,
};
use regex::Regex;
use syntect::easy::HighlightLines;
use syntect::highlighting::ThemeSet;
use syntect::parsing::SyntaxSet;
use syntect::util::LinesWithEndings;

/// ASCII art banner displayed at the top of the application.
/// 
/// This constant contains the stylized "LazyLlama" text that appears
/// in the header section of the terminal interface.
pub const BANNER: &str = r#"
| |    __ _  ______  __| |    | | __ _ _ __ ___   __ _
| |   / _` ||_  /\ \/ /| |    | |/ _` | '_ ` _ \ / _` |
| |__| (_| | / /  \  / | |___ | | (_| | | | | | | (_| |
|_____\__,_|/___| /_/  |_____||_|\__,_|_| |_| |_|\__,_|
"#;

/// Converts a syntect Color to a ratatui Color.
///
/// Syntect uses RGBA colors while ratatui uses RGB. This function
/// extracts the RGB components and creates a ratatui RGB color.
fn syntect_color_to_ratatui(color: syntect::highlighting::Color) -> Color {
    Color::Rgb(color.r, color.g, color.b)
}

/// Maps common markdown language tags to syntect language names.
///
/// Markdown code fences often use different identifiers than syntect's
/// internal language names. This function provides a mapping to ensure
/// proper syntax highlighting for commonly used language tags.
///
/// # Arguments
///
/// * `lang` - The language tag from markdown (e.g., "js", "py", "csharp")
///
/// # Returns
///
/// The syntect-compatible language name (e.g., "JavaScript", "Python", "C#")
fn map_language_tag(lang: &str) -> &str {
    match lang.to_lowercase().as_str() {
        // JavaScript variants
        "javascript" | "js" => "JavaScript",
        "typescript" | "ts" => "TypeScript",
        "jsx" => "JavaScript (Babel)",
        "tsx" => "TypeScript",
        
        // Python
        "python" | "py" => "Python",
        
        // Rust
        "rust" | "rs" => "Rust",
        
        // C family
        "c" => "C",
        "cpp" | "c++" | "cxx" => "C++",
        "csharp" | "cs" | "c#" => "C#",
        
        // JVM languages
        "java" => "Java",
        "kotlin" | "kt" => "Kotlin",
        "scala" => "Scala",
        "groovy" => "Groovy",
        
        // Other compiled languages
        "go" | "golang" => "Go",
        "swift" => "Swift",
        "objective-c" | "objc" => "Objective-C",
        "objective-c++" | "objc++" => "Objective-C++",
        
        // Scripting languages
        "ruby" | "rb" => "Ruby",
        "php" => "PHP",
        "perl" | "pl" => "Perl",
        "lua" => "Lua",
        "r" => "R",
        
        // Shell scripting
        "bash" | "sh" | "shell" => "Bourne Again Shell (bash)",
        "zsh" => "Bourne Again Shell (bash)", // Close enough
        "fish" => "Bourne Again Shell (bash)",
        "powershell" | "ps1" => "PowerShell",
        
        // Web technologies
        "html" | "htm" => "HTML",
        "css" => "CSS",
        "scss" | "sass" => "SCSS",
        "less" => "LESS",
        
        // Data formats
        "json" => "JSON",
        "yaml" | "yml" => "YAML",
        "toml" => "TOML",
        "xml" => "XML",
        "csv" => "CSV",
        
        // Markup
        "markdown" | "md" => "Markdown",
        "latex" | "tex" => "LaTeX",
        "rst" | "restructuredtext" => "reStructuredText",
        
        // SQL
        "sql" | "mysql" | "postgresql" | "postgres" => "SQL",
        
        // Functional languages
        "haskell" | "hs" => "Haskell",
        "ocaml" | "ml" => "OCaml",
        "erlang" | "erl" => "Erlang",
        "elixir" | "ex" | "exs" => "Elixir",
        "clojure" | "clj" => "Clojure",
        "fsharp" | "fs" | "f#" => "F#",
        
        // Lisp family
        "lisp" => "Lisp",
        "scheme" => "Scheme",
        
        // Other languages
        "dart" => "Dart",
        "julia" | "jl" => "Julia",
        "zig" => "Zig",
        "nim" => "Nim",
        "crystal" => "Crystal",
        "d" => "D",
        "v" | "vlang" => "V",
        
        // Config files
        "ini" | "cfg" => "INI",
        "env" | "dotenv" => "Shell Script (Bash)", // Approximation
        "dockerfile" | "docker" => "Dockerfile",
        "makefile" | "make" => "Makefile",
        
        // Default: return as-is
        _ => lang,
    }
}

/// Applies syntax highlighting to a code block and returns styled lines.
///
/// Uses syntect to parse and highlight code based on the specified language.
/// Falls back to plain text if the language is not recognized.
///
/// # Arguments
///
/// * `code` - The code content to highlight
/// * `language` - The programming language identifier (e.g., "rust", "python")
/// * `theme_name` - The name of the syntect theme to use for highlighting
///
/// # Returns
///
/// A vector of Lines with syntax-highlighted spans, each prefixed with a
/// yellow border character (│).
fn highlight_code_block(code: &str, language: &str, theme_name: &str) -> Vec<Line<'static>> {
    let ps = SyntaxSet::load_defaults_newlines();
    let ts = ThemeSet::load_defaults();
    
    // Map the language tag to syntect's expected name
    let mapped_lang = map_language_tag(language);
    
    // Try to find the syntax by mapped name, then extension, then original name
    let syntax = ps.find_syntax_by_name(mapped_lang)
        .or_else(|| ps.find_syntax_by_extension(mapped_lang))
        .or_else(|| ps.find_syntax_by_extension(language))
        .unwrap_or_else(|| ps.find_syntax_plain_text());
    
    // Use the specified theme, fallback to base16-ocean.dark if not found
    let theme = ts.themes.get(theme_name)
        .unwrap_or_else(|| &ts.themes["base16-ocean.dark"]);
    
    let mut highlighter = HighlightLines::new(syntax, theme);
    let mut lines = Vec::new();
    
    for line in LinesWithEndings::from(code) {
        let ranges = highlighter.highlight_line(line, &ps).unwrap_or_default();
        let mut spans = vec![
            Span::styled("".to_string(), Style::default().fg(Color::Yellow))
        ];
        
        for (style, text) in ranges {
            let fg_color = syntect_color_to_ratatui(style.foreground);
            let mut ratatui_style = Style::default().fg(fg_color);
            
            // Apply text modifiers based on syntect font style
            if style.font_style.contains(syntect::highlighting::FontStyle::BOLD) {
                ratatui_style = ratatui_style.add_modifier(Modifier::BOLD);
            }
            if style.font_style.contains(syntect::highlighting::FontStyle::ITALIC) {
                ratatui_style = ratatui_style.add_modifier(Modifier::ITALIC);
            }
            if style.font_style.contains(syntect::highlighting::FontStyle::UNDERLINE) {
                ratatui_style = ratatui_style.add_modifier(Modifier::UNDERLINED);
            }
            
            spans.push(Span::styled(text.to_string(), ratatui_style));
        }
        
        lines.push(Line::from(spans));
    }
    
    lines
}

/// Main rendering function for the Ratatui terminal interface.
///
/// This function orchestrates the complete UI layout and rendering process,
/// creating a responsive three-panel interface with header, main content,
/// and status bar. The layout dynamically adjusts to terminal size and
/// provides real-time updates during AI interactions.
///
/// # Arguments
///
/// * `f` - Mutable reference to the Ratatui frame for widget rendering
/// * `app` - Mutable reference to application state for data access and updates
///
/// # Layout Structure
///
/// ```text
/// ┌─────────────────────────────────────────┐
/// │              ASCII Banner               │ 7 lines
/// ├─────────────┬───────────────────────────┤
/// │   Models    │    Conversation History   │ Flexible
/// │   (25%)     │         (75%)             │ height
/// │             ├───────────────────────────┤
/// │             │      Input Field          │ 3-7 lines
/// ├─────────────┴───────────────────────────┤  (dynamic)
/// │            Status Bar                   │ 1 line
/// └─────────────────────────────────────────┘
/// ```
///
/// # Features
///
/// - **Model List**: Shows available AI models with status indicators
/// - **Chat History**: Displays conversation with markdown and code highlighting
/// - **Input Field**: Multiline text entry with dynamic height (1-5 content lines)
///   - Automatically expands based on newline characters
///   - Selection highlighting with blue background
///   - Blinking cursor with reversed colors
/// - **Status Bar**: Keyboard shortcuts and current model information
/// - **Responsive Design**: Adapts to terminal size changes
/// - **Smart Scrolling**: Auto-scroll with manual override capability
///
/// # Visual Elements
///
/// - Models with conversation history show file icons (📝/📄)
/// - Selected model highlighted with different colors
/// - Loading state shows animated spinner in input field
/// - Scroll status indicator in conversation header
/// - Color-coded borders for different UI states
///
/// # Performance
///
/// This function is called frequently (up to 20fps during streaming)
/// and is optimized for minimal computational overhead while providing
/// smooth visual feedback.
pub fn ui(f: &mut Frame, app: &mut App) {
    if app.debug_keys {
        app.render_count = app.render_count.wrapping_add(1);
    }
    let root_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(7),
            Constraint::Min(0),
            Constraint::Length(1),
        ])
        .split(f.area());

    f.render_widget(
        Paragraph::new(BANNER)
            .style(Style::default().fg(Color::Cyan))
            .alignment(Alignment::Center),
        root_layout[0],
    );

    let main_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(25), Constraint::Percentage(75)])
        .split(root_layout[1]);

    // Modellliste rendern mit erweiterten Informationen
    let selected_model = app.list_state.selected()
        .and_then(|i| app.models.get(i))
        .cloned()
        .unwrap_or_else(|| "None".to_string());
    
    let items: Vec<ListItem> = app
        .models
        .iter()
        .enumerate()
        .map(|(i, m)| {
            let is_selected = app.list_state.selected() == Some(i);
            let history_len = app.model_histories.get(m).map(|h| h.len()).unwrap_or(0);
            let display = if history_len > 0 {
                format!("{} [{}]", m, if history_len > 1000 { "📝" } else { "📄" })
            } else {
                m.clone()
            };
            ListItem::new(display)
                .style(if is_selected {
                    Style::default().fg(Color::Yellow)
                } else {
                    Style::default()
                })
        })
        .collect();
    let list = List::new(items)
        .block(Block::default().borders(Borders::ALL)
            .title(format!(" Models ({}) ", app.models.len())))
        .highlight_style(
            Style::default()
                .bg(Color::Blue)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol(">> ");
    f.render_stateful_widget(list, main_chunks[0], &mut app.list_state);

    // Calculate dynamic input height based on newlines (1-5 content lines + 2 for borders)
    let input_line_count = app.input.lines().count().max(1).min(5);
    let input_height = (input_line_count + 2) as u16; // +2 for top and bottom border

    let chat_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(3), Constraint::Length(input_height)])
        .split(main_chunks[1]);

    // Verlauf parsen und Scrollen berechnen
    let history_text = parse_history(&app.history, app.settings.syntax_theme.as_str());
    let visible_height = chat_chunks[0].height.saturating_sub(2);
    // The inner width of the chat panel (minus the two border columns).
    let visible_width = chat_chunks[0].width.saturating_sub(2) as usize;

    // `Text::height()` only counts logical lines.  When `Wrap` is active,
    // every line whose display width exceeds `visible_width` occupies
    // *multiple* visual rows.  Using the raw logical count makes `max_scroll`
    // too small so the bottom of the history is unreachable.
    // We therefore sum up the wrapped row count for every logical line.
    let total_lines: u16 = if visible_width == 0 {
        history_text.height() as u16
    } else {
        history_text
            .lines
            .iter()
            .map(|line| {
                let line_width: usize = line
                    .spans
                    .iter()
                    .map(|s| s.content.chars().count())
                    .sum();
                if line_width == 0 {
                    1u16
                } else {
                    ((line_width + visible_width - 1) / visible_width) as u16
                }
            })
            .sum()
    };

    if app.autoscroll {
        app.scroll = total_lines.saturating_sub(visible_height);
    } else {
        let max_scroll = total_lines.saturating_sub(visible_height);
        if app.scroll > max_scroll {
            app.scroll = max_scroll;
        }
    }

    let scroll_status = if app.autoscroll {
        " [AUTOSCROLL] "
    } else {
        " [MANUAL SCROLL 🔒] "
    };
    f.render_widget(Clear, chat_chunks[0]);
    f.render_widget(
        Paragraph::new(history_text)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(format!(" Conversation History{} ", scroll_status))
                    .border_style(if !app.autoscroll {
                        Style::default().fg(Color::Yellow)
                    } else {
                        Style::default()
                    }),
            )
            .wrap(Wrap { trim: true })
            .scroll((app.scroll, 0)),
        chat_chunks[0],
    );

    // Spinner-Animation berechnen
    let spinner_frames = ["", "", "", "", "", "", "", "", "", ""];
    let frame_idx = (app.start_time.elapsed().as_millis() / 100) as usize % spinner_frames.len();
    let input_title = if app.is_loading {
        format!(" {} AI is thinking... ", spinner_frames[frame_idx])
    } else {
        " > Input ".into()
    };

    // Build multiline input text with selection and cursor support
    let input_chars: Vec<char> = app.input.chars().collect();
    let cursor_pos = app.cursor_pos.min(input_chars.len());
    let selection_range = app.get_selection_range();
    
    let cursor_style = Style::default().add_modifier(Modifier::REVERSED);
    let selection_style = Style::default()
        .bg(Color::Blue)
        .fg(Color::White);

    // Pre-calculate which line the cursor is on by counting newlines before cursor
    let cursor_line = input_chars.iter()
        .take(cursor_pos)
        .filter(|&&c| c == '\n')
        .count();
    
    // Build lines with proper selection and cursor handling
    let mut lines = Vec::new();
    let mut current_line_spans = Vec::new();
    let mut char_index = 0;

    for ch in input_chars.iter().chain(std::iter::once(&'\0')) {
        let is_newline = *ch == '\n';
        let is_end = *ch == '\0';
        
        if !is_newline && !is_end {
            // Determine style for this character
            let mut style = Style::default();
            let mut is_cursor = false;
            
            if char_index == cursor_pos && app.cursor_visible {
                style = cursor_style;
                is_cursor = true;
            }
            
            if let Some((sel_start, sel_end)) = selection_range {
                if char_index >= sel_start && char_index < sel_end {
                    style = selection_style;
                    if char_index == cursor_pos && app.cursor_visible {
                        // Cursor within selection - combine styles
                        style = selection_style.add_modifier(Modifier::REVERSED);
                    }
                }
            }
            
            if is_cursor || style.bg.is_some() || style.add_modifier != Modifier::empty() {
                current_line_spans.push(Span::styled(ch.to_string(), style));
            } else {
                current_line_spans.push(Span::raw(ch.to_string()));
            }
            
            char_index += 1;
        } else if is_newline {
            // End current line and start new one
            if current_line_spans.is_empty() {
                current_line_spans.push(Span::raw(" "));
            }
            lines.push(Line::from(current_line_spans.clone()));
            current_line_spans.clear();
            char_index += 1;
        } else {
            // End of input (\0 marker)
            // If cursor is at the end, ensure line is visible even when cursor blinks
            if char_index == cursor_pos {
                if app.cursor_visible {
                    current_line_spans.push(Span::styled(" ", cursor_style));
                } else {
                    // Placeholder space to keep empty line visible when cursor is invisible
                    current_line_spans.push(Span::raw(" "));
                }
            }
            
            // Add final line if it has content or if it's the first line
            if !current_line_spans.is_empty() {
                lines.push(Line::from(current_line_spans));
            } else if lines.is_empty() {
                // Ensure at least one line exists
                lines.push(Line::from(vec![Span::raw(" ")]));
            }
            break;
        }
    }

    // Calculate input scrolling to keep cursor visible  
    // Do NOT modify app state during rendering - only calculate local scroll offset
    let visible_input_height = input_height.saturating_sub(2) as usize; // Subtract borders
    let total_input_lines = lines.len();
    
    // Calculate the optimal scroll position based on cursor location
    let mut scroll_offset = app.input_scroll;
    
    if cursor_line < scroll_offset as usize {
        // Cursor is above visible area, scroll up
        scroll_offset = cursor_line as u16;
    } else if cursor_line >= (scroll_offset as usize + visible_input_height) {
        // Cursor is below visible area, scroll down
        scroll_offset = (cursor_line + 1).saturating_sub(visible_input_height) as u16;
    }
    
    // Clamp scroll to valid range
    let max_input_scroll = total_input_lines.saturating_sub(visible_input_height);
    scroll_offset = scroll_offset.min(max_input_scroll as u16);

    let input_text = Text::from(lines);

    f.render_widget(
        Paragraph::new(input_text)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(input_title)
                    .border_style(if app.is_loading {
                        Style::default().fg(Color::Yellow)
                    } else {
                        Style::default()
                    }),
            )
            .wrap(Wrap { trim: false })
            .scroll((scroll_offset, 0)),
        chat_chunks[1],
    );
    let mut status = format!(
        " C-q: Quit | C-o: Settings | C-S-c: Copy | C-S-v: Paste | S-Enter: Newline | PgUp/Dn: Scroll | C-↑↓: Model [{}] ",
        selected_model
    );
    if app.debug_keys {
        let max_scroll = total_lines.saturating_sub(visible_height);
        let last_key = app.debug_last_key.as_deref().unwrap_or("-");
        status.push_str(&format!(
            "| Scroll: {}/{} | Render: {} | Key: {} ",
            app.scroll, max_scroll, app.render_count, last_key
        ));
    }
    f.render_widget(
        Paragraph::new(status).style(Style::default().bg(Color::White).fg(Color::Black)),
        root_layout[2],
    );
    
    // Render settings dialog if open
    if app.show_settings_dialog {
        render_settings_dialog(f, app);
    }
}

/// Renders the settings dialog popup.
///
/// This function displays a centered popup dialog that allows users to configure
/// application settings, primarily the syntax highlighting theme. The dialog shows
/// all available themes grouped by dark and light categories.
///
/// # Arguments
///
/// * `f` - The frame to render into
/// * `app` - The application state containing current settings and selection
///
/// # Navigation
///
/// - Up/Down arrows: Navigate through themes
/// - Enter: Apply selected theme and close dialog
/// - Esc/q: Close dialog without changes
fn render_settings_dialog(f: &mut Frame, app: &App) {
    let area = f.area();
    
    // Create a centered popup area (60% width, 70% height)
    let popup_width = (area.width * 60) / 100;
    let popup_height = (area.height * 70) / 100;
    let popup_x = (area.width.saturating_sub(popup_width)) / 2;
    let popup_y = (area.height.saturating_sub(popup_height)) / 2;
    
    let popup_area = ratatui::layout::Rect {
        x: popup_x,
        y: popup_y,
        width: popup_width,
        height: popup_height,
    };
    
    // Clear the popup area first
    f.render_widget(Clear, popup_area);
    
    // Build the settings content
    let themes = crate::app::SyntaxTheme::all();
    let mut items: Vec<ListItem> = Vec::new();
    
    // Add header
    items.push(ListItem::new(Line::from(vec![
        Span::styled("Settings", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)),
    ])));
    items.push(ListItem::new(""));
    
    // Add theme section header
    items.push(ListItem::new(Line::from(vec![
        Span::styled("Syntax Highlighting Theme:", Style::default().fg(Color::Yellow)),
    ])));
    items.push(ListItem::new(""));
    
    // Add dark themes
    items.push(ListItem::new(Line::from(vec![
        Span::styled("  Dark Themes:", Style::default().fg(Color::Gray)),
    ])));
    for (idx, theme) in themes.iter().enumerate() {
        if !theme.is_dark() {
            break;
        }
        
        let is_selected = idx == app.settings_selection;
        let is_current = theme == &app.settings.syntax_theme;
        
        let mut label = format!("    {}", theme.display_name());
        if is_current {
            label.push_str("");
        }
        
        let style = if is_selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else if is_current {
            Style::default().fg(Color::Green)
        } else {
            Style::default()
        };
        
        items.push(ListItem::new(label).style(style));
    }
    
    items.push(ListItem::new(""));
    
    // Add light themes
    items.push(ListItem::new(Line::from(vec![
        Span::styled("  Light Themes:", Style::default().fg(Color::Gray)),
    ])));
    
    for (idx, theme) in themes.iter().enumerate() {
        if theme.is_dark() {
            continue;
        }
        
        let is_selected = idx == app.settings_selection;
        let is_current = theme == &app.settings.syntax_theme;
        
        let mut label = format!("    {}", theme.display_name());
        if is_current {
            label.push_str("");
        }
        
        let style = if is_selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else if is_current {
            Style::default().fg(Color::Green)
        } else {
            Style::default()
        };
        
        items.push(ListItem::new(label).style(style));
    }
    
    items.push(ListItem::new(""));
    items.push(ListItem::new(Line::from(vec![
        Span::styled("↑↓: Navigate  Enter: Apply  Esc/q: Close", 
            Style::default().fg(Color::DarkGray)),
    ])));
    
    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Cyan))
                .title(" Settings ")
        );
    
    f.render_widget(list, popup_area);
}

/// Parses conversation history and converts it into a formatted Ratatui Text object.
///
/// This function processes the raw conversation history string and applies syntax
/// highlighting for markdown elements, particularly code blocks. It uses regex
/// pattern matching to identify code blocks and delegates regular text processing
/// to [`process_styled_text`].
///
/// # Arguments
///
/// * `history` - The raw conversation history string containing user and AI messages
///
/// # Returns
///
/// A formatted [`Text`] object ready for rendering with Ratatui, containing:
/// - Syntax-highlighted code blocks with language-specific borders
/// - Styled user/AI message labels with appropriate colors
/// - Markdown formatting for headers and emphasis
///
/// # Code Block Processing
///
/// Code blocks are detected using the regex pattern:
/// ```regex
/// (?s)```(?P<lang>\w+)?\n(?P<code>.*?)```
/// ```
///
/// Each code block is rendered with:
/// - Language-specific header: `┌── rust ──`
/// - Yellow-colored borders and prefixes
/// - Preserved indentation and formatting
/// - Consistent visual separation from regular text
///
/// # Performance
///
/// Uses single-pass regex processing with efficient string slicing to minimize
/// allocations. The function handles large conversation histories gracefully
/// without significant performance degradation.
///
/// # Example Input/Output
///
/// ```text
/// Input: "YOU: Hello\n\nAI: Here's some code:\n\n```rust\nfn main() {}\n```"
/// Output: Formatted Text with colored labels and bordered code block
/// ```
pub fn parse_history<'a>(history: &'a str, theme_name: &str) -> Text<'a> {
    // Updated regex to allow optional whitespace after language name
    let code_block_re = Regex::new(r"(?s)```(?P<lang>\w+)?\s*\n(?P<code>.*?)```").unwrap();
    let mut text = Text::default();
    let mut last_match_end = 0;

    for caps in code_block_re.captures_iter(history) {
        let full_match = caps.get(0).unwrap();
        if full_match.start() > last_match_end {
            process_styled_text(&history[last_match_end..full_match.start()], &mut text);
        }
        let lang = caps.name("lang").map_or("code", |m| m.as_str());
        let code_content = caps.name("code").map_or("", |m| m.as_str());

        // Header with language name
        text.push_line(Line::from(Span::styled(
            format!(" ┌── {} ──", lang),
            Style::default().fg(Color::Yellow),
        )));
        
        // Syntax-highlighted code lines
        let highlighted_lines = highlight_code_block(code_content, lang, theme_name);
        for line in highlighted_lines {
            text.push_line(line);
        }
        
        // Footer
        text.push_line(Line::from(Span::styled(
            " └──────────",
            Style::default().fg(Color::Yellow),
        )));
        last_match_end = full_match.end();
    }
    if last_match_end < history.len() {
        process_styled_text(&history[last_match_end..], &mut text);
    }
    text
}

/// Processes regular text line-by-line and applies GitHub-flavored markdown styling.
///
/// This function handles comprehensive markdown formatting using pulldown-cmark parser,
/// supporting all major GitHub markdown features including inline formatting, lists,
/// blockquotes, headers, and special text markers like task lists.
///
/// # Arguments
///
/// * `text` - The raw text string to be processed and styled
/// * `target` - Mutable reference to the Text object where styled content is appended
///
/// # Supported Markdown Features
///
/// - **Inline Formatting**:
///   - Bold: `**text**` or `__text__`
///   - Italic: `*text*` or `_text_`
///   - Strikethrough: `~~text~~`
///   - Inline code: `` `code` ``
///   - Combined formatting: `***bold italic***`
///
/// - **Headers**: All levels `#` to `######`
///
/// - **Lists**:
///   - Unordered lists: `-`, `*`, `+`
///   - Ordered lists: `1.`, `2.`, etc.
///   - Task lists: `- [ ]` and `- [x]`
///
/// - **Blockquotes**: `> quote text`
///
/// - **Horizontal Rules**: `---`, `***`, `___`
///
/// - **Links**: `[text](url)` - displays the link text
///
/// # Special Labels
///
/// - `YOU:` prefix styled in bold magenta
/// - `AI:` prefix styled in bold cyan
/// 
/// # Color Scheme
///
/// - Headers: White with bold modifier (levels indicated by bullet style)
/// - Bold text: Bold modifier
/// - Italic text: Italic modifier  
/// - Strikethrough: Crossed-out modifier
/// - Inline code: Yellow foreground with dim modifier
/// - User labels: Magenta with bold modifier
/// - AI labels: Cyan with bold modifier
/// - Blockquotes: Green with italic modifier
/// - Links: Blue with underline modifier
/// - List items: Bullet points in appropriate colors
///
/// # Side Effects
///
/// Appends styled content directly to the provided `target` Text object,
/// allowing for incremental building of complex formatted documents.
pub fn process_styled_text<'a>(text: &'a str, target: &mut Text<'a>) {
    for line in text.lines() {
        // Check for special YOU:/AI: labels first
        if line.starts_with("YOU:") {
            let rest = if line.len() > 4 { &line[4..] } else { "" };
            let mut spans: Vec<Span<'static>> = vec![
                Span::styled(
                    "YOU:".to_string(),
                    Style::default()
                        .fg(Color::Magenta)
                        .add_modifier(Modifier::BOLD),
                ),
            ];
            // Add the rest as-is (including leading space if present)
            if !rest.is_empty() {
                spans.push(Span::raw(rest.to_string()));
            }
            target.push_line(Line::from(spans));
            continue;
        } else if line.starts_with("AI:") {
            let rest = if line.len() > 3 { &line[3..] } else { "" };
            let mut spans: Vec<Span<'static>> = vec![
                Span::styled(
                    "AI: ".to_string(),
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
            ];
            // Add the rest as-is (including leading space if present)
            if !rest.is_empty() {
                spans.push(Span::raw(rest.to_string()));
            }
            target.push_line(Line::from(spans));
            continue;
        }

        // Parse the line as markdown
        let mut spans: Vec<Span<'static>> = Vec::new();
        parse_line_markdown(line, &mut spans);
        target.push_line(Line::from(spans));
    }
}

/// Parses a single line of markdown and converts it to styled spans.
///
/// Handles block-level markdown elements like headers, lists, blockquotes,
/// and horizontal rules, as well as inline formatting.
fn parse_line_markdown(line: &str, spans: &mut Vec<Span<'static>>) {
    let trimmed = line.trim();
    
    // Check for horizontal rule
    if trimmed == "---" || trimmed == "***" || trimmed == "___" {
        spans.push(Span::styled(
            "".repeat(40),
            Style::default().fg(Color::DarkGray),
        ));
        return;
    }

    // Check for headers (# to ######)
    if let Some(header_text) = trimmed.strip_prefix("######").map(|s| (6, s))
        .or_else(|| trimmed.strip_prefix("#####").map(|s| (5, s)))
        .or_else(|| trimmed.strip_prefix("####").map(|s| (4, s)))
        .or_else(|| trimmed.strip_prefix("###").map(|s| (3, s)))
        .or_else(|| trimmed.strip_prefix("##").map(|s| (2, s)))
        .or_else(|| trimmed.strip_prefix("#").map(|s| (1, s)))
    {
        let (_level, text) = header_text;
        // Use consistent bullet style for all headers to maintain compatibility
        let bullet = "";
        spans.push(Span::styled(
            format!("{}{}", bullet, text.trim()),
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ));
        return;
    }

    // Check for blockquote
    if let Some(quote_text) = trimmed.strip_prefix(">") {
        spans.push(Span::styled(
            "".to_string(),
            Style::default().fg(Color::Green),
        ));
        parse_inline_markdown(quote_text.trim(), spans, Style::default().fg(Color::Green).add_modifier(Modifier::ITALIC));
        return;
    }

    // Check for unordered list
    if let Some(list_text) = trimmed.strip_prefix("- ")
        .or_else(|| trimmed.strip_prefix("* "))
        .or_else(|| trimmed.strip_prefix("+ "))
    {
        // Check for task list
        if list_text.trim().starts_with("[ ]") {
            spans.push(Span::styled("".to_string(), Style::default().fg(Color::Yellow)));
            parse_inline_markdown(&list_text.trim()[3..].trim(), spans, Style::default());
        } else if list_text.trim().starts_with("[x]") || list_text.trim().starts_with("[X]") {
            spans.push(Span::styled("".to_string(), Style::default().fg(Color::Green)));
            parse_inline_markdown(&list_text.trim()[3..].trim(), spans, Style::default().add_modifier(Modifier::DIM));
        } else {
            spans.push(Span::styled("".to_string(), Style::default().fg(Color::Cyan)));
            parse_inline_markdown(list_text, spans, Style::default());
        }
        return;
    }

    // Check for ordered list
    if let Some(caps) = Regex::new(r"^(\d+)\.\s+(.*)$").unwrap().captures(trimmed) {
        let prefix = format!("{}. ", &caps[1]);
        let rest = caps[2].to_string();
        spans.push(Span::styled(
            prefix,
            Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
        ));
        parse_inline_markdown(&rest, spans, Style::default());
        return;
    }

    // Regular text with inline markdown
    parse_inline_markdown(line, spans, Style::default());
}

/// Parses inline markdown formatting within a text string.
///
/// Supports bold, italic, strikethrough, inline code, and links.
/// Uses pulldown-cmark for accurate CommonMark/GFM parsing.
/// Returns owned Span objects to avoid lifetime issues.
fn parse_inline_markdown(text: &str, spans: &mut Vec<Span<'static>>, base_style: Style) {
    let parser = Parser::new(text);
    let mut current_style = base_style;
    let mut style_stack = Vec::new();

    for event in parser {
        match event {
            Event::Text(t) => {
                spans.push(Span::styled(t.to_string(), current_style));
            }
            Event::Code(code) => {
                spans.push(Span::styled(
                    format!("`{}`", code),
                    base_style.fg(Color::Yellow).add_modifier(Modifier::DIM),
                ));
            }
            Event::Start(tag) => {
                style_stack.push(current_style);
                current_style = match tag {
                    Tag::Strong => current_style.add_modifier(Modifier::BOLD),
                    Tag::Emphasis => current_style.add_modifier(Modifier::ITALIC),
                    Tag::Strikethrough => current_style.add_modifier(Modifier::CROSSED_OUT),
                    Tag::Link { .. } => current_style.fg(Color::Blue).add_modifier(Modifier::UNDERLINED),
                    _ => current_style,
                };
            }
            Event::End(tag_end) => {
                if let Some(previous_style) = style_stack.pop() {
                    match tag_end {
                        TagEnd::Link => {
                            // For links, we've already shown the link text
                            // Skip the URL part as it's not useful in TUI
                        }
                        _ => {}
                    }
                    current_style = previous_style;
                }
            }
            Event::SoftBreak | Event::HardBreak => {
                // Breaks within inline text are handled by line processing
            }
            _ => {
                // Handle other events if needed
            }
        }
    }
}