branchdiff 0.62.1

Terminal UI showing unified diff of current branch vs its base
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
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
use std::time::Instant;

use anyhow::Result;
use arboard::Clipboard;

use super::{App, DisplayableItem};
use crate::diff::LineSource;
use crate::patch;
use crate::ui::{ScreenRowInfo, PREFIX_CHAR_WIDTH};

/// Multi-click detection window in milliseconds.
/// Shared between click detection and deferred copy timeout.
pub(crate) const MULTI_CLICK_MS: u128 = 500;

/// Get substring by character positions (not byte positions)
fn char_slice(s: &str, start: usize, end: usize) -> &str {
    let mut char_indices = s.char_indices();
    let start_byte = char_indices.nth(start).map(|(i, _)| i).unwrap_or(s.len());
    let end_byte = if end <= start {
        start_byte
    } else {
        char_indices
            .nth(end - start - 1)
            .map(|(i, _)| i)
            .unwrap_or(s.len())
    };
    &s[start_byte..end_byte]
}

/// Get substring from character position to end
fn char_slice_from(s: &str, start: usize) -> &str {
    let start_byte = s.char_indices().nth(start).map(|(i, _)| i).unwrap_or(s.len());
    &s[start_byte..]
}

/// Get substring from start to character position
fn char_slice_to(s: &str, end: usize) -> &str {
    let end_byte = s.char_indices().nth(end).map(|(i, _)| i).unwrap_or(s.len());
    &s[..end_byte]
}

/// Check if a character is a word character (alphanumeric or underscore)
fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

/// Check if a character is a symbol (non-word, non-whitespace)
fn is_symbol_char(c: char) -> bool {
    !is_word_char(c) && !c.is_whitespace()
}

/// Find selection boundaries around a given column position.
/// Returns (start_col, end_col) where end_col is exclusive.
///
/// Behavior:
/// - On a word character: select the word
/// - On a symbol character: select consecutive symbols
/// - On whitespace: select the first word/symbol to the right
/// - Past end of line: select entire line (handled by caller)
fn find_selection_boundaries(s: &str, col: usize) -> Option<(usize, usize)> {
    let chars: Vec<char> = s.chars().collect();

    if col >= chars.len() {
        return None;
    }

    let c = chars[col];

    if is_word_char(c) {
        // Select word
        find_word_boundaries_impl(&chars, col)
    } else if is_symbol_char(c) {
        // Select consecutive symbols
        find_symbol_boundaries_impl(&chars, col)
    } else {
        // Whitespace: find first non-whitespace to the right
        let mut start = col;
        while start < chars.len() && chars[start].is_whitespace() {
            start += 1;
        }
        if start >= chars.len() {
            return None;
        }
        if is_word_char(chars[start]) {
            find_word_boundaries_impl(&chars, start)
        } else {
            find_symbol_boundaries_impl(&chars, start)
        }
    }
}

fn find_word_boundaries_impl(chars: &[char], col: usize) -> Option<(usize, usize)> {
    if col >= chars.len() || !is_word_char(chars[col]) {
        return None;
    }

    let mut start = col;
    while start > 0 && is_word_char(chars[start - 1]) {
        start -= 1;
    }

    let mut end = col;
    while end < chars.len() && is_word_char(chars[end]) {
        end += 1;
    }

    Some((start, end))
}

fn find_symbol_boundaries_impl(chars: &[char], col: usize) -> Option<(usize, usize)> {
    if col >= chars.len() || !is_symbol_char(chars[col]) {
        return None;
    }

    let mut start = col;
    while start > 0 && is_symbol_char(chars[start - 1]) {
        start -= 1;
    }

    let mut end = col;
    while end < chars.len() && is_symbol_char(chars[end]) {
        end += 1;
    }

    Some((start, end))
}

/// Backward-compatible wrapper for tests that specifically test word boundaries
#[cfg(test)]
fn find_word_boundaries(s: &str, col: usize) -> Option<(usize, usize)> {
    let chars: Vec<char> = s.chars().collect();
    find_word_boundaries_impl(&chars, col)
}

/// Represents a position in the diff view (row, column)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Position {
    pub row: usize,
    pub col: usize,
}

/// Selection state for text copy
#[derive(Debug, Clone)]
pub struct Selection {
    pub start: Position,
    pub end: Position,
    pub active: bool,
}

impl App {
    /// Calculate the prefix length for selection operations.
    /// This matches the prefix_width calculation in diff_view.rs.
    fn prefix_len(&self) -> usize {
        if self.view.line_num_width > 0 {
            self.view.line_num_width + 1 + PREFIX_CHAR_WIDTH
        } else {
            PREFIX_CHAR_WIDTH
        }
    }

    /// Set the row map (called during rendering)
    pub fn set_row_map(&mut self, row_map: Vec<ScreenRowInfo>) {
        self.view.row_map = row_map;
    }

    /// Start a selection at the given screen coordinates
    pub fn start_selection(&mut self, screen_x: u16, screen_y: u16) {
        self.view.word_selection_anchor = None;
        self.view.line_selection_anchor = None;
        if let Some(pos) = self.screen_to_content_position(screen_x, screen_y) {
            self.view.selection = Some(Selection {
                start: pos,
                end: pos,
                active: true,
            });
        }
    }

