pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
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
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
use ratatui::{
    Frame,
    prelude::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap},
};
use unicode_width::UnicodeWidthStr;

use crate::i18n;
use crate::state::AppState;
use crate::theme::theme;

/// Minimum width for announcement modal.
const MODAL_MIN_WIDTH: u16 = 40;
/// Maximum width ratio for announcement modal.
const MODAL_MAX_WIDTH_RATIO: u16 = 3;
/// Maximum width divisor for announcement modal.
const MODAL_MAX_WIDTH_DIVISOR: u16 = 4;
/// Minimum height for announcement modal.
const MODAL_MIN_HEIGHT: u16 = 6;
/// Maximum height for announcement modal.
const MODAL_MAX_HEIGHT: u16 = 25;
/// Height padding for announcement modal.
const MODAL_HEIGHT_PADDING: u16 = 4;
/// Border width for announcement modal.
const BORDER_WIDTH: u16 = 2;
/// Number of header lines.
const HEADER_LINES: u16 = 2;
/// Number of footer lines.
const FOOTER_LINES: u16 = 1;
/// Total header and footer lines.
const TOTAL_HEADER_FOOTER_LINES: u16 = HEADER_LINES + FOOTER_LINES;
/// Left/right padding for content.
const CONTENT_PADDING: u16 = 2;
/// Buffer lines between content and footer.
const CONTENT_FOOTER_BUFFER: u16 = 2;

/// What: Calculate the number of display lines needed for content with wrapping.
///
/// Inputs:
/// - `content`: Markdown content string
/// - `available_width`: Width available for content (inside borders and padding)
///
/// Output:
/// - Number of display lines the content will take after wrapping
///
/// Details:
/// - Calculates how many lines each source line will wrap to
/// - Accounts for word wrapping at the available width
fn calculate_wrapped_lines(content: &str, available_width: u16) -> u16 {
    if content.trim().is_empty() {
        return 1;
    }

    let width = available_width.max(1) as usize;
    let mut total_lines: u16 = 0;

    for line in content.lines() {
        if line.is_empty() {
            total_lines = total_lines.saturating_add(1);
        } else {
            // Calculate wrapped line count for this source line using display width
            let line_width = line.width();
            #[allow(clippy::cast_possible_truncation)]
            let wrapped = line_width.div_ceil(width).max(1).min(u16::MAX as usize) as u16;
            total_lines = total_lines.saturating_add(wrapped);
        }
    }

    total_lines.max(1)
}

/// What: Calculate the maximum width needed for content lines.
///
/// Inputs:
/// - `content`: Markdown content string
/// - `max_width`: Maximum width to consider
///
/// Output:
/// - Maximum line width needed (capped at `max_width`)
///
/// Details:
/// - Finds the longest line in the content
/// - Accounts for markdown formatting that might add characters
fn calculate_content_width(content: &str, max_width: u16) -> u16 {
    let mut max_line_len = 0;
    for line in content.lines() {
        // Remove markdown formatting for width calculation
        let cleaned = line
            .replace("**", "")
            .replace("## ", "")
            .replace("### ", "")
            .replace("# ", "");
        // Use display width instead of byte length for multi-byte UTF-8 characters
        let line_width = cleaned.trim().width();
        #[allow(clippy::cast_possible_truncation)]
        let line_len = line_width.min(u16::MAX as usize) as u16;
        max_line_len = max_line_len.max(line_len);
    }
    max_line_len.min(max_width).max(MODAL_MIN_WIDTH)
}

