revw 0.1.5

A vim-like TUI for managing notes and resources
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
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Paragraph, Wrap},
    Frame,
};

use crate::app::{App, FormatMode, InputMode};
use crate::rendering::{RelfEntry, RelfLineStyle};

// JSON syntax highlighting
fn highlight_json_line(line: &str) -> Vec<Span<'static>> {
    let mut spans = Vec::new();
    let mut chars = line.chars().peekable();
    let mut current = String::new();

    while let Some(ch) = chars.next() {
        match ch {
            '"' => {
                // Push accumulated text
                if !current.is_empty() {
                    spans.push(Span::styled(
                        current.clone(),
                        Style::default().fg(Color::Gray),
                    ));
                    current.clear();
                }

                // Start collecting string
                let mut string_content = String::from("\"");
                let mut escaped = false;

                while let Some(next_ch) = chars.next() {
                    string_content.push(next_ch);
                    if next_ch == '\\' && !escaped {
                        escaped = true;
                    } else if next_ch == '"' && !escaped {
                        break;
                    } else {
                        escaped = false;
                    }
                }

                // Determine if this is a key (followed by ':')
                let mut temp_chars = chars.clone();
                let mut is_key = false;
                while let Some(peek_ch) = temp_chars.next() {
                    if peek_ch == ':' {
                        is_key = true;
                        break;
                    } else if !peek_ch.is_whitespace() {
                        break;
                    }
                }

                let color = if is_key {
                    Color::Rgb(156, 220, 254) // Keys in light blue (VS Code style)
                } else {
                    Color::Rgb(206, 145, 120) // String values in orange/peach (VS Code style)
                };

                spans.push(Span::styled(
                    string_content,
                    Style::default().fg(color),
                ));
            }
            '{' | '}' | '[' | ']' => {
                if !current.is_empty() {
                    spans.push(Span::styled(
                        current.clone(),
                        Style::default().fg(Color::Gray),
                    ));
                    current.clear();
                }
                spans.push(Span::styled(
                    ch.to_string(),
                    Style::default().fg(Color::Rgb(255, 217, 102)), // Yellow/gold (VS Code style)
                ));
            }
            ':' | ',' => {
                if !current.is_empty() {
                    spans.push(Span::styled(
                        current.clone(),
                        Style::default().fg(Color::Gray),
                    ));
                    current.clear();
                }
                spans.push(Span::styled(
                    ch.to_string(),
                    Style::default().fg(Color::White),
                ));
            }
            't' | 'f' | 'n' => {
                // Check for true, false, null
                let peek_str: String = std::iter::once(ch)
                    .chain(chars.clone().take(4))
                    .collect();

                if peek_str.starts_with("true") || peek_str.starts_with("false") || peek_str.starts_with("null") {
                    if !current.is_empty() {
                        spans.push(Span::styled(
                            current.clone(),
                            Style::default().fg(Color::Gray),
                        ));
                        current.clear();
                    }

                    let keyword = if peek_str.starts_with("true") {
                        chars.nth(2); // skip 'r', 'u', 'e'
                        "true"
                    } else if peek_str.starts_with("false") {
                        chars.nth(3); // skip 'a', 'l', 's', 'e'
                        "false"
                    } else {
                        chars.nth(2); // skip 'u', 'l', 'l'
                        "null"
                    };

                    spans.push(Span::styled(
                        keyword.to_string(),
                        Style::default().fg(Color::Rgb(86, 156, 214)), // Purple/blue (VS Code style)
                    ));
                } else {
                    current.push(ch);
                }
            }
            '0'..='9' | '-' => {
                // Numbers
                let mut num = String::from(ch);
                while let Some(&next_ch) = chars.peek() {
                    if next_ch.is_ascii_digit() || next_ch == '.' || next_ch == 'e' || next_ch == 'E' || next_ch == '-' || next_ch == '+' {
                        num.push(chars.next().unwrap());
                    } else {
                        break;
                    }
                }

                if !current.is_empty() {
                    spans.push(Span::styled(
                        current.clone(),
                        Style::default().fg(Color::Gray),
                    ));
                    current.clear();
                }

                spans.push(Span::styled(
                    num,
                    Style::default().fg(Color::Rgb(181, 206, 168)), // Light green (VS Code style)
                ));
            }
            _ => {
                current.push(ch);
            }
        }
    }

    if !current.is_empty() {
        spans.push(Span::styled(
            current,
            Style::default().fg(Color::Gray),
        ));
    }

    if spans.is_empty() {
        spans.push(Span::styled(
            String::new(),
            Style::default().fg(Color::Gray),
        ));
    }

    spans
}

