gitlogue 0.9.0

A Git history screensaver - watch your code rewrite itself
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
use std::cell::RefCell;
use std::time::{Duration, Instant};

use globset::{Glob, GlobMatcher};
use rand::RngExt;
use std::collections::VecDeque;
use unicode_width::UnicodeWidthStr;

use crate::git::{CommitMetadata, DiffHunk, FileChange, FileStatus, LineChangeType};
use crate::syntax::Highlighter;

/// A rule that specifies typing speed for files matching a glob pattern
#[derive(Debug, Clone)]
pub struct SpeedRule {
    pub matcher: GlobMatcher,
    pub speed_ms: u64,
}

impl SpeedRule {
    /// Parse a speed rule from string format "PATTERN:SPEED_MS"
    /// Example: "*.java:50" or "src/**/*.rs:30"
    pub fn parse(s: &str) -> Option<Self> {
        let parts: Vec<&str> = s.rsplitn(2, ':').collect();
        if parts.len() != 2 {
            return None;
        }
        let speed_ms = parts[0].parse::<u64>().ok()?;
        let pattern_str = parts[1];
        let glob = Glob::new(pattern_str).ok()?;
        let matcher = glob.compile_matcher();
        Some(Self { matcher, speed_ms })
    }

    /// Check if a file path matches this rule
    pub fn matches(&self, path: &str) -> bool {
        self.matcher.is_match(path)
    }
}

// Duration multipliers relative to typing speed
const CURSOR_MOVE_PAUSE: f64 = 0.5; // Cursor movement between lines (base speed)
const CURSOR_MOVE_SHORT_MULTIPLIER: f64 = 1.0; // Speed for short distances (1-50 lines)
const CURSOR_MOVE_MEDIUM_MULTIPLIER: f64 = 0.3; // Speed for medium distances (51-200 lines)
const CURSOR_MOVE_LONG_MULTIPLIER: f64 = 0.05; // Speed for long distances (201+ lines)
const MAX_SCROLL_STEPS: usize = 60; // Maximum animation steps for any scroll distance
const MIN_LOG_STEPS: usize = 50; // Minimum steps for logarithmic scaling (aligned with SHORT threshold)
const LOG_SCALE_FACTOR: f64 = 8.0; // Scaling factor for logarithmic step calculation
const DELETE_LINE_PAUSE: f64 = 10.0; // After deleting a line
const INSERT_LINE_PAUSE: f64 = 6.7; // After inserting a line
const HUNK_PAUSE: f64 = 50.0; // Between hunks
const CHECKOUT_PAUSE: f64 = 16.7; // After git checkout command
const CHECKOUT_OUTPUT_PAUSE: f64 = 33.3; // After git checkout output
const OPEN_FILE_FIRST_PAUSE: f64 = 33.3; // Before opening first file
const OPEN_FILE_PAUSE: f64 = 50.0; // Before opening subsequent files
const OPEN_CMD_PAUSE: f64 = 16.7; // After open command
const FILE_SWITCH_PAUSE: f64 = 26.7; // After switching file
const GIT_ADD_PAUSE: f64 = 33.3; // Before git add
const GIT_ADD_CMD_PAUSE: f64 = 16.7; // After git add command
const GIT_COMMIT_PAUSE: f64 = 26.7; // After git commit command
const COMMIT_OUTPUT_PAUSE: f64 = 33.3; // After commit output
const GIT_PUSH_PAUSE: f64 = 16.7; // After git push command
const PUSH_OUTPUT_PAUSE: f64 = 10.0; // Between push output lines
const PUSH_FINAL_PAUSE: f64 = 66.7; // After final push output

const MAX_LINE_CHECKPOINTS: usize = 200;
const MAX_CHANGE_CHECKPOINTS: usize = 64;

/// Represents the current state of the editor buffer
#[derive(Debug, Clone)]
pub struct EditorBuffer {
    pub lines: Vec<String>,
    pub cursor_line: usize,
    pub cursor_col: usize,
    pub scroll_offset: usize,
    pub cached_highlights: Vec<crate::syntax::HighlightSpan>,
    /// Pre-calculated highlights for old and new content
    pub old_highlights: Vec<crate::syntax::HighlightSpan>,
    pub new_highlights: Vec<crate::syntax::HighlightSpan>,
    /// Store old and new content for byte offset calculation
    pub old_content_lines: Vec<String>,
    pub new_content_lines: Vec<String>,
    /// Pre-calculated byte offsets for each line (handles CRLF correctly)
    pub old_content_line_offsets: Vec<usize>,
    pub new_content_line_offsets: Vec<usize>,
}

impl EditorBuffer {
    /// Creates a new empty editor buffer with default values.
    pub fn new() -> Self {
        Self {
            lines: vec![String::new()],
            cursor_line: 0,
            cursor_col: 0,
            scroll_offset: 0,
            cached_highlights: Vec::new(),
            old_highlights: Vec::new(),
            new_highlights: Vec::new(),
            old_content_lines: Vec::new(),
            new_content_lines: Vec::new(),
            old_content_line_offsets: Vec::new(),
            new_content_line_offsets: Vec::new(),
        }
    }

    /// Creates an editor buffer initialized with the given content.
    pub fn from_content(content: &str) -> Self {
        let lines: Vec<String> = if content.is_empty() {
            vec![String::new()]
        } else {
            content.lines().map(|s| s.to_string()).collect()
        };

        Self {
            lines,
            cursor_line: 0,
            cursor_col: 0,
            scroll_offset: 0,
            cached_highlights: Vec::new(),
            old_highlights: Vec::new(),
            new_highlights: Vec::new(),
            old_content_lines: Vec::new(),
            new_content_lines: Vec::new(),
            old_content_line_offsets: Vec::new(),
            new_content_line_offsets: Vec::new(),
        }
    }

