tinyharness-ui 0.2.0

ui library for tinyharness
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
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
// ── Conversation widget ─────────────────────────────────────────────────────
//
// Displays the conversation history in a scrollable pane with
// color-coded messages, tool call blocks, and thinking chains.

use crate::tui::cell::{Cell, Color, Style};
use crate::tui::event::{Event, Key, KeyEvent};
use crate::tui::layout::Rect;
use crate::tui::screen::Screen;
use crate::tui::widget::{Action, Widget, styles, truncate_str};

/// A single line in the conversation display.
#[derive(Clone, Debug)]
pub enum ConversationLine {
    /// A user message.
    User { text: String },
    /// An assistant message.
    Assistant { text: String },
    /// A tool call header (e.g., "── Tool: read ──").
    ToolCall { name: String, args_summary: String },
    /// A tool result.
    ToolResult {
        name: String,
        content: String,
        is_error: bool,
    },
    /// A system message.
    System { text: String },
    /// Thinking/reasoning chain content.
    Thinking { text: String },
    /// A horizontal separator line.
    Separator,
    /// A confirmation prompt for a tool call, awaiting user y/n/a response.
    /// `diff_preview` contains a plain-text unified diff to show (for edit/write).
    ConfirmPrompt {
        name: String,
        args_summary: String,
        diff_preview: Option<String>,
    },
    /// A question prompt from the question tool with numbered answers.
    Question {
        question: String,
        answers: Vec<String>,
    },
}

/// Context warning level for the banner at the top of the conversation.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum ContextWarningLevel {
    #[default]
    None,
    /// 70%+ of context window used.
    Warning(f64),
    /// 90%+ of context window used.
    Critical(f64),
}

/// Search state for the conversation widget.
#[derive(Clone, Debug, Default)]
struct SearchState {
    /// Whether search mode is active (Ctrl+F toggled).
    active: bool,
    /// The current search query.
    query: String,
    /// Cursor position within the search query (byte offset).
    cursor: usize,
    /// Visual row offsets where matches start. Computed on each render.
    match_rows: Vec<usize>,
    /// Index of the currently highlighted match (for navigation).
    current_match: usize,
}

/// Scrollable conversation pane.
pub struct ConversationWidget {
    lines: Vec<ConversationLine>,
    /// Scroll offset in **visual row units** (not conversation line units).
    scroll_offset: usize,
    auto_scroll: bool,
    /// Context warning level (shown as a banner at the top).
    context_warning: ContextWarningLevel,
    /// Search state (Ctrl+F to toggle).
    search: SearchState,
}

impl ConversationWidget {
    pub fn new() -> Self {
        Self {
            lines: Vec::new(),
            scroll_offset: 0,
            auto_scroll: true,
            context_warning: ContextWarningLevel::None,
            search: SearchState::default(),
        }
    }

    /// Add a line to the conversation.
    pub fn push(&mut self, line: ConversationLine) {
        self.lines.push(line);
        if self.auto_scroll {
            self.scroll_to_bottom();
        }
    }

    /// Add multiple lines at once.
    pub fn extend(&mut self, lines: Vec<ConversationLine>) {
        self.lines.extend(lines);
        if self.auto_scroll {
            self.scroll_to_bottom();
        }
    }

    /// Clear all conversation lines.
    pub fn clear(&mut self) {
        self.lines.clear();
        self.scroll_offset = 0;
    }

    /// Get a mutable reference to the last line, if any.
    pub fn last_mut(&mut self) -> Option<&mut ConversationLine> {
        self.lines.last_mut()
    }

    /// Check if the last line is an assistant message.
    pub fn last_is_assistant(&self) -> bool {
        matches!(self.lines.last(), Some(ConversationLine::Assistant { .. }))
    }

    /// Set the context warning level.
    pub fn set_context_warning(&mut self, level: ContextWarningLevel) {
        self.context_warning = level;
    }

    /// Get the current context warning level.
    pub fn context_warning(&self) -> &ContextWarningLevel {
        &self.context_warning
    }

    /// Toggle search mode on/off.
    pub fn toggle_search(&mut self) {
        if self.search.active {
            self.close_search();
        } else {
            self.search.active = true;
            self.search.query.clear();
            self.search.cursor = 0;
            self.search.match_rows.clear();
            self.search.current_match = 0;
        }
    }

    /// Close search mode and clear search state.
    pub fn close_search(&mut self) {
        self.search.active = false;
        self.search.query.clear();
        self.search.cursor = 0;
        self.search.match_rows.clear();
        self.search.current_match = 0;
    }

    /// Check if search mode is active.
    pub fn is_search_active(&self) -> bool {
        self.search.active
    }

    /// Type a character into the search query.
    fn search_type_char(&mut self, ch: char) {
        self.search.query.insert(self.search.cursor, ch);
        self.search.cursor += ch.len_utf8();
        self.recompute_search_matches();
        self.search.current_match = 0;
    }

    /// Delete the character before the cursor in the search query.
    fn search_backspace(&mut self) {
        if self.search.cursor > 0 {
            // Find the previous char boundary
            let prev = self.search.query[..self.search.cursor]
                .char_indices()
                .next_back()
                .map(|(i, _)| i)
                .unwrap_or(0);
            self.search.query.drain(prev..self.search.cursor);
            self.search.cursor = prev;
            self.recompute_search_matches();
            self.search.current_match = 0;
        }
    }

    /// Move cursor left in the search query.
    fn search_cursor_left(&mut self) {
        if self.search.cursor > 0 {
            let prev = self.search.query[..self.search.cursor]
                .char_indices()
                .next_back()
                .map(|(i, _)| i)
                .unwrap_or(0);
            self.search.cursor = prev;
        }
    }

    /// Move cursor right in the search query.
    fn search_cursor_right(&mut self) {
        if self.search.cursor < self.search.query.len() {
            let next = self.search.query[self.search.cursor..]
                .char_indices()
                .nth(1)
                .map(|(i, _)| self.search.cursor + i)
                .unwrap_or(self.search.query.len());
            self.search.cursor = next;
        }
    }

    /// Navigate to the next search match.
    fn search_next(&mut self) {
        if !self.search.match_rows.is_empty() {
            self.search.current_match =
                (self.search.current_match + 1) % self.search.match_rows.len();
            let target_row = self.search.match_rows[self.search.current_match];
            self.scroll_offset = target_row;
            self.auto_scroll = false;
        }
    }

    /// Navigate to the previous search match.
    fn search_prev(&mut self) {
        if !self.search.match_rows.is_empty() {
            if self.search.current_match == 0 {
                self.search.current_match = self.search.match_rows.len() - 1;
            } else {
                self.search.current_match -= 1;
            }
            let target_row = self.search.match_rows[self.search.current_match];
            self.scroll_offset = target_row;
            self.auto_scroll = false;
        }
    }

