kimun-notes 0.11.0

A terminal-based notes application
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
use std::sync::Arc;

use kimun_core::NoteVault;
use kimun_core::nfs::VaultPath;
use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent};
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph};

use crate::components::event_state::EventState;
use crate::components::events::{AppEvent, AppTx};
use crate::components::file_list::{SortField, SortOrder};
use crate::keys::action_shortcuts::ActionShortcuts;
use crate::keys::{KeyBindings, key_event_to_combo};
use crate::settings::themes::Theme;

// ---------------------------------------------------------------------------
// BacklinkEntry
// ---------------------------------------------------------------------------

/// A single backlink entry with preloaded context.
#[derive(Debug, Clone)]
pub struct BacklinkEntry {
    pub path: VaultPath,
    pub title: String,
    pub filename: String,
    /// The paragraph in this note that contains the link to the current note.
    pub context: String,
    /// Full note text, loaded when backlinks are fetched.
    pub full_text: Option<String>,
}

// ---------------------------------------------------------------------------
// ExpandState (private)
// ---------------------------------------------------------------------------

#[derive(Clone, Copy, PartialEq)]
enum ExpandState {
    Collapsed,
    Context,
    Full,
}

// ---------------------------------------------------------------------------
// BacklinksPanel
// ---------------------------------------------------------------------------

pub struct BacklinksPanel {
    entries: Vec<BacklinkEntry>,
    expand_states: Vec<ExpandState>,
    list_state: ListState,
    loading: bool,
    current_note: VaultPath,
    sort_field: SortField,
    sort_order: SortOrder,
    vault: Arc<NoteVault>,
    key_bindings: KeyBindings,
    /// Scroll offset for full-expanded content view.
    content_scroll: usize,
    /// Maximum scroll offset (computed during render).
    content_scroll_max: usize,
}

impl BacklinksPanel {
    pub fn new(vault: Arc<NoteVault>, key_bindings: KeyBindings) -> Self {
        Self {
            entries: Vec::new(),
            expand_states: Vec::new(),
            list_state: ListState::default(),
            loading: false,
            current_note: VaultPath::empty(),
            sort_field: SortField::Name,
            sort_order: SortOrder::Ascending,
            vault,
            key_bindings,
            content_scroll: 0,
            content_scroll_max: 0,
        }
    }

    // ── Helpers ─────────────────────────────────────────────────────────