pub fn ui(f: &mut Frame, app: &mut App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(0), Constraint::Length(1)])
        .split(f.area());

    // Always render content and status bar
    if !app.editing_entry {
        render_content(f, app, chunks[0]);
    } else {
        // Render empty content area with border when overlay is active
        render_empty_content(f, app, chunks[0]);
    }
    render_status_bar(f, app, chunks[1]);

    // Render editing overlay on top if active
    if app.editing_entry {
        render_edit_overlay(f, app);
    }
}

fn render_empty_content(f: &mut Frame, app: &App, area: Rect) {
    // Render background cards with colors but no text when overlay is active
    let title = match &app.file_path {
        Some(path) => format!(" {} ", path.display()),
        None => String::new(),
    };

    let outer_block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .style(Style::default().fg(Color::DarkGray));

    let inner_area = outer_block.inner(area);
    f.render_widget(outer_block, area);

    // Render empty cards with background colors
    let num_entries = app.relf_entries.len();
    if num_entries == 0 {
        return;
    }

    let selected = app.selected_entry_index;
    let max_visible_cards = 5;
    let scroll_start = if selected < max_visible_cards {
        0
    } else {
        selected - max_visible_cards + 1
    };

    let visible_entries: Vec<(usize, &RelfEntry)> = app.relf_entries
        .iter()
        .enumerate()
        .skip(scroll_start)
        .take(max_visible_cards)
        .collect();

    if visible_entries.is_empty() {
        return;
    }

    let constraints: Vec<Constraint> = visible_entries
        .iter()
        .map(|_| Constraint::Min(3))
        .collect();

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(inner_area);

    // Render only background colors (no borders, no text)
    for (i, (_entry_idx, entry)) in visible_entries.iter().enumerate() {
        // Fill the entire card area with just background color
        let filler = Block::default()
            .style(Style::default().bg(entry.bg_color));
        f.render_widget(filler, chunks[i]);
    }
}