    /// Inserts a character at the specified line and column position.
    pub fn insert_char(&mut self, line: usize, col: usize, ch: char) {
        if line >= self.lines.len() {
            self.lines.resize(line + 1, String::new());
        }
        let line_str = &mut self.lines[line];

        // Convert char index to byte index
        let byte_idx = line_str
            .char_indices()
            .nth(col)
            .map(|(idx, _)| idx)
            .unwrap_or_else(|| line_str.len());

        line_str.insert(byte_idx, ch);
    }

    /// Inserts a new line with the given content at the specified position.
    pub fn insert_line(&mut self, line: usize, content: String) {
        if line > self.lines.len() {
            self.lines.resize(line, String::new());
        }
        self.lines.insert(line, content);
    }

    /// Deletes the line at the specified position.
    pub fn delete_line(&mut self, line: usize) {
        if line < self.lines.len() {
            self.lines.remove(line);
        }
        if self.lines.is_empty() {
            self.lines.push(String::new());
        }
    }
}

/// Individual animation step
#[derive(Debug, Clone)]
pub enum AnimationStep {
    InsertChar {
        line: usize,
        col: usize,
        ch: char,
    },
    InsertLine {
        line: usize,
        content: String,
    },
    DeleteLine {
        line: usize,
    },
    MoveCursor {
        line: usize,
        col: usize,
    },
    Pause {
        multiplier: f64,
    },
    SwitchFile {
        file_index: usize,
        old_content: String,
        new_content: String,
        path: String,
    },
    OpenFileDialogStart,
    DialogTypeChar {
        ch: char,
    },
    TerminalPrompt,
    TerminalTypeChar {
        ch: char,
    },
    TerminalOutput {
        text: String,
    },
    ResetState,
}

/// Animation state machine
#[derive(Debug, Clone, PartialEq)]
pub enum AnimationState {
    Idle,
    Playing,
    Finished,
}

/// Which pane is currently active
#[derive(Debug, Clone, PartialEq)]
pub enum ActivePane {
    Editor,
    Terminal,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum StepMode {
    Line,
    Change,
}

#[derive(Clone)]
struct ManualCheckpoint {
    step_index: usize,
    buffer: EditorBuffer,
    current_file_index: usize,
    current_file_path: Option<String>,
    terminal_lines: Vec<String>,
    active_pane: ActivePane,
    line_offset: isize,
    dialog_title: Option<String>,
    dialog_typing_text: String,
    speed_ms: u64,
}

impl ManualCheckpoint {
    fn new(engine: &AnimationEngine) -> Self {
        let resume_step = engine
            .current_step
            .saturating_add(1)
            .min(engine.steps.len());
        Self {
            step_index: resume_step,
            buffer: engine.buffer.clone(),
            current_file_index: engine.current_file_index,
            current_file_path: engine.current_file_path.clone(),
            terminal_lines: engine.terminal_lines.clone(),
            active_pane: engine.active_pane.clone(),
            line_offset: engine.line_offset,
            dialog_title: engine.dialog_title.clone(),
            dialog_typing_text: engine.dialog_typing_text.clone(),
            speed_ms: engine.speed_ms,
        }
    }
}

#[derive(Clone, Copy, PartialEq)]
enum CheckpointKind {
    Line,
    Change,
}

/// Main animation engine
pub struct AnimationEngine {
    pub buffer: EditorBuffer,
    pub state: AnimationState,
    steps: Vec<AnimationStep>,
    current_step: usize,
    last_update: Instant,
    speed_ms: u64,
    base_speed_ms: u64,
    next_step_delay: u64,
    pause_until: Option<Instant>,
    pub cursor_visible: bool,
    cursor_blink_timer: Instant,
    viewport_height: usize,
    content_width: usize,
    pub current_file_index: usize,
    pub current_file_path: Option<String>,
    pub terminal_lines: Vec<String>,
    pub active_pane: ActivePane,
    pub highlighter: RefCell<Highlighter>,
    /// Track cumulative line offset from old_content (insertions - deletions)
    pub line_offset: isize,
    /// Target frames per second for rendering
    #[allow(dead_code)]
    target_fps: u64,
    /// Frame interval in milliseconds (calculated from target_fps)
    frame_interval_ms: u64,
    /// Last frame render time
    last_frame: Instant,
    /// Dialog title (e.g., "Open File...")
    pub dialog_title: Option<String>,
    /// Text being typed in the dialog
    pub dialog_typing_text: String,
    /// Current metadata being displayed
    current_metadata: Option<CommitMetadata>,
    /// Pending metadata to be applied on ResetState
    pending_metadata: Option<CommitMetadata>,
    /// Speed rules for different file patterns
    speed_rules: Vec<SpeedRule>,
    paused: bool,
    line_checkpoints: VecDeque<ManualCheckpoint>,
    change_checkpoints: VecDeque<ManualCheckpoint>,
}

impl AnimationEngine {
    /// Creates a new animation engine with the specified typing speed.
    pub fn new(speed_ms: u64) -> Self {
        let target_fps: u64 = 120;
        let frame_interval_ms = 1000 / target_fps;
        let now = Instant::now();
        Self {
            buffer: EditorBuffer::new(),
            state: AnimationState::Idle,
            steps: Vec::new(),
            current_step: 0,
            last_update: now,
            speed_ms,
            base_speed_ms: speed_ms,
            next_step_delay: speed_ms,
            pause_until: None,
            cursor_visible: true,
            cursor_blink_timer: now,
            viewport_height: 20, // Default, will be updated from UI
            content_width: 80,   // Default, will be updated from UI
            current_file_index: 0,
            current_file_path: None,
            terminal_lines: Vec::new(),
            active_pane: ActivePane::Terminal, // Start with terminal (git checkout)
            highlighter: RefCell::new(Highlighter::new()),
            line_offset: 0,
            target_fps,
            frame_interval_ms,
            last_frame: now,
            dialog_title: None,
            dialog_typing_text: String::new(),
            current_metadata: None,
            pending_metadata: None,
            speed_rules: Vec::new(),
            paused: false,
            line_checkpoints: VecDeque::new(),
            change_checkpoints: VecDeque::new(),
        }
    }