    /// Recompute the visual row offsets where search matches occur.
    fn recompute_search_matches(&mut self) {
        self.search.match_rows.clear();
        if self.search.query.is_empty() {
            return;
        }
        let query_lower = self.search.query.to_lowercase();
        let mut visual_row = 0usize;
        for line in &self.lines {
            let text = match line {
                ConversationLine::User { text } => text.clone(),
                ConversationLine::Assistant { text } => text.clone(),
                ConversationLine::System { text } => text.clone(),
                ConversationLine::Thinking { text } => text.clone(),
                ConversationLine::ToolResult { content, .. } => content.clone(),
                ConversationLine::ToolCall { name, args_summary } => {
                    format!("{} {}", name, args_summary)
                }
                ConversationLine::ConfirmPrompt {
                    name, args_summary, ..
                } => {
                    format!("{} {}", name, args_summary)
                }
                ConversationLine::Question { question, answers } => {
                    format!("{} {}", question, answers.join(" "))
                }
                ConversationLine::Separator => String::new(),
            };
            if text.to_lowercase().contains(&query_lower) {
                self.search.match_rows.push(visual_row);
            }
            // Advance visual_row — we just need a rough estimate for scrolling
            // Use a simple heuristic: each line is at least 1 visual row
            visual_row += 1;
        }
    }

    /// Calculate how many visual rows a conversation line occupies given the
    /// area width. Uses character-level wrapping to match actual rendering.
    fn line_height(&self, line: &ConversationLine, area_width: u16) -> usize {
        let (text, prefix_len) = match line {
            ConversationLine::User { text } => (text, 7),
            ConversationLine::Assistant { text } => (text, 7),
            ConversationLine::System { text } => (text, 2),
            ConversationLine::Thinking { text } => (text, 13),
            ConversationLine::ToolResult { content, .. } => {
                // For tool results, trim trailing blank lines and limit to
                // a reasonable number of visible lines
                let trimmed = content.trim_end_matches('\n');
                let lines: Vec<&str> = trimmed.lines().collect();
                // Show at most 20 lines for a tool result
                let visible_lines = lines.iter().copied().take(20).collect::<Vec<&str>>();
                let joined = visible_lines.join("\n");
                return self.line_height_for_text(&joined, 4, area_width).max(1); // At least 1 row even for empty content
            }
            ConversationLine::ToolCall { name, args_summary } => {
                let header = format!("  ── {}", name);
                let header_len = header.len();
                if args_summary.is_empty() {
                    return 1;
                }
                // Calculate wrapping for args_summary starting after the header
                let total_text = if args_summary.is_empty() {
                    String::new()
                } else {
                    args_summary.clone()
                };
                return self.line_height_for_text_with_offset(&total_text, header_len, area_width);
            }
            ConversationLine::Question { question, answers } => {
                // "  ❓ " (4 chars) for question line, plus one line per answer
                let question_rows = self.line_height_for_text(question, 4, area_width);
                let answer_rows: usize = answers
                    .iter()
                    .map(|a| {
                        // "    N. " prefix = 6 chars for single-digit, 7 for double
                        let prefix_len = if answers.len() >= 10 { 7 } else { 6 };
                        self.line_height_for_text(a, prefix_len, area_width)
                    })
                    .sum();
                return question_rows + answer_rows;
            }
            ConversationLine::Separator => return 1,
            ConversationLine::ConfirmPrompt { diff_preview, .. } => {
                // Base prompt line = 1 row
                let mut rows = 1usize;
                // Diff preview lines add extra rows
                if let Some(diff) = diff_preview
                    && !diff.is_empty()
                {
                    let _max_content_width = (area_width as usize).saturating_sub(4);
                    for line in diff.lines() {
                        rows += self.line_height_for_text(line, 4, area_width);
                    }
                }
                return rows;
            }
        };

        self.line_height_for_text(text, prefix_len, area_width)
    }

    /// Helper: calculate visual row count for text with a given prefix and area width.
    fn line_height_for_text(&self, text: &str, prefix_len: usize, area_width: u16) -> usize {
        if area_width == 0 || text.is_empty() {
            return 1;
        }

        let wrap_col = area_width as usize;
        let mut rows = 1usize;
        let mut col = prefix_len;

        for ch in text.chars() {
            if ch == '\n' {
                rows += 1;
                col = prefix_len;
            } else if col >= wrap_col {
                rows += 1;
                col = prefix_len + 1;
            } else {
                col += 1;
            }
        }
        rows
    }

    /// Helper: calculate visual row count for text where the first line starts
    /// at `first_line_offset` (header length) and wrapped lines indent to the
    /// same offset. This is used for tool call args that wrap.
    fn line_height_for_text_with_offset(
        &self,
        text: &str,
        first_line_offset: usize,
        area_width: u16,
    ) -> usize {
        if area_width == 0 || text.is_empty() {
            return 1;
        }

        let wrap_col = area_width as usize;
        let mut rows = 1usize;
        let mut col = first_line_offset;

        for ch in text.chars() {
            if ch == '\n' {
                rows += 1;
                col = first_line_offset;
            } else if col >= wrap_col {
                rows += 1;
                col = first_line_offset + 1;
            } else {
                col += 1;
            }
        }
        rows
    }

    /// Calculate the total visual height of all conversation lines.
    fn total_visual_height(&self, width: u16) -> usize {
        self.lines.iter().map(|l| self.line_height(l, width)).sum()
    }

    /// Scroll to the bottom of the conversation.
    pub fn scroll_to_bottom(&mut self) {
        // Use a sentinel large value that will be clamped during render.
        // We track whether auto_scroll is active separately.
        self.auto_scroll = true;
    }

    /// Scroll up by `n` visual rows.
    pub fn scroll_up(&mut self, n: usize) {
        self.scroll_offset = self.scroll_offset.saturating_sub(n);
        self.auto_scroll = false;
    }

    /// Scroll down by `n` visual rows.
    pub fn scroll_down(&mut self, n: usize) {
        self.scroll_offset = self.scroll_offset.saturating_add(n);
    }

    /// Scroll to the very top.
    pub fn scroll_home(&mut self) {
        self.scroll_offset = 0;
        self.auto_scroll = false;
    }

