tuit-bin 0.1.2

A TUI git log viewer built with ratatui and gix (gitoxide)
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
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};
use clap::Parser;
use crossterm::ExecutableCommand;
use crossterm::event::{
    self, Event, KeyCode, KeyEventKind, KeyModifiers, MouseButton, MouseEventKind, poll,
};
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::{Backend, CrosstermBackend};

use crate::app::{App, Screen};

/// Simplified input event for the application.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Key {
    Up,
    Down,
    Enter,
    Esc,
    PageUp,
    PageDown,
    Char(char),
    Ctrl(char),
    /// Left mouse button click at the given terminal row.
    MouseClick(u16),
}

mod app;
mod config;
mod git;
mod ui;

/// Command-line arguments for tuit.
#[derive(Parser)]
#[command(name = "tuit", version)]
struct Cli {
    /// Path to the Git repository to open.
    #[arg(short, long, value_name = "PATH")]
    repo: Option<PathBuf>,
}

/// Main entry point – production mode.
fn main() -> Result<()> {
    let cli = Cli::parse();
    let explicit_repo = cli.repo.is_some();
    let repo_path = cli
        .repo
        .map(|p| p.canonicalize().unwrap_or(p))
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));

    // Validate an explicitly supplied repository path before entering the TUI.
    if explicit_repo {
        validate_repo_path(&repo_path)?;
    }

    enable_raw_mode()?;
    io::stdout().execute(EnterAlternateScreen)?;
    io::stdout().execute(event::EnableMouseCapture)?;
    let mut terminal = Terminal::new(CrosstermBackend::new(io::stdout()))?;

    // Load config.
    let cfg = config::load().unwrap_or_else(|_| config::Config {
        theme: "default".into(),
        colors: config::default_colors(),
        poll_interval_ms: 2000,
        notification_timeout_ms: 3000,
    });

    // Initialise app and load commits.
    let mut app = App::new(cfg, repo_path);
    app.load_commits();

    // Draw initial state.
    terminal.draw(|frame| {
        ui::render(frame, &app);
    })?;

    let poll_interval = Duration::from_millis(app.poll_interval_ms);

    // Live event loop: poll for both keyboard input and timer-based git sync.
    loop {
        // Block up to `poll_interval` for a key press.
        if poll(poll_interval)? {
            if let Some(key) = read_key()? {
                handle_input(&mut app, key);
            }
        }

        // Git state sync (throttled internally to `poll_interval_ms`).
        app.poll();

        // Re-render.
        terminal.draw(|frame| {
            ui::render(frame, &app);
        })?;

        if app.should_quit {
            break;
        }
    }

    // Teardown.
    disable_raw_mode()?;
    io::stdout().execute(event::DisableMouseCapture)?;
    io::stdout().execute(LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    Ok(())
}

/// Read a single input event from crossterm.
fn read_key() -> Result<Option<Key>> {
    match event::read()? {
        Event::Key(key) if key.kind == KeyEventKind::Press => {
            let k = match key.code {
                KeyCode::Esc => Key::Esc,
                KeyCode::Enter => Key::Enter,
                KeyCode::Up => Key::Up,
                KeyCode::Down => Key::Down,
                KeyCode::PageUp => Key::PageUp,
                KeyCode::PageDown => Key::PageDown,
                KeyCode::Char(c) if key.modifiers.contains(KeyModifiers::CONTROL) => Key::Ctrl(c),
                KeyCode::Char(c) => Key::Char(c),
                _ => return Ok(None),
            };
            Ok(Some(k))
        }
        Event::Mouse(mouse) if mouse.kind == MouseEventKind::Down(MouseButton::Left) => {
            Ok(Some(Key::MouseClick(mouse.row)))
        }
        _ => Ok(None),
    }
}

/// Validate that `path` exists, is a directory, and is a git repository.
fn validate_repo_path(path: &Path) -> Result<()> {
    if !path.exists() {
        anyhow::bail!("リポジトリパスが存在しません: {}", path.display());
    }
    if !path.is_dir() {
        anyhow::bail!(
            "リポジトリパスはディレクトリである必要があります: {}",
            path.display()
        );
    }
    git::open_repo(path)
        .with_context(|| format!("無効な Git リポジトリです: {}", path.display()))?;
    Ok(())
}

