bmrk 0.2.1

A fast TUI for directory navigation and bookmark management
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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::PathBuf;

/// A single bookmark entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bookmark {
    pub key: String,
    pub path: PathBuf,
    pub name: Option<String>,
}

impl Bookmark {
    /// Validate bookmark name according to filesystem naming rules
    /// Allows alphanumeric, hyphens, underscores, dots (max 255 chars)
    /// Forbids path separators and null bytes
    pub fn validate_name(name: &str) -> Result<()> {
        if name.is_empty() {
            anyhow::bail!("Bookmark name cannot be empty");
        }

        if name.len() > 255 {
            anyhow::bail!("Bookmark name too long (max 255 characters)");
        }

        // Check for forbidden characters (path separators, null byte, control chars)
        if name.contains('/') || name.contains('\\') || name.contains('\0') {
            anyhow::bail!("Bookmark name cannot contain path separators (/, \\) or null bytes");
        }

        // Forbid control characters
        if name.chars().any(|c| c.is_control()) {
            anyhow::bail!("Bookmark name cannot contain control characters");
        }

        // Forbid reserved names on Windows (optional, but safer for cross-platform)
        let reserved = [
            "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7",
            "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
        ];
        if reserved.contains(&name.to_uppercase().as_str()) {
            anyhow::bail!("Bookmark name '{}' is reserved", name);
        }

        Ok(())
    }
}

/// Manages persistent bookmarks
#[derive(Debug, Default)]
pub struct Bookmarks {
    bookmarks: BTreeMap<String, Bookmark>,
    file_path: PathBuf,
    pub is_selecting: bool,
    pub is_creating: bool,
    pub input_buffer: String,
    pub selected_index: usize,                 // Current selection in list
    pub filter_mode: bool,                     // True = filter/search mode, False = navigation mode
    filtered_keys: Vec<String>,                // Cached filtered bookmark keys
    pub scroll_offset: usize,                  // Scroll offset for bookmark list in creation mode
    pub pending_deletion_index: Option<usize>, // Index of bookmark marked for deletion
    /// `true` after keyboard navigation (center in viewport); `false` after mouse (minimal scroll).
    pub center_selection: bool,
}

impl Bookmarks {
    /// Create a new Bookmarks instance and load from file
    pub fn new() -> Result<Self> {
        let config_dir = dirs::config_dir()
            .context("Could not find config directory")?
            .join("bmrk");

        // Ensure config directory exists
        fs::create_dir_all(&config_dir)?;

        let file_path = config_dir.join("bookmarks.json");

        let mut bookmarks = Self {
            bookmarks: BTreeMap::new(),
            file_path,
            is_selecting: false,
            is_creating: false,
            input_buffer: String::new(),
            selected_index: 0,
            filter_mode: false,
            filtered_keys: Vec::new(),
            scroll_offset: 0,
            pending_deletion_index: None,
            center_selection: false,
        };

        // Try to load, but don't fail if JSON is corrupted
        if let Err(e) = bookmarks.load() {
            eprintln!("\n┌─────────────────────────────────────────────────────────────┐");
            eprintln!("│ WARNING: Bookmarks file is corrupted                       │");
            eprintln!("└─────────────────────────────────────────────────────────────┘\n");
            eprintln!("{}\n", e);
            eprintln!("Press Enter to continue...");

            // Wait for user to press Enter
            let mut input = String::new();
            let _ = std::io::stdin().read_line(&mut input);
        }

        Ok(bookmarks)
    }