    /// Render a single conversation line, with clipping support for scroll.
    fn render_line_clipped(
        &self,
        line: &ConversationLine,
        start_row: u16,
        screen: &mut Screen,
        _width: u16,
        area: Rect,
        skip_top: usize,
        rows_available: usize,
    ) {
        let max_row = area.bottom().saturating_sub(1);
        let effective_max_row = (start_row + rows_available as u16)
            .saturating_sub(1)
            .min(max_row);
        // Reserve 1 column for the scrollbar on the right edge
        let wrap_col = area.x + area.width.saturating_sub(1);

        match line {
            ConversationLine::User { text } => {
                let prefix = "  You: ";
                if skip_top == 0 && start_row <= max_row {
                    screen.write_str(
                        start_row,
                        area.x,
                        prefix,
                        Color::GREEN,
                        Color::Default,
                        Style::bold(),
                    );
                    screen.write_str_wrapped_clipped(
                        start_row,
                        area.x + prefix.len() as u16,
                        text,
                        Color::GREEN,
                        Color::Default,
                        Style::default(),
                        area.x,
                        effective_max_row,
                        wrap_col,
                    );
                } else if skip_top > 0 {
                    screen.write_str_wrapped_skip_clipped(
                        start_row,
                        area.x + prefix.len() as u16,
                        text,
                        Color::GREEN,
                        Color::Default,
                        Style::default(),
                        area.x,
                        effective_max_row,
                        wrap_col,
                        skip_top,
                    );
                }
            }
            ConversationLine::Assistant { text } => {
                let prefix = "  AI:  ";
                if skip_top == 0 && start_row <= max_row {
                    screen.write_str(
                        start_row,
                        area.x,
                        prefix,
                        Color::CYAN,
                        Color::Default,
                        Style::bold(),
                    );
                    screen.write_str_wrapped_clipped(
                        start_row,
                        area.x + prefix.len() as u16,
                        text,
                        Color::WHITE,
                        Color::Default,
                        Style::default(),
                        area.x,
                        effective_max_row,
                        wrap_col,
                    );
                } else if skip_top > 0 {
                    screen.write_str_wrapped_skip_clipped(
                        start_row,
                        area.x + prefix.len() as u16,
                        text,
                        Color::WHITE,
                        Color::Default,
                        Style::default(),
                        area.x,
                        effective_max_row,
                        wrap_col,
                        skip_top,
                    );
                }
            }
            ConversationLine::ToolCall { name, args_summary } => {
                let header = format!("  ── {}", name);
                if skip_top == 0 && start_row <= max_row {
                    screen.write_str(
                        start_row,
                        area.x,
                        &header,
                        styles::TOOL_MSG_FG,
                        Color::Default,
                        Style::default(),
                    );
                    if !args_summary.is_empty() {
                        let args_indent = area.x + header.len() as u16;
                        screen.write_str_wrapped_clipped(
                            start_row,
                            args_indent,
                            args_summary,
                            Color::Ansi(96),
                            Color::Default,
                            Style::dim(),
                            args_indent,
                            effective_max_row,
                            wrap_col,
                        );
                    }
                } else if skip_top > 0 && !args_summary.is_empty() {
                    let header = format!("  ── {}", name);
                    let args_indent = area.x + header.len() as u16;
                    screen.write_str_wrapped_skip_clipped(
                        start_row,
                        args_indent,
                        args_summary,
                        Color::Ansi(96),
                        Color::Default,
                        Style::dim(),
                        args_indent,
                        effective_max_row,
                        wrap_col,
                        skip_top,
                    );
                }
            }
            ConversationLine::ToolResult {
                name: _,
                content,
                is_error,
            } => {
                let default_color = if *is_error {
                    Color::RED
                } else {
                    Color::Ansi(252)
                };
                let bg = if *is_error {
                    Color::Ansi(52)
                } else {
                    Color::Default
                };
                // Trim trailing blank lines and limit to 20 visible lines
                let trimmed = content.trim_end_matches('\n');
                let content_lines: Vec<&str> = trimmed.lines().take(20).collect();
                let mut current_row = start_row;
                let max_content_width = (area.width as usize).saturating_sub(5);

                for (i, content_line) in content_lines.iter().enumerate() {
                    if i < skip_top {
                        current_row += 1;
                        continue;
                    }
                    if current_row > max_row {
                        break;
                    }

                    // Detect diff lines and apply appropriate colors with backgrounds
                    let (line_color, line_bg, line_prefix) = if !is_error {
                        if content_line.starts_with("@@") {
                            // Hunk header: @@ -1,3 +1,3 @@
                            (Color::CYAN, Color::Default, "  │ ")
                        } else if content_line.starts_with("---") || content_line.starts_with("+++")
                        {
                            // File header: --- a/file.rs or +++ b/file.rs
                            (Color::WHITE, Color::Default, "  │ ")
                        } else if content_line.starts_with("-") {
                            // Removed line — red text with dark red background
                            (Color::RED, Color::Ansi(52), "  │ ")
                        } else if content_line.starts_with("+") {
                            // Added line — green text with dark green background
                            (Color::GREEN, Color::Ansi(22), "  │ ")
                        } else {
                            (default_color, bg, "  │ ")
                        }
                    } else {
                        (default_color, bg, "  │ ")
                    };

                    let display = if content_line.is_empty() {
                        line_prefix.to_string()
                    } else if content_line.len() > max_content_width {
                        format!(
                            "{}{}…",
                            line_prefix,
                            truncate_str(content_line, max_content_width.saturating_sub(1))
                        )
                    } else {
                        format!("{}{}", line_prefix, content_line)
                    };
                    screen.write_str(
                        current_row,
                        area.x,
                        &display,
                        line_color,
                        line_bg,
                        Style::default(),
                    );
                    // Fill background for diff lines and error tool results
                    if line_bg != Color::Default || *is_error {
                        let fill_bg = if line_bg != Color::Default {
                            line_bg
                        } else {
                            bg
                        };
                        let fill_end = area.x + area.width.saturating_sub(1);
                        let end_col = area.x + display.len().min(area.width as usize - 1) as u16;
                        if end_col < fill_end {
                            for c in end_col..fill_end {
                                if let Some(cell) = screen.get_mut(current_row, c) {
                                    cell.bg = fill_bg;
                                }
                            }
                        }
                    }
                    current_row += 1;
                }
                // If content was truncated, show a truncation indicator
                let total_lines = trimmed.lines().count();
                if total_lines > 20 && skip_top == 0 && current_row <= max_row {
                    let truncation = "  │ …";
                    let trunc_bg = if *is_error { bg } else { Color::Default };
                    screen.write_str(
                        current_row,
                        area.x,
                        truncation,
                        Color::Ansi(244),
                        trunc_bg,
                        Style::dim(),
                    );
                    if *is_error {
                        let fill_end = area.x + area.width.saturating_sub(1);
                        for c in (area.x + truncation.len() as u16)..fill_end {
                            if let Some(cell) = screen.get_mut(current_row, c) {
                                cell.bg = bg;
                            }
                        }
                    }
                }
            }
            ConversationLine::System { text } => {
                if skip_top == 0 && start_row <= max_row {
                    screen.write_str(
                        start_row,
                        area.x,
                        "  ",
                        Color::Default,
                        Color::Default,
                        Style::default(),
                    );
                    screen.write_str_wrapped_clipped(
                        start_row,
                        area.x + 2,
                        text,
                        Color::YELLOW,
                        Color::Default,
                        Style::default(),
                        area.x,
                        effective_max_row,
                        wrap_col,
                    );
                } else if skip_top > 0 {
                    screen.write_str_wrapped_skip_clipped(
                        start_row,
                        area.x + 2,
                        text,
                        Color::YELLOW,
                        Color::Default,
                        Style::default(),
                        area.x,
                        effective_max_row,
                        wrap_col,
                        skip_top,
                    );
                }
            }
            ConversationLine::Thinking { text } => {
                let prefix = "  [thinking] ";
                let content_indent = area.x + prefix.len() as u16;
                if skip_top == 0 && start_row <= max_row {
                    screen.write_str(
                        start_row,
                        area.x,
                        prefix,
                        styles::THINKING_FG,
                        Color::Default,
                        Style::dim(),
                    );
                    let display_text = if text.is_empty() {
                        "⋯".to_string()
                    } else {
                        text.clone()
                    };
                    screen.write_str_wrapped_clipped(
                        start_row,
                        content_indent,
                        &display_text,
                        styles::THINKING_FG,
                        Color::Default,
                        Style::dim(),
                        content_indent,
                        effective_max_row,
                        wrap_col,
                    );
                } else if skip_top > 0 {
                    let display_text = if text.is_empty() {
                        "⋯".to_string()
                    } else {
                        text.clone()
                    };
                    screen.write_str_wrapped_skip_clipped(
                        start_row,
                        content_indent,
                        &display_text,
                        styles::THINKING_FG,
                        Color::Default,
                        Style::dim(),
                        content_indent,
                        effective_max_row,
                        wrap_col,
                        skip_top,
                    );
                }
            }
            ConversationLine::Separator => {
                if skip_top == 0 && start_row <= max_row {
                    screen.hline(
                        start_row,
                        area.x + 2,
                        area.x + area.width.saturating_sub(4),
                        '─',
                        Color::Ansi(240),
                        Color::Default,
                    );
                }
            }
            ConversationLine::ConfirmPrompt {
                name,
                args_summary,
                diff_preview,
            } => {
                let mut current_row = start_row;
                let mut lines_remaining = rows_available;

                // Render the prompt line
                if skip_top == 0 && current_row <= max_row && lines_remaining > 0 {
                    let prompt = format!("  ⚠ Confirm {} {}", name, args_summary);
                    let suffix = " [y/n/a]?";
                    screen.write_str(
                        current_row,
                        area.x,
                        &prompt,
                        Color::YELLOW,
                        Color::Default,
                        Style::bold(),
                    );
                    let prompt_end =
                        area.x + prompt.len().min(area.width as usize - suffix.len()) as u16;
                    screen.write_str(
                        current_row,
                        prompt_end,
                        suffix,
                        Color::YELLOW,
                        Color::Default,
                        Style::default(),
                    );
                    current_row += 1;
                    lines_remaining = lines_remaining.saturating_sub(1);
                }

                // Render diff preview lines
                if let Some(diff) = diff_preview
                    && !diff.is_empty()
                {
                    let max_content_width = (area.width as usize).saturating_sub(5);
                    for line in diff.lines() {
                        if lines_remaining == 0 || current_row > max_row {
                            break;
                        }

                        // Determine color based on diff prefix (enhanced)
                        let (line_color, line_bg, prefix) = if line.starts_with("@@") {
                            // Hunk header
                            (Color::CYAN, Color::Default, "  │ ")
                        } else if line.starts_with("---") || line.starts_with("+++") {
                            // File header
                            (Color::WHITE, Color::Default, "  │ ")
                        } else if line.starts_with('-') {
                            // Removed line — red text with dark red background
                            (Color::RED, Color::Ansi(52), "  │ ")
                        } else if line.starts_with('+') {
                            // Added line — green text with dark green background
                            (Color::GREEN, Color::Ansi(22), "  │ ")
                        } else {
                            (Color::Ansi(252), Color::Default, "  │ ")
                        };

                        let display = if line.is_empty() {
                            prefix.to_string()
                        } else if line.len() > max_content_width {
                            format!(
                                "{}{}…",
                                prefix,
                                truncate_str(line, max_content_width.saturating_sub(1))
                            )
                        } else {
                            format!("{}{}", prefix, line)
                        };

                        screen.write_str(
                            current_row,
                            area.x,
                            &display,
                            line_color,
                            line_bg,
                            Style::default(),
                        );
                        // Fill background for diff lines with colored backgrounds
                        if line_bg != Color::Default {
                            let fill_end = area.x + area.width.saturating_sub(1);
                            let end_col =
                                area.x + display.len().min(area.width as usize - 1) as u16;
                            if end_col < fill_end {
                                for c in end_col..fill_end {
                                    if let Some(cell) = screen.get_mut(current_row, c) {
                                        cell.bg = line_bg;
                                    }
                                }
                            }
                        }

                        current_row += 1;
                        lines_remaining = lines_remaining.saturating_sub(1);
                    }
                }
            }
            ConversationLine::Question { question, answers } => {
                // Question header: "  ❓ <question>"
                let question_prefix = "  ❓ ";
                let answer_prefix_len = if answers.len() >= 10 { 7 } else { 6 };
                let mut current_row = start_row;
                let mut lines_remaining = rows_available;

                // Render question line
                if skip_top == 0 && current_row <= max_row && lines_remaining > 0 {
                    screen.write_str(
                        current_row,
                        area.x,
                        question_prefix,
                        Color::YELLOW,
                        Color::Default,
                        Style::bold(),
                    );
                    screen.write_str_wrapped_clipped(
                        current_row,
                        area.x + question_prefix.len() as u16,
                        question,
                        Color::YELLOW,
                        Color::Default,
                        Style::default(),
                        area.x + question_prefix.len() as u16,
                        effective_max_row,
                        wrap_col,
                    );
                    current_row += 1;
                    lines_remaining -= 1;
                } else if skip_top > 0 {
                    // Skip question lines
                    let q_height =
                        self.line_height_for_text(question, question_prefix.len(), area.width);
                    if skip_top >= q_height {
                        // Question entirely skipped; adjust for remaining skip
                    }
                }

                // Render answer lines: "    N. <answer>"
                for (i, answer) in answers.iter().enumerate() {
                    let answer_label = format!("    {}. ", i + 1);
                    let a_height = self.line_height_for_text(answer, answer_prefix_len, area.width);

                    if skip_top > 0 {
                        // Still skipping
                        if a_height <= skip_top {
                            // This answer is entirely skipped
                        } else {
                            // Partially visible — render with skip
                            if current_row <= max_row && lines_remaining > 0 {
                                screen.write_str(
                                    current_row,
                                    area.x,
                                    &answer_label,
                                    Color::CYAN,
                                    Color::Default,
                                    Style::bold(),
                                );
                                screen.write_str_wrapped_skip_clipped(
                                    current_row,
                                    area.x + answer_label.len() as u16,
                                    answer,
                                    Color::WHITE,
                                    Color::Default,
                                    Style::default(),
                                    area.x + answer_label.len() as u16,
                                    effective_max_row,
                                    wrap_col,
                                    skip_top,
                                );
                            }
                        }
                    } else if current_row <= max_row && lines_remaining > 0 {
                        // Normal rendering (no skipping)
                        screen.write_str(
                            current_row,
                            area.x,
                            &answer_label,
                            Color::CYAN,
                            Color::Default,
                            Style::bold(),
                        );
                        screen.write_str_wrapped_clipped(
                            current_row,
                            area.x + answer_label.len() as u16,
                            answer,
                            Color::WHITE,
                            Color::Default,
                            Style::default(),
                            area.x + answer_label.len() as u16,
                            effective_max_row,
                            wrap_col,
                        );
                        current_row += 1;
                        lines_remaining = lines_remaining.saturating_sub(1);
                    }
                }
            }
        }
    }