/// Generic application entry point that accepts any Backend and any key-event
/// iterator.  Used by both `main()` (production) and tests (TestBackend).
pub fn run_app<B: Backend>(
    terminal: &mut Terminal<B>,
    events: impl Iterator<Item = Key>,
    repo_path: PathBuf,
) -> Result<()>
where
    <B as Backend>::Error: Send + Sync + 'static,
{
    // 1. Load config (falls back to default colours if no files found).
    let cfg = config::load().unwrap_or_else(|_| config::Config {
        theme: "default".into(),
        colors: config::default_colors(),
        poll_interval_ms: 2000,
        notification_timeout_ms: 3000,
    });
    let config = cfg;

    // 2. Initialise app and load commits.
    let mut app = App::new(config, repo_path);
    app.load_commits();

    // Draw initial state before waiting for input.
    terminal.draw(|frame| {
        ui::render(frame, &app);
    })?;

    // 3. Event loop.
    for key in events {
        handle_input(&mut app, key);

        // Draw current state.
        terminal.draw(|frame| {
            ui::render(frame, &app);
        })?;

        if app.should_quit {
            break;
        }
    }

    // Final draw
    let _ = terminal.draw(|frame| {
        ui::render(frame, &app);
    });

    Ok(())
}

/// Process a single key-press against the current app state.
pub fn handle_input(app: &mut App, key: Key) {
    // Help overlay takes all input except toggle/close.
    if app.show_help {
        match key {
            Key::Char('?') | Key::Esc => app.show_help = false,
            _ => {}
        }
        return;
    }

    // Global: ? opens help from any screen.
    if key == Key::Char('?') {
        app.show_help = true;
        return;
    }

    // Global: r reloads commit list from the current branch.
    if key == Key::Char('r') {
        app.reload();
        return;
    }

    match &app.screen {
        Screen::List => match key {
            Key::Up | Key::Char('k') => app.navigate_up(),
            Key::Down | Key::Char('j') => app.navigate_down(),
            Key::Ctrl('f') | Key::PageDown => app.navigate_page_down(),
            Key::Ctrl('b') | Key::PageUp => app.navigate_page_up(),
            Key::Enter => app.select_commit(),
            Key::Char('c') => copy_commit_hash(app),
            Key::Char('q') => app.quit(),
            Key::MouseClick(row) => select_commit_at_row(app, row),
            _ => {}
        },
        Screen::Detail => match key {
            Key::Esc => app.close_detail(),
            Key::Up | Key::Char('k') => app.scroll_detail_up(),
            Key::Down | Key::Char('j') => app.scroll_detail_down(),
            Key::Ctrl('f') | Key::PageDown => app.scroll_detail_page_down(),
            Key::Ctrl('b') | Key::PageUp => app.scroll_detail_page_up(),
            Key::Char('c') => copy_commit_hash(app),
            _ => {}
        },
        Screen::Error(_) => match key {
            Key::Enter => app.quit(),
            _ => {}
        },
        Screen::Alert(_) => match key {
            Key::Enter | Key::Esc => app.dismiss_alert(),
            _ => {}
        },
        Screen::Loading => {
            // Ignore all input while loading.
        }
    }
}

/// Select the commit visible at the given terminal row in the commit list.
///
/// The header occupies row 0; the list itself begins at row 1.  Clicks
/// outside the list area are ignored.
fn select_commit_at_row(app: &mut App, row: u16) {
    if app.commits.is_empty() || row < 1 {
        return;
    }
    let visible_row = (row as usize).saturating_sub(1);
    let new_index = app.list_scroll.get() + visible_row;
    let max_index = app.commits.len().saturating_sub(1);
    if new_index <= max_index {
        app.selected_index = new_index;
    }
}

/// Copy the currently focused commit's full OID to the system clipboard.
/// Shows a footer notification on success; fails silently if the clipboard
/// is unavailable (headless environment, etc.).
fn copy_commit_hash(app: &mut App) {
    let oid = match app.current_commit_oid() {
        Some(o) => o,
        None => return,
    };

    if let Ok(mut clipboard) = arboard::Clipboard::new() {
        if clipboard.set_text(oid.clone()).is_ok() {
            let short = oid.chars().take(7).collect::<String>();
            app.set_notification(format!("Copied {} to clipboard", short));
        }
    }
}