    /// Update selection end point during drag
    pub fn update_selection(&mut self, screen_x: u16, screen_y: u16) {
        let pos = match self.screen_to_content_position(screen_x, screen_y) {
            Some(p) => p,
            None => return,
        };

        // Early return if no active selection
        let is_active = self.view.selection.as_ref().is_some_and(|s| s.active);
        if !is_active {
            return;
        }

        let prefix_len = self.prefix_len();

        // Line selection mode (triple-click drag)
        if let Some((anchor_start_row, anchor_end_row)) = self.view.line_selection_anchor {
            // Find the logical line boundaries at current position
            let (drag_start_row, drag_end_row) = self.find_logical_line_bounds(pos.row);

            // Extend selection to encompass both anchor line and current line
            let (new_start, new_end) = if pos.row < anchor_start_row {
                // Dragging before anchor
                let end_content_len = self.view.row_map.get(anchor_end_row)
                    .map(|r| r.content.chars().count())
                    .unwrap_or(0);
                (
                    Position { row: drag_start_row, col: prefix_len },
                    Position { row: anchor_end_row, col: end_content_len + prefix_len },
                )
            } else {
                // Dragging after or at anchor
                let end_content_len = self.view.row_map.get(drag_end_row)
                    .map(|r| r.content.chars().count())
                    .unwrap_or(0);
                (
                    Position { row: anchor_start_row, col: prefix_len },
                    Position { row: drag_end_row, col: end_content_len + prefix_len },
                )
            };

            if let Some(ref mut sel) = self.view.selection {
                sel.start = new_start;
                sel.end = new_end;
            }
            return;
        }

        // Word/symbol selection mode (double-click drag)
        if let Some((anchor_row, anchor_start, anchor_end)) = self.view.word_selection_anchor {
            // Get selection boundaries at current position
            let (drag_start, drag_end) = if pos.row < self.view.row_map.len() {
                let content = &self.view.row_map[pos.row].content;
                let content_col = pos.col.saturating_sub(prefix_len);
                find_selection_boundaries(content, content_col)
                    .map(|(s, e)| (s + prefix_len, e + prefix_len))
                    .unwrap_or((pos.col, pos.col))
            } else {
                (pos.col, pos.col)
            };

            // Extend selection to encompass both anchor word and current word
            let (new_start, new_end) =
                if pos.row < anchor_row || (pos.row == anchor_row && drag_start < anchor_start) {
                    // Dragging before anchor - selection goes from drag_start to anchor_end
                    (
                        Position { row: pos.row, col: drag_start },
                        Position { row: anchor_row, col: anchor_end },
                    )
                } else {
                    // Dragging after anchor - selection goes from anchor_start to drag_end
                    (
                        Position { row: anchor_row, col: anchor_start },
                        Position { row: pos.row, col: drag_end },
                    )
                };

            if let Some(ref mut sel) = self.view.selection {
                sel.start = new_start;
                sel.end = new_end;
            }
        } else {
            // Normal character-based selection
            if let Some(ref mut sel) = self.view.selection {
                sel.end = pos;
            }
        }
    }

    /// End selection (mouse released)
    pub fn end_selection(&mut self) {
        self.view.word_selection_anchor = None;
        self.view.line_selection_anchor = None;
        if let Some(ref mut sel) = self.view.selection {
            sel.active = false;
        }
    }

    /// End selection and auto-copy based on how the selection was made.
    ///
    /// - Drag (last_click cleared): copy immediately if non-empty
    /// - Multi-click (count >= 2): defer copy until multi-click window expires
    /// - Single click without drag: no copy (nothing meaningful selected)
    pub fn end_selection_with_auto_copy(&mut self) {
        let click_info = self.view.last_click;
        self.end_selection();

        match click_info {
            None => {
                // Drag happened (UpdateSelection clears last_click).
                // Copy immediately if there's a real selection.
                if self.has_non_empty_selection() {
                    let _ = self.copy_selection();
                }
            }
            Some((_, _, _, count)) if count >= 2 => {
                // Multi-click (double/triple). Defer copy to allow higher click counts.
                if self.has_non_empty_selection() {
                    self.view.pending_copy = Some(Instant::now());
                }
            }
            _ => {
                // Single click without drag. Nothing to copy.
            }
        }
    }

    /// Cancel any pending deferred copy (called when a new click arrives).
    pub fn cancel_pending_copy(&mut self) {
        self.view.pending_copy = None;
    }

    /// Execute pending copy if the multi-click window has expired.
    /// Returns true if a copy was executed (caller should trigger redraw).
    pub fn check_and_execute_pending_copy(&mut self) -> bool {
        if let Some(pending_time) = self.view.pending_copy
            && pending_time.elapsed().as_millis() >= MULTI_CLICK_MS
        {
            self.view.pending_copy = None;
            let _ = self.copy_selection();
            return true;
        }
        false
    }

    /// Check if there's a selection with actual content (not just a point click).
    pub fn has_non_empty_selection(&self) -> bool {
        self.view.selection.as_ref().is_some_and(|sel| {
            sel.start.row != sel.end.row || sel.start.col != sel.end.col
        })
    }

    /// Select the word at the given screen coordinates (for double-click)
    /// If clicking past end of line, selects the entire logical line (including wrapped segments)
    pub fn select_word_at(&mut self, screen_x: u16, screen_y: u16) {
        let pos = match self.screen_to_content_position(screen_x, screen_y) {
            Some(p) => p,
            None => return,
        };

        let is_status_bar = pos.row >= self.view.row_map.len();

        let (content, prefix_len) = match self.row_content(pos.row) {
            Some(r) => (r.0.to_string(), r.1),
            None => return,
        };

        let content_col = pos.col.saturating_sub(prefix_len);
        let content_len = content.chars().count();

        // Determine selection bounds
        if content_col >= content_len {
            if is_status_bar {
                // Select entire status bar line
                self.select_status_bar_line(pos.row, &content);
            } else {
                // Clicking past end of line - select entire logical line (including wrapped segments)
                self.select_logical_line(pos.row, prefix_len);
            }
        } else if let Some((start, end)) = find_selection_boundaries(&content, content_col) {
            let sel_start = start + prefix_len;
            let sel_end = end + prefix_len;

            // Set anchor for word-drag mode
            self.view.word_selection_anchor = Some((pos.row, sel_start, sel_end));

            self.view.selection = Some(Selection {
                start: Position {
                    row: pos.row,
                    col: sel_start,
                },
                end: Position {
                    row: pos.row,
                    col: sel_end,
                },
                active: true, // Allow dragging to extend
            });
        }
        // else: nothing to select (shouldn't happen with current logic)
    }