    /// Render the context warning banner at the top of the conversation area.
    fn render_context_warning(&self, area: Rect, screen: &mut Screen) {
        let row = area.y;
        let (fg, bg, msg) = match &self.context_warning {
            ContextWarningLevel::None => return,
            ContextWarningLevel::Warning(pct) => (
                Color::YELLOW,
                Color::Ansi(17), // dark blue bg
                format!(
                    " ⚠ Context {:.0}% full — consider /compact to free space ",
                    pct
                ),
            ),
            ContextWarningLevel::Critical(pct) => (
                Color::WHITE,
                Color::Ansi(52), // dark red bg
                format!(" ⚠ Context {:.0}% — exceeded! Use /compact now ", pct),
            ),
        };

        // Fill the banner row with background color
        for col in area.x..area.x + area.width {
            if let Some(cell) = screen.get_mut(row, col) {
                cell.bg = bg;
                cell.char = ' ';
            }
        }

        // Write the warning text (truncate if wider than area)
        let display = if msg.len() > area.width as usize {
            truncate_str(&msg, area.width as usize).to_string()
        } else {
            msg
        };
        screen.write_str(row, area.x, &display, fg, bg, Style::bold());
    }

    /// Render the search bar at the bottom of the conversation area.
    fn render_search_bar(&self, row: u16, area: Rect, screen: &mut Screen) {
        // Fill the search bar background
        for col in area.x..area.x + area.width {
            if let Some(cell) = screen.get_mut(row, col) {
                cell.bg = styles::STATUS_BAR_BG;
                cell.char = ' ';
            }
        }

        // "Search: " label
        let label = " Search: ";
        screen.write_str(
            row,
            area.x,
            label,
            Color::YELLOW,
            styles::STATUS_BAR_BG,
            Style::bold(),
        );

        let query_col = area.x + label.len() as u16;

        // Search query text
        let query_text = &self.search.query;
        let max_query_width = area.width.saturating_sub(label.len() as u16 + 20); // reserve for match count
        let display_query = if query_text.len() > max_query_width as usize {
            truncate_str(query_text, max_query_width as usize).to_string()
        } else {
            query_text.clone()
        };
        screen.write_str(
            row,
            query_col,
            &display_query,
            Color::WHITE,
            styles::STATUS_BAR_BG,
            Style::default(),
        );

        // Cursor indicator (underline the character at cursor position or show block if at end)
        let cursor_col_in_display = if self.search.cursor > query_text.len() {
            display_query.len()
        } else {
            // Find the display position corresponding to the cursor byte offset
            let before_cursor = &query_text[..self.search.cursor.min(query_text.len())];
            let display_offset = before_cursor.chars().count();
            if display_offset > max_query_width as usize {
                max_query_width as usize
            } else {
                display_offset
            }
        };
        let cursor_screen_col = area.x + label.len() as u16 + cursor_col_in_display as u16;
        if cursor_screen_col < area.x + area.width {
            if let Some(cell) = screen.get_mut(row, cursor_screen_col) {
                cell.style.underline = true;
                if cell.char == ' ' {
                    cell.fg = Color::WHITE;
                }
            }
        }

        // Match count on the right side
        let match_count = if !self.search.match_rows.is_empty() {
            format!(
                " {}/{} ",
                self.search.current_match + 1,
                self.search.match_rows.len()
            )
        } else if !self.search.query.is_empty() {
            " No matches ".to_string()
        } else {
            String::new()
        };

        if !match_count.is_empty() {
            let match_start = area
                .x
                .saturating_add(area.width)
                .saturating_sub(match_count.len() as u16);
            screen.write_str(
                row,
                match_start,
                &match_count,
                Color::Ansi(244),
                styles::STATUS_BAR_BG,
                Style::dim(),
            );
        }
    }