// ── End-to-end tests ──────────────────────────────────────────────────

#[cfg(test)]
mod e2e_tests {
    use std::path::Path;
    use std::process::Command;

    use ratatui::backend::TestBackend;

    use super::*;

    /// Helper: create a temporary git repository at `path` with `n` commits.
    /// Each commit adds a unique file (commit-0, commit-1, …) with a known subject line.
    fn init_repo(path: &Path, n: usize) {
        let _ = std::fs::remove_dir_all(path);
        std::fs::create_dir_all(path).unwrap();

        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .arg(path)
            .status()
            .unwrap();

        for i in 0..n {
            let file = path.join(format!("file-{i}.txt"));
            std::fs::write(&file, format!("content {i}")).unwrap();
            Command::new("git")
                .args([
                    "-C",
                    &path.to_string_lossy(),
                    "add",
                    &file.to_string_lossy(),
                ])
                .status()
                .unwrap();
            Command::new("git")
                .args([
                    "-C",
                    &path.to_string_lossy(),
                    "commit",
                    "-m",
                    &format!("Commit subject {i}"),
                    "--allow-empty",
                ])
                .env("GIT_AUTHOR_NAME", "Test User")
                .env("GIT_AUTHOR_EMAIL", "test@example.com")
                .env("GIT_COMMITTER_NAME", "Test User")
                .env("GIT_COMMITTER_EMAIL", "test@example.com")
                .status()
                .unwrap();
        }
    }

    /// Create an empty git repo (no commits) at `path`.
    fn init_empty_repo(path: &Path) {
        let _ = std::fs::remove_dir_all(path);
        std::fs::create_dir_all(path).unwrap();
        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .arg(path)
            .status()
            .unwrap();
    }

    /// Run tuit against a git repo at `repo_path` with the given key events.
    fn run_with_events(repo_path: &Path, events: Vec<Key>) -> TestBackend {
        // Change to the repo directory before testing.
        let prev_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(repo_path).unwrap();

        let backend = TestBackend::new(210, 24);
        let mut terminal = Terminal::new(backend).unwrap();

        // Override XDG_CONFIG_HOME so the test doesn't read the user's real config.
        let config_home = repo_path.join(".tuit-config");
        std::fs::create_dir_all(&config_home).unwrap();
        // We can't easily override this in-process, but config::load() will
        // fall back to defaults when no files exist, which is fine.

        let _ = super::run_app(&mut terminal, events.into_iter(), repo_path.to_path_buf());

        // Restore working directory.
        std::env::set_current_dir(prev_dir).unwrap();

        terminal.backend().clone()
    }

    #[test]
    fn happy_path_commit_list_shows_all_commits() {
        let tmp = std::env::temp_dir().join("tuit-e2e-happy");
        init_repo(&tmp, 3);

        let backend = run_with_events(&tmp, vec![Key::Char('q')]);
        let buf = backend.buffer();

        // The buffer should contain each commit's subject (hash and author not checked:
        // hash visibility depends on width, author is never shown in list view).
        let content = buf_to_string(buf);
        assert!(
            content.contains("Commit subject 0"),
            "Expected 'Commit subject 0' in buffer, got:\n{content}",
        );
        assert!(
            content.contains("Commit subject 1"),
            "Expected 'Commit subject 1' in buffer, got:\n{content}",
        );
        assert!(
            content.contains("Commit subject 2"),
            "Expected 'Commit subject 2' in buffer, got:\n{content}",
        );
        // At 210 columns wide hash should be visible.
        assert!(
            !content.contains("Test User"),
            "Author 'Test User' should NOT appear in commit list, got:\n{content}",
        );
    }

    #[test]
    fn non_git_directory_shows_error() {
        let tmp = std::env::temp_dir().join("tuit-e2e-non-git");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(&tmp).unwrap();

        let backend = run_with_events(&tmp, vec![Key::Enter]);
        let buf = backend.buffer();
        let content = buf_to_string(buf);

        // The error message may have spacing artifacts in buffer concatenation.
        let stripped: String = content.chars().filter(|c| !c.is_whitespace()).collect();
        assert!(
            stripped.contains("tuitはgitリポジトリの中で実行してください"),
            "Expected error message, got:\n{content}",
        );
    }