fn render_content(f: &mut Frame, app: &mut App, area: Rect) {
    // In View mode with entries, render as cards
    if app.format_mode == FormatMode::View && !app.relf_entries.is_empty() {
        render_relf_cards(f, app, area);
        return;
    }

    let inner_area = area.inner(Margin {
        horizontal: 1,
        vertical: 1,
    });
    // Update the app's notion of the current content width for accurate wrapping
    // Use inner area width (inside borders and margins)
    app.content_width = inner_area.width;
    // In View mode, disable horizontal scrolling entirely
    if app.format_mode == FormatMode::View {
        app.hscroll = 0;
    }
    // Remember actual visible height for correct scroll math elsewhere
    app.visible_height = inner_area.height;
    // Build visual (wrapped) lines and compute scroll bounds in visual rows
    let visual_lines = app.build_visual_lines();
    let lines_count = visual_lines.len() as u16;
    let visible_height = inner_area.height;
    let bottom_padding = 10u16; // Allow scrolling past end
    let padded_lines_count = lines_count + bottom_padding;
    app.max_scroll = padded_lines_count.saturating_sub(visible_height);

    let empty_line = String::new();
    let visible_content: Vec<_> = visual_lines
        .iter()
        .skip(app.scroll as usize)
        .chain(std::iter::repeat(&empty_line).take(bottom_padding as usize))
        .take(visible_height as usize)
        .collect();

    // Build content with cursor and horizontal viewport
    let content_text = {
        let w_cols = app.get_content_width() as usize;
        let off_cols = if app.format_mode == FormatMode::View {
            0
        } else {
            app.hscroll as usize
        };
        let mut lines_vec: Vec<Line> = Vec::new();

        for (line_idx, s) in visible_content.iter().enumerate() {
            let actual_idx = line_idx + app.scroll as usize;
            let slice = app.slice_columns(s, off_cols, w_cols);

            // Build spans for the line with search highlighting
            let mut spans: Vec<Span> = Vec::new();
            let line_style = if app.format_mode == FormatMode::View {
                app.relf_visual_styles.get(actual_idx)
            } else {
                None
            };

            if !app.search_query.is_empty() && app.format_mode == FormatMode::Edit {
                // In Edit mode with search: apply JSON highlighting first, then add search backgrounds
                let json_spans = highlight_json_line(&slice);

                // Merge JSON highlighting with search match backgrounds
                let query_lower = app.search_query.to_lowercase();
                let line_lower = slice.to_lowercase();
                let mut result_spans: Vec<Span> = Vec::new();
                let mut char_pos = 0;

                for json_span in json_spans {
                    let span_text = json_span.content.to_string();
                    let span_len = span_text.len();
                    let span_start = char_pos;
                    let span_end = char_pos + span_len;

                    // Check if this span overlaps with any search match
                    let mut last_split = 0;

                    while let Some(match_pos) = line_lower[span_start..span_end].find(&query_lower) {
                        let abs_match_pos = span_start + match_pos;

                        if abs_match_pos < span_start + last_split {
                            break;
                        }

                        let rel_match_start = abs_match_pos - span_start;
                        let rel_match_end = (abs_match_pos + app.search_query.len()).min(span_end) - span_start;

                        // Check if this is the current match
                        let is_current_match = app
                            .current_match_index
                            .and_then(|idx| app.search_matches.get(idx))
                            .map(|(line, col)| *line == actual_idx && *col == abs_match_pos + off_cols)
                            .unwrap_or(false);

                        let bg_color = if is_current_match {
                            Color::Rgb(255, 255, 150) // Light yellow
                        } else {
                            Color::Rgb(100, 180, 200) // Light cyan
                        };

                        // Add text before match (with original JSON color)
                        if rel_match_start > last_split {
                            result_spans.push(Span::styled(
                                span_text[last_split..rel_match_start].to_string(),
                                json_span.style,
                            ));
                        }

                        // Add matched text with background
                        result_spans.push(Span::styled(
                            span_text[rel_match_start..rel_match_end].to_string(),
                            json_span.style.bg(bg_color),
                        ));

                        last_split = rel_match_end;
                    }

                    // Add remaining text from this span
                    if last_split < span_len {
                        result_spans.push(Span::styled(
                            span_text[last_split..].to_string(),
                            json_span.style,
                        ));
                    }

                    char_pos = span_end;
                }

                spans = result_spans;
            } else if !app.search_query.is_empty() {
                // View mode with search: original search highlighting logic
                let query_lower = app.search_query.to_lowercase();
                let line_lower = slice.to_lowercase();
                let mut last_pos = 0;

                while let Some(match_pos) = line_lower[last_pos..].find(&query_lower) {
                    let actual_pos = last_pos + match_pos;

                    // Add text before match
                    if actual_pos > last_pos {
                        spans.push(Span::styled(
                            slice[last_pos..actual_pos].to_string(),
                            apply_relf_style(Style::default().fg(Color::Gray), line_style),
                        ));
                    }

                    // Check if this is the current match
                    let is_current_match = app
                        .current_match_index
                        .and_then(|idx| app.search_matches.get(idx))
                        .map(|(line, col)| *line == actual_idx && *col == actual_pos + off_cols)
                        .unwrap_or(false);

                    // Add highlighted match
                    let match_end = actual_pos + app.search_query.len();
                    let highlight_style = if is_current_match {
                        Style::default().fg(Color::Black).bg(Color::Yellow) // Current match
                    } else {
                        Style::default().fg(Color::Black).bg(Color::Cyan) // Other matches
                    };

                    spans.push(Span::styled(
                        slice[actual_pos..match_end.min(slice.len())].to_string(),
                        highlight_style,
                    ));

                    last_pos = match_end;
                }

                // Add remaining text after last match
                if last_pos < slice.len() {
                    spans.push(Span::styled(
                        slice[last_pos..].to_string(),
                        apply_relf_style(Style::default().fg(Color::Gray), line_style),
                    ));
                }
            } else {
                // No search highlighting
                if app.format_mode == FormatMode::Edit {
                    // Apply JSON syntax highlighting in Edit mode
                    spans = highlight_json_line(&slice);
                } else {
                    // In View mode, use plain text with line style
                    spans.push(Span::styled(
                        slice.clone(),
                        apply_relf_style(Style::default().fg(Color::Gray), line_style),
                    ));
                }
            }

            // Add cursor if needed
            if app.format_mode == FormatMode::Edit
                && (app.input_mode == InputMode::Insert || app.input_mode == InputMode::Normal)
                && app.show_cursor
            {
                if actual_idx == app.content_cursor_line {
                    let cursor_char_pos = app.content_cursor_col;
                    let prefix_cols = app.prefix_display_width(s, cursor_char_pos);
                    if prefix_cols >= off_cols && prefix_cols < off_cols + w_cols {
                        // Insert cursor while preserving existing highlighting
                        let insert_col_in_view = prefix_cols - off_cols;

                        // Calculate character position across all spans
                        let mut char_count = 0;
                        let mut cursor_inserted = false;
                        let mut new_spans: Vec<Span> = Vec::new();

                        for span in spans.iter() {
                            let span_text = span.content.to_string();
                            let span_chars: Vec<char> = span_text.chars().collect();
                            let span_len = span_chars.len();

                            if !cursor_inserted && char_count + span_len >= insert_col_in_view {
                                // Cursor belongs in this span
                                let pos_in_span = insert_col_in_view - char_count;

                                // Split span at cursor position
                                if pos_in_span == 0 {
                                    // Cursor at start
                                    new_spans.push(Span::styled("│".to_string(), span.style));
                                    new_spans.push(span.clone());
                                } else if pos_in_span >= span_len {
                                    // Cursor at end
                                    new_spans.push(span.clone());
                                    new_spans.push(Span::styled("│".to_string(), span.style));
                                } else {
                                    // Cursor in middle
                                    let before: String = span_chars[..pos_in_span].iter().collect();
                                    let after: String = span_chars[pos_in_span..].iter().collect();

                                    new_spans.push(Span::styled(before, span.style));
                                    new_spans.push(Span::styled("│".to_string(), span.style));
                                    new_spans.push(Span::styled(after, span.style));
                                }
                                cursor_inserted = true;
                            } else {
                                new_spans.push(span.clone());
                            }

                            char_count += span_len;
                        }

                        // If cursor wasn't inserted yet, add it at the end
                        if !cursor_inserted {
                            let last_style = spans.last().map(|s| s.style).unwrap_or_default();
                            new_spans.push(Span::styled("│".to_string(), last_style));
                        }

                        spans = new_spans;
                    }
                }
            }

            if spans.is_empty() {
                spans.push(Span::styled(
                    String::new(),
                    apply_relf_style(Style::default(), line_style),
                ));
            }

            lines_vec.push(Line::from(spans));
        }

        lines_vec
    };

    let title = match &app.file_path {
        Some(path) => format!(" {} ", path.display()),
        None => String::new(),
    };

    let content = Paragraph::new(content_text).block(
        Block::default()
            .title(title)
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .style(Style::default().fg(Color::DarkGray).bg(Color::Rgb(26, 28, 34))),
    );

    f.render_widget(content, area);
}