    /// Load bookmarks from JSON file
    fn load(&mut self) -> Result<()> {
        if !self.file_path.exists() {
            // Create empty file if it doesn't exist
            self.save()?;
            return Ok(());
        }

        let content = match fs::read_to_string(&self.file_path) {
            Ok(c) => c,
            Err(_) => {
                // If cannot read file, create new empty one
                self.save()?;
                return Ok(());
            }
        };

        if content.trim().is_empty() {
            return Ok(());
        }

        // Parse JSON
        match serde_json::from_str::<Vec<Bookmark>>(&content) {
            Ok(bookmarks_vec) => {
                self.bookmarks.clear();
                for bookmark in bookmarks_vec {
                    self.bookmarks.insert(bookmark.key.clone(), bookmark);
                }
                Ok(())
            }
            Err(e) => {
                // Backup corrupted file
                let backup_path = self.file_path.with_extension("json.backup");
                let _ = fs::copy(&self.file_path, &backup_path);

                // Create new empty bookmarks file
                self.bookmarks.clear();
                self.save()?;

                // Return error with helpful message
                Err(anyhow::anyhow!(
                    "Failed to parse bookmarks JSON: {}.\n\
                    The corrupted file has been backed up to: {}\n\
                    A new empty bookmarks file has been created.",
                    e,
                    backup_path.display()
                ))
            }
        }
    }

    /// Save bookmarks to JSON file (atomic: write to .tmp then rename)
    fn save(&self) -> Result<()> {
        let bookmarks_vec: Vec<&Bookmark> = self.bookmarks.values().collect();
        let json = serde_json::to_string_pretty(&bookmarks_vec)
            .context("Failed to serialize bookmarks")?;

        // Write to a sibling temp file first so an interrupted write never
        // leaves the target file truncated or empty.
        let tmp_path = self.file_path.with_extension("json.tmp");
        fs::write(&tmp_path, &json).context("Failed to write temp bookmarks file")?;

        // Atomic rename: on the same volume this replaces the target in one step.
        fs::rename(&tmp_path, &self.file_path).context("Failed to rename temp bookmarks file")?;

        Ok(())
    }

    /// Add or update a bookmark
    pub fn add(&mut self, key: String, path: PathBuf, name: Option<String>) -> Result<()> {
        // Validate bookmark name
        Bookmark::validate_name(&key)?;

        let bookmark = Bookmark {
            key: key.clone(),
            path,
            name,
        };

        self.bookmarks.insert(key, bookmark);
        self.save()?;
        Ok(())
    }

    /// Get a bookmark by key
    pub fn get(&self, key: &str) -> Option<&Bookmark> {
        self.bookmarks.get(key)
    }

    /// Remove a bookmark
    pub fn remove(&mut self, key: &str) -> Result<()> {
        if self.bookmarks.remove(key).is_none() {
            anyhow::bail!("Bookmark '{}' not found", key);
        }
        self.save()?;
        Ok(())
    }

    /// Get all bookmarks sorted by key.
    pub fn list(&self) -> Vec<&Bookmark> {
        self.bookmarks.values().collect()
    }

    /// Enter bookmark selection mode
    pub fn enter_selection_mode(&mut self) {
        self.is_selecting = true;
        self.is_creating = false;
        self.input_buffer.clear();
        self.selected_index = 0;
        self.filter_mode = false;
        self.pending_deletion_index = None;
        self.center_selection = false;
        self.update_filtered_list();
    }

    /// Exit bookmark selection mode
    pub fn exit_selection_mode(&mut self) {
        self.is_selecting = false;
        self.input_buffer.clear();
        self.selected_index = 0;
        self.filter_mode = false;
        self.filtered_keys.clear();
        self.pending_deletion_index = None;
        self.center_selection = false;
    }

    /// Enter bookmark creation mode (after pressing 'm')
    pub fn enter_creation_mode(&mut self) {
        self.is_creating = true;
        self.is_selecting = false;
        self.input_buffer.clear();
        self.selected_index = 0;
        self.filter_mode = false;
        self.scroll_offset = 0;
    }

    /// Exit bookmark creation mode
    pub fn exit_creation_mode(&mut self) {
        self.is_creating = false;
        self.input_buffer.clear();
        self.scroll_offset = 0;
    }