    /// Pause the animation playback.
    pub fn pause(&mut self) {
        self.paused = true;
    }

    /// Resume animation playback from the current position.
    pub fn resume(&mut self) {
        if self.paused {
            self.paused = false;
            let now = Instant::now();
            self.last_update = now;
            self.last_frame = now;
        }
    }

    /// Execute animation steps manually until the next boundary for the given mode.
    pub fn manual_step(&mut self, mode: StepMode) -> bool {
        if self.state != AnimationState::Playing {
            return false;
        }

        if self.current_step >= self.steps.len() {
            self.state = AnimationState::Finished;
            return false;
        }

        self.pause_until = None;
        let mut executed = false;

        while self.current_step < self.steps.len() {
            let step = self.steps[self.current_step].clone();
            self.execute_step(step.clone());
            self.current_step += 1;
            executed = true;

            if self.current_step >= self.steps.len() {
                self.state = AnimationState::Finished;
            }

            if Self::is_boundary_step(&step, mode) {
                break;
            }
        }

        if executed {
            let now = Instant::now();
            self.last_update = now;
            self.last_frame = now;
        }

        executed
    }

    pub fn restore_line_checkpoint(&mut self) -> bool {
        if self.line_checkpoints.len() < 2 {
            return false;
        }
        self.line_checkpoints.pop_back();
        if let Some(snapshot) = self.line_checkpoints.back().cloned() {
            self.apply_checkpoint(snapshot);
            true
        } else {
            false
        }
    }

    pub fn restore_change_checkpoint(&mut self) -> bool {
        if self.change_checkpoints.len() < 2 {
            return false;
        }
        self.change_checkpoints.pop_back();
        if let Some(snapshot) = self.change_checkpoints.back().cloned() {
            self.apply_checkpoint(snapshot);
            true
        } else {
            false
        }
    }

    fn apply_checkpoint(&mut self, snapshot: ManualCheckpoint) {
        self.current_step = snapshot.step_index;
        self.buffer = snapshot.buffer;
        self.current_file_index = snapshot.current_file_index;
        self.current_file_path = snapshot.current_file_path;
        self.terminal_lines = snapshot.terminal_lines;
        self.active_pane = snapshot.active_pane;
        self.line_offset = snapshot.line_offset;
        self.dialog_title = snapshot.dialog_title;
        self.dialog_typing_text = snapshot.dialog_typing_text;
        self.speed_ms = snapshot.speed_ms;
        self.pause_until = None;
        self.paused = true;
        self.state = AnimationState::Playing;
    }

    fn is_boundary_step(step: &AnimationStep, mode: StepMode) -> bool {
        match mode {
            StepMode::Line => matches!(
                step,
                AnimationStep::Pause { .. }
                    | AnimationStep::SwitchFile { .. }
                    | AnimationStep::TerminalPrompt
                    | AnimationStep::TerminalOutput { .. }
                    | AnimationStep::ResetState
            ),
            StepMode::Change => match step {
                AnimationStep::SwitchFile { .. }
                | AnimationStep::TerminalPrompt
                | AnimationStep::TerminalOutput { .. }
                | AnimationStep::ResetState => true,
                AnimationStep::Pause { multiplier } => Self::is_change_pause(*multiplier),
                _ => false,
            },
        }
    }

    fn handle_step_checkpoint(&mut self, step: &AnimationStep) {
        match step {
            AnimationStep::ResetState => {
                self.clear_checkpoints();
                self.record_checkpoint(CheckpointKind::Change);
                self.record_checkpoint(CheckpointKind::Line);
            }
            AnimationStep::SwitchFile { .. } => {
                self.line_checkpoints.clear();
                self.record_checkpoint(CheckpointKind::Change);
                self.record_checkpoint(CheckpointKind::Line);
            }
            AnimationStep::Pause { multiplier } if self.active_pane == ActivePane::Editor => {
                self.record_checkpoint(CheckpointKind::Line);
                if Self::is_change_pause(*multiplier) {
                    self.record_checkpoint(CheckpointKind::Change);
                }
            }
            _ => {}
        }
    }

    fn is_change_pause(multiplier: f64) -> bool {
        (multiplier - HUNK_PAUSE).abs() < f64::EPSILON
    }