fn render_relf_cards(f: &mut Frame, app: &mut App, area: Rect) {
    let title = match &app.file_path {
        Some(path) => format!(" {} ", path.display()),
        None => String::new(),
    };

    let outer_block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .style(Style::default().fg(Color::DarkGray));

    let inner_area = outer_block.inner(area);
    f.render_widget(outer_block, area);

    app.content_width = inner_area.width;
    app.visible_height = inner_area.height;
    app.hscroll = 0;

    let num_entries = app.relf_entries.len();
    if num_entries == 0 {
        return;
    }

    // Use selected_entry_index to determine which entries to show
    let selected = app.selected_entry_index;

    // Limit number of visible cards
    let max_visible_cards = 5;

    // Calculate scroll window to keep selected entry visible
    let scroll_start = if selected < max_visible_cards {
        0
    } else {
        selected - max_visible_cards + 1
    };

    // Get visible entries
    let visible_entries: Vec<(usize, &RelfEntry)> = app.relf_entries
        .iter()
        .enumerate()
        .skip(scroll_start)
        .take(max_visible_cards)
        .collect();

    if visible_entries.is_empty() {
        return;
    }

    // Create constraints with Min for flexible heights
    let constraints: Vec<Constraint> = visible_entries
        .iter()
        .map(|_| Constraint::Min(3)) // Minimum 3 lines per card
        .collect();

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(inner_area);

    // Render each card with Block border
    for (i, (entry_idx, entry)) in visible_entries.iter().enumerate() {
        let is_selected = *entry_idx == selected;

        let mut lines = Vec::new();

        // First line is bold title (with search highlight)
        if let Some(first) = entry.lines.first() {
            if !app.search_query.is_empty() {
                lines.push(highlight_search_in_line(
                    first,
                    &app.search_query,
                    Style::default()
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD),
                ));
            } else {
                lines.push(Line::styled(
                    first.as_str(),
                    Style::default()
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD),
                ));
            }
        }

        // Remaining lines (with search highlight)
        for (idx, line) in entry.lines.iter().enumerate().skip(1) {
            let fg = if idx == entry.lines.len() - 1 {
                Color::Rgb(160, 200, 120)
            } else if line.starts_with("http") {
                Color::Rgb(120, 170, 255)
            } else {
                Color::Gray
            };

            if !app.search_query.is_empty() {
                lines.push(highlight_search_in_line(
                    line,
                    &app.search_query,
                    Style::default().fg(fg),
                ));
            } else {
                lines.push(Line::styled(line.as_str(), Style::default().fg(fg)));
            }
        }

        // Highlight selected card with different border color
        let border_style = if is_selected {
            Style::default().fg(Color::Yellow).bg(entry.bg_color)
        } else {
            Style::default().bg(entry.bg_color)
        };

        let card = Paragraph::new(lines)
            .wrap(Wrap { trim: false })
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .style(border_style),
            );

        f.render_widget(card, chunks[i]);
    }
}