    /// Select the entire logical line at the given screen position (for triple-click)
    pub fn select_line_at(&mut self, screen_x: u16, screen_y: u16) {
        let pos = match self.screen_to_content_position(screen_x, screen_y) {
            Some(p) => p,
            None => return,
        };

        let is_status_bar = pos.row >= self.view.row_map.len();

        if is_status_bar {
            if let Some((content, _)) = self.row_content(pos.row) {
                let content = content.to_string();
                self.select_status_bar_line(pos.row, &content);
            }
            return;
        }

        let prefix_len = self.prefix_len();
        let (start_row, end_row) = self.find_logical_line_bounds(pos.row);

        // Set line selection anchor for line-based drag extension
        self.view.line_selection_anchor = Some((start_row, end_row));

        // Calculate end column for the last row
        let end_content_len = self.view.row_map[end_row].content.chars().count();

        self.view.selection = Some(Selection {
            start: Position { row: start_row, col: prefix_len },
            end: Position { row: end_row, col: end_content_len + prefix_len },
            active: true,
        });
    }

    /// Select an entire status bar line (no prefix, no continuation logic)
    fn select_status_bar_line(&mut self, row: usize, content: &str) {
        let content_len = content.chars().count();

        self.view.line_selection_anchor = Some((row, row));
        self.view.word_selection_anchor = None;

        self.view.selection = Some(Selection {
            start: Position { row, col: 0 },
            end: Position { row, col: content_len },
            active: true,
        });
    }

    /// Find the start and end rows of the logical line containing the given screen row
    fn find_logical_line_bounds(&self, screen_row: usize) -> (usize, usize) {
        if screen_row >= self.view.row_map.len() {
            return (screen_row, screen_row);
        }

        // Find the start of the logical line (go backwards while is_continuation)
        let mut start_row = screen_row;
        while start_row > 0 && self.view.row_map[start_row].is_continuation {
            start_row -= 1;
        }

        // Find the end of the logical line (go forward while next row is_continuation)
        let mut end_row = screen_row;
        while end_row + 1 < self.view.row_map.len() && self.view.row_map[end_row + 1].is_continuation {
            end_row += 1;
        }

        (start_row, end_row)
    }

    /// Select an entire logical line, including all wrapped segments
    fn select_logical_line(&mut self, screen_row: usize, prefix_len: usize) {
        // Find the start of the logical line (go backwards while is_continuation)
        let mut start_row = screen_row;
        while start_row > 0 && self.view.row_map[start_row].is_continuation {
            start_row -= 1;
        }

        // Find the end of the logical line (go forward while next row is_continuation)
        let mut end_row = screen_row;
        while end_row + 1 < self.view.row_map.len() && self.view.row_map[end_row + 1].is_continuation {
            end_row += 1;
        }

        // Calculate end column for the last row
        let end_content_len = self.view.row_map[end_row].content.chars().count();

        // Set anchor spanning the entire logical line
        let sel_start = prefix_len;
        let sel_end = end_content_len + prefix_len;
        self.view.word_selection_anchor = Some((start_row, sel_start, sel_end));

        self.view.selection = Some(Selection {
            start: Position {
                row: start_row,
                col: sel_start,
            },
            end: Position {
                row: end_row,
                col: sel_end,
            },
            active: true,
        });
    }

    /// Clear current selection
    pub fn clear_selection(&mut self) {
        self.view.selection = None;
        self.view.word_selection_anchor = None;
        self.view.line_selection_anchor = None;
    }

    /// Check if there's an active selection
    pub fn has_selection(&self) -> bool {
        self.view.selection.is_some()
    }

    /// Convert screen coordinates to content position.
    /// Handles both the diff content area and the status bar area.
    fn screen_to_content_position(&self, screen_x: u16, screen_y: u16) -> Option<Position> {
        let (offset_x, offset_y) = self.view.content_offset;

        // Check status bar first (more specific bounds)
        let sb_y = self.view.status_bar_screen_y;
        let sb_lines = &self.view.status_bar_lines;
        if !sb_lines.is_empty()
            && sb_y > 0
            && screen_y >= sb_y
            && (screen_y - sb_y) < sb_lines.len() as u16
        {
            let virtual_row = self.view.row_map.len() + (screen_y - sb_y) as usize;
            return Some(Position {
                row: virtual_row,
                col: screen_x as usize,
            });
        }

        // Check if within diff content area
        if screen_x >= offset_x && screen_y >= offset_y {
            let content_x = (screen_x - offset_x) as usize;
            let content_y = (screen_y - offset_y) as usize;
            return Some(Position {
                row: content_y,
                col: content_x,
            });
        }

        None
    }

    /// Get the text content and prefix length for a given row index.
    /// Returns None if the row is out of bounds for both row_map and status bar.
    fn row_content(&self, screen_row: usize) -> Option<(&str, usize)> {
        let row_map_len = self.view.row_map.len();
        if screen_row < row_map_len {
            Some((&self.view.row_map[screen_row].content, self.prefix_len()))
        } else {
            let sb_idx = screen_row - row_map_len;
            self.view.status_bar_lines.get(sb_idx).map(|s| (s.as_str(), 0))
        }
    }

    /// Check if the next row is a continuation of a wrapped line.
    fn is_next_row_continuation(&self, screen_row: usize) -> bool {
        let next = screen_row + 1;
        next < self.view.row_map.len()
            && self.view.row_map[next].is_continuation
    }

    /// Get selected text (content only, without line numbers or prefixes).
    /// Handles both diff content rows and status bar rows.
    pub fn get_selected_text(&self) -> Option<String> {
        let sel = self.view.selection.as_ref()?;

        // Normalize selection (start should be before end)
        let (start, end) = if sel.start.row < sel.end.row
            || (sel.start.row == sel.end.row && sel.start.col <= sel.end.col)
        {
            (sel.start, sel.end)
        } else {
            (sel.end, sel.start)
        };

        let mut result = String::new();

        for screen_row in start.row..=end.row {
            let (content, prefix_len) = match self.row_content(screen_row) {
                Some(r) => r,
                None => break,
            };

            let char_count = content.chars().count();

            if start.row == end.row {
                // Single row selection
                let start_in_content = start.col.saturating_sub(prefix_len);
                let end_in_content = end.col.saturating_sub(prefix_len);
                if start_in_content < char_count {
                    let actual_end = end_in_content.min(char_count);
                    if actual_end > start_in_content {
                        result.push_str(char_slice(content, start_in_content, actual_end));
                    }
                }
            } else if screen_row == start.row {
                // First row of multi-row selection
                let start_in_content = start.col.saturating_sub(prefix_len);
                if start_in_content < char_count {
                    result.push_str(char_slice_from(content, start_in_content));
                }
                if !self.is_next_row_continuation(screen_row) {
                    result.push('\n');
                }
            } else if screen_row == end.row {
                // Last row of multi-row selection
                let end_in_content = end.col.saturating_sub(prefix_len);
                let actual_end = end_in_content.min(char_count);
                result.push_str(char_slice_to(content, actual_end));
            } else {
                // Middle rows - take entire content
                result.push_str(content);
                if !self.is_next_row_continuation(screen_row) {
                    result.push('\n');
                }
            }
        }

        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }

    /// Copy selected text to clipboard
    pub fn copy_selection(&mut self) -> Result<bool> {
        if let Some(text) = self.get_selected_text() {
            let mut clipboard = Clipboard::new()
                .map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
            clipboard.set_text(text)
                .map_err(|e| anyhow::anyhow!("Failed to copy to clipboard: {}", e))?;
            self.clear_selection();
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Copy current file path to clipboard
    pub fn copy_current_path(&mut self) -> Result<bool> {
        if let Some(path) = self.current_file() {
            let mut clipboard = Clipboard::new()
                .map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
            clipboard.set_text(path)
                .map_err(|e| anyhow::anyhow!("Failed to copy to clipboard: {}", e))?;
            self.view.path_copied_at = Some(std::time::Instant::now());
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Copy entire diff to clipboard (respects view mode and collapsed files)
    pub fn copy_diff(&mut self) -> Result<bool> {
        let text = self.format_diff_for_copy();
        if text.is_empty() {
            return Ok(false);
        }

        let mut clipboard = Clipboard::new()
            .map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
        clipboard.set_text(text)
            .map_err(|e| anyhow::anyhow!("Failed to copy to clipboard: {}", e))?;
        self.view.path_copied_at = Some(std::time::Instant::now());
        Ok(true)
    }

    /// Copy git patch format to clipboard (for use with `git apply`)
    pub fn copy_patch(&mut self) -> Result<bool> {
        let text = patch::generate_patch(&self.lines);
        if text.is_empty() {
            return Ok(false);
        }

        let mut clipboard = Clipboard::new()
            .map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
        clipboard
            .set_text(text)
            .map_err(|e| anyhow::anyhow!("Failed to copy to clipboard: {}", e))?;
        self.view.path_copied_at = Some(std::time::Instant::now());
        Ok(true)
    }

    /// Format the diff for copying to clipboard
    pub(crate) fn format_diff_for_copy(&self) -> String {
        let items = self.compute_displayable_items();
        if items.is_empty() {
            return String::new();
        }

        // Calculate max line number width
        let max_line_num = items
            .iter()
            .filter_map(|item| {
                if let DisplayableItem::Line(idx) = item {
                    self.lines[*idx].line_number
                } else {
                    None
                }
            })
            .max()
            .unwrap_or(0);
        let line_num_width = if max_line_num > 0 {
            max_line_num.to_string().len()
        } else {
            0
        };

        let mut result = String::new();

        for item in &items {
            match item {
                DisplayableItem::Elided(count) => {
                    let padding = if line_num_width > 0 {
                        " ".repeat(line_num_width + 1)
                    } else {
                        String::new()
                    };
                    result.push_str(&format!("{}... {} lines hidden ...\n", padding, count));
                }
                DisplayableItem::Message(msg) => {
                    result.push_str(&format!("{}\n", msg));
                }
                DisplayableItem::Line(idx) => {
                    let line = &self.lines[*idx];

                    // Format line number
                    let line_num_str = if let Some(num) = line.line_number {
                        format!("{:>width$} ", num, width = line_num_width)
                    } else if line_num_width > 0 {
                        " ".repeat(line_num_width + 1)
                    } else {
                        String::new()
                    };

                    if line.source == LineSource::FileHeader {
                        result.push_str(&format!("{}── {} ──\n", line_num_str, line.content));
                    } else {
                        result.push_str(&format!(
                            "{}{} {}\n",
                            line_num_str, line.prefix, line.content
                        ));
                    }
                }
            }
        }

        result
    }

    /// Check if the "copied" flash should be shown (within 800ms of copy)
    pub fn should_show_copied_flash(&self) -> bool {
        if let Some(copied_at) = self.view.path_copied_at {
            copied_at.elapsed() < std::time::Duration::from_millis(800)
        } else {
            false
        }
    }

    /// Check if a screen position is on a file header, and return the file path if so
    pub fn get_file_header_at(&self, screen_x: u16, screen_y: u16) -> Option<String> {
        let (offset_x, offset_y) = self.view.content_offset;

        // Check if within content area
        if screen_x < offset_x || screen_y < offset_y {
            return None;
        }

        let content_y = (screen_y - offset_y) as usize;

        // Look up in row_map
        if content_y < self.view.row_map.len() {
            let row_info = &self.view.row_map[content_y];
            if row_info.is_file_header {
                return row_info.file_path.clone();
            }
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::TestAppBuilder;
    use crate::ui::ScreenRowInfo;

    fn make_row(content: &str, is_continuation: bool) -> ScreenRowInfo {
        ScreenRowInfo {
            content: content.to_string(),
            is_file_header: false,
            file_path: None,
            is_continuation,
        }
    }

    #[test]
    fn test_get_selected_text_unwrapped_lines() {
        // Two separate logical lines (no wrapping)
        // With line_num_width=3, prefix_len = 3 + 1 + 4 = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.row_map = vec![
            make_row("line one", false),
            make_row("line two", false),
        ];
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 8 }, // prefix_len = 8
            end: Position { row: 1, col: 16 },  // "line two" is 8 chars, so 8 + 8 = 16
            active: false,
        });

        let text = app.get_selected_text().unwrap();
        assert_eq!(text, "line one\nline two");
    }

    #[test]
    fn test_get_selected_text_wrapped_line_no_extra_newlines() {
        // One logical line wrapped across two screen rows
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.row_map = vec![
            make_row("first part ", false), // Start of logical line (11 chars)
            make_row("second part", true),  // Continuation (wrapped) (11 chars)
        ];
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 8 },
            end: Position { row: 1, col: 19 },  // 8 + 11 = 19
            active: false,
        });