    fn record_checkpoint(&mut self, kind: CheckpointKind) {
        if self.current_step == 0 {
            return;
        }

        let snapshot = ManualCheckpoint::new(self);
        match kind {
            CheckpointKind::Line => {
                if self
                    .line_checkpoints
                    .back()
                    .map(|c| c.step_index == snapshot.step_index)
                    .unwrap_or(false)
                {
                    return;
                }
                self.line_checkpoints.push_back(snapshot);
                if self.line_checkpoints.len() > MAX_LINE_CHECKPOINTS {
                    self.line_checkpoints.pop_front();
                }
            }
            CheckpointKind::Change => {
                if self
                    .change_checkpoints
                    .back()
                    .map(|c| c.step_index == snapshot.step_index)
                    .unwrap_or(false)
                {
                    return;
                }
                self.change_checkpoints.push_back(snapshot);
                if self.change_checkpoints.len() > MAX_CHANGE_CHECKPOINTS {
                    self.change_checkpoints.pop_front();
                }
            }
        }
    }

    fn clear_checkpoints(&mut self) {
        self.line_checkpoints.clear();
        self.change_checkpoints.clear();
    }

    /// Set speed rules for file-specific typing speeds
    pub fn set_speed_rules(&mut self, rules: Vec<SpeedRule>) {
        self.speed_rules = rules;
    }

    /// Get the speed for a given file path based on speed rules
    /// Returns the first matching rule's speed, or the base speed if no match
    fn get_speed_for_file(&self, path: &str) -> u64 {
        for rule in &self.speed_rules {
            if rule.matches(path) {
                return rule.speed_ms;
            }
        }
        self.base_speed_ms
    }

    /// Sets the viewport height for scroll calculations.
    pub fn set_viewport_height(&mut self, height: usize) {
        self.viewport_height = height;
    }

    /// Sets the content width for line wrapping calculations.
    pub fn set_content_width(&mut self, width: usize) {
        self.content_width = width;
    }

    /// Get the current metadata being displayed
    pub fn current_metadata(&self) -> Option<&CommitMetadata> {
        self.current_metadata.as_ref()
    }

    fn calculate_line_offsets(content: &str) -> Vec<usize> {
        std::iter::once(0)
            .chain(content.bytes().enumerate().filter_map(|(i, b)| {
                if b == b'\n' {
                    Some(i + 1)
                } else {
                    None
                }
            }))
            .collect()
    }

    /// Add a terminal command with typing animation
    fn add_terminal_command(&mut self, command: &str) {
        self.steps.push(AnimationStep::TerminalPrompt);
        for ch in command.chars() {
            self.steps.push(AnimationStep::TerminalTypeChar { ch });
        }
    }