    /// Scroll bookmark list up in creation mode
    pub fn scroll_up(&mut self) {
        self.scroll_offset = self.scroll_offset.saturating_sub(1);
    }

    /// Scroll bookmark list down in creation mode
    pub fn scroll_down(&mut self, max_visible: usize) {
        let total_bookmarks = self.list().len();
        let max_offset = total_bookmarks.saturating_sub(max_visible);
        if self.scroll_offset < max_offset {
            self.scroll_offset += 1;
        }
    }

    /// Add character to input buffer
    pub fn add_char(&mut self, c: char) {
        self.input_buffer.push(c);
        // Update filtered list if in filter mode
        if self.filter_mode {
            self.update_filtered_list();
            // Clamp selection to valid range
            let list_len = self.get_filtered_bookmarks().len();
            if list_len == 0 {
                self.selected_index = 0;
            } else if self.selected_index >= list_len {
                self.selected_index = list_len - 1;
            }
        }
    }

    /// Remove last character from input buffer
    pub fn backspace(&mut self) {
        self.input_buffer.pop();
        // Update filtered list if in filter mode
        if self.filter_mode {
            self.update_filtered_list();
            // Clamp selection to valid range
            let list_len = self.get_filtered_bookmarks().len();
            if list_len == 0 {
                self.selected_index = 0;
            } else if self.selected_index >= list_len {
                self.selected_index = list_len - 1;
            }
        }
    }

    /// Get current input buffer
    pub fn get_input(&self) -> &str {
        &self.input_buffer
    }

    /// Toggle between navigation mode and filter mode
    pub fn toggle_filter_mode(&mut self) {
        self.filter_mode = !self.filter_mode;
        // When switching modes, keep the current filter and list
        // Just change whether user can type (filter mode) or navigate (navigation mode)

        // Clamp selected_index to valid range after toggle
        let list_len = self.get_filtered_bookmarks().len();
        if list_len > 0 && self.selected_index >= list_len {
            self.selected_index = list_len - 1;
        }
    }

    /// Update filtered list based on input buffer
    fn update_filtered_list(&mut self) {
        let query = self.input_buffer.to_lowercase();

        if query.is_empty() {
            // No filter - show all bookmarks
            self.filtered_keys = self.list().iter().map(|b| b.key.clone()).collect();
        } else {
            // Filter bookmarks by key or name
            self.filtered_keys = self
                .list()
                .iter()
                .filter(|b| {
                    let key_match = b.key.to_lowercase().contains(&query);
                    let name_match = b
                        .name
                        .as_ref()
                        .map(|n| n.to_lowercase().contains(&query))
                        .unwrap_or(false);
                    key_match || name_match
                })
                .map(|b| b.key.clone())
                .collect();
        }
    }

    /// Get filtered bookmarks for display
    pub fn get_filtered_bookmarks(&self) -> Vec<&Bookmark> {
        if self.filtered_keys.is_empty() {
            Vec::new()
        } else {
            self.filtered_keys
                .iter()
                .filter_map(|key| self.bookmarks.get(key))
                .collect()
        }
    }

    /// Move selection up in bookmark list
    pub fn move_up(&mut self) {
        if self.selected_index > 0 {
            self.selected_index -= 1;
        }
        self.pending_deletion_index = None;
        self.center_selection = true;
    }

    /// Move selection down in bookmark list
    pub fn move_down(&mut self) {
        let list_len = self.get_filtered_bookmarks().len();
        if list_len > 0 && self.selected_index < list_len - 1 {
            self.selected_index += 1;
        }
        self.pending_deletion_index = None;
        self.center_selection = true;
    }

    /// Get currently selected bookmark
    pub fn get_selected_bookmark(&self) -> Option<&Bookmark> {
        let filtered = self.get_filtered_bookmarks();
        filtered.get(self.selected_index).copied()
    }