/// What: Calculate the modal rectangle dimensions and position centered in the given area.
///
/// Inputs:
/// - `area`: Full screen area to center the modal within
/// - `content`: Content string to size the modal for
/// - `app`: Application state for i18n (to get footer text)
///
/// Output:
/// - `Rect` representing the modal's position and size
///
/// Details:
/// - Width: Based on max of content width and footer width, with min/max constraints
/// - Height: Based on content lines + header + footer, with min/max constraints
/// - Modal is centered both horizontally and vertically
fn calculate_modal_rect(area: Rect, content: &str, app: &crate::state::AppState) -> Rect {
    // Calculate max available width first
    let max_available_width = (area.width * MODAL_MAX_WIDTH_RATIO) / MODAL_MAX_WIDTH_DIVISOR;
    let content_width = calculate_content_width(content, max_available_width);

    // Calculate footer text width dynamically using display width
    let footer_text = crate::i18n::t(app, "app.modals.announcement.footer_hint");
    let footer_text_display_width = footer_text.width();
    #[allow(clippy::cast_possible_truncation)]
    let footer_text_width = footer_text_display_width.min(u16::MAX as usize) as u16;
    let footer_width = footer_text_width + CONTENT_PADDING * 2;

    // Calculate modal width (max of content width and footer width, with padding + borders)
    let required_width = content_width.max(footer_width) + CONTENT_PADDING * 2 + BORDER_WIDTH;
    let modal_width = required_width.min(max_available_width).max(MODAL_MIN_WIDTH);

    // Calculate content area width (inside borders and padding)
    let content_area_width = modal_width.saturating_sub(BORDER_WIDTH + CONTENT_PADDING * 2);

    // Calculate wrapped content lines based on available width
    let content_lines = calculate_wrapped_lines(content, content_area_width);

    // Calculate modal height (content + header + footer + buffer + borders)
    let modal_height =
        (content_lines + TOTAL_HEADER_FOOTER_LINES + CONTENT_FOOTER_BUFFER + BORDER_WIDTH)
            .min(area.height.saturating_sub(MODAL_HEIGHT_PADDING))
            .min(MODAL_MAX_HEIGHT)
            .clamp(MODAL_MIN_HEIGHT, MODAL_MAX_HEIGHT);

    // Center the modal
    let x = area.x + (area.width.saturating_sub(modal_width)) / 2;
    let y = area.y + (area.height.saturating_sub(modal_height)) / 2;

    Rect {
        x,
        y,
        width: modal_width,
        height: modal_height,
    }
}

/// What: Detect URLs in text and return vector of (`start_pos`, `end_pos`, `url_string`).
///
/// Inputs:
/// - `text`: Text to search for URLs.
///
/// Output:
/// - Vector of tuples: (`start_byte_pos`, `end_byte_pos`, `url_string`).
///
/// Details:
/// - Detects http://, https://, and www. URLs.
/// - Returns positions in byte offsets for string slicing.
fn detect_urls(text: &str) -> Vec<(usize, usize, String)> {
    let mut urls = Vec::new();
    let text_bytes = text.as_bytes();
    let mut i = 0;

    while i < text_bytes.len() {
        // Look for http:// or https://
        let is_http = i + 7 < text_bytes.len() && &text_bytes[i..i + 7] == b"http://";
        let is_https = i + 8 < text_bytes.len() && &text_bytes[i..i + 8] == b"https://";

        if is_http || is_https {
            let offset = if is_https { 8 } else { 7 };
            if let Some(end) = find_url_end(text, i + offset) {
                let url = text[i..end].to_string();
                urls.push((i, end, url));
                i = end;
                continue;
            }
        }

        // Look for www. (must be at word boundary)
        if i + 4 < text_bytes.len()
            && (i == 0 || text_bytes[i - 1].is_ascii_whitespace())
            && &text_bytes[i..i + 4] == b"www."
            && let Some(end) = find_url_end(text, i + 4)
        {
            let url = format!("https://{}", &text[i..end]);
            urls.push((i, end, url));
            i = end;
            continue;
        }
        i += 1;
    }

    urls
}

/// What: Find the end position of a URL in text.
///
/// Inputs:
/// - `text`: Text containing the URL.
/// - `start`: Starting byte position of the URL.
///
/// Output:
/// - `Some(usize)` with end byte position, or `None` if URL is invalid.
///
/// Details:
/// - URL ends at whitespace, closing parenthesis, or end of string.
/// - Removes trailing punctuation that's not part of the URL.
fn find_url_end(text: &str, start: usize) -> Option<usize> {
    let mut end = start;
    let text_bytes = text.as_bytes();

    // Find the end of the URL (stop at whitespace or closing paren)
    while end < text_bytes.len() {
        let byte = text_bytes[end];
        if byte.is_ascii_whitespace() || byte == b')' || byte == b']' || byte == b'>' {
            break;
        }
        end += 1;
    }

    // Remove trailing punctuation that's likely not part of the URL
    while end > start {
        let last_char = text_bytes[end - 1];
        if matches!(last_char, b'.' | b',' | b';' | b':' | b'!' | b'?') {
            end -= 1;
        } else {
            break;
        }
    }

    if end > start { Some(end) } else { None }
}