    #[test]
    fn empty_repository_shows_empty_message() {
        let tmp = std::env::temp_dir().join("tuit-e2e-empty");
        init_empty_repo(&tmp);

        let backend = run_with_events(&tmp, vec![Key::Enter]);
        let buf = backend.buffer();
        let content = buf_to_string(buf);

        let stripped: String = content.chars().filter(|c| !c.is_whitespace()).collect();
        assert!(
            stripped.contains("このリポジトリにはまだコミットがありません"),
            "Expected empty repo message, got:\n{content}",
        );
    }

    /// Convert a TestBackend buffer cells to a plain string for easy assertion.
    /// Skips cells that are hidden (empty symbols) and collapses runs of spaces.
    fn buf_to_string(buf: &ratatui::buffer::Buffer) -> String {
        let mut s = String::new();
        let area = buf.area;
        for y in 0..area.height {
            let mut prev_was_space = false;
            for x in 0..area.width {
                let cell = buf.cell((x, y)).unwrap();
                let sym = cell.symbol();
                if sym.is_empty() {
                    continue;
                }
                if sym == " " {
                    if prev_was_space {
                        continue;
                    }
                    prev_was_space = true;
                } else {
                    prev_was_space = false;
                }
                s.push_str(sym);
            }
            if y + 1 < area.height {
                s.push('\n');
            }
        }
        s
    }

    #[test]
    fn poll_detects_new_commit() {
        let tmp = std::env::temp_dir().join("tuit-e2e-poll-new");
        init_repo(&tmp, 2);

        let prev_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&tmp).unwrap();

        let cfg = config::Config {
            theme: "default".into(),
            colors: config::default_colors(),
            poll_interval_ms: 2000,
            notification_timeout_ms: 3000,
        };
        let mut app = App::new(cfg, tmp.clone());
        app.load_commits();

        // Initial state: 2 commits
        assert_eq!(app.commits.len(), 2);
        assert_eq!(app.screen, Screen::List);
        let first_head = app.current_head_oid.clone();