    /// Returns true if the selected entry is in full-expand mode (content takes
    /// the whole panel, up/down scrolls content).
    fn is_full_expanded(&self) -> bool {
        self.list_state
            .selected()
            .and_then(|i| self.expand_states.get(i))
            .is_some_and(|s| *s == ExpandState::Full)
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub fn selected_path(&self) -> Option<&VaultPath> {
        self.list_state
            .selected()
            .and_then(|i| self.entries.get(i))
            .map(|e| &e.path)
    }

    // ── Loading ─────────────────────────────────────────────────────────

    /// Begin loading backlinks for `note_path`. Clears existing state, sets
    /// `loading = true`, and spawns a background task that sends
    /// `AppEvent::BacklinksLoaded` when finished.
    pub fn load(&mut self, note_path: VaultPath, tx: AppTx) {
        self.entries.clear();
        self.expand_states.clear();
        self.list_state.select(None);
        self.loading = true;
        self.current_note = note_path.clone();
        self.content_scroll = 0;
        self.content_scroll_max = 0;

        let vault = Arc::clone(&self.vault);
        tokio::spawn(async move {
            let entries = load_backlinks(&vault, &note_path).await;
            let _ = tx.send(AppEvent::BacklinksLoaded(entries));
        });
    }

    /// Called when the background task completes. Stores the entries, applies
    /// the current sort, and initialises expand states.
    pub fn on_loaded(&mut self, entries: Vec<BacklinkEntry>) {
        self.entries = entries;
        self.apply_sort();
        self.expand_states = vec![ExpandState::Collapsed; self.entries.len()];
        self.loading = false;
        if !self.entries.is_empty() {
            self.list_state.select(Some(0));
        }
    }

    /// Sort `entries` (and their parallel `expand_states`) by the active
    /// sort field and order.
    pub fn apply_sort(&mut self) {
        let field = self.sort_field;
        let order = self.sort_order;

        // Build index permutation so we can reorder expand_states in sync.
        let mut indices: Vec<usize> = (0..self.entries.len()).collect();
        indices.sort_by(|&a, &b| {
            let cmp = match field {
                SortField::Name => self.entries[a]
                    .filename
                    .to_lowercase()
                    .cmp(&self.entries[b].filename.to_lowercase()),
                SortField::Title => self.entries[a]
                    .title
                    .to_lowercase()
                    .cmp(&self.entries[b].title.to_lowercase()),
            };
            match order {
                SortOrder::Ascending => cmp,
                SortOrder::Descending => cmp.reverse(),
            }
        });

        let sorted_entries: Vec<BacklinkEntry> =
            indices.iter().map(|&i| self.entries[i].clone()).collect();
        let sorted_states: Vec<ExpandState> = if self.expand_states.len() == self.entries.len() {
            indices.iter().map(|&i| self.expand_states[i]).collect()
        } else {
            vec![ExpandState::Collapsed; sorted_entries.len()]
        };

        self.entries = sorted_entries;
        self.expand_states = sorted_states;
    }

    // ── Input handling ──────────────────────────────────────────────────

    pub fn handle_key(&mut self, key: &KeyEvent, tx: &AppTx) -> EventState {
        // Check for action shortcuts first.
        if let Some(combo) = key_event_to_combo(key) {
            match self.key_bindings.get_action(&combo) {
                Some(ActionShortcuts::CycleSortField) => {
                    self.sort_field = self.sort_field.cycle();
                    self.apply_sort();
                    self.expand_states = vec![ExpandState::Collapsed; self.entries.len()];
                    return EventState::Consumed;
                }
                Some(ActionShortcuts::SortReverseOrder) => {
                    self.sort_order = self.sort_order.toggle();
                    self.apply_sort();
                    self.expand_states = vec![ExpandState::Collapsed; self.entries.len()];
                    return EventState::Consumed;
                }
                // FocusSidebar / FocusEditor are intercepted at the
                // EditorScreen level for directional navigation.
                Some(ActionShortcuts::FollowLink) => {
                    if let Some(path) = self.selected_path().cloned() {
                        tx.send(AppEvent::OpenPath(path)).ok();
                    }
                    return EventState::Consumed;
                }
                _ => {}
            }
        }

        match key.code {
            KeyCode::Up => {
                if self.is_full_expanded() {
                    self.content_scroll = self.content_scroll.saturating_sub(1);
                } else {
                    self.move_selection(-1);
                }
                EventState::Consumed
            }
            KeyCode::Down => {
                if self.is_full_expanded() {
                    // Increment freely; render() clamps to content_scroll_max.
                    self.content_scroll += 1;
                } else {
                    self.move_selection(1);
                }
                EventState::Consumed
            }
            KeyCode::Enter => {
                self.toggle_expand();
                EventState::Consumed
            }
            KeyCode::Esc => EventState::NotConsumed,
            _ => EventState::NotConsumed,
        }
    }

    fn move_selection(&mut self, delta: i32) {
        if self.entries.is_empty() {
            return;
        }
        let current = self.list_state.selected().unwrap_or(0) as i32;
        let next = (current + delta).clamp(0, self.entries.len() as i32 - 1) as usize;
        self.list_state.select(Some(next));
    }

    fn toggle_expand(&mut self) {
        let Some(idx) = self.list_state.selected() else {
            return;
        };
        if idx >= self.expand_states.len() {
            return;
        }

        match self.expand_states[idx] {
            ExpandState::Collapsed => {
                self.expand_states[idx] = ExpandState::Context;
            }
            ExpandState::Context => {
                self.content_scroll = 0;
                self.expand_states[idx] = ExpandState::Full;
            }
            ExpandState::Full => {
                self.content_scroll = 0;
                self.expand_states[idx] = ExpandState::Collapsed;
            }
        }
    }

    pub fn hint_shortcuts(&self) -> Vec<(String, String)> {
        [
            (ActionShortcuts::FocusSidebar, "\u{2190} editor"),
            (ActionShortcuts::FollowLink, "open note"),
            (ActionShortcuts::CycleSortField, "sort"),
        ]
        .iter()
        .filter_map(|(action, label)| {
            self.key_bindings
                .first_combo_for(action)
                .map(|k| (k, label.to_string()))
        })
        .collect()
    }

    // ── Rendering ──────────────────────────────────────────────────────

    pub fn render(&mut self, f: &mut Frame, rect: Rect, theme: &Theme, focused: bool) {
        let border_style = theme.border_style(focused);
        let fg = theme.fg.to_ratatui();
        let fg_muted = theme.fg_muted.to_ratatui();
        let bg = theme.bg_panel.to_ratatui();

        let sort_indicator = format!("{}{}", self.sort_field.label(), self.sort_order.label());
        let title = format!("Backlinks ({}) {}", self.entries.len(), sort_indicator);

        let outer = Block::default()
            .title(title)
            .borders(Borders::ALL)
            .border_style(border_style)
            .style(theme.panel_style());
        let inner = outer.inner(rect);
        f.render_widget(outer, rect);

        if self.loading {
            f.render_widget(
                Paragraph::new("  Loading...").style(Style::default().fg(fg_muted).bg(bg)),
                inner,
            );
            return;
        }

        if self.entries.is_empty() {
            f.render_widget(
                Paragraph::new("  No backlinks").style(Style::default().fg(fg_muted).bg(bg)),
                inner,
            );
            return;
        }

        let selected = self.list_state.selected();
        let selected_state = selected
            .and_then(|i| self.expand_states.get(i).copied())
            .unwrap_or(ExpandState::Collapsed);

        // Full mode: content takes the entire panel, no list visible.
        if selected_state == ExpandState::Full {
            if let Some(idx) = selected
                && let Some(entry) = self.entries.get(idx)
            {
                let text = entry.full_text.as_deref().unwrap_or(&entry.context);

                // Split into fixed header (title + divider) and scrollable content.
                let title_display = if entry.title.is_empty() {
                    &entry.filename
                } else {
                    &entry.title
                };

                let parts = Layout::default()
                    .direction(Direction::Vertical)
                    .constraints([
                        Constraint::Length(1), // title
                        Constraint::Length(1), // divider
                        Constraint::Min(0),    // content
                    ])
                    .split(inner);

                // Fixed title header.
                f.render_widget(
                    Paragraph::new(Line::from(vec![
                        Span::styled(
                            format!("\u{25BC} {} ", title_display),
                            Style::default()
                                .fg(theme.fg_selected.to_ratatui())
                                .bg(bg)
                                .add_modifier(Modifier::BOLD),
                        ),
                        Span::styled(
                            format!(" {}", entry.filename),
                            Style::default().fg(fg_muted).bg(bg),
                        ),
                    ]))
                    .style(Style::default().bg(bg)),
                    parts[0],
                );

                // Fixed divider.
                f.render_widget(
                    Paragraph::new("\u{2500}".repeat(parts[1].width as usize))
                        .style(Style::default().fg(fg_muted).bg(bg)),
                    parts[1],
                );

                // Scrollable content.
                let indent = 2usize;
                let wrap_width = parts[2].width.saturating_sub(indent as u16 + 1) as usize;
                let target = self.current_note.get_clean_name().to_lowercase();

                let mut lines = Vec::new();
                for line in text.lines() {
                    let wrapped = wrap_line(line, wrap_width);
                    for wline in wrapped {
                        let spans = highlight_link(&wline, &target, fg_muted, bg, theme);
                        let mut indented =
                            vec![Span::styled(" ".repeat(indent), Style::default().bg(bg))];
                        indented.extend(spans);
                        lines.push(Line::from(indented));
                    }
                }

                let total_lines = lines.len();
                let viewport = parts[2].height as usize;
                self.content_scroll_max = total_lines.saturating_sub(viewport);
                self.content_scroll = self.content_scroll.min(self.content_scroll_max);

                f.render_widget(
                    Paragraph::new(lines)
                        .scroll((self.content_scroll as u16, 0))
                        .style(Style::default().bg(bg)),
                    parts[2],
                );
            }
            return;
        }

        // Context or Collapsed: show the list, optionally with preview below.
        let has_context = selected_state == ExpandState::Context;

        let (list_area, divider_area, content_area) = if has_context {
            let max_list = inner.height / 2;
            let list_height = (self.entries.len() as u16).min(max_list).max(1);
            let areas = Layout::default()
                .direction(Direction::Vertical)
                .constraints([
                    Constraint::Length(list_height),
                    Constraint::Length(1),
                    Constraint::Min(0),
                ])
                .split(inner);
            (areas[0], Some(areas[1]), Some(areas[2]))
        } else {
            (inner, None, None)
        };

        // Build list items (1 line per entry).
        let items: Vec<ListItem> = self
            .entries
            .iter()
            .enumerate()
            .map(|(i, entry)| {
                let is_selected = selected == Some(i);
                let title_style = if is_selected {
                    Style::default()
                        .fg(theme.fg_selected.to_ratatui())
                        .bg(theme.bg_selected.to_ratatui())
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(fg).bg(bg)
                };
                let title_display = if entry.title.is_empty() {
                    &entry.filename
                } else {
                    &entry.title
                };
                let expand_marker = match self.expand_states.get(i) {
                    Some(ExpandState::Context) => "\u{25BC}",
                    _ => " ",
                };
                ListItem::new(Line::from(vec![
                    Span::styled(format!("{} {} ", expand_marker, title_display), title_style),
                    Span::styled(
                        format!(" {}", entry.filename),
                        Style::default().fg(fg_muted).bg(if is_selected {
                            theme.bg_selected.to_ratatui()
                        } else {
                            bg
                        }),
                    ),
                ]))
            })
            .collect();

        let list = List::new(items)
            .style(Style::default().bg(bg))
            .highlight_style(Style::default().bg(theme.bg_selected.to_ratatui()));

        f.render_stateful_widget(list, list_area, &mut self.list_state);

        // Divider between list and content.
        if let Some(div) = divider_area {
            f.render_widget(
                Paragraph::new("\u{2500}".repeat(div.width as usize))
                    .style(Style::default().fg(fg_muted).bg(bg)),
                div,
            );
        }

        // Render context preview below the list: show the full note text
        // scrolled so the first link occurrence is visible with context above.
        if let Some(area) = content_area
            && let Some(idx) = selected
            && let Some(entry) = self.entries.get(idx)
            && selected_state == ExpandState::Context
        {
            let text = entry.full_text.as_deref().unwrap_or(&entry.context);
            let indent = 2usize;
            let wrap_width = area.width.saturating_sub(indent as u16 + 1) as usize;
            let target = self.current_note.get_clean_name().to_lowercase();

            let mut lines = Vec::new();

            // Track which rendered line contains the first link match.
            let mut link_line: Option<usize> = None;

            for line in text.lines() {
                let wrapped = wrap_line(line, wrap_width);
                for wline in wrapped {
                    if link_line.is_none()
                        && (find_case_insensitive(&wline, &format!("[[{}", target)).is_some()
                            || find_case_insensitive(&wline, &format!("({})", target)).is_some())
                    {
                        link_line = Some(lines.len());
                    }
                    let spans = highlight_link(&wline, &target, fg_muted, bg, theme);
                    let mut indented =
                        vec![Span::styled(" ".repeat(indent), Style::default().bg(bg))];
                    indented.extend(spans);
                    lines.push(Line::from(indented));
                }
            }

            // Scroll to show the link with context above. If the content from
            // the link to the end fits within the viewport, scroll back further
            // to fill the available space.
            let viewport = area.height as usize;
            let total = lines.len();
            let link_pos = link_line.unwrap_or(0);
            let lines_after_link = total.saturating_sub(link_pos);
            let scroll_to = if lines_after_link <= viewport {
                // Content from link to end fits — scroll back to fill the viewport.
                total.saturating_sub(viewport)
            } else {
                // More content below the link — show 2 lines of context above.
                link_pos.saturating_sub(2)
            } as u16;

            f.render_widget(
                Paragraph::new(lines)
                    .scroll((scroll_to, 0))
                    .style(Style::default().bg(bg)),
                area,
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Standalone async helpers
// ---------------------------------------------------------------------------

/// Load all backlinks for `note_path` from the vault, fetching note text and
/// extracting context for each one.
async fn load_backlinks(vault: &NoteVault, note_path: &VaultPath) -> Vec<BacklinkEntry> {
    let backlinks = match vault.get_backlinks(note_path).await {
        Ok(bl) => bl,
        Err(_) => return Vec::new(),
    };

    let target_name = note_path.get_clean_name();

    let mut entries = Vec::with_capacity(backlinks.len());
    for (entry_data, content_data) in backlinks {
        let text = vault
            .get_note_text(&entry_data.path)
            .await
            .unwrap_or_default();
        let context = extract_context(&text, &target_name);
        let (_parent, filename) = entry_data.path.get_parent_path();

        entries.push(BacklinkEntry {
            path: entry_data.path,
            title: content_data.title,
            filename,
            context,
            full_text: Some(text),
        });
    }

    entries
}

/// Find the paragraph in `text` that contains a link to `target_name`.
///
/// A "paragraph" is a run of consecutive non-blank lines. The function
/// searches for several link patterns (case-insensitive):
/// - `[[target_name]]`        — full wikilink
/// - `[[target_name`          — partial wikilink (e.g. with alias)
/// - `(target_name)`          — markdown link
/// - `(target_name.md)`       — markdown link with extension
///
/// If no match is found, returns the first non-blank line as a fallback.
fn extract_context(text: &str, target_name: &str) -> String {
    let target_lower = target_name.to_lowercase();

    // Build the name with extension via VaultPath (avoids hardcoding `.md`).
    let with_ext = VaultPath::note_path_from(&target_lower)
        .to_string_with_ext()
        .to_lowercase();
    // Extract just the filename portion (after the last `/`).
    let filename_ext = with_ext.rsplit('/').next().unwrap_or(&with_ext);

    // Build search needles (lowercase).
    let wikilink_full = format!("[[{}]]", target_lower);
    let wikilink_partial = format!("[[{}", target_lower);
    let md_link = format!("({})", target_lower);
    let md_link_ext = format!("({})", filename_ext);

    // Split text into paragraphs (groups of consecutive non-blank lines).
    let paragraphs = split_paragraphs(text);

    for para in &paragraphs {
        let lower = para.to_lowercase();
        if lower.contains(&wikilink_full)
            || lower.contains(&wikilink_partial)
            || lower.contains(&md_link)
            || lower.contains(&md_link_ext)
        {
            return para.clone();
        }
    }

    // Fallback: first non-blank line.
    text.lines()
        .find(|l| !l.trim().is_empty())
        .unwrap_or("")
        .to_string()
}

/// Split text into paragraphs. A paragraph is one or more consecutive
/// non-blank lines. Blank lines act as separators.
fn split_paragraphs(text: &str) -> Vec<String> {
    let mut paragraphs = Vec::new();
    let mut current: Vec<&str> = Vec::new();

    for line in text.lines() {
        if line.trim().is_empty() {
            if !current.is_empty() {
                paragraphs.push(current.join("\n"));
                current.clear();
            }
        } else {
            current.push(line);
        }
    }
    if !current.is_empty() {
        paragraphs.push(current.join("\n"));
    }

    paragraphs
}

// ---------------------------------------------------------------------------
// Rendering helpers
// ---------------------------------------------------------------------------

/// Wrap a single line into multiple lines that fit within `max_width` characters.
/// Uses character count (not byte length) for width. Wraps at word boundaries
/// when possible, hard-breaks otherwise.
fn wrap_line(line: &str, max_width: usize) -> Vec<String> {
    if max_width == 0 || line.chars().count() <= max_width {
        return vec![line.to_string()];
    }

    let mut result = Vec::new();
    let mut remaining = line;

    while remaining.chars().count() > max_width {
        // Find the byte index of the max_width-th character.
        let byte_limit = remaining
            .char_indices()
            .nth(max_width)
            .map(|(i, _)| i)
            .unwrap_or(remaining.len());

        // Try to find a space to break at (within the allowed character range).
        let break_at = remaining[..byte_limit]
            .rfind(' ')
            .map(|i| i + 1) // include the space on the current line
            .unwrap_or(byte_limit); // hard break if no space
        result.push(remaining[..break_at].trim_end().to_string());
        remaining = &remaining[break_at..];
    }
    if !remaining.is_empty() {
        result.push(remaining.to_string());
    }
    result
}

/// Case-insensitive search for `needle` in `haystack`, returning the byte
/// range `(start, end)` in `haystack` where the match occurs. Compares
/// char-by-char via `to_lowercase()` so byte lengths are always derived from
/// the original string, avoiding the case-folding byte-mismatch problem.
fn find_case_insensitive(haystack: &str, needle: &str) -> Option<(usize, usize)> {
    let needle_chars: Vec<char> = needle.chars().collect();
    if needle_chars.is_empty() {
        return None;
    }
    let hay_indices: Vec<(usize, char)> = haystack.char_indices().collect();
    'outer: for start_idx in 0..hay_indices.len() {
        if start_idx + needle_chars.len() > hay_indices.len() {
            break;
        }
        for (j, &nc) in needle_chars.iter().enumerate() {
            let hc = hay_indices[start_idx + j].1;
            // Compare lowercased chars.
            let mut h_lower = hc.to_lowercase();
            let mut n_lower = nc.to_lowercase();
            if h_lower.next() != n_lower.next() {
                continue 'outer;
            }
        }
        // Match found — compute byte range from haystack char indices.
        let byte_start = hay_indices[start_idx].0;
        let byte_end = if start_idx + needle_chars.len() < hay_indices.len() {
            hay_indices[start_idx + needle_chars.len()].0
        } else {
            haystack.len()
        };
        return Some((byte_start, byte_end));
    }
    None
}

/// Render a line with link references to `target` in bold.
/// Splits the line into owned spans: normal text in `fg_muted`, link matches in bold accent.
/// Uses case-insensitive char-by-char matching to avoid byte-index mismatches.
fn highlight_link(
    line: &str,
    target: &str,
    fg_muted: ratatui::style::Color,
    bg: ratatui::style::Color,
    theme: &Theme,
) -> Vec<Span<'static>> {
    let normal_style = Style::default().fg(fg_muted).bg(bg);
    let bold_style = Style::default()
        .fg(theme.accent.to_ratatui())
        .bg(bg)
        .add_modifier(Modifier::BOLD);

    // Build the with-extension form for markdown links.
    let with_ext = VaultPath::note_path_from(target)
        .to_string_with_ext()
        .to_lowercase();
    let filename_ext = with_ext.rsplit('/').next().unwrap_or(&with_ext).to_string();

    // Build all needles to search for.
    let needles = [
        format!("[[{}]]", target),
        format!("[[{}", target),
        format!("({})", target),
        format!("({})", filename_ext),
    ];

    // Find the earliest matching needle by byte position.
    let mut best_match: Option<(usize, usize)> = None; // (byte_start, byte_end)
    for needle in &needles {
        if let Some((start, end)) = find_case_insensitive(line, needle)
            && (best_match.is_none() || start < best_match.unwrap().0)
        {
            best_match = Some((start, end));
        }
    }

    let Some((start, end)) = best_match else {
        return vec![Span::styled(line.to_string(), normal_style)];
    };

    let mut spans = Vec::new();
    if start > 0 {
        spans.push(Span::styled(line[..start].to_string(), normal_style));
    }
    spans.push(Span::styled(line[start..end].to_string(), bold_style));
    if end < line.len() {
        spans.push(Span::styled(line[end..].to_string(), normal_style));
    }
    spans
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn extract_context_finds_wikilink_paragraph() {
        let text = "\
# Heading

This is an intro paragraph.

Here I reference [[my-note]] in some context
that spans two lines.

Another paragraph without links.";

        let result = extract_context(text, "my-note");
        assert!(result.contains("[[my-note]]"));
        assert!(result.contains("that spans two lines"));
    }

    #[test]
    fn extract_context_fallback_to_first_line() {
        let text = "\
# No links here

Just a normal paragraph.";

        let result = extract_context(text, "other-note");
        assert_eq!(result, "# No links here");
    }

    #[test]
    fn extract_context_finds_markdown_link() {
        let text = "\
# Title

See [related](my-note.md) for details.

Unrelated content.";

        let result = extract_context(text, "my-note");
        assert!(result.contains("(my-note.md)"));
    }

    #[test]
    fn wrap_line_fits_within_width() {
        let result = wrap_line("short", 20);
        assert_eq!(result, vec!["short"]);
    }

    #[test]
    fn wrap_line_breaks_at_word_boundary() {
        let result = wrap_line("hello world foo bar", 12);
        assert_eq!(result, vec!["hello world", "foo bar"]);
    }

    #[test]
    fn wrap_line_hard_breaks_long_word() {
        let result = wrap_line("abcdefghij", 5);
        assert_eq!(result, vec!["abcde", "fghij"]);
    }

    #[test]
    fn wrap_line_handles_multibyte_chars() {
        // 5 CJK characters — each is 1 char, should wrap at char boundary
        let result = wrap_line("日本語テスト", 3);
        assert_eq!(result, vec!["日本語", "テスト"]);
    }

    #[test]
    fn wrap_line_empty_string() {
        let result = wrap_line("", 10);
        assert_eq!(result, vec![""]);
    }

    #[test]
    fn highlight_link_bolds_wikilink() {
        let spans = highlight_link(
            "see [[my-note]] here",
            "my-note",
            ratatui::style::Color::Gray,
            ratatui::style::Color::Black,
            &crate::settings::themes::Theme::default(),
        );
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[0].content, "see ");
        assert_eq!(spans[1].content, "[[my-note]]");
        assert!(spans[1].style.add_modifier.contains(Modifier::BOLD));
        assert_eq!(spans[2].content, " here");
    }

    #[test]
    fn highlight_link_case_insensitive() {
        let spans = highlight_link(
            "See [[My-Note]] here",
            "my-note",
            ratatui::style::Color::Gray,
            ratatui::style::Color::Black,
            &crate::settings::themes::Theme::default(),
        );
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[1].content, "[[My-Note]]");
        assert!(spans[1].style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn highlight_link_markdown_with_extension() {
        let spans = highlight_link(
            "see [link](my-note.md) here",
            "my-note",
            ratatui::style::Color::Gray,
            ratatui::style::Color::Black,
            &crate::settings::themes::Theme::default(),
        );
        assert_eq!(spans.len(), 3);
        assert!(spans[1].content.contains("my-note.md"));
        assert!(spans[1].style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn highlight_link_no_match_returns_single_span() {
        let spans = highlight_link(
            "nothing here",
            "other",
            ratatui::style::Color::Gray,
            ratatui::style::Color::Black,
            &crate::settings::themes::Theme::default(),
        );
        assert_eq!(spans.len(), 1);
    }
}