    /// Handle deletion key press - marks for deletion or confirms deletion
    /// Returns true if bookmark was deleted, false if just marked
    pub fn handle_deletion_key(&mut self) -> Result<bool> {
        if let Some(pending_idx) = self.pending_deletion_index {
            if pending_idx == self.selected_index {
                // Second press on same bookmark - confirm deletion
                if let Some(bookmark) = self.get_selected_bookmark() {
                    let key = bookmark.key.clone();
                    self.remove(&key)?;

                    // Update filtered list after deletion
                    self.update_filtered_list();

                    // Adjust selected_index if needed
                    let list_len = self.get_filtered_bookmarks().len();
                    if list_len == 0 {
                        self.selected_index = 0;
                    } else if self.selected_index >= list_len {
                        self.selected_index = list_len - 1;
                    }

                    self.pending_deletion_index = None;
                    return Ok(true);
                }
            }
        }

        // First press or different bookmark - mark for deletion
        self.pending_deletion_index = Some(self.selected_index);
        Ok(false)
    }

    /// Check if current selection is marked for deletion
    #[allow(dead_code)]
    pub fn is_marked_for_deletion(&self) -> bool {
        self.pending_deletion_index == Some(self.selected_index)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::TempDir;

    /// Helper function to create a Bookmarks instance with a temporary file
    fn create_test_bookmarks(temp_dir: &TempDir) -> Bookmarks {
        let file_path = temp_dir.path().join("bookmarks.json");
        Bookmarks {
            bookmarks: BTreeMap::new(),
            file_path,
            is_selecting: false,
            is_creating: false,
            input_buffer: String::new(),
            selected_index: 0,
            filter_mode: false,
            filtered_keys: Vec::new(),
            scroll_offset: 0,
            pending_deletion_index: None,
            center_selection: false,
        }
    }

    #[test]
    fn test_save_and_load_bookmarks() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        // Add some bookmarks
        bookmarks
            .add(
                "a".to_string(),
                PathBuf::from("/tmp/test1"),
                Some("Test 1".to_string()),
            )
            .unwrap();
        bookmarks
            .add(
                "b".to_string(),
                PathBuf::from("/tmp/test2"),
                Some("Test 2".to_string()),
            )
            .unwrap();

        // Save
        bookmarks.save().unwrap();

        // Create new instance and load
        let mut bookmarks2 = create_test_bookmarks(&temp_dir);
        bookmarks2.load().unwrap();

        // Verify
        assert_eq!(bookmarks2.list().len(), 2);
        assert_eq!(
            bookmarks2.get("a").unwrap().path,
            PathBuf::from("/tmp/test1")
        );
        assert_eq!(
            bookmarks2.get("b").unwrap().path,
            PathBuf::from("/tmp/test2")
        );
    }

    #[test]
    fn test_corrupted_json_creates_backup() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("bookmarks.json");
        let backup_path = temp_dir.path().join("bookmarks.json.backup");

        // Write invalid JSON (trailing comma)
        let mut file = std::fs::File::create(&file_path).unwrap();
        file.write_all(b"[\n  {\"key\": \"a\", \"path\": \"/tmp/test\", \"name\": \"test\"},\n]")
            .unwrap();
        drop(file);

        // Try to load
        let mut bookmarks = Bookmarks {
            bookmarks: BTreeMap::new(),
            file_path: file_path.clone(),
            is_selecting: false,
            is_creating: false,
            input_buffer: String::new(),
            selected_index: 0,
            filter_mode: false,
            filtered_keys: Vec::new(),
            scroll_offset: 0,
            pending_deletion_index: None,
            center_selection: false,
        };

        let result = bookmarks.load();

        // Should return error
        assert!(result.is_err());

        // Backup should exist
        assert!(backup_path.exists());