        let text = app.get_selected_text().unwrap();
        // Should NOT have newline between wrapped parts
        assert_eq!(text, "first part second part");
    }

    #[test]
    fn test_get_selected_text_mixed_wrapped_and_unwrapped() {
        // Two logical lines, first one wraps
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.row_map = vec![
            make_row("wrapped ", false),    // Line 1, part 1 (8 chars)
            make_row("line", true),         // Line 1, part 2 (4 chars)
            make_row("normal line", false), // Line 2 (11 chars)
        ];
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 8 },
            end: Position { row: 2, col: 19 },  // 8 + 11 = 19
            active: false,
        });

        let text = app.get_selected_text().unwrap();
        // Newline only between logical lines, not within wrapped line
        assert_eq!(text, "wrapped line\nnormal line");
    }

    #[test]
    fn test_get_selected_text_starting_on_continuation() {
        // Selection starts on a continuation row
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.row_map = vec![
            make_row("first ", false),       // Line 1, part 1
            make_row("second", true),        // Line 1, part 2 (6 chars)
            make_row("next line", false),    // Line 2 (9 chars)
        ];
        // Start selection on the continuation row
        app.view.selection = Some(Selection {
            start: Position { row: 1, col: 8 },
            end: Position { row: 2, col: 17 },  // 8 + 9 = 17
            active: false,
        });

        let text = app.get_selected_text().unwrap();
        // Should get content from continuation + newline + next line
        assert_eq!(text, "second\nnext line");
    }

    #[test]
    fn test_find_word_boundaries_simple() {
        assert_eq!(find_word_boundaries("hello world", 0), Some((0, 5)));
        assert_eq!(find_word_boundaries("hello world", 2), Some((0, 5)));
        assert_eq!(find_word_boundaries("hello world", 4), Some((0, 5)));
        assert_eq!(find_word_boundaries("hello world", 6), Some((6, 11)));
        assert_eq!(find_word_boundaries("hello world", 10), Some((6, 11)));
    }

    #[test]
    fn test_find_word_boundaries_with_underscores() {
        assert_eq!(find_word_boundaries("foo_bar_baz", 0), Some((0, 11)));
        assert_eq!(find_word_boundaries("foo_bar_baz", 4), Some((0, 11)));
        assert_eq!(find_word_boundaries("snake_case_name", 6), Some((0, 15)));
    }

    #[test]
    fn test_find_word_boundaries_not_on_word() {
        // find_word_boundaries only finds words, not symbols or whitespace
        assert_eq!(find_word_boundaries("hello world", 5), None); // space
        assert_eq!(find_word_boundaries("foo.bar", 3), None); // dot
        assert_eq!(find_word_boundaries("a + b", 2), None); // plus
    }

    #[test]
    fn test_find_selection_boundaries_symbols() {
        // Triple slash should be selected as a group
        assert_eq!(find_selection_boundaries("/// comment", 0), Some((0, 3)));
        assert_eq!(find_selection_boundaries("/// comment", 1), Some((0, 3)));
        assert_eq!(find_selection_boundaries("/// comment", 2), Some((0, 3)));

        // Double colon
        assert_eq!(find_selection_boundaries("std::vec", 3), Some((3, 5)));
        assert_eq!(find_selection_boundaries("std::vec", 4), Some((3, 5)));

        // Arrow operator
        assert_eq!(find_selection_boundaries("foo->bar", 3), Some((3, 5)));

        // Mixed symbols
        assert_eq!(find_selection_boundaries("a := b", 2), Some((2, 4)));
    }

    #[test]
    fn test_find_selection_boundaries_whitespace_selects_next() {
        // Whitespace should select the word to the right
        assert_eq!(find_selection_boundaries("hello world", 5), Some((6, 11)));
        assert_eq!(find_selection_boundaries("  word", 0), Some((2, 6)));
        assert_eq!(find_selection_boundaries("  word", 1), Some((2, 6)));

        // Whitespace before symbols should select the symbols
        assert_eq!(find_selection_boundaries("foo /// bar", 4), Some((4, 7)));

        // Trailing whitespace should return None
        assert_eq!(find_selection_boundaries("word  ", 5), None);
    }

    #[test]
    fn test_find_selection_boundaries_words() {
        // Words still work as before
        assert_eq!(find_selection_boundaries("hello world", 0), Some((0, 5)));
        assert_eq!(find_selection_boundaries("hello world", 6), Some((6, 11)));
        assert_eq!(find_selection_boundaries("foo_bar", 3), Some((0, 7)));
    }

    #[test]
    fn test_find_word_boundaries_at_edges() {
        assert_eq!(find_word_boundaries("word", 0), Some((0, 4)));
        assert_eq!(find_word_boundaries("word", 3), Some((0, 4)));
        assert_eq!(find_word_boundaries("  word  ", 2), Some((2, 6)));
    }

    #[test]
    fn test_find_word_boundaries_empty_and_out_of_bounds() {
        assert_eq!(find_word_boundaries("", 0), None);
        assert_eq!(find_word_boundaries("hello", 10), None);
    }

    #[test]
    fn test_select_word_at_basic() {
        // With line_num_width=3, prefix_len = 3 + 1 + 4 = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello world", false)];

        // Click on 'w' in "world" - content col 6, screen col = 6 + prefix_len(8) + offset(1) = 15
        app.select_word_at(15, 1);

        let sel = app.view.selection.as_ref().expect("Should have selection");
        // Word "world" at content cols 6-11, + prefix_len 8
        assert_eq!(sel.start.col, 14); // 6 + 8
        assert_eq!(sel.end.col, 19); // 11 + 8
        assert!(sel.active, "Should be active to allow word-drag");

        // Should have word anchor set for drag mode
        let anchor = app.view.word_selection_anchor.expect("Should have word anchor");
        assert_eq!(anchor, (0, 14, 19));
    }

    #[test]
    fn test_select_word_at_whitespace_selects_next_word() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello world", false)];

        // Click on space between words - content col 5, screen col = 5 + 8 + 1 = 14
        app.select_word_at(14, 1);

        // Should select "world" (the word to the right)
        let sel = app.view.selection.as_ref().expect("Should have selection");
        assert_eq!(sel.start.col, 14); // "world" at content col 6 + prefix 8
        assert_eq!(sel.end.col, 19); // ends at content col 11 + prefix 8
    }

    #[test]
    fn test_select_word_at_symbols() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("/// comment", false)];

        // Click on second slash - content col 1, screen col = 1 + 8 + 1 = 10
        app.select_word_at(10, 1);

        // Should select "///" (all three slashes)
        let sel = app.view.selection.as_ref().expect("Should have selection");
        assert_eq!(sel.start.col, 8); // starts at content col 0 + prefix 8
        assert_eq!(sel.end.col, 11); // ends at content col 3 + prefix 8
    }

    #[test]
    fn test_select_word_at_past_end_of_line() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello", false)]; // 5 chars

        // Click past end of line - content has 5 chars, click at col 10
        // screen_x = 10 + prefix(8) + offset(1) = 19
        app.select_word_at(19, 1);

        let sel = app.view.selection.as_ref().expect("Should select whole line");
        // Should select entire line: prefix_len to prefix_len + content_len
        assert_eq!(sel.start.col, 8); // prefix_len
        assert_eq!(sel.end.col, 13); // 5 + 8
    }

    #[test]
    fn test_word_drag_extends_by_words() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("one two three four", false)];

        // Double-click on "two" (content col 4-7)
        // screen_x for 't' in "two" = 4 + 8 + 1 = 13
        app.select_word_at(13, 1);

        let sel = app.view.selection.as_ref().unwrap();
        assert_eq!(sel.start.col, 12); // "two" starts at content col 4 + prefix 8
        assert_eq!(sel.end.col, 15); // "two" ends at content col 7 + prefix 8

        // Now drag to "four" (content col 14-18)
        // screen_x for 'f' in "four" = 14 + 8 + 1 = 23
        app.update_selection(23, 1);

        let sel = app.view.selection.as_ref().unwrap();
        // Should extend from "two" start to "four" end
        assert_eq!(sel.start.col, 12); // "two" starts at 4 + 8
        assert_eq!(sel.end.col, 26); // "four" ends at 18 + 8
    }

    #[test]
    fn test_word_drag_backwards() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("one two three four", false)];

        // Double-click on "three" (content col 8-13)
        // screen_x for 't' in "three" = 8 + 8 + 1 = 17
        app.select_word_at(17, 1);

        // Now drag backwards to "one" (content col 0-3)
        // screen_x for 'o' in "one" = 0 + 8 + 1 = 9
        app.update_selection(9, 1);

        let sel = app.view.selection.as_ref().unwrap();
        // Should extend from "one" start to "three" end
        assert_eq!(sel.start.col, 8); // "one" starts at 0 + 8
        assert_eq!(sel.end.col, 21); // "three" ends at 13 + 8
    }

    #[test]
    fn test_word_anchor_cleared_on_end_selection() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello world", false)];

        // Click on 'w' in "world" - screen_x = 6 + 8 + 1 = 15
        app.select_word_at(15, 1);
        assert!(app.view.word_selection_anchor.is_some());

        app.end_selection();
        assert!(app.view.word_selection_anchor.is_none());
    }

    #[test]
    fn test_word_anchor_cleared_on_start_selection() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello world", false)];

        // Click on 'w' in "world" - screen_x = 6 + 8 + 1 = 15
        app.select_word_at(15, 1);
        assert!(app.view.word_selection_anchor.is_some());

        // Normal click should clear word anchor
        app.start_selection(9, 1);  // 0 + 8 + 1 = 9
        assert!(app.view.word_selection_anchor.is_none());
    }

    #[test]
    fn test_select_word_at_empty_line() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("", false)]; // Empty line

        // Click on empty line (any position)
        app.select_word_at(12, 1);

        // Should create an empty selection (start == end at prefix boundary)
        let sel = app.view.selection.as_ref().expect("Should have selection");
        assert_eq!(sel.start.col, 8); // prefix_len
        assert_eq!(sel.end.col, 8); // prefix_len + 0 chars
    }

    #[test]
    fn test_word_drag_across_rows() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![
            make_row("first line", false),
            make_row("second line", false),
        ];

        // Double-click on "first" (content col 0-5)
        app.select_word_at(9, 1); // screen_x = 0 + 8 + 1 = 9

        let sel = app.view.selection.as_ref().unwrap();
        assert_eq!(sel.start.row, 0);
        assert_eq!(sel.end.row, 0);

        // Drag to "second" on row 1 (content col 0-6)
        app.update_selection(9, 2); // screen_y = 1 + 1 = 2

        let sel = app.view.selection.as_ref().unwrap();
        // Should extend from "first" start (row 0) to "second" end (row 1)
        assert_eq!(sel.start.row, 0);
        assert_eq!(sel.start.col, 8); // "first" at col 0 + prefix 8
        assert_eq!(sel.end.row, 1);
        assert_eq!(sel.end.col, 14); // "second" ends at col 6 + prefix 8
    }

    #[test]
    fn test_word_drag_to_whitespace_selects_next_word() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("one   two", false)]; // Multiple spaces

        // Double-click on "one"
        app.select_word_at(9, 1); // col 0 + prefix 8 + offset 1 = 9

        // Drag to whitespace (col 4, between words)
        // screen_x = 4 + 8 + 1 = 13
        app.update_selection(13, 1);

        let sel = app.view.selection.as_ref().unwrap();
        // Whitespace selects word to the right ("two" at cols 6-9)
        // So selection extends from "one" start to "two" end
        assert_eq!(sel.start.col, 8); // "one" starts at 0 + 8
        assert_eq!(sel.end.col, 17); // "two" ends at content col 9 + prefix 8
    }

    #[test]
    fn test_word_drag_to_trailing_whitespace() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("word   ", false)]; // Trailing spaces

        // Double-click on "word"
        app.select_word_at(9, 1);  // 0 + 8 + 1 = 9

        // Drag to trailing whitespace (col 5)
        // screen_x = 5 + 8 + 1 = 14
        app.update_selection(14, 1);

        let sel = app.view.selection.as_ref().unwrap();
        // No word to the right, so falls back to cursor position
        assert_eq!(sel.start.col, 8); // "word" starts at 0 + 8
        assert_eq!(sel.end.col, 13); // cursor at 5 + 8
    }

    #[test]
    fn test_select_past_eol_on_wrapped_line_selects_entire_logical_line() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        // Simulate a wrapped line: first row is start, second is continuation
        app.view.row_map = vec![
            make_row("first part ", false),      // Start of logical line (11 chars)
            make_row("second part", true),       // Continuation (wrapped) (11 chars)
            make_row("next line", false),        // Different logical line
        ];

        // Click past end of the wrapped segment (row 1)
        // Content is "second part" (11 chars), click at col 15
        // screen_x = 15 + 8 + 1 = 24
        app.select_word_at(24, 2); // screen_y = 1 + 1 = 2 (row 1)

        let sel = app.view.selection.as_ref().expect("Should have selection");
        // Should select from start of logical line (row 0) to end of last segment (row 1)
        assert_eq!(sel.start.row, 0);
        assert_eq!(sel.start.col, 8); // prefix_len
        assert_eq!(sel.end.row, 1);
        assert_eq!(sel.end.col, 19); // "second part" is 11 chars + prefix 8
    }

    #[test]
    fn test_select_past_eol_on_first_segment_of_wrapped_line() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        // Simulate a wrapped line spanning 3 rows
        app.view.row_map = vec![
            make_row("part one ", false),   // Start (9 chars)
            make_row("part two ", true),    // Continuation (9 chars)
            make_row("part three", true),   // Continuation (10 chars)
        ];

        // Click past end of the first segment (row 0)
        // screen_x = 12 + 8 + 1 = 21
        app.select_word_at(21, 1); // screen_y = 0 + 1 = 1 (row 0)

        let sel = app.view.selection.as_ref().expect("Should have selection");
        // Should select entire logical line from row 0 to row 2
        assert_eq!(sel.start.row, 0);
        assert_eq!(sel.start.col, 8);
        assert_eq!(sel.end.row, 2);
        assert_eq!(sel.end.col, 18); // "part three" is 10 chars + prefix 8
    }

    #[test]
    fn test_select_line_at_basic() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello world", false)]; // 11 chars

        // Triple-click anywhere on the line - screen_x = 5 + 8 + 1 = 14
        app.select_line_at(14, 1);

        let sel = app.view.selection.as_ref().expect("Should have selection");
        assert_eq!(sel.start.row, 0);
        assert_eq!(sel.end.row, 0);
        assert_eq!(sel.start.col, 8); // prefix_len
        assert_eq!(sel.end.col, 19); // 11 + 8
        assert!(sel.active, "Should be active for line-drag");

        // Line selection anchor should be set
        let anchor = app.view.line_selection_anchor.expect("Should have line anchor");
        assert_eq!(anchor, (0, 0)); // start_row, end_row
    }

    #[test]
    fn test_select_line_at_wrapped_line() {
        // With line_num_width=3, prefix_len = 8
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![
            make_row("first part ", false),  // 11 chars
            make_row("second part", true),   // 11 chars (continuation)
        ];

        // Triple-click on the continuation row
        app.select_line_at(14, 2); // screen_y = 1 + 1 = 2 (row 1)

        let sel = app.view.selection.as_ref().expect("Should have selection");
        // Should select entire logical line (both rows)
        assert_eq!(sel.start.row, 0);
        assert_eq!(sel.end.row, 1);
        assert_eq!(sel.start.col, 8); // prefix_len
        assert_eq!(sel.end.col, 19); // 11 + 8

        // Line selection anchor spans entire logical line
        let anchor = app.view.line_selection_anchor.expect("Should have line anchor");
        assert_eq!(anchor, (0, 1)); // start_row, end_row
    }

    #[test]
    fn test_prefix_len_with_zero_line_num_width() {
        // When line_num_width=0, prefix_len = 0 + PREFIX_CHAR_WIDTH = 4
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 0;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello", false)]; // 5 chars

        // Triple-click - screen_x = 2 + 4 + 1 = 7
        app.select_line_at(7, 1);

        let sel = app.view.selection.as_ref().expect("Should have selection");
        assert_eq!(sel.start.col, 4); // prefix_len = 4 when line_num_width = 0
        assert_eq!(sel.end.col, 9); // 5 + 4
    }

    #[test]
    fn test_select_word_at_with_zero_line_num_width() {
        // When line_num_width=0, prefix_len = 4
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 0;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello world", false)];

        // Click on 'w' in "world" - content col 6, screen col = 6 + 4 + 1 = 11
        app.select_word_at(11, 1);

        let sel = app.view.selection.as_ref().expect("Should have selection");
        assert_eq!(sel.start.col, 10); // 6 + 4
        assert_eq!(sel.end.col, 15); // 11 + 4
    }

    // --- Auto-copy tests ---

    #[test]
    fn test_has_non_empty_selection_point() {
        let mut app = TestAppBuilder::new().build();
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 5 },
            end: Position { row: 0, col: 5 },
            active: false,
        });
        assert!(!app.has_non_empty_selection());
    }

    #[test]
    fn test_has_non_empty_selection_range() {
        let mut app = TestAppBuilder::new().build();
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 5 },
            end: Position { row: 0, col: 10 },
            active: false,
        });
        assert!(app.has_non_empty_selection());
    }

    #[test]
    fn test_has_non_empty_selection_none() {
        let app = TestAppBuilder::new().build();
        assert!(!app.has_non_empty_selection());
    }

    #[test]
    fn test_end_selection_after_drag_clears_selection() {
        // Simulate drag: set non-empty selection, clear last_click (drag clears it)
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello world", false)];
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 8 },
            end: Position { row: 0, col: 14 },
            active: true,
        });
        app.view.last_click = None; // Drag clears last_click

        app.end_selection_with_auto_copy();

        // copy_selection clears the selection on success
        // In test env clipboard may fail, but selection should still be processed
        // Check that pending_copy was NOT set (drag = immediate copy)
        assert!(app.view.pending_copy.is_none());
    }

    #[test]
    fn test_end_selection_after_double_click_sets_pending_copy() {
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 3;
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("hello world", false)];
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 8 },
            end: Position { row: 0, col: 13 },
            active: true,
        });
        app.view.last_click = Some((Instant::now(), 15, 1, 2)); // double-click

        app.end_selection_with_auto_copy();

        // Should defer copy for multi-click
        assert!(app.view.pending_copy.is_some());
        // Selection should still exist (not yet copied)
        assert!(app.view.selection.is_some());
    }

    #[test]
    fn test_end_selection_single_click_no_copy() {
        let mut app = TestAppBuilder::new().build();
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 5 },
            end: Position { row: 0, col: 5 },
            active: true,
        });
        app.view.last_click = Some((Instant::now(), 5, 0, 1)); // single click

        app.end_selection_with_auto_copy();

        assert!(app.view.pending_copy.is_none());
    }

    #[test]
    fn test_cancel_pending_copy() {
        let mut app = TestAppBuilder::new().build();
        app.view.pending_copy = Some(Instant::now());

        app.cancel_pending_copy();

        assert!(app.view.pending_copy.is_none());
    }

    #[test]
    fn test_check_and_execute_pending_copy_too_soon() {
        let mut app = TestAppBuilder::new().build();
        app.view.pending_copy = Some(Instant::now());
        app.view.row_map = vec![make_row("hello", false)];
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 0 },
            end: Position { row: 0, col: 5 },
            active: false,
        });

        // Should NOT execute yet (just created)
        let executed = app.check_and_execute_pending_copy();
        assert!(!executed);
        assert!(app.view.pending_copy.is_some());
    }

    #[test]
    fn test_check_and_execute_pending_copy_after_timeout() {
        let mut app = TestAppBuilder::new().build();
        app.view.line_num_width = 0;
        app.view.content_offset = (0, 0);
        // Set pending_copy to 600ms ago
        app.view.pending_copy = Some(Instant::now() - std::time::Duration::from_millis(600));
        app.view.row_map = vec![make_row("hello", false)];
        app.view.selection = Some(Selection {
            start: Position { row: 0, col: 4 },
            end: Position { row: 0, col: 9 },
            active: false,
        });

        let executed = app.check_and_execute_pending_copy();
        assert!(executed);
        assert!(app.view.pending_copy.is_none());
    }

    // --- Status bar selection tests ---

    #[test]
    fn test_screen_to_content_position_status_bar() {
        let mut app = TestAppBuilder::new().build();
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("line1", false), make_row("line2", false)];
        app.view.status_bar_lines = vec!["status line".to_string()];
        app.view.status_bar_screen_y = 10;

        // Click in status bar area (screen_y=10)
        let pos = app.screen_to_content_position(5, 10);
        assert!(pos.is_some());
        let pos = pos.unwrap();
        // Virtual row = row_map.len() + (10 - 10) = 2
        assert_eq!(pos.row, 2);
        assert_eq!(pos.col, 5);
    }

    #[test]
    fn test_screen_to_content_position_outside_all_areas() {
        let mut app = TestAppBuilder::new().build();
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("line1", false)];
        app.view.status_bar_lines = vec!["status".to_string()];
        app.view.status_bar_screen_y = 10;

        // Click above content area and not in status bar
        let pos = app.screen_to_content_position(0, 0);
        assert!(pos.is_none());
    }

    #[test]
    fn test_get_selected_text_from_status_bar() {
        let mut app = TestAppBuilder::new().build();
        app.view.content_offset = (1, 1);
        app.view.line_num_width = 0;
        app.view.row_map = vec![make_row("diff content", false)];
        app.view.status_bar_lines = vec!["repo | feat vs main".to_string()];
        app.view.status_bar_screen_y = 10;

        // Select "feat" from status bar (virtual row 1, cols 7..11, no prefix)
        app.view.selection = Some(Selection {
            start: Position { row: 1, col: 7 },
            end: Position { row: 1, col: 11 },
            active: false,
        });

        let text = app.get_selected_text();
        assert_eq!(text, Some("feat".to_string()));
    }

    #[test]
    fn test_double_click_status_bar_selects_word() {
        let mut app = TestAppBuilder::new().build();
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("diff line", false)];
        app.view.status_bar_lines = vec!["repo | feature vs main".to_string()];
        app.view.status_bar_screen_y = 5;

        // Double-click on "feature" (starts at col 7, status bar screen_y=5)
        // screen_to_content_position maps (10, 5) → virtual row 1, col 10
        // "feature" spans cols 7..14 in the status bar text
        app.select_word_at(10, 5);

        let sel = app.view.selection.as_ref().expect("Should have selection");
        assert_eq!(sel.start.row, 1); // virtual row (row_map.len() + 0)
        assert_eq!(sel.start.col, 7); // "feature" starts at col 7 (no prefix)
        assert_eq!(sel.end.col, 14);  // "feature" ends at col 14

        let text = app.get_selected_text();
        assert_eq!(text, Some("feature".to_string()));
    }

    #[test]
    fn test_triple_click_status_bar_selects_line() {
        let mut app = TestAppBuilder::new().build();
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("diff line", false)];
        app.view.status_bar_lines = vec!["repo | feat vs main".to_string()];
        app.view.status_bar_screen_y = 5;

        // Triple-click anywhere on the status bar line
        app.select_line_at(10, 5);

        let sel = app.view.selection.as_ref().expect("Should have selection");
        assert_eq!(sel.start.row, 1); // virtual row
        assert_eq!(sel.start.col, 0); // line select starts at 0 (no prefix)
        assert_eq!(sel.end.col, 19);  // "repo | feat vs main" = 19 chars

        let text = app.get_selected_text();
        assert_eq!(text, Some("repo | feat vs main".to_string()));
    }

    #[test]
    fn test_double_click_status_bar_past_end_selects_line() {
        let mut app = TestAppBuilder::new().build();
        app.view.content_offset = (1, 1);
        app.view.row_map = vec![make_row("diff line", false)];
        app.view.status_bar_lines = vec!["short".to_string()];
        app.view.status_bar_screen_y = 5;

        // Double-click past end of status bar content
        app.select_word_at(50, 5);

        let sel = app.view.selection.as_ref().expect("Should have selection");
        // Should select entire line since click was past content
        assert_eq!(sel.start.col, 0);
        assert_eq!(sel.end.col, 5); // "short" = 5 chars
    }
}