/// What: Parse markdown content into styled lines for display.
///
/// Inputs:
/// - `content`: Markdown content string
/// - `scroll`: Scroll offset in lines
/// - `max_lines`: Maximum number of lines to display
/// - `url_positions`: Mutable vector to track URL positions for click detection
/// - `content_rect`: Rectangle where content is rendered (for position tracking)
/// - `start_y`: Starting Y coordinate for content (after header)
///
/// Output:
/// - Vector of styled lines for rendering
///
/// Details:
/// What: Parse a header line and return styled line.
///
/// Inputs:
/// - `trimmed`: Trimmed line text
///
/// Output:
/// - `Some(Line)` if line is a header, `None` otherwise
///
/// Details:
/// - Handles #, ##, and ### headers with appropriate styling
fn parse_header_line(trimmed: &str) -> Option<Line<'static>> {
    let th = theme();
    if trimmed.starts_with("# ") {
        let text = trimmed.strip_prefix("# ").unwrap_or(trimmed).to_string();
        Some(Line::from(Span::styled(
            text,
            Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
        )))
    } else if trimmed.starts_with("## ") {
        let text = trimmed.strip_prefix("## ").unwrap_or(trimmed).to_string();
        Some(Line::from(Span::styled(
            text,
            Style::default().fg(th.mauve),
        )))
    } else if trimmed.starts_with("### ") {
        let text = trimmed.strip_prefix("### ").unwrap_or(trimmed).to_string();
        Some(Line::from(Span::styled(
            text,
            Style::default()
                .fg(th.subtext1)
                .add_modifier(Modifier::BOLD),
        )))
    } else {
        None
    }
}

/// What: Parse a code block line.
///
/// Inputs:
/// - `trimmed`: Trimmed line text
///
/// Output:
/// - `Some(Line)` if line is a code block marker, `None` otherwise
///
/// Details:
/// - Styles code block markers with subtext0 color
fn parse_code_block_line(trimmed: &str) -> Option<Line<'static>> {
    if trimmed.starts_with("```") {
        let th = theme();
        Some(Line::from(Span::styled(
            trimmed.to_string(),
            Style::default().fg(th.subtext0),
        )))
    } else {
        None
    }
}

/// What: Parse text into segments (URLs, bold, plain text).
///
/// Inputs:
/// - `trimmed`: Trimmed line text
///
/// Output:
/// - Vector of segments: (`text`, `style`, `is_url`, `url_string`)
///
/// Details:
/// - Detects URLs and bold markers (**text**)
/// - Returns styled segments for rendering
fn parse_text_segments(trimmed: &str) -> Vec<(String, Style, bool, Option<String>)> {
    let th = theme();
    let urls = detect_urls(trimmed);
    let mut segments: Vec<(String, Style, bool, Option<String>)> = Vec::new();
    let mut i = 0usize;
    let trimmed_bytes = trimmed.as_bytes();

    while i < trimmed_bytes.len() {
        // Check if we're at a URL position
        if let Some((url_start, url_end, url)) = urls.iter().find(|(s, _e, _)| *s == i) {
            // Add text before URL
            if *url_start > i {
                segments.push((
                    trimmed[i..*url_start].to_string(),
                    Style::default().fg(th.text),
                    false,
                    None,
                ));
            }
            // Add URL segment
            segments.push((
                trimmed[*url_start..*url_end].to_string(),
                Style::default()
                    .fg(th.mauve)
                    .add_modifier(Modifier::UNDERLINED | Modifier::BOLD),
                true,
                Some(url.clone()),
            ));
            i = *url_end;
            continue;
        }

        // Check for bold markers
        if let Some(pos) = trimmed[i..].find("**") {
            let pos = i + pos;
            if pos > i {
                segments.push((
                    trimmed[i..pos].to_string(),
                    Style::default().fg(th.text),
                    false,
                    None,
                ));
            }
            // Find closing **
            if let Some(end_pos) = trimmed[pos + 2..].find("**") {
                let end_pos = pos + 2 + end_pos;
                segments.push((
                    trimmed[pos + 2..end_pos].to_string(),
                    Style::default()
                        .fg(th.lavender)
                        .add_modifier(Modifier::BOLD),
                    false,
                    None,
                ));
                i = end_pos + 2;
            } else {
                // Unclosed bold, treat rest as bold
                segments.push((
                    trimmed[pos + 2..].to_string(),
                    Style::default()
                        .fg(th.lavender)
                        .add_modifier(Modifier::BOLD),
                    false,
                    None,
                ));
                break;
            }
            continue;
        }

        // No more special markers, add remaining text
        if i < trimmed.len() {
            segments.push((
                trimmed[i..].to_string(),
                Style::default().fg(th.text),
                false,
                None,
            ));
        }
        break;
    }

    if segments.is_empty() {
        segments.push((
            trimmed.to_string(),
            Style::default().fg(th.text),
            false,
            None,
        ));
    }

    segments
}