    /// Load a commit and generate animation steps
    pub fn load_commit(&mut self, metadata: &CommitMetadata) {
        // Store pending metadata to be applied on ResetState
        self.pending_metadata = Some(metadata.clone());

        self.steps.clear();
        self.current_step = 0;
        self.state = AnimationState::Playing;
        self.last_update = Instant::now();
        self.pause_until = None;

        // Check if this is a working tree diff (not a real commit)
        let is_working_tree = metadata.hash == "working-tree";

        if is_working_tree {
            // Simplified intro for working tree diffs
            self.add_terminal_command("git diff --stat");
            self.steps.push(AnimationStep::Pause {
                multiplier: CHECKOUT_PAUSE,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: format!("📝 {}", metadata.message),
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: format!(
                    "📁 {} file{} changed",
                    metadata.changes.len(),
                    if metadata.changes.len() == 1 { "" } else { "s" }
                ),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: CHECKOUT_OUTPUT_PAUSE,
            });
        } else {
            // Time travel to commit date
            let datetime_str = metadata.date.format("%Y-%m-%d %H:%M:%S").to_string();
            self.add_terminal_command(&format!("time-travel {}", datetime_str));
            self.steps.push(AnimationStep::Pause {
                multiplier: CHECKOUT_PAUSE,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: "⚡ Initializing temporal displacement field...".to_string(),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: CHECKOUT_OUTPUT_PAUSE * 0.5,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: "✨ Warping through spacetime...".to_string(),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: CHECKOUT_OUTPUT_PAUSE * 0.5,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: format!("🕰️  Arrived at {}", datetime_str),
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: format!(
                    "📍 Location: commit {} by {}",
                    &metadata.hash[..7],
                    metadata.author
                ),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: CHECKOUT_OUTPUT_PAUSE,
            });
        }

        // Apply new metadata after intro animation
        self.steps.push(AnimationStep::ResetState);

        // Sort file changes to match FileTree display order (directory -> filename)
        let sorted_indices = metadata.sorted_file_indices();

        // Process all file changes in sorted order
        for &index in &sorted_indices {
            let change = &metadata.changes[index];
            match (change.is_excluded, &change.status) {
                // Skip excluded files (lock files and generated files)
                (true, _) => {
                    // Switch to the excluded file to show in file tree
                    let old_content = change.old_content.clone().unwrap_or_default();
                    let new_content = change.new_content.clone().unwrap_or_default();
                    self.steps.push(AnimationStep::SwitchFile {
                        file_index: index,
                        old_content,
                        new_content,
                        path: change.path.clone(),
                    });

                    self.steps.push(AnimationStep::Pause {
                        multiplier: OPEN_FILE_PAUSE,
                    });
                    let reason = change
                        .exclusion_reason
                        .as_deref()
                        .unwrap_or("excluded file");
                    self.steps.push(AnimationStep::TerminalOutput {
                        text: format!("📦 {} (skipped - {})", change.path, reason),
                    });
                    self.steps.push(AnimationStep::Pause {
                        multiplier: OPEN_CMD_PAUSE,
                    });
                }
                // For deleted files, skip editor animation and only run rm + git add
                (false, FileStatus::Deleted) => {
                    // Switch to the deleted file to show in file tree
                    let old_content = change.old_content.clone().unwrap_or_default();
                    self.steps.push(AnimationStep::SwitchFile {
                        file_index: index,
                        old_content,
                        new_content: String::new(),
                        path: change.path.clone(),
                    });

                    self.steps.push(AnimationStep::Pause {
                        multiplier: GIT_ADD_PAUSE,
                    });
                    self.add_terminal_command(&format!("rm {}", change.path));
                    self.steps.push(AnimationStep::Pause {
                        multiplier: GIT_ADD_CMD_PAUSE,
                    });
                    self.add_terminal_command(&format!("git add {}", change.path));
                    self.steps.push(AnimationStep::Pause {
                        multiplier: GIT_ADD_CMD_PAUSE,
                    });
                }
                // For renamed/moved files, skip editor animation and only run mv + git add
                (false, FileStatus::Renamed) => {
                    // Switch to the renamed file to show in file tree
                    let old_content = change.old_content.clone().unwrap_or_default();
                    let new_content = change.new_content.clone().unwrap_or_default();
                    self.steps.push(AnimationStep::SwitchFile {
                        file_index: index,
                        old_content,
                        new_content,
                        path: change.path.clone(),
                    });

                    self.steps.push(AnimationStep::Pause {
                        multiplier: GIT_ADD_PAUSE,
                    });
                    if let Some(old_path) = &change.old_path {
                        self.add_terminal_command(&format!("mv {} {}", old_path, change.path));
                        self.steps.push(AnimationStep::Pause {
                            multiplier: GIT_ADD_CMD_PAUSE,
                        });
                    }
                    self.add_terminal_command(&format!("git add {}", change.path));
                    self.steps.push(AnimationStep::Pause {
                        multiplier: GIT_ADD_CMD_PAUSE,
                    });
                }
                // Normal files (Added, Modified, etc.) - full editor animation
                (false, _) => {
                    // Open file in editor
                    if index == 0 {
                        self.steps.push(AnimationStep::Pause {
                            multiplier: OPEN_FILE_FIRST_PAUSE,
                        });
                    } else {
                        self.steps.push(AnimationStep::Pause {
                            multiplier: OPEN_FILE_PAUSE,
                        });
                    }
                    // Show "Open File..." dialog and type the file path
                    self.steps.push(AnimationStep::OpenFileDialogStart);
                    self.steps.push(AnimationStep::Pause { multiplier: 5.0 });

                    // Type each character of the file path
                    for ch in change.path.chars() {
                        self.steps.push(AnimationStep::DialogTypeChar { ch });
                    }

                    self.steps.push(AnimationStep::Pause {
                        multiplier: OPEN_CMD_PAUSE,
                    });

                    // Add file switch step with both old and new content
                    let old_content = change.old_content.clone().unwrap_or_default();
                    let new_content = change.new_content.clone().unwrap_or_default();
                    self.steps.push(AnimationStep::SwitchFile {
                        file_index: index,
                        old_content,
                        new_content,
                        path: change.path.clone(),
                    });

                    // Add pause before starting file animation
                    self.steps.push(AnimationStep::Pause {
                        multiplier: FILE_SWITCH_PAUSE,
                    });

                    // Generate animation steps for this file
                    self.generate_steps_for_file(change);

                    // Git add this file after editing
                    self.steps.push(AnimationStep::Pause {
                        multiplier: GIT_ADD_PAUSE,
                    });
                    self.add_terminal_command(&format!("git add {}", change.path));
                    self.steps.push(AnimationStep::Pause {
                        multiplier: GIT_ADD_CMD_PAUSE,
                    });
                }
            }
        }

        // Skip git commit/push animation for working tree diffs
        if is_working_tree {
            // Just add a final pause for working tree mode
            self.steps.push(AnimationStep::Pause {
                multiplier: PUSH_FINAL_PAUSE,
            });
        } else {
            // Git commit
            let parent_hash = format!("{}^", &metadata.hash[..7]);
            let commit_message = metadata.message.lines().next().unwrap_or("Update");
            self.add_terminal_command(&format!("git commit -m \"{}\"", commit_message));
            self.steps.push(AnimationStep::Pause {
                multiplier: GIT_COMMIT_PAUSE,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: format!("💾 [main {}] {}", &metadata.hash[..7], commit_message),
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: format!(
                    "📝 {} file{} changed - immortalized forever!",
                    metadata.changes.len(),
                    if metadata.changes.len() == 1 { "" } else { "s" }
                ),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: COMMIT_OUTPUT_PAUSE,
            });

            // Git push
            self.add_terminal_command("git push origin main");
            self.steps.push(AnimationStep::Pause {
                multiplier: GIT_PUSH_PAUSE,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: "🚀 Launching code into the cloud...".to_string(),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: PUSH_OUTPUT_PAUSE,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: "📦 Compressing digital dreams: 100% (5/5)".to_string(),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: PUSH_OUTPUT_PAUSE,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: "✍️  Signing with invisible ink: done.".to_string(),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: GIT_PUSH_PAUSE,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: "📡 Beaming to origin/main via satellite...".to_string(),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: PUSH_OUTPUT_PAUSE,
            });
            self.steps.push(AnimationStep::TerminalOutput {
                text: format!(
                    "   {}..{} ✨ SUCCESS",
                    &parent_hash[..7],
                    &metadata.hash[..7]
                ),
            });
            self.steps.push(AnimationStep::Pause {
                multiplier: PUSH_FINAL_PAUSE,
            });
        }

        // Start with empty editor (no file opened yet)
        self.buffer = EditorBuffer::new();
        self.clear_checkpoints();
    }