fn highlight_search_in_line<'a>(line: &'a str, query: &str, base_style: Style) -> Line<'a> {
    let query_lower = query.to_lowercase();
    let line_lower = line.to_lowercase();
    let mut spans = Vec::new();
    let mut byte_pos = 0;

    while byte_pos < line_lower.len() {
        if let Some(match_pos) = line_lower[byte_pos..].find(&query_lower) {
            let actual_byte_pos = byte_pos + match_pos;

            // Add text before match (ensuring char boundaries)
            if actual_byte_pos > byte_pos && line.is_char_boundary(byte_pos) && line.is_char_boundary(actual_byte_pos) {
                spans.push(Span::styled(
                    line[byte_pos..actual_byte_pos].to_string(),
                    base_style,
                ));
            }

            // Add highlighted match (ensuring char boundaries)
            let match_end_byte = actual_byte_pos + query_lower.len();
            if line.is_char_boundary(actual_byte_pos) && match_end_byte <= line.len() {
                let safe_end = if line.is_char_boundary(match_end_byte) {
                    match_end_byte
                } else {
                    // Find next char boundary
                    (match_end_byte..=line.len())
                        .find(|&i| line.is_char_boundary(i))
                        .unwrap_or(line.len())
                };

                spans.push(Span::styled(
                    line[actual_byte_pos..safe_end].to_string(),
                    Style::default().fg(Color::Black).bg(Color::Cyan),
                ));
                byte_pos = safe_end;
            } else {
                byte_pos = match_end_byte;
            }

            // Ensure we're on a char boundary
            while byte_pos < line.len() && !line.is_char_boundary(byte_pos) {
                byte_pos += 1;
            }
        } else {
            break;
        }
    }

    // Add remaining text after last match
    if byte_pos < line.len() && line.is_char_boundary(byte_pos) {
        spans.push(Span::styled(line[byte_pos..].to_string(), base_style));
    }

    if spans.is_empty() {
        spans.push(Span::styled(line.to_string(), base_style));
    }

    Line::from(spans)
}