/// What: Build wrapped lines from text segments with URL position tracking.
///
/// Inputs:
/// - `segments`: Text segments with styles
/// - `content_width`: Available width for wrapping
/// - `content_rect`: Content rectangle for URL position calculation
/// - `start_y`: Starting Y position
/// - `url_positions`: Mutable vector to track URL positions
///
/// Output:
/// - Tuple of (wrapped lines, final Y position)
///
/// Details:
/// - Wraps text at word boundaries
/// - Tracks URL positions for click detection
fn build_wrapped_lines_from_segments(
    segments: Vec<(String, Style, bool, Option<String>)>,
    content_width: usize,
    content_rect: Rect,
    start_y: u16,
    url_positions: &mut Vec<(u16, u16, u16, String)>,
) -> (Vec<Line<'static>>, u16) {
    let mut lines = Vec::new();
    let mut current_line_spans: Vec<Span<'static>> = Vec::new();
    let mut current_line_width = 0usize;
    let mut line_y = start_y;

    for (text, style, is_url, url_string) in segments {
        let words: Vec<&str> = text.split_whitespace().collect();

        for word in words {
            let word_width = word.width();
            let separator_width = usize::from(current_line_width > 0);
            let test_width = current_line_width + separator_width + word_width;

            if test_width > content_width && !current_line_spans.is_empty() {
                // Wrap to new line
                lines.push(Line::from(current_line_spans.clone()));
                current_line_spans.clear();
                current_line_width = 0;
                line_y += 1;
            }

            // Track URL position if this is a URL
            if is_url && let Some(ref url) = url_string {
                let url_x = content_rect.x
                    + u16::try_from(current_line_width + separator_width).unwrap_or(u16::MAX);
                let url_width = u16::try_from(word_width).unwrap_or(u16::MAX);
                url_positions.push((url_x, line_y, url_width, url.clone()));
            }

            if current_line_width > 0 {
                current_line_spans.push(Span::raw(" "));
                current_line_width += 1;
            }

            current_line_spans.push(Span::styled(word.to_string(), style));
            current_line_width += word_width;
        }
    }

    if !current_line_spans.is_empty() {
        lines.push(Line::from(current_line_spans));
    }

    (lines, line_y + 1)
}

/// What: Parse markdown content into styled lines with wrapping and URL detection.
///
/// Inputs:
/// - `content`: Markdown content string
/// - `scroll`: Scroll offset (lines)
/// - `max_lines`: Maximum number of lines to render
/// - `url_positions`: Mutable vector to track URL positions for click detection
/// - `content_rect`: Content rectangle for width calculation and URL positioning
/// - `start_y`: Starting Y position for rendering
///
/// Output:
/// - Vector of styled lines for rendering
///
/// Details:
/// - Basic markdown parsing: headers (#), bold (**text**), code blocks (triple backticks)
/// - Detects and styles URLs with mauve color, underlined and bold
/// - Tracks URL positions for click detection
fn parse_markdown(
    content: &str,
    scroll: u16,
    max_lines: usize,
    url_positions: &mut Vec<(u16, u16, u16, String)>,
    content_rect: Rect,
    start_y: u16,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    let content_lines: Vec<&str> = content.lines().collect();
    let scroll_usize = scroll as usize;
    let start_idx = scroll_usize.min(content_lines.len());
    // Take up to max_lines starting from start_idx
    let lines_to_take = max_lines.min(content_lines.len().saturating_sub(start_idx));
    let mut current_y = start_y;
    let content_width = content_rect.width as usize;

    for line in content_lines.iter().skip(start_idx).take(lines_to_take) {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            lines.push(Line::from(""));
            current_y += 1;
            continue;
        }

        // Check for headers
        if let Some(header_line) = parse_header_line(trimmed) {
            lines.push(header_line);
            current_y += 1;
            continue;
        }

        // Check for code blocks
        if let Some(code_line) = parse_code_block_line(trimmed) {
            lines.push(code_line);
            current_y += 1;
            continue;
        }

        // Regular text - handle URLs and bold markers
        let segments = parse_text_segments(trimmed);
        let (wrapped_lines, final_y) = build_wrapped_lines_from_segments(
            segments,
            content_width,
            content_rect,
            current_y,
            url_positions,
        );
        lines.extend(wrapped_lines);
        current_y = final_y;
    }

    lines
}

/// What: Build footer line with keybindings hint.
///
/// Inputs:
/// - `app`: Application state for i18n
///
/// Output:
/// - `Line<'static>` containing the formatted footer hint
///
/// Details:
/// - Shows keybindings for marking as read and dismissing
fn build_footer(app: &AppState) -> Line<'static> {
    let th = theme();
    let footer_text = i18n::t(app, "app.modals.announcement.footer_hint");
    Line::from(Span::styled(footer_text, Style::default().fg(th.overlay1)))
}