        // New file should be valid (empty array)
        let content = std::fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "[]");

        // Bookmarks should be empty
        assert_eq!(bookmarks.list().len(), 0);
    }

    #[test]
    fn test_save_leaves_no_tmp_file() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        bookmarks
            .add("a".to_string(), PathBuf::from("/tmp/a"), None)
            .unwrap();

        // After a successful save the .tmp file must not remain
        let tmp_path = bookmarks.file_path.with_extension("json.tmp");
        assert!(
            !tmp_path.exists(),
            ".tmp file must not exist after successful save"
        );

        // The target file must exist and contain valid JSON
        let content = fs::read_to_string(&bookmarks.file_path).unwrap();
        let parsed: Vec<serde_json::Value> = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed.len(), 1);
    }

    #[test]
    fn test_empty_file() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("bookmarks.json");

        // Create empty file
        std::fs::File::create(&file_path).unwrap();

        let mut bookmarks = Bookmarks {
            bookmarks: BTreeMap::new(),
            file_path,
            is_selecting: false,
            is_creating: false,
            input_buffer: String::new(),
            selected_index: 0,
            filter_mode: false,
            filtered_keys: Vec::new(),
            scroll_offset: 0,
            pending_deletion_index: None,
            center_selection: false,
        };

        // Should load without error
        bookmarks.load().unwrap();
        assert_eq!(bookmarks.list().len(), 0);
    }

    #[test]
    fn test_add_and_remove_bookmarks() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        // Add bookmark
        bookmarks
            .add(
                "x".to_string(),
                PathBuf::from("/tmp/testx"),
                Some("TestX".to_string()),
            )
            .unwrap();
        assert_eq!(bookmarks.list().len(), 1);
        assert!(bookmarks.get("x").is_some());

        // Remove bookmark
        bookmarks.remove("x").unwrap();
        assert_eq!(bookmarks.list().len(), 0);
        assert!(bookmarks.get("x").is_none());
    }

    #[test]
    fn test_list_sorted_by_key() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        // Add bookmarks in random order
        bookmarks
            .add("z".to_string(), PathBuf::from("/tmp/z"), None)
            .unwrap();
        bookmarks
            .add("a".to_string(), PathBuf::from("/tmp/a"), None)
            .unwrap();
        bookmarks
            .add("m".to_string(), PathBuf::from("/tmp/m"), None)
            .unwrap();

        let list = bookmarks.list();
        assert_eq!(list.len(), 3);

        // Should be sorted by key
        assert_eq!(list[0].key, "a");
        assert_eq!(list[1].key, "m");
        assert_eq!(list[2].key, "z");
    }

    #[test]
    fn test_selection_mode() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        assert!(!bookmarks.is_selecting);

        bookmarks.enter_selection_mode();
        assert!(bookmarks.is_selecting);

        bookmarks.exit_selection_mode();
        assert!(!bookmarks.is_selecting);
    }

    #[test]
    fn test_creation_mode() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        assert!(!bookmarks.is_creating);

        bookmarks.enter_creation_mode();
        assert!(bookmarks.is_creating);

        bookmarks.exit_creation_mode();
        assert!(!bookmarks.is_creating);
    }

    #[test]
    fn test_overwrite_existing_bookmark() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        // Add bookmark
        bookmarks
            .add(
                "t".to_string(),
                PathBuf::from("/tmp/first"),
                Some("First".to_string()),
            )
            .unwrap();
        assert_eq!(
            bookmarks.get("t").unwrap().path,
            PathBuf::from("/tmp/first")
        );

        // Overwrite with same key
        bookmarks
            .add(
                "t".to_string(),
                PathBuf::from("/tmp/second"),
                Some("Second".to_string()),
            )
            .unwrap();

        // Should have updated path
        assert_eq!(
            bookmarks.get("t").unwrap().path,
            PathBuf::from("/tmp/second")
        );
        assert_eq!(bookmarks.get("t").unwrap().name, Some("Second".to_string()));

        // Should still have only one bookmark
        assert_eq!(bookmarks.list().len(), 1);
    }

    #[test]
    fn test_multi_character_bookmark_names() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        // Add multi-character bookmarks
        bookmarks
            .add(
                "work".to_string(),
                PathBuf::from("/tmp/work"),
                Some("Work".to_string()),
            )
            .unwrap();
        bookmarks
            .add(
                "project-123".to_string(),
                PathBuf::from("/tmp/proj"),
                Some("Project".to_string()),
            )
            .unwrap();
        bookmarks
            .add(
                "my_home".to_string(),
                PathBuf::from("/home/user"),
                Some("Home".to_string()),
            )
            .unwrap();

        assert_eq!(bookmarks.list().len(), 3);
        assert_eq!(
            bookmarks.get("work").unwrap().path,
            PathBuf::from("/tmp/work")
        );
        assert_eq!(
            bookmarks.get("project-123").unwrap().path,
            PathBuf::from("/tmp/proj")
        );
        assert_eq!(
            bookmarks.get("my_home").unwrap().path,
            PathBuf::from("/home/user")
        );
    }

    #[test]
    fn test_bookmark_name_validation() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        // Empty name should fail
        let result = bookmarks.add("".to_string(), PathBuf::from("/tmp/test"), None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cannot be empty"));

        // Name with path separator should fail
        let result = bookmarks.add("work/project".to_string(), PathBuf::from("/tmp/test"), None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("path separators"));

        // Name with null byte should fail
        let result = bookmarks.add("work\0test".to_string(), PathBuf::from("/tmp/test"), None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("path separators"));

        // Reserved Windows name should fail (cross-platform safety)
        let result = bookmarks.add("CON".to_string(), PathBuf::from("/tmp/test"), None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("reserved"));

        // Valid names should succeed
        assert!(bookmarks
            .add("work".to_string(), PathBuf::from("/tmp/work"), None)
            .is_ok());
        assert!(bookmarks
            .add("project-123".to_string(), PathBuf::from("/tmp/proj"), None)
            .is_ok());
        assert!(bookmarks
            .add(
                "my_home.backup".to_string(),
                PathBuf::from("/tmp/home"),
                None
            )
            .is_ok());
    }

    #[test]
    fn test_bookmark_remove_error() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        // Removing non-existent bookmark should fail
        let result = bookmarks.remove("nonexistent");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_scroll_down_reaches_y_and_z_bookmarks() {
        let temp_dir = TempDir::new().unwrap();
        let mut bookmarks = create_test_bookmarks(&temp_dir);

        // Add bookmarks a–h and y, z: 10 total, alphabetically y/z are last
        for ch in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'y', 'z'] {
            bookmarks
                .add(ch.to_string(), PathBuf::from(format!("/tmp/{ch}")), None)
                .unwrap();
        }

        bookmarks.enter_creation_mode();
        assert_eq!(bookmarks.scroll_offset, 0);

        // Simulate a panel that can show 4 items at a time (compact mode scenario).
        // max_visible = 4 → max_offset = 10 - 4 = 6, so we must be able to scroll 6 times.
        let max_visible = 4;
        for _ in 0..6 {
            bookmarks.scroll_down(max_visible);
        }
        // At scroll_offset 6, items 6..10 are visible: g, h, y, z
        assert_eq!(
            bookmarks.scroll_offset, 6,
            "should reach offset 6 to expose y and z"
        );

        // A 7th scroll should be blocked (offset stays at 6)
        bookmarks.scroll_down(max_visible);
        assert_eq!(bookmarks.scroll_offset, 6, "should not scroll past the end");

        // Verify y and z are reachable via skip(scroll_offset)
        let visible: Vec<String> = bookmarks
            .list()
            .iter()
            .skip(bookmarks.scroll_offset)
            .take(max_visible)
            .map(|b| b.key.clone())
            .collect();
        assert!(
            visible.contains(&"y".to_string()),
            "y must be visible after scrolling"
        );
        assert!(
            visible.contains(&"z".to_string()),
            "z must be visible after scrolling"
        );
    }
}