    /// Generate animation steps for a file change
    fn generate_steps_for_file(&mut self, change: &FileChange) {
        let mut current_cursor_line = 0;
        let mut line_offset = 0i64; // Track how buffer lines differ from old file

        // Parse old_content into lines for indentation calculation during cursor movement
        let old_lines: Vec<&str> = change
            .old_content
            .as_ref()
            .map(|c| c.lines().collect())
            .unwrap_or_default();

        // Process each hunk
        for hunk in &change.hunks {
            // Calculate target line in current buffer
            // hunk.old_start is 1-indexed (Git line numbers start at 1)
            // We need to convert to 0-indexed and adjust by how many lines we've added/removed
            let target_line = ((hunk.old_start as i64) - 1 + line_offset).max(0) as usize;

            // Calculate distance for speed adjustment
            let distance = target_line.abs_diff(current_cursor_line);

            current_cursor_line = self.generate_cursor_movement(
                current_cursor_line,
                target_line,
                distance,
                &old_lines,
            );

            let (final_cursor_line, _final_buffer_line) =
                self.generate_steps_for_hunk(hunk, current_cursor_line, target_line);

            current_cursor_line = final_cursor_line;

            // Update offset based on changes in this hunk
            // Count additions and deletions to update the offset
            let additions = hunk
                .lines
                .iter()
                .filter(|l| matches!(l.change_type, LineChangeType::Addition))
                .count() as i64;
            let deletions = hunk
                .lines
                .iter()
                .filter(|l| matches!(l.change_type, LineChangeType::Deletion))
                .count() as i64;

            line_offset += additions - deletions;

            // Add pause between hunks
            self.steps.push(AnimationStep::Pause {
                multiplier: HUNK_PAUSE,
            });
        }
    }

    /// Generate cursor movement steps from current line to target line
    fn generate_cursor_movement(
        &mut self,
        from_line: usize,
        to_line: usize,
        distance: usize,
        lines: &[&str],
    ) -> usize {
        if from_line == to_line {
            return to_line;
        }

        // Determine base speed multiplier based on total distance
        let base_speed_multiplier = if distance <= 50 {
            CURSOR_MOVE_SHORT_MULTIPLIER
        } else if distance <= 200 {
            CURSOR_MOVE_MEDIUM_MULTIPLIER
        } else {
            CURSOR_MOVE_LONG_MULTIPLIER
        };

        // Limit total animation steps for performance
        // For very long distances, use fewer steps with larger jumps
        // Threshold aligned with SHORT distance category (50) to ensure monotonicity
        let num_steps = if distance <= MIN_LOG_STEPS {
            distance // Show every line for short distances
        } else {
            // Scale steps logarithmically for longer distances
            // This ensures smooth animation while limiting total steps
            let log_steps = (distance as f64).ln() * LOG_SCALE_FACTOR;
            (log_steps as usize).clamp(MIN_LOG_STEPS, MAX_SCROLL_STEPS)
        };

        let mut positions = Vec::with_capacity(num_steps + 1);

        for i in 0..=num_steps {
            let t = i as f64 / num_steps as f64;
            let eased = self.ease_in_out_cubic(t);
            let line_progress = (eased * distance as f64).round() as usize;

            let actual_line = if from_line < to_line {
                from_line + line_progress
            } else {
                from_line - line_progress
            };

            // Avoid duplicate positions
            if positions.is_empty() || positions.last() != Some(&actual_line) {
                positions.push(actual_line);
            }
        }

        // Generate movement steps
        let pause_multiplier = (CURSOR_MOVE_PAUSE * base_speed_multiplier).max(0.01);

        for line in positions {
            if line != from_line {
                // Calculate indentation (first non-whitespace character position)
                let col = lines
                    .get(line)
                    .map(|l| l.chars().take_while(|c| c.is_whitespace()).count())
                    .unwrap_or(0);
                self.steps.push(AnimationStep::MoveCursor { line, col });
                self.steps.push(AnimationStep::Pause {
                    multiplier: pause_multiplier,
                });
            }
        }

        to_line
    }

    /// Ease-in-out cubic easing function
    /// Starts slow, accelerates in middle, ends slow
    fn ease_in_out_cubic(&self, t: f64) -> f64 {
        if t < 0.5 {
            4.0 * t * t * t
        } else {
            1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
        }
    }

    /// Generate animation steps for a diff hunk
    /// Returns (final_cursor_line, final_buffer_line)
    fn generate_steps_for_hunk(
        &mut self,
        hunk: &DiffHunk,
        start_cursor_line: usize,
        start_buffer_line: usize,
    ) -> (usize, usize) {
        // buffer_line tracks the actual line number in the current buffer
        let mut buffer_line = start_buffer_line;
        let mut cursor_line = start_cursor_line;

        for line_change in &hunk.lines {
            match line_change.change_type {
                LineChangeType::Deletion => {
                    // Delete the entire line at current buffer position
                    self.steps
                        .push(AnimationStep::DeleteLine { line: buffer_line });
                    self.steps.push(AnimationStep::Pause {
                        multiplier: DELETE_LINE_PAUSE,
                    });
                    cursor_line = buffer_line;
                    // After deletion, buffer_line stays the same
                    // (the next line moves up to this position)
                }
                LineChangeType::Addition => {
                    let content = &line_change.content;
                    let indentation_len = content.chars().take_while(|c| c.is_whitespace()).count();

                    // Insert line with indentation already included
                    let indentation: String = content.chars().take(indentation_len).collect();
                    self.steps.push(AnimationStep::InsertLine {
                        line: buffer_line,
                        content: indentation,
                    });

                    // Type each character after the indentation
                    for (i, ch) in content.chars().skip(indentation_len).enumerate() {
                        self.steps.push(AnimationStep::InsertChar {
                            line: buffer_line,
                            col: indentation_len + i,
                            ch,
                        });
                    }

                    cursor_line = buffer_line;
                    buffer_line += 1; // Move to next line after insertion

                    self.steps.push(AnimationStep::Pause {
                        multiplier: INSERT_LINE_PAUSE,
                    });
                }
                LineChangeType::Context => {
                    // Move cursor to next line if needed
                    if buffer_line != cursor_line {
                        // Calculate indentation (first non-whitespace character position)
                        let col = line_change
                            .content
                            .chars()
                            .take_while(|c| c.is_whitespace())
                            .count();
                        self.steps.push(AnimationStep::MoveCursor {
                            line: buffer_line,
                            col,
                        });
                        self.steps.push(AnimationStep::Pause {
                            multiplier: CURSOR_MOVE_PAUSE,
                        });
                    }
                    cursor_line = buffer_line;
                    buffer_line += 1; // Move to next line
                }
            }
        }

        (cursor_line, buffer_line)
    }