fn apply_relf_style(mut style: Style, line_style: Option<&RelfLineStyle>) -> Style {
    if let Some(ls) = line_style {
        if let Some(fg) = ls.fg {
            style = style.fg(fg);
        }
        if let Some(bg) = ls.bg {
            style = style.bg(bg);
        }
        if ls.bold {
            style = style.add_modifier(Modifier::BOLD);
        }
    }
    style
}

fn render_edit_overlay(f: &mut Frame, app: &App) {
    // Create a centered popup area
    let area = f.area();

    let popup_width = area.width.min(80);
    // Increase height to show more of the background: use 70% of screen height or calculated size
    let calculated_height = app.edit_buffer.len() as u16 + 4;
    let max_height = (area.height * 7) / 10; // 70% of screen height
    let popup_height = calculated_height.max(max_height.min(area.height - 4));

    let popup_area = Rect {
        x: (area.width.saturating_sub(popup_width)) / 2,
        y: (area.height.saturating_sub(popup_height)) / 2,
        width: popup_width,
        height: popup_height,
    };

    // Determine if editing INSIDE or OUTSIDE entry
    let title = if app.edit_buffer.len() == 2 {
        " Edit INSIDE Entry "
    } else {
        " Edit OUTSIDE Entry "
    };

    // Render the popup as a single card with rounded borders
    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .style(Style::default().bg(Color::Rgb(30, 30, 35)).fg(Color::White));

    f.render_widget(block.clone(), popup_area);

    let inner_area = block.inner(popup_area);

    // Render each field as simple lines with color-based selection
    let mut lines = Vec::new();
    for (i, field) in app.edit_buffer.iter().enumerate() {
        let is_selected = i == app.edit_field_index;

        let style = if is_selected {
            if app.edit_insert_mode {
                Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)
            }
        } else {
            Style::default().fg(Color::Gray)
        };

        // Add cursor in insert mode or field editing mode
        let display_text = if is_selected && (app.edit_insert_mode || app.edit_field_editing_mode) {
            // Convert character position to byte index
            let char_count = field.chars().count();
            let cursor_char_pos = app.edit_cursor_pos.min(char_count);
            let byte_pos = if cursor_char_pos == 0 {
                0
            } else if cursor_char_pos >= char_count {
                field.len()
            } else {
                field.char_indices().nth(cursor_char_pos).map(|(i, _)| i).unwrap_or(field.len())
            };

            let mut text = field.clone();
            text.insert(byte_pos, '|');
            text
        } else {
            field.clone()
        };

        lines.push(Line::styled(display_text, style));

        // Add blank line between fields
        if i < app.edit_buffer.len() - 1 {
            lines.push(Line::from(""));
        }
    }

    let content = Paragraph::new(lines).wrap(Wrap { trim: false });
    f.render_widget(content, inner_area);
}

fn render_status_bar(f: &mut Frame, app: &App, area: Rect) {
    let mut spans = Vec::new();

    // Left side: status message
    if !app.status_message.is_empty() {
        let status_text = format!(" {} ", app.status_message);
        spans.push(Span::styled(
            status_text,
            Style::default().fg(Color::Cyan),
        ));
    }

    // Right side: cursor position in Edit mode
    if app.format_mode == FormatMode::Edit {
        let current_line = app.content_cursor_line + 1;
        let current_col = app.content_cursor_col + 1;
        let position_text = format!("{}:{} ", current_line, current_col);

        // Calculate padding to right-align
        let status_width = if !app.status_message.is_empty() {
            app.status_message.len() + 2
        } else {
            0
        };
        let position_width = position_text.len();
        let available_width = area.width as usize;

        if available_width > status_width + position_width {
            let padding_width = available_width - status_width - position_width;
            spans.push(Span::raw(" ".repeat(padding_width)));
        }

        spans.push(Span::styled(
            position_text,
            Style::default().fg(Color::DarkGray),
        ));
    }

    let status_widget = Paragraph::new(Line::from(spans))
        .alignment(Alignment::Left);

    f.render_widget(status_widget, area);
}