    /// Highlight search matches in the visible area of the conversation.
    fn highlight_search_matches(&self, area: Rect, screen: &mut Screen, content_width: u16) {
        if self.search.query.is_empty() {
            return;
        }

        let query_lower = self.search.query.to_lowercase();
        let visible_start = self.scroll_offset;
        let visible_end = visible_start + area.height as usize;

        // Walk through conversation lines, computing visual row offsets,
        // and highlight matches in visible lines.
        let mut visual_row = 0usize;
        let mut screen_row = area.y;
        let mut match_idx = 0usize;

        for line in &self.lines {
            let height = self.line_height(line, content_width);

            // Skip lines entirely above the visible area
            if visual_row + height <= visible_start {
                visual_row += height;
                continue;
            }

            // Stop if we're past the visible area
            if visual_row >= visible_end {
                break;
            }

            let skip_top = visible_start.saturating_sub(visual_row);
            let rows_available = area.bottom().saturating_sub(screen_row) as usize;
            if rows_available == 0 {
                break;
            }

            // Get the searchable text for this line
            let text = match line {
                ConversationLine::User { text } => text.clone(),
                ConversationLine::Assistant { text } => text.clone(),
                ConversationLine::System { text } => text.clone(),
                ConversationLine::Thinking { text } => text.clone(),
                ConversationLine::ToolResult { content, .. } => content.clone(),
                ConversationLine::ToolCall { name, args_summary } => {
                    format!("{} {}", name, args_summary)
                }
                ConversationLine::ConfirmPrompt {
                    name, args_summary, ..
                } => {
                    format!("{} {}", name, args_summary)
                }
                ConversationLine::Question { question, answers } => {
                    format!("{} {}", question, answers.join(" "))
                }
                ConversationLine::Separator => String::new(),
            };

            if !text.is_empty() {
                let text_lower = text.to_lowercase();
                let mut search_start = 0usize;
                while let Some(pos) = text_lower[search_start..].find(&query_lower) {
                    let abs_pos = search_start + pos;
                    search_start = abs_pos + query_lower.len();

                    // Compute the screen column for this match
                    // The match may span multiple visual rows due to wrapping
                    let prefix = &text[..abs_pos];
                    let prefix_chars: Vec<char> = prefix.chars().collect();
                    let query_chars: Vec<char> = self.search.query.chars().collect();
                    let query_len = query_chars.len();

                    // Determine which visual row within this line the match starts on
                    // Use the same wrapping logic as render (simplified)
                    let line_prefix_len = match line {
                        ConversationLine::User { .. } => 7,
                        ConversationLine::Assistant { .. } => 7,
                        ConversationLine::System { .. } => 2,
                        ConversationLine::Thinking { .. } => 13,
                        _ => 4, // tool result, etc.
                    };
                    let wrap_at = content_width as usize;

                    // Calculate the visual row offset for the start of the match
                    let mut row_offset = 0usize;
                    let mut col = line_prefix_len;
                    for _ in prefix_chars.iter() {
                        col += 1;
                        if col >= wrap_at {
                            row_offset += 1;
                            col = line_prefix_len;
                        }
                    }

                    // Calculate the starting column for the match
                    let start_col = col;

                    // Check if this match is visible (considering skip_top)
                    let actual_visual_row = visual_row + row_offset;
                    if actual_visual_row >= visible_end {
                        break;
                    }
                    if actual_visual_row < visible_start {
                        // Match is above visible area but might span into it
                        // For simplicity, skip matches that start above the visible area
                        continue;
                    }

                    let match_screen_row = screen_row + row_offset as u16;
                    if skip_top > 0 && row_offset < skip_top {
                        continue;
                    }

                    // Determine if this is the current match
                    let is_current = match_idx < self.search.match_rows.len()
                        && self.search.match_rows[match_idx] == visual_row;

                    // Highlight the match characters on screen
                    let highlight_fg = if is_current {
                        Color::BLACK
                    } else {
                        Color::WHITE
                    };
                    let highlight_bg = if is_current {
                        Color::ORANGE
                    } else {
                        Color::Ansi(58) // dark yellow/olive
                    };

                    let mut highlight_col = area.x + start_col as u16;
                    for _ in 0..query_len {
                        if highlight_col >= area.x + area.width.saturating_sub(1) {
                            break; // Don't overwrite scrollbar
                        }
                        if let Some(cell) = screen.get_mut(match_screen_row, highlight_col) {
                            cell.fg = highlight_fg;
                            cell.bg = highlight_bg;
                        }
                        highlight_col += 1;
                    }

                    match_idx += 1;
                }
            }

            screen_row += height.saturating_sub(skip_top) as u16;
            screen_row = screen_row.min(area.bottom());
            visual_row += height;
        }
    }