    /// Updates animation state and returns true if display needs refresh.
    pub fn tick(&mut self) -> bool {
        self.update_cursor_blink();

        if self.paused {
            return true;
        }

        if self.is_paused() {
            return true;
        }

        if self.state != AnimationState::Playing {
            return false;
        }

        let now = Instant::now();
        if !self.should_render_frame(now) {
            return false;
        }

        let executed = self.execute_batch_steps(now);

        if self.current_step >= self.steps.len() {
            self.state = AnimationState::Finished;
        }

        executed
    }

    fn update_cursor_blink(&mut self) {
        if self.cursor_blink_timer.elapsed() >= Duration::from_millis(500) {
            self.cursor_visible = !self.cursor_visible;
            self.cursor_blink_timer = Instant::now();
        }
    }

    fn is_paused(&mut self) -> bool {
        if let Some(pause_until) = self.pause_until {
            if Instant::now() < pause_until {
                return true;
            }
            self.pause_until = None;
        }
        false
    }

    fn should_render_frame(&self, now: Instant) -> bool {
        now.duration_since(self.last_frame) >= Duration::from_millis(self.frame_interval_ms)
    }

    fn execute_batch_steps(&mut self, frame_start: Instant) -> bool {
        let mut accumulated_delay = 0u64;
        let mut executed_any = false;

        while self.current_step < self.steps.len() {
            if !self.can_execute_step(executed_any, accumulated_delay) {
                break;
            }

            let step_delay = self.next_step_delay;
            let step = self.steps[self.current_step].clone();

            self.execute_step(step);
            self.current_step += 1;
            executed_any = true;
            accumulated_delay += step_delay;
        }

        if executed_any {
            self.last_update = Instant::now();
            self.last_frame = frame_start;
        }

        executed_any
    }

    fn can_execute_step(&self, executed_any: bool, accumulated_delay: u64) -> bool {
        // First step: check if enough time has elapsed since last step
        if !executed_any {
            return self.last_update.elapsed() >= Duration::from_millis(self.next_step_delay);
        }

        // Subsequent steps: check if they fit within frame budget
        accumulated_delay + self.next_step_delay <= self.frame_interval_ms
    }