        // Add a third commit via git CLI
        let file = tmp.join("file-2.txt");
        std::fs::write(&file, "content 2").unwrap();
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "add", &file.to_string_lossy()])
            .status()
            .unwrap();
        Command::new("git")
            .args([
                "-C",
                &tmp.to_string_lossy(),
                "commit",
                "--allow-empty",
                "-m",
                "Commit subject 2",
            ])
            .env("GIT_AUTHOR_NAME", "Test User")
            .env("GIT_AUTHOR_EMAIL", "test@example.com")
            .env("GIT_COMMITTER_NAME", "Test User")
            .env("GIT_COMMITTER_EMAIL", "test@example.com")
            .status()
            .unwrap();

        // First poll: just records HEAD (skip change detection)
        app.poll();
        assert!(app.current_head_oid.is_some());
        assert_ne!(app.current_head_oid, first_head);
        assert_eq!(app.commits.len(), 3);
        assert!(
            app.commits[0].message.contains("Commit subject 2"),
            "Expected newest commit at top, got: {}",
            app.commits[0].message
        );

        std::env::set_current_dir(prev_dir).unwrap();
    }

    #[test]
    fn poll_head_change_shows_notification() {
        let tmp = std::env::temp_dir().join("tuit-e2e-poll-head-notification");
        init_repo(&tmp, 2);

        let prev_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&tmp).unwrap();

        let cfg = config::Config {
            theme: "default".into(),
            colors: config::default_colors(),
            poll_interval_ms: 2000,
            notification_timeout_ms: 3000,
        };
        let mut app = App::new(cfg, tmp.clone());
        app.load_commits();

        // First poll records the initial HEAD.
        app.poll();
        assert!(app.current_head_oid.is_some());
        assert!(
            app.notification.is_none(),
            "No notification on initial HEAD recording"
        );

        // Add a new commit so HEAD changes.
        let file = tmp.join("head-notification.txt");
        std::fs::write(&file, "head notification content").unwrap();
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "add", &file.to_string_lossy()])
            .status()
            .unwrap();
        Command::new("git")
            .args([
                "-C",
                &tmp.to_string_lossy(),
                "commit",
                "--allow-empty",
                "-m",
                "Head change notification commit",
            ])
            .env("GIT_AUTHOR_NAME", "Test User")
            .env("GIT_AUTHOR_EMAIL", "test@example.com")
            .env("GIT_COMMITTER_NAME", "Test User")
            .env("GIT_COMMITTER_EMAIL", "test@example.com")
            .status()
            .unwrap();

        // Force the next poll to run despite throttle.
        app.last_poll_time = std::time::Instant::now() - std::time::Duration::from_millis(5000);
        app.poll();

        assert!(
            app.notification.is_some(),
            "Expected notification after HEAD change"
        );
        assert!(
            app.notification
                .as_ref()
                .unwrap()
                .message
                .contains("HEAD moved"),
            "Expected HEAD moved notification, got: {:?}",
            app.notification
        );

        std::env::set_current_dir(prev_dir).unwrap();
    }

    #[test]
    fn poll_timestamps_update_in_detail() {
        let tmp = std::env::temp_dir().join("tuit-e2e-poll-detail-time");
        init_repo(&tmp, 1);

        let prev_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&tmp).unwrap();

        let cfg = config::Config {
            theme: "default".into(),
            colors: config::default_colors(),
            poll_interval_ms: 2000,
            notification_timeout_ms: 3000,
        };
        let mut app = App::new(cfg, tmp.clone());
        app.load_commits();
        app.select_commit();
        assert_eq!(app.screen, Screen::Detail);

        let _original_date = app.selected_commit.as_ref().unwrap().date.clone();

        // First poll (HEAD recording)
        app.poll();

        // Second poll: HEAD unchanged, timestamp might have advanced
        app.last_poll_time = std::time::Instant::now() - std::time::Duration::from_millis(5000); // force poll to run
        app.poll();

        // Should still be in Detail with same OID
        assert_eq!(app.screen, Screen::Detail);
        assert!(app.selected_commit.is_some());

        std::env::set_current_dir(prev_dir).unwrap();
    }

    #[test]
    fn detail_overlay_hides_commit_list_text() {
        let tmp = std::env::temp_dir().join("tuit-e2e-detail-overlay");
        init_repo(&tmp, 5);
        let backend = run_with_events(&tmp, vec![Key::Enter]);
        let content = buf_to_string(backend.buffer());

        // When detail is open for the first (most recent) commit, only its subject
        // should be visible; the other list rows must not leak through the popup.
        assert!(
            content.contains("Commit subject 4"),
            "Expected selected commit subject in buffer, got:\n{content}",
        );
        for i in 0..4 {
            assert!(
                !content.contains(&format!("Commit subject {i}")),
                "Commit subject {i} leaked through popup:\n{content}",
            );
        }
    }

    #[test]
    fn reload_detects_branch_switch() {
        let tmp = std::env::temp_dir().join("tuit-e2e-reload-branch");
        init_repo(&tmp, 2);

        // Create and switch to a second branch with one more commit.
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "checkout", "-b", "feature"])
            .status()
            .unwrap();
        let file = tmp.join("feature.txt");
        std::fs::write(&file, "feature content").unwrap();
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "add", &file.to_string_lossy()])
            .status()
            .unwrap();
        Command::new("git")
            .args([
                "-C",
                &tmp.to_string_lossy(),
                "commit",
                "-m",
                "Commit subject 2 (feature)",
            ])
            .env("GIT_AUTHOR_NAME", "Test User")
            .env("GIT_AUTHOR_EMAIL", "test@example.com")
            .env("GIT_COMMITTER_NAME", "Test User")
            .env("GIT_COMMITTER_EMAIL", "test@example.com")
            .status()
            .unwrap();

        // Switch back to main (2 commits).
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "checkout", "main"])
            .status()
            .unwrap();

        let prev_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&tmp).unwrap();

        let cfg = config::Config {
            theme: "default".into(),
            colors: config::default_colors(),
            poll_interval_ms: 2000,
            notification_timeout_ms: 3000,
        };
        let mut app = App::new(cfg, tmp.clone());
        app.load_commits();

        // Initial state: on main with 2 commits
        assert_eq!(app.current_branch, "main");
        assert_eq!(app.commits.len(), 2);

        // Switch to feature branch via CLI
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "checkout", "feature"])
            .status()
            .unwrap();

        // Reload
        app.reload();

        // Now on feature with 3 commits
        assert_eq!(app.current_branch, "feature");
        assert_eq!(app.commits.len(), 3);
        assert!(
            app.commits[0]
                .message
                .contains("Commit subject 2 (feature)"),
            "Expected feature branch commit at top, got: {}",
            app.commits[0].message
        );
        assert_eq!(app.selected_index, 0);
        assert_eq!(app.screen, Screen::List);
        assert!(app.selected_commit.is_none());

        std::env::set_current_dir(prev_dir).unwrap();
    }

    #[test]
    fn reload_via_key_event_updates_branch_in_handle_input() {
        // Test that handle_input with Key::Char('r') correctly triggers reload.
        let tmp = std::env::temp_dir().join("tuit-e2e-reload-key-event");
        init_repo(&tmp, 2);

        // Create feature branch with one extra commit.
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "checkout", "-b", "feature"])
            .status()
            .unwrap();
        let file = tmp.join("f.txt");
        std::fs::write(&file, "f").unwrap();
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "add", &file.to_string_lossy()])
            .status()
            .unwrap();
        Command::new("git")
            .args([
                "-C",
                &tmp.to_string_lossy(),
                "commit",
                "-m",
                "Feature commit",
            ])
            .env("GIT_AUTHOR_NAME", "Test User")
            .env("GIT_AUTHOR_EMAIL", "test@example.com")
            .env("GIT_COMMITTER_NAME", "Test User")
            .env("GIT_COMMITTER_EMAIL", "test@example.com")
            .status()
            .unwrap();

        // Switch back to main.
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "checkout", "main"])
            .status()
            .unwrap();

        let prev_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&tmp).unwrap();

        let cfg = config::Config {
            theme: "default".into(),
            colors: config::default_colors(),
            poll_interval_ms: 2000,
            notification_timeout_ms: 3000,
        };
        let mut app = App::new(cfg, tmp.clone());
        app.load_commits();

        assert_eq!(app.current_branch, "main");
        assert_eq!(app.commits.len(), 2);

        // Switch to feature via CLI, then simulate pressing 'r'.
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "checkout", "feature"])
            .status()
            .unwrap();

        handle_input(&mut app, Key::Char('r'));

        assert_eq!(
            app.current_branch, "feature",
            "branch name should update after reload"
        );
        assert_eq!(
            app.commits.len(),
            3,
            "commit count should reflect feature branch"
        );
        assert!(
            app.commits[0].message.contains("Feature commit"),
            "top commit should be the feature branch commit"
        );
        assert_eq!(app.screen, Screen::List);
        assert_eq!(app.selected_index, 0);

        std::env::set_current_dir(prev_dir).unwrap();
    }

    #[test]
    fn reload_via_run_app_r_key() {
        let tmp = std::env::temp_dir().join("tuit-e2e-run-app-r");
        init_repo(&tmp, 3);

        // Create a feature branch with one commit, switch back to main.
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "checkout", "-b", "feature"])
            .status()
            .unwrap();
        let file = tmp.join("ft.txt");
        std::fs::write(&file, "ft").unwrap();
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "add", &file.to_string_lossy()])
            .status()
            .unwrap();
        Command::new("git")
            .args([
                "-C",
                &tmp.to_string_lossy(),
                "commit",
                "-m",
                "Only on feature",
            ])
            .env("GIT_AUTHOR_NAME", "Test User")
            .env("GIT_AUTHOR_EMAIL", "test@example.com")
            .env("GIT_COMMITTER_NAME", "Test User")
            .env("GIT_COMMITTER_EMAIL", "test@example.com")
            .status()
            .unwrap();
        Command::new("git")
            .args(["-C", &tmp.to_string_lossy(), "checkout", "main"])
            .status()
            .unwrap();

        // Run with just 'r' then 'q' — at startup we're on main (3 commits).
        // The 'r' reloads from the same branch, so no visible change.
        // Test that the app doesn't crash and renders something.
        let backend = run_with_events(&tmp, vec![Key::Char('r'), Key::Char('q')]);
        let content = buf_to_string(backend.buffer());
        assert!(
            content.contains("main"),
            "Expected branch 'main' in header, got:\n{content}"
        );
        assert!(
            content.contains("tuit"),
            "Expected 'tuit' in header, got:\n{content}"
        );
        assert!(
            content.contains("Commit subject 0"),
            "Expected commit 0 in list after reload, got:\n{content}"
        );
    }

    #[test]
    fn reload_detaches_detail_view() {
        let tmp = std::env::temp_dir().join("tuit-e2e-reload-detail");
        init_repo(&tmp, 3);

        let prev_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&tmp).unwrap();

        let cfg = config::Config {
            theme: "default".into(),
            colors: config::default_colors(),
            poll_interval_ms: 2000,
            notification_timeout_ms: 3000,
        };
        let mut app = App::new(cfg, tmp.clone());
        app.load_commits();
        app.select_commit();

        // Confirm we are in Detail
        assert_eq!(app.screen, Screen::Detail);
        assert!(app.selected_commit.is_some());
        assert!(app.selected_index == 0);

        // Reload
        app.reload();

        // Should be back to List with selection reset
        assert_eq!(app.screen, Screen::List);
        assert!(app.selected_commit.is_none());
        assert_eq!(app.selected_index, 0);

        std::env::set_current_dir(prev_dir).unwrap();
    }

    #[test]
    fn narrow_width_hides_author_and_hash() {
        let tmp = std::env::temp_dir().join("tuit-e2e-narrow");
        init_repo(&tmp, 3);

        // Run with 30-column terminal: neither author nor hash should be visible.
        let prev_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&tmp).unwrap();

        let backend = TestBackend::new(30, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let _ = super::run_app(&mut terminal, vec![Key::Char('q')].into_iter(), tmp.clone());
        let content = buf_to_string(terminal.backend().buffer());

        std::env::set_current_dir(prev_dir).unwrap();

        // Author should NOT appear (width < 45).
        assert!(
            !content.contains("Test User"),
            "Author 'Test User' unexpectedly found in narrow (30-col) rendering:\n{content}",
        );
        // Full 7-char hex hashes should NOT appear either (width < 32 means hash hidden).
        // Commit subjects should still be visible.
        for i in 0..3 {
            assert!(
                content.contains(&format!("Commit subject {i}")),
                "Commit subject {i} missing in 30-col rendering:\n{content}",
            );
        }
    }

    #[test]
    fn mouse_click_selects_commit_in_list() {
        let tmp = std::env::temp_dir().join("tuit-e2e-mouse-click");
        init_repo(&tmp, 5);

        let prev_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&tmp).unwrap();

        let cfg = config::Config {
            theme: "default".into(),
            colors: config::default_colors(),
            poll_interval_ms: 2000,
            notification_timeout_ms: 3000,
        };
        let mut app = App::new(cfg, tmp.clone());
        app.load_commits();
        assert_eq!(app.screen, Screen::List);
        assert_eq!(app.commits.len(), 5);
        assert_eq!(app.selected_index, 0);

        // Click on the third visible row (header is row 0, list starts at row 1).
        super::handle_input(&mut app, Key::MouseClick(3));
        assert_eq!(
            app.selected_index, 2,
            "Click on row 3 should select index 2"
        );

        // Click on the first list row.
        super::handle_input(&mut app, Key::MouseClick(1));
        assert_eq!(
            app.selected_index, 0,
            "Click on row 1 should select index 0"
        );

        // Click on the header row is ignored.
        super::handle_input(&mut app, Key::MouseClick(0));
        assert_eq!(
            app.selected_index, 0,
            "Click on header row should not change selection"
        );

        // Click beyond the commit list is ignored.
        super::handle_input(&mut app, Key::MouseClick(100));
        assert_eq!(
            app.selected_index, 0,
            "Click beyond list should not change selection"
        );

        std::env::set_current_dir(prev_dir).unwrap();
    }
}