/// What: Render the announcement modal with markdown content.
///
/// Inputs:
/// - `f`: Frame to render into
/// - `app`: Mutable application state (records rect)
/// - `area`: Full screen area used to center the modal
/// - `title`: Title to display in the modal header
/// - `content`: Markdown content to display
/// - `scroll`: Scroll offset in lines
///
/// Output:
/// - Draws the announcement modal and updates rect for hit-testing
///
/// Details:
/// - Centers modal, renders markdown content with basic formatting
pub fn render_announcement(
    f: &mut Frame,
    app: &mut AppState,
    area: Rect,
    title: &str,
    content: &str,
    scroll: u16,
) {
    let rect = calculate_modal_rect(area, content, app);
    app.announcement_rect = Some((rect.x, rect.y, rect.width, rect.height));

    let th = theme();

    // Calculate areas: footer needs 1 line for text, buffer is positional gap above
    let footer_height = FOOTER_LINES; // Footer text only
    let footer_total_height = footer_height + CONTENT_FOOTER_BUFFER; // Footer + buffer space
    let inner_height = rect.height.saturating_sub(BORDER_WIDTH); // Height inside borders (top + bottom)
    // Content area should fit: header (2 lines) + content + buffer + footer (2 lines)
    // So content area = inner_height - footer_total_height (header + content share the remaining space)
    let content_area_height = inner_height.saturating_sub(footer_total_height); // Area for header + content

    // Content rect (inside borders, for header + content, excluding footer area)
    // Ensure minimum height for header + at least 1 line of content
    let min_content_height = HEADER_LINES + 1;
    let content_rect = Rect {
        x: rect.x + 1,                                       // Inside left border
        y: rect.y + 1,                                       // Inside top border
        width: rect.width.saturating_sub(2),                 // Account for left + right borders
        height: content_area_height.max(min_content_height), // At least header + 1 line for content
    };

    // Footer rect at the bottom (inside borders, footer text only)
    // Position footer after content area + buffer gap, ensuring it's inside the modal
    let footer_y = rect.y + 1 + content_area_height + CONTENT_FOOTER_BUFFER;
    // Ensure footer fits within the modal bounds
    let footer_available_height =
        inner_height.saturating_sub(content_area_height + CONTENT_FOOTER_BUFFER);
    let footer_rect = Rect {
        x: rect.x + 1, // Inside left border
        y: footer_y.min(rect.y + rect.height.saturating_sub(footer_height + 1)), // Ensure it fits
        width: rect.width.saturating_sub(2), // Account for left + right borders
        height: footer_height.min(footer_available_height),
    };

    // Clear URL positions at start of rendering
    app.announcement_urls.clear();

    // Build content lines (header + content, no footer)
    let mut content_lines = Vec::new();
    content_lines.push(Line::from(Span::styled(
        title.to_string(),
        Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
    )));
    content_lines.push(Line::from(""));

    // Available height for actual content (after header)
    let available_height = content_area_height.saturating_sub(HEADER_LINES);
    let max_content_lines = available_height.max(1) as usize;
    let start_y = content_rect.y + HEADER_LINES;
    let parsed_content = parse_markdown(
        content,
        scroll,
        max_content_lines,
        &mut app.announcement_urls,
        content_rect,
        start_y,
    );
    content_lines.extend(parsed_content);

    // Render modal border first
    f.render_widget(Clear, rect);
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(th.subtext0));
    // Render border block (empty content, just borders)
    let empty_paragraph = Paragraph::new(vec![]).block(block);
    f.render_widget(empty_paragraph, rect);

    // Render content area (no borders, borders already drawn)
    let content_paragraph = Paragraph::new(content_lines).wrap(Wrap { trim: true });
    f.render_widget(content_paragraph, content_rect);

    // Render footer separately at fixed bottom position (always visible)
    // Buffer space is provided by the positional gap between content_rect and footer_rect
    let footer_lines = vec![build_footer(app)];
    let footer_paragraph = Paragraph::new(footer_lines);
    f.render_widget(footer_paragraph, footer_rect);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    /// What: Verify URL detection for https:// URLs.
    ///
    /// Inputs:
    /// - Text containing https:// URLs.
    ///
    /// Output:
    /// - Returns correct URL positions and strings.
    ///
    /// Details:
    /// - Should detect https:// URLs and return byte positions.
    fn test_detect_urls_https() {
        let text = "Visit https://example.com for more info";
        let urls = detect_urls(text);
        assert_eq!(urls.len(), 1);
        assert_eq!(urls[0].0, 6); // start position (after "Visit ")
        assert_eq!(urls[0].1, 25); // end position (exclusive, after "https://example.com")
        assert_eq!(urls[0].2, "https://example.com");
    }

    #[test]
    /// What: Verify URL detection for http:// URLs.
    ///
    /// Inputs:
    /// - Text containing http:// URLs.
    ///
    /// Output:
    /// - Returns correct URL positions and strings.
    ///
    /// Details:
    /// - Should detect http:// URLs and return byte positions.
    fn test_detect_urls_http() {
        let text = "Visit http://example.com for more info";
        let urls = detect_urls(text);
        assert_eq!(urls.len(), 1);
        assert_eq!(urls[0].2, "http://example.com");
    }

    #[test]
    /// What: Verify URL detection for www. URLs.
    ///
    /// Inputs:
    /// - Text containing www. URLs.
    ///
    /// Output:
    /// - Returns URLs with https:// prefix added.
    ///
    /// Details:
    /// - www. URLs should be converted to https:// URLs.
    fn test_detect_urls_www() {
        let text = "Visit www.example.com for more info";
        let urls = detect_urls(text);
        assert_eq!(urls.len(), 1);
        assert_eq!(urls[0].2, "https://www.example.com");
    }

    #[test]
    /// What: Verify URL detection with multiple URLs in one line.
    ///
    /// Inputs:
    /// - Text containing multiple URLs.
    ///
    /// Output:
    /// - Returns all detected URLs with correct positions.
    ///
    /// Details:
    /// - Should detect all URLs in the text.
    fn test_detect_urls_multiple() {
        let text = "Visit https://example.com and http://test.org for more";
        let urls = detect_urls(text);
        assert_eq!(urls.len(), 2);
        assert_eq!(urls[0].2, "https://example.com");
        assert_eq!(urls[1].2, "http://test.org");
    }

    #[test]
    /// What: Verify URL detection with trailing punctuation.
    ///
    /// Inputs:
    /// - Text with URLs followed by punctuation.
    ///
    /// Output:
    /// - URLs should exclude trailing punctuation.
    ///
    /// Details:
    /// - Trailing punctuation (., ,, ;, :, !, ?) should be trimmed.
    fn test_detect_urls_trailing_punctuation() {
        let text = "Visit https://example.com. Also http://test.org!";
        let urls = detect_urls(text);
        assert_eq!(urls.len(), 2);
        assert_eq!(urls[0].2, "https://example.com");
        assert_eq!(urls[1].2, "http://test.org");
    }

    #[test]
    /// What: Verify URL detection at end of text.
    ///
    /// Inputs:
    /// - Text ending with a URL (no trailing whitespace).
    ///
    /// Output:
    /// - Should detect URL correctly.
    ///
    /// Details:
    /// - URLs at end of text should be detected without trailing whitespace.
    fn test_detect_urls_end_of_text() {
        let text = "Visit https://example.com";
        let urls = detect_urls(text);
        assert_eq!(urls.len(), 1);
        assert_eq!(urls[0].2, "https://example.com");
    }

    #[test]
    /// What: Verify URL detection with parentheses termination.
    ///
    /// Inputs:
    /// - Text with URLs inside parentheses.
    ///
    /// Output:
    /// - URLs should stop at closing parenthesis.
    ///
    /// Details:
    /// - Closing parenthesis should terminate URL detection.
    fn test_detect_urls_parentheses() {
        let text = "Visit (https://example.com) for more";
        let urls = detect_urls(text);
        assert_eq!(urls.len(), 1);
        assert_eq!(urls[0].2, "https://example.com");
    }

    #[test]
    /// What: Verify URL detection with empty text.
    ///
    /// Inputs:
    /// - Empty string.
    ///
    /// Output:
    /// - Returns empty vector.
    ///
    /// Details:
    /// - Empty text should return no URLs.
    fn test_detect_urls_empty() {
        let text = "";
        let urls = detect_urls(text);
        assert!(urls.is_empty());
    }

    #[test]
    /// What: Verify URL detection with no URLs.
    ///
    /// Inputs:
    /// - Text without any URLs.
    ///
    /// Output:
    /// - Returns empty vector.
    ///
    /// Details:
    /// - Text without URLs should return empty vector.
    fn test_detect_urls_none() {
        let text = "This is just regular text without any URLs";
        let urls = detect_urls(text);
        assert!(urls.is_empty());
    }

    #[test]
    /// What: Verify `find_url_end` function behavior.
    ///
    /// Inputs:
    /// - Text with URL and various termination conditions.
    ///
    /// Output:
    /// - Returns correct end position.
    ///
    /// Details:
    /// - Should find end position correctly for different scenarios.
    fn test_find_url_end() {
        // URL with space termination - start is after "https://" (position 8)
        let text = "https://example.com more text";
        assert_eq!(find_url_end(text, 8), Some(19)); // "example.com" ends at position 19

        // URL with parenthesis termination
        let text2 = "https://example.com)";
        assert_eq!(find_url_end(text2, 8), Some(19)); // "example.com" ends before ')'

        // URL with trailing punctuation - should trim the trailing period
        let text3 = "https://example.com.";
        assert_eq!(find_url_end(text3, 8), Some(19)); // "example.com" (period trimmed)

        // URL at end of string
        let text4 = "https://example.com";
        assert_eq!(find_url_end(text4, 8), Some(19)); // "example.com" ends at position 19
    }

    #[test]
    /// What: Verify header parsing for H1 headers.
    ///
    /// Inputs:
    /// - Text starting with "# ".
    ///
    /// Output:
    /// - Returns Some(Line) with styled header.
    ///
    /// Details:
    /// - H1 headers should be parsed and styled correctly.
    fn test_parse_header_line_h1() {
        let line = "# Main Title";
        let result = parse_header_line(line);
        assert!(result.is_some());
        let line_result = result.expect("should parse H1 header");
        assert_eq!(line_result.spans.len(), 1);
        assert_eq!(line_result.spans[0].content.as_ref(), "Main Title");
    }

    #[test]
    /// What: Verify header parsing for H2 headers.
    ///
    /// Inputs:
    /// - Text starting with "## ".
    ///
    /// Output:
    /// - Returns Some(Line) with styled header.
    ///
    /// Details:
    /// - H2 headers should be parsed and styled correctly.
    fn test_parse_header_line_h2() {
        let line = "## Section Title";
        let result = parse_header_line(line);
        assert!(result.is_some());
        let line_result = result.expect("should parse H2 header");
        assert_eq!(line_result.spans.len(), 1);
        assert_eq!(line_result.spans[0].content.as_ref(), "Section Title");
    }

    #[test]
    /// What: Verify header parsing for H3 headers.
    ///
    /// Inputs:
    /// - Text starting with "### ".
    ///
    /// Output:
    /// - Returns Some(Line) with styled header.
    ///
    /// Details:
    /// - H3 headers should be parsed and styled correctly.
    fn test_parse_header_line_h3() {
        let line = "### Subsection Title";
        let result = parse_header_line(line);
        assert!(result.is_some());
        let line_result = result.expect("should parse H3 header");
        assert_eq!(line_result.spans.len(), 1);
        assert_eq!(line_result.spans[0].content.as_ref(), "Subsection Title");
    }

    #[test]
    /// What: Verify header parsing for non-header lines.
    ///
    /// Inputs:
    /// - Text that is not a header.
    ///
    /// Output:
    /// - Returns None.
    ///
    /// Details:
    /// - Non-header lines should return None.
    fn test_parse_header_line_non_header() {
        let line = "This is not a header";
        let result = parse_header_line(line);
        assert!(result.is_none());

        let line2 = "#Not a header (no space)";
        let result2 = parse_header_line(line2);
        assert!(result2.is_none());
    }

    #[test]
    /// What: Verify code block parsing.
    ///
    /// Inputs:
    /// - Text starting with triple backticks.
    ///
    /// Output:
    /// - Returns Some(Line) with styled code block marker.
    ///
    /// Details:
    /// - Code block markers should be parsed and styled correctly.
    fn test_parse_code_block_line() {
        let line = "```rust";
        let result = parse_code_block_line(line);
        assert!(result.is_some());
        let line_result = result.expect("should parse code block");
        assert_eq!(line_result.spans.len(), 1);
        assert_eq!(line_result.spans[0].content.as_ref(), "```rust");

        let line2 = "```";
        let result2 = parse_code_block_line(line2);
        assert!(result2.is_some());
    }

    #[test]
    /// What: Verify code block parsing for non-code-block lines.
    ///
    /// Inputs:
    /// - Text that is not a code block marker.
    ///
    /// Output:
    /// - Returns None.
    ///
    /// Details:
    /// - Non-code-block lines should return None.
    fn test_parse_code_block_line_non_code() {
        let line = "This is not a code block";
        let result = parse_code_block_line(line);
        assert!(result.is_none());
    }

    #[test]
    /// What: Verify line wrapping calculation for empty content.
    ///
    /// Inputs:
    /// - Empty string.
    ///
    /// Output:
    /// - Returns 1 line (minimum).
    ///
    /// Details:
    /// - Empty content should return at least 1 line.
    fn test_calculate_wrapped_lines_empty() {
        let result = calculate_wrapped_lines("", 40);
        assert_eq!(result, 1);
    }

    #[test]
    /// What: Verify line wrapping calculation for single line content.
    ///
    /// Inputs:
    /// - Single line of text.
    ///
    /// Output:
    /// - Returns correct number of wrapped lines.
    ///
    /// Details:
    /// - Short lines should not wrap, long lines should wrap.
    fn test_calculate_wrapped_lines_single_line() {
        // Short line should not wrap
        let result = calculate_wrapped_lines("Short line", 40);
        assert_eq!(result, 1);

        // Long line should wrap
        let long_line = "This is a very long line that should wrap when the width is limited";
        let result2 = calculate_wrapped_lines(long_line, 20);
        assert!(result2 > 1);
    }

    #[test]
    /// What: Verify line wrapping calculation for multi-line content.
    ///
    /// Inputs:
    /// - Multi-line text content.
    ///
    /// Output:
    /// - Returns correct total wrapped lines.
    ///
    /// Details:
    /// - Each line should be wrapped independently.
    fn test_calculate_wrapped_lines_multi_line() {
        let content = "Line one\nLine two\nLine three";
        let result = calculate_wrapped_lines(content, 40);
        assert_eq!(result, 3);

        let content2 = "Line one\n\nLine two";
        let result2 = calculate_wrapped_lines(content2, 40);
        assert_eq!(result2, 3); // Empty line counts as 1
    }

    #[test]
    /// What: Verify line wrapping calculation with Unicode characters.
    ///
    /// Inputs:
    /// - Text containing Unicode/multi-byte characters.
    ///
    /// Output:
    /// - Returns correct wrapped lines using display width.
    ///
    /// Details:
    /// - Should use Unicode width for proper wrapping.
    fn test_calculate_wrapped_lines_unicode() {
        // Unicode characters have different display widths
        let content = "测试中文";
        let result = calculate_wrapped_lines(content, 4);
        // Each Chinese character is typically 2 display width units
        assert!(result >= 1);
    }

    #[test]
    /// What: Verify content width calculation for empty content.
    ///
    /// Inputs:
    /// - Empty string.
    ///
    /// Output:
    /// - Returns minimum width.
    ///
    /// Details:
    /// - Empty content should return minimum width.
    fn test_calculate_content_width_empty() {
        let result = calculate_content_width("", 100);
        assert_eq!(result, MODAL_MIN_WIDTH);
    }

    #[test]
    /// What: Verify content width calculation for single line.
    ///
    /// Inputs:
    /// - Single line of text.
    ///
    /// Output:
    /// - Returns correct content width.
    ///
    /// Details:
    /// - Should calculate width based on longest line.
    fn test_calculate_content_width_single_line() {
        let content = "Short line";
        let result = calculate_content_width(content, 100);
        assert_eq!(result, 10.max(MODAL_MIN_WIDTH));
    }

    #[test]
    /// What: Verify content width calculation with markdown formatting.
    ///
    /// Inputs:
    /// - Text with markdown formatting characters.
    ///
    /// Output:
    /// - Should remove markdown formatting for width calculation.
    ///
    /// Details:
    /// - Markdown markers (**, ##, etc.) should be removed before calculating width.
    fn test_calculate_content_width_markdown() {
        let content = "## Header with **bold** text";
        let result = calculate_content_width(content, 100);
        // Should remove "## " and "**" markers, but result is clamped to MODAL_MIN_WIDTH
        // "Header with bold text" is 22 chars, but MODAL_MIN_WIDTH is 40
        assert_eq!(result, MODAL_MIN_WIDTH); // Should be clamped to minimum width
    }

    #[test]
    /// What: Verify content width calculation respects max width.
    ///
    /// Inputs:
    /// - Very long line of text.
    ///
    /// Output:
    /// - Returns width capped at `max_width`.
    ///
    /// Details:
    /// - Should not exceed the provided `max_width` parameter.
    fn test_calculate_content_width_max() {
        let content = "This is a very long line that exceeds the maximum width limit";
        let max_width = 30;
        let result = calculate_content_width(content, max_width);
        assert_eq!(result, max_width.max(MODAL_MIN_WIDTH));
    }
}