    fn execute_step(&mut self, step: AnimationStep) {
        let step_clone = step.clone();
        // Calculate delay for next step with randomization for typing steps
        let mut rng = rand::rng();
        self.next_step_delay = match &step {
            AnimationStep::InsertChar { .. } | AnimationStep::TerminalTypeChar { .. } => {
                // Add 70-130% variation to typing speed
                let variation = rng.random_range(0.7..=1.3);
                ((self.speed_ms as f64) * variation) as u64
            }
            AnimationStep::DialogTypeChar { .. } => {
                // Dialog typing is slower (2x speed with variation)
                let variation = rng.random_range(0.7..=1.3);
                ((self.speed_ms as f64) * 2.0 * variation) as u64
            }
            AnimationStep::Pause { .. } => {
                // Pause timing is driven by `pause_until`; don't add extra delay
                0
            }
            _ => {
                // Other steps use base speed
                self.speed_ms
            }
        };

        match step {
            AnimationStep::InsertChar { line, col, ch } => {
                self.active_pane = ActivePane::Editor;
                self.buffer.insert_char(line, col, ch);
                self.buffer.cursor_line = line;
                self.buffer.cursor_col = col + 1;
            }
            AnimationStep::InsertLine { line, content } => {
                self.active_pane = ActivePane::Editor;
                let content_len = content.chars().count();
                self.buffer.insert_line(line, content);
                self.buffer.cursor_line = line;
                self.buffer.cursor_col = content_len;

                // Track line offset for old_highlights mapping
                self.line_offset += 1;
            }
            AnimationStep::DeleteLine { line } => {
                self.active_pane = ActivePane::Editor;
                self.buffer.delete_line(line);
                self.buffer.cursor_line = line;
                // Set cursor to first non-whitespace position of the line that moved up
                self.buffer.cursor_col = self
                    .buffer
                    .lines
                    .get(line)
                    .map(|l| l.chars().take_while(|c| c.is_whitespace()).count())
                    .unwrap_or(0);

                // Track line offset for old_highlights mapping
                self.line_offset -= 1;
            }
            AnimationStep::MoveCursor { line, col } => {
                self.active_pane = ActivePane::Editor;
                self.buffer.cursor_line = line;
                self.buffer.cursor_col = col;
            }
            AnimationStep::Pause { multiplier } => {
                let duration_ms = (self.speed_ms as f64 * multiplier) as u64;
                self.pause_until = Some(Instant::now() + Duration::from_millis(duration_ms));
            }
            AnimationStep::OpenFileDialogStart => {
                self.dialog_typing_text = String::new();
                self.dialog_title = Some("Open File...".to_string());
            }
            AnimationStep::DialogTypeChar { ch } => {
                self.dialog_typing_text.push(ch);
            }
            AnimationStep::SwitchFile {
                file_index,
                old_content,
                new_content,
                path,
            } => {
                self.active_pane = ActivePane::Editor;
                // Clear dialog when file is actually switched
                self.dialog_title = None;
                self.dialog_typing_text = String::new();
                // Switch to new file
                self.current_file_index = file_index;
                self.current_file_path = Some(path.clone());
                self.buffer = EditorBuffer::from_content(&old_content);

                // Update typing speed based on file-specific rules
                self.speed_ms = self.get_speed_for_file(&path);

                // Update syntax highlighter for new file
                // This will clear language settings if not supported
                self.highlighter.borrow_mut().set_language_from_path(&path);

                // Pre-calculate highlights for both old and new content
                self.buffer.old_highlights = self.highlighter.borrow_mut().highlight(&old_content);
                self.buffer.new_highlights = self.highlighter.borrow_mut().highlight(&new_content);

                // Store content lines for byte offset calculation
                self.buffer.old_content_lines = if old_content.is_empty() {
                    vec![String::new()]
                } else {
                    old_content.lines().map(|s| s.to_string()).collect()
                };
                self.buffer.new_content_lines = if new_content.is_empty() {
                    vec![String::new()]
                } else {
                    new_content.lines().map(|s| s.to_string()).collect()
                };

                // Pre-calculate line byte offsets (handles CRLF correctly)
                self.buffer.old_content_line_offsets = Self::calculate_line_offsets(&old_content);
                self.buffer.new_content_line_offsets = Self::calculate_line_offsets(&new_content);

                // Initialize cached_highlights with old_highlights
                self.buffer.cached_highlights = self.buffer.old_highlights.clone();

                // Reset line offset
                self.line_offset = 0;
            }
            AnimationStep::TerminalPrompt => {
                self.active_pane = ActivePane::Terminal;
                // Start a new command line with prompt
                self.terminal_lines.push("~ ".to_string());
            }
            AnimationStep::TerminalTypeChar { ch } => {
                self.active_pane = ActivePane::Terminal;
                // Add character to the last terminal line
                if let Some(last_line) = self.terminal_lines.last_mut() {
                    last_line.push(ch);
                }
            }
            AnimationStep::TerminalOutput { text } => {
                self.active_pane = ActivePane::Terminal;
                // Add output line
                self.terminal_lines.push(text);
            }
            AnimationStep::ResetState => {
                // Apply pending metadata and reset UI state after time-travel animation
                if let Some(metadata) = self.pending_metadata.take() {
                    self.current_metadata = Some(metadata);
                }
                self.current_file_index = 0;
                // Keep terminal_lines to preserve time-travel command and output
                self.buffer = EditorBuffer::new();
                self.current_file_path = None;
                self.active_pane = ActivePane::Terminal;
            }
        }

        self.handle_step_checkpoint(&step_clone);

        // Update scroll to keep cursor centered
        self.update_scroll();
    }

    fn calculate_line_display_height(&self, line: &str) -> usize {
        if self.content_width == 0 {
            return 1;
        }

        // Calculate text area width (excluding line numbers, padding, etc.)
        let line_num_width = format!("{}", self.buffer.lines.len()).len().max(3);
        let left_padding = 2;
        let line_num_and_space = line_num_width + 1;
        let separator = 2;
        let right_padding = 2;
        let fixed_width = left_padding + line_num_and_space + separator + right_padding;

        let text_width = self.content_width.saturating_sub(fixed_width);
        if text_width == 0 {
            return 1;
        }

        // Calculate how many lines this text will take when wrapped (using display width)
        let display_width = line.width();
        display_width.div_ceil(text_width).max(1)
    }

    fn update_scroll(&mut self) {
        if self.viewport_height == 0 {
            return;
        }

        let cursor_line = self.buffer.cursor_line;

        // Calculate display line positions for each logical line
        let mut display_line_positions = Vec::with_capacity(self.buffer.lines.len());
        let mut current_display_line = 0;

        for line in &self.buffer.lines {
            display_line_positions.push(current_display_line);
            current_display_line += self.calculate_line_display_height(line);
        }

        let total_display_lines = current_display_line;
        let cursor_display_line = display_line_positions
            .get(cursor_line)
            .copied()
            .unwrap_or(0);

        // Calculate target scroll position (in display lines)
        let half_viewport = self.viewport_height / 2;
        let target_display_offset = if cursor_display_line < half_viewport {
            0
        } else if cursor_display_line + half_viewport >= total_display_lines {
            total_display_lines.saturating_sub(self.viewport_height)
        } else {
            cursor_display_line.saturating_sub(half_viewport)
        };

        // Find the logical line that corresponds to the target display offset
        let mut logical_offset = 0;
        for (line_idx, &display_pos) in display_line_positions.iter().enumerate() {
            if display_pos >= target_display_offset {
                logical_offset = line_idx;
                break;
            }
        }

        self.buffer.scroll_offset = logical_offset;
    }

    /// Returns true if the animation has completed.
    pub fn is_finished(&self) -> bool {
        self.state == AnimationState::Finished
    }
}