    /// Render a scrollbar on the right edge of the area.
    fn render_scrollbar(&self, area: Rect, screen: &mut Screen, total_lines: usize) {
        if total_lines <= area.height as usize {
            return;
        }

        let scrollbar_height = area.height;
        let thumb_size =
            ((scrollbar_height as usize * scrollbar_height as usize) / total_lines).max(1) as u16;
        let thumb_position = if total_lines > area.height as usize {
            (self.scroll_offset as u16 * (scrollbar_height - thumb_size))
                / (total_lines as u16 - area.height)
        } else {
            0
        };

        let x = area.x + area.width - 1;
        for row in area.y..area.y + area.height {
            if let Some(cell) = screen.get_mut(row, x) {
                cell.char = '│';
                cell.fg = styles::SCROLLBAR_FG;
                cell.bg = styles::SCROLLBAR_BG;
            }
        }

        for i in 0..thumb_size {
            let row = area.y + thumb_position + i;
            if row < area.y + area.height {
                if let Some(cell) = screen.get_mut(row, x) {
                    cell.char = '█';
                    cell.fg = styles::SCROLLBAR_FG;
                }
            }
        }
    }
}

impl Widget for ConversationWidget {
    fn render(&mut self, area: Rect, screen: &mut Screen) {
        if area.is_empty() {
            return;
        }

        screen.fill_rect(area, Cell::default());

        // Reserve space for search bar if active (1 row at bottom of conversation)
        let search_active = self.search.active;
        let search_bar_rows: u16 = if search_active { 1 } else { 0 };

        // Reserve space for context warning banner (1 row at top)
        let warning_banner_rows: u16 = if matches!(self.context_warning, ContextWarningLevel::None)
        {
            0
        } else {
            1
        };

        let content_area = Rect::new(
            area.x,
            area.y + warning_banner_rows,
            area.width,
            area.height
                .saturating_sub(warning_banner_rows + search_bar_rows),
        );

        // Render context warning banner
        if warning_banner_rows > 0 {
            self.render_context_warning(area, screen);
        }

        // Render search bar at the bottom of the conversation area
        if search_active {
            let search_row = area.y + area.height.saturating_sub(1);
            self.render_search_bar(search_row, area, screen);
        }

        let visible_rows = content_area.height as usize;
        // Reserve 1 column for the scrollbar
        let content_width = content_area.width.saturating_sub(1);
        let total_height = self.total_visual_height(content_width);

        let max_scroll = total_height.saturating_sub(visible_rows);
        if self.auto_scroll {
            self.scroll_offset = max_scroll;
        }
        if self.scroll_offset > max_scroll {
            self.scroll_offset = max_scroll;
        }

        let mut visual_row = 0usize;
        let mut screen_row = content_area.y;
        let skip_rows = self.scroll_offset;

        for line in &self.lines {
            let height = self.line_height(line, content_width);

            if visual_row + height <= skip_rows {
                visual_row += height;
                continue;
            }

            let skip_top = skip_rows.saturating_sub(visual_row);
            let rows_available = content_area.bottom().saturating_sub(screen_row) as usize;

            if rows_available == 0 {
                break;
            }

            self.render_line_clipped(
                line,
                screen_row,
                screen,
                content_width,
                content_area,
                skip_top,
                rows_available,
            );

            screen_row += height.saturating_sub(skip_top) as u16;
            screen_row = screen_row.min(content_area.bottom());
            visual_row += height;

            if screen_row >= content_area.bottom() {
                break;
            }
        }

        self.render_scrollbar(content_area, screen, total_height);

        // Highlight search matches if active
        if self.search.active && !self.search.query.is_empty() {
            self.highlight_search_matches(content_area, screen, content_width);
        }
    }

    fn handle_event(&mut self, event: &Event) -> Action {
        // If search mode is active, intercept all key events
        if self.search.active {
            if let Event::Key(key) = event {
                match key {
                    KeyEvent {
                        key: Key::Escape,
                        modifiers,
                    } if !modifiers.ctrl && !modifiers.alt => {
                        self.close_search();
                        return Action::None;
                    }
                    KeyEvent {
                        key: Key::Enter,
                        modifiers,
                    } if modifiers.shift => {
                        // Shift+Enter: previous match
                        self.search_prev();
                        return Action::None;
                    }
                    KeyEvent {
                        key: Key::Enter,
                        modifiers,
                    } if !modifiers.ctrl && !modifiers.alt => {
                        // Enter: next match
                        self.search_next();
                        return Action::None;
                    }
                    KeyEvent {
                        key: Key::Char(ch),
                        modifiers,
                    } if !modifiers.ctrl && !modifiers.alt => {
                        self.search_type_char(*ch);
                        return Action::None;
                    }
                    KeyEvent {
                        key: Key::Backspace,
                        ..
                    } => {
                        self.search_backspace();
                        return Action::None;
                    }
                    KeyEvent {
                        key: Key::Left,
                        modifiers,
                    } if !modifiers.ctrl && !modifiers.alt => {
                        self.search_cursor_left();
                        return Action::None;
                    }
                    KeyEvent {
                        key: Key::Right,
                        modifiers,
                    } if !modifiers.ctrl && !modifiers.alt => {
                        self.search_cursor_right();
                        return Action::None;
                    }
                    _ => {
                        // Let other keys pass through (e.g., Ctrl+C for quit)
                        let _ = key;
                    }
                }
            }
            // Non-key events pass through
            return Action::None;
        }

        if let Event::Key(key) = event {
            match key {
                KeyEvent {
                    key: Key::Char('f'),
                    modifiers,
                } if modifiers.ctrl => {
                    self.toggle_search();
                    return Action::None;
                }
                KeyEvent {
                    key: Key::Tab,
                    modifiers,
                } if !modifiers.shift && !modifiers.alt && !modifiers.ctrl => {
                    return Action::CycleFocusForward;
                }
                KeyEvent {
                    key: Key::BackTab, ..
                } => {
                    return Action::CycleFocusBackward;
                }
                _ => {}
            }
        }
        let _ = event;
        Action::None
    }
}

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

    #[test]
    fn test_conversation_new() {
        let conv = ConversationWidget::new();
        assert!(conv.lines.is_empty());
        assert!(conv.auto_scroll);
    }

    #[test]
    fn test_conversation_push() {
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::User {
            text: "Hello".to_string(),
        });
        conv.push(ConversationLine::Assistant {
            text: "Hi there!".to_string(),
        });
        assert_eq!(conv.lines.len(), 2);
    }

    #[test]
    fn test_conversation_scroll() {
        let mut conv = ConversationWidget::new();
        for i in 0..50 {
            conv.push(ConversationLine::User {
                text: format!("Message {}", i),
            });
        }
        assert!(conv.auto_scroll);

        conv.scroll_up(10);
        assert!(!conv.auto_scroll);

        conv.scroll_down(10);
    }

    #[test]
    fn test_conversation_clear() {
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::User {
            text: "Hello".to_string(),
        });
        conv.clear();
        assert!(conv.lines.is_empty());
    }

    #[test]
    fn test_conversation_render() {
        let mut screen = Screen::new(80, 24);
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::User {
            text: "Hello".to_string(),
        });
        conv.push(ConversationLine::Separator);
        conv.push(ConversationLine::Assistant {
            text: "Hi there!".to_string(),
        });

        let area = Rect::new(0, 0, 80, 20);
        conv.render(area, &mut screen);

        assert!(screen.get(0, 0).unwrap().char != '\0');
    }

    #[test]
    fn test_tool_result_line_height() {
        let conv = ConversationWidget::new();
        let line = ConversationLine::ToolResult {
            name: "read".to_string(),
            content: "line1\nline2\nline3".to_string(),
            is_error: false,
        };
        assert_eq!(conv.line_height(&line, 80), 3);
    }

    #[test]
    fn test_tool_result_trailing_newlines() {
        let conv = ConversationWidget::new();
        // Trailing newlines should be trimmed
        let line = ConversationLine::ToolResult {
            name: "read".to_string(),
            content: "line1\nline2\n\n\n".to_string(),
            is_error: false,
        };
        // Should count 2 visible lines, not 4
        assert_eq!(conv.line_height(&line, 80), 2);
    }

    #[test]
    fn test_tool_result_truncated() {
        let conv = ConversationWidget::new();
        // Content with more than 20 lines should be capped
        let long_content: String = (0..30)
            .map(|i| format!("line {}", i))
            .collect::<Vec<_>>()
            .join("\n");
        let line = ConversationLine::ToolResult {
            name: "run".to_string(),
            content: long_content,
            is_error: false,
        };
        // Should be capped at 20 lines + truncation indicator
        let height = conv.line_height(&line, 80);
        assert!(
            height <= 21,
            "Tool result should be capped at ~20 lines, got {}",
            height
        );
    }

    #[test]
    fn test_tool_result_single_line() {
        let conv = ConversationWidget::new();
        let line = ConversationLine::ToolResult {
            name: "read".to_string(),
            content: "single line".to_string(),
            is_error: false,
        };
        assert_eq!(conv.line_height(&line, 80), 1);
    }

    #[test]
    fn test_assistant_wrapping_line_height() {
        let conv = ConversationWidget::new();
        // With width=20, prefix "  AI:  " (7 chars), text "12345678901234567890" (20 chars)
        // First row: prefix + 13 chars, second row: 7 more chars
        let line = ConversationLine::Assistant {
            text: "12345678901234567890".to_string(),
        };
        let height = conv.line_height(&line, 20);
        assert!(
            height >= 2,
            "Long text should wrap to multiple rows, got {}",
            height
        );
    }

    #[test]
    fn test_confirm_prompt_line_height() {
        let conv = ConversationWidget::new();
        let line = ConversationLine::ConfirmPrompt {
            name: "run".to_string(),
            args_summary: "cargo test".to_string(),
            diff_preview: None,
        };
        // ConfirmPrompt with no diff takes 1 row
        assert_eq!(conv.line_height(&line, 80), 1);
    }

    #[test]
    fn test_confirm_prompt_with_diff_line_height() {
        let conv = ConversationWidget::new();
        let diff = "-  old line\n+  new line\n  context line".to_string();
        let line = ConversationLine::ConfirmPrompt {
            name: "edit".to_string(),
            args_summary: "src/main.rs".to_string(),
            diff_preview: Some(diff),
        };
        // 1 row for prompt + 3 rows for diff lines
        assert_eq!(conv.line_height(&line, 80), 4);
    }

    #[test]
    fn test_confirm_prompt_push() {
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::ConfirmPrompt {
            name: "run".to_string(),
            args_summary: "cargo build".to_string(),
            diff_preview: None,
        });
        assert_eq!(conv.lines.len(), 1);
    }

    // ── Search tests ────────────────────────────────────────────────────

    #[test]
    fn test_search_toggle() {
        let mut conv = ConversationWidget::new();
        assert!(!conv.is_search_active());
        conv.toggle_search();
        assert!(conv.is_search_active());
        conv.toggle_search();
        assert!(!conv.is_search_active());
    }

    #[test]
    fn test_search_close() {
        let mut conv = ConversationWidget::new();
        conv.toggle_search();
        assert!(conv.is_search_active());
        conv.close_search();
        assert!(!conv.is_search_active());
    }

    #[test]
    fn test_search_type_char_and_backspace() {
        let mut conv = ConversationWidget::new();
        conv.toggle_search();
        conv.search_type_char('h');
        conv.search_type_char('i');
        assert_eq!(conv.search.query, "hi");
        assert_eq!(conv.search.cursor, 2);
        conv.search_backspace();
        assert_eq!(conv.search.query, "h");
        assert_eq!(conv.search.cursor, 1);
        conv.search_backspace();
        assert_eq!(conv.search.query, "");
        assert_eq!(conv.search.cursor, 0);
        // Backspace on empty query is a no-op
        conv.search_backspace();
        assert_eq!(conv.search.query, "");
    }

    #[test]
    fn test_search_cursor_movement() {
        let mut conv = ConversationWidget::new();
        conv.toggle_search();
        conv.search_type_char('a');
        conv.search_type_char('b');
        conv.search_type_char('c');
        assert_eq!(conv.search.cursor, 3);
        conv.search_cursor_left();
        assert_eq!(conv.search.cursor, 2);
        conv.search_cursor_left();
        assert_eq!(conv.search.cursor, 1);
        conv.search_cursor_right();
        assert_eq!(conv.search.cursor, 2);
        // Can't go past the end
        conv.search_cursor_right();
        conv.search_cursor_right();
        assert_eq!(conv.search.cursor, 3);
    }

    #[test]
    fn test_search_matches() {
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::User {
            text: "Hello world".to_string(),
        });
        conv.push(ConversationLine::Assistant {
            text: "Hi there!".to_string(),
        });
        conv.push(ConversationLine::User {
            text: "Hello again".to_string(),
        });
        conv.toggle_search();
        conv.search_type_char('h');
        conv.search_type_char('e');
        conv.search_type_char('l');
        // "hel" matches "Hello world" and "Hello again" (case-insensitive)
        assert_eq!(conv.search.match_rows.len(), 2);
    }

    #[test]
    fn test_search_no_matches() {
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::User {
            text: "Hello world".to_string(),
        });
        conv.toggle_search();
        conv.search_type_char('z');
        conv.search_type_char('z');
        conv.search_type_char('z');
        assert!(conv.search.match_rows.is_empty());
    }

    #[test]
    fn test_search_navigation() {
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::User {
            text: "First match".to_string(),
        });
        conv.push(ConversationLine::Assistant {
            text: "No hit here".to_string(),
        });
        conv.push(ConversationLine::User {
            text: "Second match".to_string(),
        });
        conv.toggle_search();
        conv.search_type_char('m');
        conv.search_type_char('a');
        conv.search_type_char('t');
        conv.search_type_char('c');
        conv.search_type_char('h');
        assert_eq!(conv.search.match_rows.len(), 2);
        assert_eq!(conv.search.current_match, 0);
        conv.search_next();
        assert_eq!(conv.search.current_match, 1);
        conv.search_next();
        assert_eq!(conv.search.current_match, 0); // wraps around
        conv.search_prev();
        assert_eq!(conv.search.current_match, 1); // wraps around
    }

    #[test]
    fn test_search_clears_on_close() {
        let mut conv = ConversationWidget::new();
        conv.toggle_search();
        conv.search_type_char('x');
        conv.close_search();
        assert!(!conv.is_search_active());
        assert!(conv.search.query.is_empty());
        assert!(conv.search.match_rows.is_empty());
    }

    // ── Context warning tests ──────────────────────────────────────────

    #[test]
    fn test_context_warning_default() {
        let conv = ConversationWidget::new();
        assert!(matches!(conv.context_warning(), ContextWarningLevel::None));
    }

    #[test]
    fn test_context_warning_set_warning() {
        let mut conv = ConversationWidget::new();
        conv.set_context_warning(ContextWarningLevel::Warning(75.0));
        assert!(matches!(
            conv.context_warning(),
            ContextWarningLevel::Warning(75.0)
        ));
    }

    #[test]
    fn test_context_warning_set_critical() {
        let mut conv = ConversationWidget::new();
        conv.set_context_warning(ContextWarningLevel::Critical(92.0));
        assert!(matches!(
            conv.context_warning(),
            ContextWarningLevel::Critical(92.0)
        ));
    }

    #[test]
    fn test_context_warning_render() {
        let mut screen = Screen::new(80, 24);
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::User {
            text: "Hello".to_string(),
        });
        conv.set_context_warning(ContextWarningLevel::Warning(75.0));
        let area = Rect::new(0, 0, 80, 20);
        conv.render(area, &mut screen);
        // First row should have the warning banner (non-default background)
        let first_cell = screen.get(0, 0).unwrap();
        assert_ne!(first_cell.bg, Color::Default);
        assert_eq!(first_cell.char, ' ');
    }

    #[test]
    fn test_context_warning_critical_render() {
        let mut screen = Screen::new(80, 24);
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::User {
            text: "Hello".to_string(),
        });
        conv.set_context_warning(ContextWarningLevel::Critical(95.0));
        let area = Rect::new(0, 0, 80, 20);
        conv.render(area, &mut screen);
        let first_cell = screen.get(0, 0).unwrap();
        assert_eq!(first_cell.bg, Color::Ansi(52)); // dark red bg for critical
    }

    // ── Diff coloring tests ─────────────────────────────────────────────

    #[test]
    fn test_diff_coloring_in_tool_result() {
        let mut screen = Screen::new(80, 24);
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::ToolResult {
            name: "edit".to_string(),
            content:
                "--- a/file.rs\n+++ b/file.rs\n@@ -1,3 +1,3 @@\n- old line\n+ new line\n  context"
                    .to_string(),
            is_error: false,
        });
        let area = Rect::new(0, 0, 80, 20);
        conv.render(area, &mut screen);
        // Just verify it doesn't panic and renders something
        assert!(screen.get(0, 0).unwrap().char != '\0');
    }

    #[test]
    fn test_diff_coloring_in_confirm_prompt() {
        let mut screen = Screen::new(80, 24);
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::ConfirmPrompt {
            name: "edit".to_string(),
            args_summary: "src/main.rs".to_string(),
            diff_preview: Some("@@ -1,3 +1,3 @@\n- old line\n+ new line".to_string()),
        });
        let area = Rect::new(0, 0, 80, 20);
        conv.render(area, &mut screen);
        assert!(screen.get(0, 0).unwrap().char != '\0');
    }

    #[test]
    fn test_search_bar_render() {
        let mut screen = Screen::new(80, 24);
        let mut conv = ConversationWidget::new();
        conv.push(ConversationLine::User {
            text: "Hello".to_string(),
        });
        conv.toggle_search();
        conv.search_type_char('H');
        let area = Rect::new(0, 0, 80, 20);
        conv.render(area, &mut screen);
        // Search bar should be at the bottom row (row 19)
        let search_bar_row = 19u16;
        let cell = screen.get(search_bar_row, 1).unwrap();
        assert_eq!(cell.char, 'S'); // "Search: " starts with S
    }
}