presentar-terminal 0.3.5

Terminal backend for Presentar UI framework with zero-allocation rendering
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
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
//! TUI application runner with Jidoka verification gates.
//!
//! ## Non-Blocking UI Pattern (CB-INPUT-006)
//!
//! For applications with heavy data collection (system monitors, dashboards),
//! use the [`AsyncCollector`] pattern to ensure the main thread never blocks.
//!
//! ```ignore
//! // Background thread owns collectors, sends snapshots through channel
//! let (tx, rx) = mpsc::channel::<MySnapshot>();
//!
//! std::thread::spawn(move || {
//!     let mut collector = MyCollector::new();
//!     loop {
//!         let snapshot = collector.collect();  // Can take seconds
//!         tx.send(snapshot).ok();
//!         std::thread::sleep(Duration::from_secs(1));
//!     }
//! });
//!
//! // Main thread: input + render only (always <16ms)
//! loop {
//!     while let Ok(snapshot) = rx.try_recv() {
//!         app.apply_snapshot(snapshot);  // O(1) operation
//!     }
//!     app.handle_input();  // Non-blocking
//!     app.render();        // <16ms budget
//! }
//! ```

#![allow(dead_code, unreachable_pub)]

use crate::color::ColorMode;
use crate::direct::{CellBuffer, DiffRenderer, DirectTerminalCanvas};
use crate::error::{TuiError, VerificationError};
use crate::input::InputHandler;
use crossterm::{
    cursor,
    event::{self, Event as CrosstermEvent, KeyCode},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use presentar_core::{Constraints, Rect, Widget};
use std::io::{self, Stdout, Write};
use std::time::{Duration, Instant};

// =============================================================================
// Non-Blocking UI Pattern (CB-INPUT-006)
// =============================================================================

/// Snapshot of collected metrics, transportable via channel.
///
/// Implement this trait for data structures that are sent from a background
/// collector thread to the main UI thread.
///
/// # Requirements
/// - Must be `Clone` (for potential buffering)
/// - Must be `Send` (for channel transport)
/// - Must be `'static` (for thread safety)
pub trait Snapshot: Clone + Send + 'static {
    /// Create an empty snapshot for initial state before first collection.
    fn empty() -> Self;
}

/// Background collector that produces snapshots.
///
/// Implement this trait for objects that collect metrics in a background thread.
/// The collector owns all heavy I/O objects (System, Disks, Networks, etc.)
/// and produces lightweight snapshots that can be sent through a channel.
///
/// # Example
/// ```ignore
/// struct SystemCollector {
///     system: System,
///     disks: Disks,
/// }
///
/// impl AsyncCollector for SystemCollector {
///     type Snapshot = MetricsSnapshot;
///
///     fn collect(&mut self) -> MetricsSnapshot {
///         self.system.refresh_all();  // Heavy I/O
///         MetricsSnapshot {
///             cpu_usage: self.system.global_cpu_usage(),
///             // ... extract other data
///         }
///     }
/// }
/// ```
pub trait AsyncCollector: Send + 'static {
    /// The snapshot type produced by this collector.
    type Snapshot: Snapshot;

    /// Collect metrics and return a snapshot.
    ///
    /// This method may take seconds to complete (heavy I/O).
    /// It runs in a background thread, never blocking the UI.
    fn collect(&mut self) -> Self::Snapshot;
}

/// Application that can apply snapshots to update its state.
///
/// Implement this trait for your application state. The `apply_snapshot`
/// method is called on the main thread and MUST complete in <1ms.
///
/// # Example
/// ```ignore
/// impl SnapshotReceiver for MyApp {
///     type Snapshot = MetricsSnapshot;
///
///     fn apply_snapshot(&mut self, snapshot: MetricsSnapshot) {
///         // O(1) operations only - just copy/swap data
///         self.cpu_usage = snapshot.cpu_usage;
///         self.processes = snapshot.processes;
///     }
/// }
/// ```
pub trait SnapshotReceiver {
    /// The snapshot type this receiver accepts.
    type Snapshot: Snapshot;

    /// Apply a snapshot to update the application state.
    ///
    /// **MUST be O(1) and complete in <1ms.**
    /// Only perform simple assignments, no I/O or heavy computation.
    fn apply_snapshot(&mut self, snapshot: Self::Snapshot);
}

/// QA timing diagnostics for non-blocking UI verification.
///
/// Use this struct to collect timing data for `--qa-timing` output.
#[derive(Debug, Clone, Default)]
pub struct QaTimings {
    /// Input event processing times in microseconds.
    pub input_times_us: Vec<u64>,
    /// Lock acquisition times in microseconds (should be 0 with channel pattern).
    pub lock_times_us: Vec<u64>,
    /// Render times in microseconds.
    pub render_times_us: Vec<u64>,
    /// Last collect duration in microseconds (from background thread).
    pub last_collect_us: u64,
}

impl QaTimings {
    /// Create new QA timing collector.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Record an input event processing time.
    pub fn record_input(&mut self, duration: Duration) {
        self.input_times_us.push(duration.as_micros() as u64);
    }

    /// Record a lock acquisition time.
    pub fn record_lock(&mut self, duration: Duration) {
        self.lock_times_us.push(duration.as_micros() as u64);
    }

    /// Record a render time.
    pub fn record_render(&mut self, duration: Duration) {
        self.render_times_us.push(duration.as_micros() as u64);
    }

    /// Format timing report for stderr output.
    #[must_use]
    pub fn format_report(&self) -> String {
        let avg = |v: &[u64]| {
            if v.is_empty() {
                0
            } else {
                v.iter().sum::<u64>() / v.len() as u64
            }
        };
        let max = |v: &[u64]| v.iter().max().copied().unwrap_or(0);

        format!(
            "[QA] input: avg={}us max={}us | lock: avg={}us max={}us | render: avg={}us max={}us | collect: {}us",
            avg(&self.input_times_us), max(&self.input_times_us),
            avg(&self.lock_times_us), max(&self.lock_times_us),
            avg(&self.render_times_us), max(&self.render_times_us),
            self.last_collect_us
        )
    }

    /// Clear accumulated timing data.
    pub fn clear(&mut self) {
        self.input_times_us.clear();
        self.lock_times_us.clear();
        self.render_times_us.clear();
    }
}

// =============================================================================
// Terminal Abstraction
// =============================================================================

/// Terminal abstraction for testability.
pub trait Terminal {
    /// Enter raw mode and alternate screen.
    fn enter(&mut self) -> Result<(), TuiError>;
    /// Leave alternate screen and raw mode.
    fn leave(&mut self) -> Result<(), TuiError>;
    /// Get terminal size (width, height).
    fn size(&self) -> Result<(u16, u16), TuiError>;
    /// Poll for events with timeout.
    fn poll(&self, timeout: Duration) -> Result<bool, TuiError>;
    /// Read the next event.
    fn read_event(&self) -> Result<CrosstermEvent, TuiError>;
    /// Flush output.
    fn flush(
        &mut self,
        buffer: &mut CellBuffer,
        renderer: &mut DiffRenderer,
    ) -> Result<(), TuiError>;
    /// Enable mouse capture.
    fn enable_mouse(&mut self) -> Result<(), TuiError>;
    /// Disable mouse capture.
    fn disable_mouse(&mut self) -> Result<(), TuiError>;
}

/// Backend trait for raw terminal operations (crossterm calls).
/// This layer exists purely for testability.
pub trait TerminalBackend {
    fn enable_raw_mode(&mut self) -> Result<(), TuiError>;
    fn disable_raw_mode(&mut self) -> Result<(), TuiError>;
    fn enter_alternate_screen(&mut self) -> Result<(), TuiError>;
    fn leave_alternate_screen(&mut self) -> Result<(), TuiError>;
    fn hide_cursor(&mut self) -> Result<(), TuiError>;
    fn show_cursor(&mut self) -> Result<(), TuiError>;
    fn size(&self) -> Result<(u16, u16), TuiError>;
    fn poll(&self, timeout: Duration) -> Result<bool, TuiError>;
    fn read_event(&self) -> Result<CrosstermEvent, TuiError>;
    fn write_flush(
        &mut self,
        buffer: &mut CellBuffer,
        renderer: &mut DiffRenderer,
    ) -> Result<(), TuiError>;
    fn enable_mouse_capture(&mut self) -> Result<(), TuiError>;
    fn disable_mouse_capture(&mut self) -> Result<(), TuiError>;
}

/// Real crossterm backend.
pub struct CrosstermBackend {
    stdout: Stdout,
}

impl CrosstermBackend {
    pub fn new() -> Self {
        Self {
            stdout: io::stdout(),
        }
    }
}

impl Default for CrosstermBackend {
    fn default() -> Self {
        Self::new()
    }
}

impl TerminalBackend for CrosstermBackend {
    fn enable_raw_mode(&mut self) -> Result<(), TuiError> {
        enable_raw_mode()?;
        Ok(())
    }
    fn disable_raw_mode(&mut self) -> Result<(), TuiError> {
        let _ = disable_raw_mode();
        Ok(())
    }
    fn enter_alternate_screen(&mut self) -> Result<(), TuiError> {
        execute!(self.stdout, EnterAlternateScreen)?;
        Ok(())
    }
    fn leave_alternate_screen(&mut self) -> Result<(), TuiError> {
        let _ = execute!(self.stdout, LeaveAlternateScreen);
        Ok(())
    }
    fn hide_cursor(&mut self) -> Result<(), TuiError> {
        execute!(self.stdout, cursor::Hide)?;
        Ok(())
    }
    fn show_cursor(&mut self) -> Result<(), TuiError> {
        let _ = execute!(self.stdout, cursor::Show);
        Ok(())
    }
    fn size(&self) -> Result<(u16, u16), TuiError> {
        Ok(crossterm::terminal::size()?)
    }
    fn poll(&self, timeout: Duration) -> Result<bool, TuiError> {
        Ok(event::poll(timeout)?)
    }
    fn read_event(&self) -> Result<CrosstermEvent, TuiError> {
        Ok(event::read()?)
    }
    fn write_flush(
        &mut self,
        buffer: &mut CellBuffer,
        renderer: &mut DiffRenderer,
    ) -> Result<(), TuiError> {
        renderer.flush(buffer, &mut self.stdout)?;
        self.stdout.flush()?;
        Ok(())
    }
    fn enable_mouse_capture(&mut self) -> Result<(), TuiError> {
        execute!(self.stdout, crossterm::event::EnableMouseCapture)?;
        Ok(())
    }
    fn disable_mouse_capture(&mut self) -> Result<(), TuiError> {
        let _ = execute!(self.stdout, crossterm::event::DisableMouseCapture);
        Ok(())
    }
}

/// Testable backend with generic writer for capturing escape sequences.
/// This backend allows testing terminal output without a real TTY.
#[allow(clippy::struct_excessive_bools)]
pub struct TestableBackend<W: Write> {
    writer: W,
    size: (u16, u16),
    raw_mode: bool,
    alternate_screen: bool,
    cursor_hidden: bool,
    mouse_captured: bool,
    events: std::cell::RefCell<std::collections::VecDeque<CrosstermEvent>>,
    poll_results: std::cell::RefCell<std::collections::VecDeque<bool>>,
}

impl<W: Write> TestableBackend<W> {
    /// Create a new testable backend with the given writer and size.
    pub fn new(writer: W, width: u16, height: u16) -> Self {
        Self {
            writer,
            size: (width, height),
            raw_mode: false,
            alternate_screen: false,
            cursor_hidden: false,
            mouse_captured: false,
            events: std::cell::RefCell::new(std::collections::VecDeque::new()),
            poll_results: std::cell::RefCell::new(std::collections::VecDeque::new()),
        }
    }

    /// Queue events to be returned by `read_event`.
    pub fn with_events(self, events: Vec<CrosstermEvent>) -> Self {
        *self.events.borrow_mut() = events.into_iter().collect();
        self
    }

    /// Queue poll results.
    pub fn with_polls(self, polls: Vec<bool>) -> Self {
        *self.poll_results.borrow_mut() = polls.into_iter().collect();
        self
    }

    /// Check if raw mode was enabled.
    pub fn is_raw_mode(&self) -> bool {
        self.raw_mode
    }

    /// Check if alternate screen was entered.
    pub fn is_alternate_screen(&self) -> bool {
        self.alternate_screen
    }

    /// Check if cursor is hidden.
    pub fn is_cursor_hidden(&self) -> bool {
        self.cursor_hidden
    }

    /// Check if mouse is captured.
    pub fn is_mouse_captured(&self) -> bool {
        self.mouse_captured
    }

    /// Get the underlying writer (consumes self).
    pub fn into_writer(self) -> W {
        self.writer
    }
}

impl<W: Write> TerminalBackend for TestableBackend<W> {
    fn enable_raw_mode(&mut self) -> Result<(), TuiError> {
        self.raw_mode = true;
        Ok(())
    }

    fn disable_raw_mode(&mut self) -> Result<(), TuiError> {
        self.raw_mode = false;
        Ok(())
    }

    fn enter_alternate_screen(&mut self) -> Result<(), TuiError> {
        self.alternate_screen = true;
        // Write the actual escape sequence for testing
        execute!(self.writer, EnterAlternateScreen)?;
        Ok(())
    }

    fn leave_alternate_screen(&mut self) -> Result<(), TuiError> {
        self.alternate_screen = false;
        let _ = execute!(self.writer, LeaveAlternateScreen);
        Ok(())
    }

    fn hide_cursor(&mut self) -> Result<(), TuiError> {
        self.cursor_hidden = true;
        execute!(self.writer, cursor::Hide)?;
        Ok(())
    }

    fn show_cursor(&mut self) -> Result<(), TuiError> {
        self.cursor_hidden = false;
        let _ = execute!(self.writer, cursor::Show);
        Ok(())
    }

    fn size(&self) -> Result<(u16, u16), TuiError> {
        Ok(self.size)
    }

    fn poll(&self, _timeout: Duration) -> Result<bool, TuiError> {
        Ok(self.poll_results.borrow_mut().pop_front().unwrap_or(false))
    }

    fn read_event(&self) -> Result<CrosstermEvent, TuiError> {
        self.events
            .borrow_mut()
            .pop_front()
            .ok_or_else(|| TuiError::Io(io::Error::new(io::ErrorKind::WouldBlock, "no events")))
    }

    fn write_flush(
        &mut self,
        buffer: &mut CellBuffer,
        renderer: &mut DiffRenderer,
    ) -> Result<(), TuiError> {
        renderer.flush(buffer, &mut self.writer)?;
        self.writer.flush()?;
        Ok(())
    }

    fn enable_mouse_capture(&mut self) -> Result<(), TuiError> {
        self.mouse_captured = true;
        execute!(self.writer, crossterm::event::EnableMouseCapture)?;
        Ok(())
    }

    fn disable_mouse_capture(&mut self) -> Result<(), TuiError> {
        self.mouse_captured = false;
        let _ = execute!(self.writer, crossterm::event::DisableMouseCapture);
        Ok(())
    }
}

/// Generic terminal implementation using a backend.
pub struct GenericTerminal<B: TerminalBackend> {
    backend: B,
}

impl<B: TerminalBackend> GenericTerminal<B> {
    pub fn new(backend: B) -> Self {
        Self { backend }
    }
}

impl<B: TerminalBackend> Terminal for GenericTerminal<B> {
    fn enter(&mut self) -> Result<(), TuiError> {
        self.backend.enable_raw_mode()?;
        self.backend.enter_alternate_screen()?;
        self.backend.hide_cursor()?;
        Ok(())
    }

    fn leave(&mut self) -> Result<(), TuiError> {
        self.backend.show_cursor()?;
        self.backend.leave_alternate_screen()?;
        self.backend.disable_raw_mode()?;
        Ok(())
    }

    fn size(&self) -> Result<(u16, u16), TuiError> {
        self.backend.size()
    }

    fn poll(&self, timeout: Duration) -> Result<bool, TuiError> {
        self.backend.poll(timeout)
    }

    fn read_event(&self) -> Result<CrosstermEvent, TuiError> {
        self.backend.read_event()
    }

    fn flush(
        &mut self,
        buffer: &mut CellBuffer,
        renderer: &mut DiffRenderer,
    ) -> Result<(), TuiError> {
        self.backend.write_flush(buffer, renderer)
    }

    fn enable_mouse(&mut self) -> Result<(), TuiError> {
        self.backend.enable_mouse_capture()
    }

    fn disable_mouse(&mut self) -> Result<(), TuiError> {
        self.backend.disable_mouse_capture()
    }
}

/// Convenience alias for crossterm-backed terminal.
pub type CrosstermTerminal = GenericTerminal<CrosstermBackend>;

/// Configuration for the TUI application.
#[derive(Debug, Clone)]
pub struct TuiConfig {
    /// Tick rate in milliseconds for input polling.
    pub tick_rate_ms: u64,
    /// Enable mouse support.
    pub enable_mouse: bool,
    /// Color mode (auto-detected if not specified).
    pub color_mode: Option<ColorMode>,
    /// Skip Brick verification (DANGEROUS - for debugging only).
    pub skip_verification: bool,
    /// Target frame rate (used for budget calculation).
    pub target_fps: u32,
}

impl Default for TuiConfig {
    fn default() -> Self {
        Self {
            tick_rate_ms: 250,
            enable_mouse: false,
            color_mode: None,
            target_fps: 60,
            skip_verification: false,
        }
    }
}

impl TuiConfig {
    /// Create a high-performance config (60fps, fast tick).
    #[must_use]
    pub fn high_performance() -> Self {
        Self {
            tick_rate_ms: 16,
            target_fps: 60,
            ..Default::default()
        }
    }

    /// Create a power-saving config (30fps, slow tick).
    #[must_use]
    pub fn power_saving() -> Self {
        Self {
            tick_rate_ms: 100,
            target_fps: 30,
            ..Default::default()
        }
    }
}

/// Frame timing metrics.
#[derive(Debug, Clone, Default)]
pub struct FrameMetrics {
    /// Time spent in verification phase.
    pub verify_time: Duration,
    /// Time spent in measure phase.
    pub measure_time: Duration,
    /// Time spent in layout phase.
    pub layout_time: Duration,
    /// Time spent in paint phase.
    pub paint_time: Duration,
    /// Total frame time.
    pub total_time: Duration,
    /// Frame number.
    pub frame_count: u64,
}

/// Main TUI application runner.
pub struct TuiApp<W: Widget> {
    root: W,
    config: TuiConfig,
    input_handler: InputHandler,
    metrics: FrameMetrics,
    should_quit: bool,
    color_mode: ColorMode,
}

/// Internal app runner that accepts a Terminal implementation.
struct AppRunner<'a, W: Widget, T: Terminal> {
    app: &'a mut TuiApp<W>,
    terminal: T,
    buffer: CellBuffer,
    renderer: DiffRenderer,
}

impl<W: Widget, T: Terminal> AppRunner<'_, W, T> {
    fn run_loop(&mut self) -> Result<(), TuiError> {
        let tick_duration = Duration::from_millis(self.app.config.tick_rate_ms);

        loop {
            let frame_start = Instant::now();

            // Check for terminal resize
            let (width, height) = self.terminal.size()?;
            if width != self.buffer.width() || height != self.buffer.height() {
                self.buffer.resize(width, height);
                self.renderer.reset();
            }

            // Phase 1: Verify (Jidoka gate)
            let verify_start = Instant::now();
            if !self.app.config.skip_verification {
                let verification = self.app.root.verify();
                if !verification.is_valid() {
                    return Err(TuiError::VerificationFailed(VerificationError::from(
                        verification,
                    )));
                }
            }
            self.app.metrics.verify_time = verify_start.elapsed();

            // Phase 2: Render frame
            self.app.render_frame(&mut self.buffer);

            // Phase 3: Flush to terminal
            self.terminal.flush(&mut self.buffer, &mut self.renderer)?;

            self.app.metrics.total_time = frame_start.elapsed();
            self.app.metrics.frame_count += 1;

            // Phase 4: Handle input
            if self.terminal.poll(tick_duration)? {
                if let CrosstermEvent::Key(key) = self.terminal.read_event()? {
                    if key.code == KeyCode::Char('q')
                        || key.code == KeyCode::Char('c')
                            && key
                                .modifiers
                                .contains(crossterm::event::KeyModifiers::CONTROL)
                    {
                        self.app.should_quit = true;
                    }

                    if let Some(event) = self.app.input_handler.convert(CrosstermEvent::Key(key)) {
                        let _ = self.app.root.event(&event);
                    }
                }
            }

            if self.app.should_quit {
                break;
            }
        }

        Ok(())
    }
}

impl<W: Widget> TuiApp<W> {
    /// Create a new TUI application with the given root widget.
    pub fn new(root: W) -> Result<Self, TuiError> {
        // Jidoka: reject Bricks with no assertions
        if root.assertions().is_empty() {
            return Err(TuiError::InvalidBrick(
                "Root widget has no assertions - every Brick must have at least one falsifiable assertion".to_string(),
            ));
        }

        Ok(Self {
            root,
            config: TuiConfig::default(),
            input_handler: InputHandler::new(),
            metrics: FrameMetrics::default(),
            should_quit: false,
            color_mode: ColorMode::detect(),
        })
    }

    /// Set the configuration.
    #[must_use]
    pub fn with_config(mut self, config: TuiConfig) -> Self {
        if let Some(mode) = config.color_mode {
            self.color_mode = mode;
        }
        self.config = config;
        self
    }

    /// Set the input handler.
    #[must_use]
    pub fn with_input_handler(mut self, handler: InputHandler) -> Self {
        self.input_handler = handler;
        self
    }

    /// Get a reference to the root widget.
    #[must_use]
    pub fn root(&self) -> &W {
        &self.root
    }

    /// Get a mutable reference to the root widget.
    pub fn root_mut(&mut self) -> &mut W {
        &mut self.root
    }

    /// Get the current frame metrics.
    #[must_use]
    pub fn metrics(&self) -> &FrameMetrics {
        &self.metrics
    }

    /// Request the application to quit.
    pub fn quit(&mut self) {
        self.should_quit = true;
    }

    /// Run the application (blocking).
    pub fn run(&mut self) -> Result<(), TuiError> {
        let backend = CrosstermBackend::new();
        let terminal = GenericTerminal::new(backend);
        self.run_with_terminal(terminal)
    }

    /// Run the application with a custom terminal implementation.
    /// This is the testable entry point.
    pub fn run_with_terminal<T: Terminal>(&mut self, mut terminal: T) -> Result<(), TuiError> {
        terminal.enter()?;

        if self.config.enable_mouse {
            terminal.enable_mouse()?;
        }

        // Get initial terminal size
        let (width, height) = terminal.size()?;
        let buffer = CellBuffer::new(width, height);
        let renderer = DiffRenderer::with_color_mode(self.color_mode);

        let mut runner = AppRunner {
            app: self,
            terminal,
            buffer,
            renderer,
        };

        let result = runner.run_loop();

        if runner.app.config.enable_mouse {
            runner.terminal.disable_mouse()?;
        }
        runner.terminal.leave()?;

        result
    }

    fn render_frame(&mut self, buffer: &mut CellBuffer) {
        let width = buffer.width();
        let height = buffer.height();

        // Phase 2a: Measure
        let measure_start = Instant::now();
        let constraints = Constraints::new(0.0, f32::from(width), 0.0, f32::from(height));
        let _size = self.root.measure(constraints);
        self.metrics.measure_time = measure_start.elapsed();

        // Phase 2b: Layout
        let layout_start = Instant::now();
        let bounds = Rect::new(0.0, 0.0, f32::from(width), f32::from(height));
        let _ = self.root.layout(bounds);
        self.metrics.layout_time = layout_start.elapsed();

        // Phase 2c: Paint
        let paint_start = Instant::now();
        {
            let mut canvas = DirectTerminalCanvas::new(buffer);
            self.root.paint(&mut canvas);
        }
        self.metrics.paint_time = paint_start.elapsed();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use presentar_core::{
        Brick, BrickAssertion, BrickBudget, BrickVerification, Canvas, Color, Event, LayoutResult,
        Size, TypeId,
    };
    use std::any::Any;
    use std::time::Duration;

    struct TestWidget {
        assertions: Vec<BrickAssertion>,
    }

    impl TestWidget {
        fn new() -> Self {
            Self {
                assertions: vec![BrickAssertion::max_latency_ms(16)],
            }
        }

        fn without_assertions() -> Self {
            Self { assertions: vec![] }
        }
    }

    impl Brick for TestWidget {
        fn brick_name(&self) -> &'static str {
            "test_widget"
        }

        fn assertions(&self) -> &[BrickAssertion] {
            &self.assertions
        }

        fn budget(&self) -> BrickBudget {
            BrickBudget::default()
        }

        fn verify(&self) -> BrickVerification {
            BrickVerification {
                passed: self.assertions.clone(),
                failed: vec![],
                verification_time: Duration::from_micros(10),
            }
        }

        fn to_html(&self) -> String {
            String::new()
        }

        fn to_css(&self) -> String {
            String::new()
        }
    }

    impl Widget for TestWidget {
        fn type_id(&self) -> TypeId {
            TypeId::of::<Self>()
        }

        fn measure(&self, constraints: Constraints) -> Size {
            constraints.constrain(Size::new(10.0, 5.0))
        }

        fn layout(&mut self, bounds: Rect) -> LayoutResult {
            LayoutResult {
                size: Size::new(bounds.width, bounds.height),
            }
        }

        fn paint(&self, canvas: &mut dyn Canvas) {
            canvas.fill_rect(Rect::new(0.0, 0.0, 10.0, 5.0), Color::BLUE);
        }

        fn event(&mut self, _event: &Event) -> Option<Box<dyn Any + Send>> {
            None
        }

        fn children(&self) -> &[Box<dyn Widget>] {
            &[]
        }

        fn children_mut(&mut self) -> &mut [Box<dyn Widget>] {
            &mut []
        }
    }

    #[test]
    fn test_tui_app_creation() {
        let widget = TestWidget::new();
        let app = TuiApp::new(widget);
        assert!(app.is_ok());
    }

    #[test]
    fn test_tui_app_rejects_empty_assertions() {
        let widget = TestWidget::without_assertions();
        let app = TuiApp::new(widget);
        assert!(app.is_err());
        let err = app.err().expect("expected error");
        assert!(matches!(err, TuiError::InvalidBrick(_)));
    }

    #[test]
    fn test_config_default() {
        let config = TuiConfig::default();
        assert_eq!(config.tick_rate_ms, 250);
        assert_eq!(config.target_fps, 60);
        assert!(!config.enable_mouse);
        assert!(!config.skip_verification);
        assert!(config.color_mode.is_none());
    }

    #[test]
    fn test_config_high_performance() {
        let config = TuiConfig::high_performance();
        assert_eq!(config.tick_rate_ms, 16);
        assert_eq!(config.target_fps, 60);
    }

    #[test]
    fn test_config_power_saving() {
        let config = TuiConfig::power_saving();
        assert_eq!(config.tick_rate_ms, 100);
        assert_eq!(config.target_fps, 30);
    }

    #[test]
    fn test_tui_app_with_config() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let config = TuiConfig {
            tick_rate_ms: 50,
            enable_mouse: true,
            color_mode: Some(ColorMode::Color256),
            skip_verification: false,
            target_fps: 30,
        };

        app = app.with_config(config);
        assert!(app.metrics().frame_count == 0);
    }

    #[test]
    fn test_tui_app_with_input_handler() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let mut handler = InputHandler::new();
        handler.add_binding(crate::input::KeyBinding::simple(
            crossterm::event::KeyCode::Char('q'),
            "quit",
        ));

        app = app.with_input_handler(handler);
        assert!(app.root().assertions().len() == 1);
    }

    #[test]
    fn test_tui_app_root_accessors() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        assert_eq!(app.root().brick_name(), "test_widget");
        assert_eq!(app.root_mut().brick_name(), "test_widget");
    }

    #[test]
    fn test_tui_app_metrics() {
        let widget = TestWidget::new();
        let app = TuiApp::new(widget).unwrap();

        let metrics = app.metrics();
        assert_eq!(metrics.frame_count, 0);
        assert_eq!(metrics.total_time, Duration::ZERO);
    }

    #[test]
    fn test_tui_app_quit() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        assert!(!app.should_quit);
        app.quit();
        assert!(app.should_quit);
    }

    #[test]
    fn test_frame_metrics_default() {
        let metrics = FrameMetrics::default();
        assert_eq!(metrics.frame_count, 0);
        assert_eq!(metrics.verify_time, Duration::ZERO);
        assert_eq!(metrics.measure_time, Duration::ZERO);
        assert_eq!(metrics.layout_time, Duration::ZERO);
        assert_eq!(metrics.paint_time, Duration::ZERO);
        assert_eq!(metrics.total_time, Duration::ZERO);
    }

    #[test]
    fn test_config_with_color_mode_override() {
        let widget = TestWidget::new();
        let app = TuiApp::new(widget).unwrap();

        let config = TuiConfig {
            color_mode: Some(ColorMode::Mono),
            ..Default::default()
        };

        let app = app.with_config(config);
        assert_eq!(app.color_mode, ColorMode::Mono);
    }

    #[test]
    fn test_config_without_color_mode() {
        let widget = TestWidget::new();
        let app = TuiApp::new(widget).unwrap();
        let original_mode = app.color_mode;

        let config = TuiConfig {
            color_mode: None,
            ..Default::default()
        };

        let app = app.with_config(config);
        assert_eq!(app.color_mode, original_mode);
    }

    #[test]
    fn test_render_frame() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();
        let mut buffer = CellBuffer::new(80, 24);

        // Render a frame and verify metrics are updated
        app.render_frame(&mut buffer);

        assert!(
            app.metrics.measure_time > Duration::ZERO || app.metrics.measure_time == Duration::ZERO
        );
        assert!(app.metrics.layout_time >= Duration::ZERO);
        assert!(app.metrics.paint_time >= Duration::ZERO);
    }

    #[test]
    fn test_render_frame_updates_metrics() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();
        let mut buffer = CellBuffer::new(40, 10);

        // Render multiple frames
        for _ in 0..3 {
            app.render_frame(&mut buffer);
        }

        // Metrics should be set (even if durations are very small)
        let metrics = app.metrics();
        assert_eq!(metrics.frame_count, 0); // frame_count is only updated in run_loop
    }

    #[test]
    fn test_render_frame_with_different_buffer_sizes() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        // Small buffer
        let mut small_buffer = CellBuffer::new(10, 5);
        app.render_frame(&mut small_buffer);

        // Large buffer
        let mut large_buffer = CellBuffer::new(200, 50);
        app.render_frame(&mut large_buffer);

        // Should not panic with any buffer size
    }

    #[test]
    fn test_frame_metrics_clone() {
        let metrics = FrameMetrics {
            verify_time: Duration::from_millis(1),
            measure_time: Duration::from_millis(2),
            layout_time: Duration::from_millis(3),
            paint_time: Duration::from_millis(4),
            total_time: Duration::from_millis(10),
            frame_count: 100,
        };

        let cloned = metrics.clone();
        assert_eq!(cloned.frame_count, 100);
        assert_eq!(cloned.verify_time, Duration::from_millis(1));
    }

    #[test]
    fn test_frame_metrics_debug() {
        let metrics = FrameMetrics::default();
        let debug_str = format!("{:?}", metrics);
        assert!(debug_str.contains("FrameMetrics"));
        assert!(debug_str.contains("frame_count"));
    }

    #[test]
    fn test_tui_config_clone() {
        let config = TuiConfig::high_performance();
        let cloned = config.clone();
        assert_eq!(cloned.tick_rate_ms, 16);
        assert_eq!(cloned.target_fps, 60);
    }

    #[test]
    fn test_tui_config_debug() {
        let config = TuiConfig::default();
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("TuiConfig"));
        assert!(debug_str.contains("tick_rate_ms"));
    }

    // Additional tests for improved coverage

    struct FailingWidget;

    impl Brick for FailingWidget {
        fn brick_name(&self) -> &'static str {
            "failing_widget"
        }

        fn assertions(&self) -> &[BrickAssertion] {
            static ASSERTIONS: &[BrickAssertion] = &[BrickAssertion::max_latency_ms(16)];
            ASSERTIONS
        }

        fn budget(&self) -> BrickBudget {
            BrickBudget::default()
        }

        fn verify(&self) -> BrickVerification {
            // This widget always fails verification
            BrickVerification {
                passed: vec![],
                failed: vec![(
                    BrickAssertion::max_latency_ms(16),
                    "Intentional failure".to_string(),
                )],
                verification_time: Duration::from_micros(10),
            }
        }

        fn to_html(&self) -> String {
            String::new()
        }

        fn to_css(&self) -> String {
            String::new()
        }
    }

    impl Widget for FailingWidget {
        fn type_id(&self) -> TypeId {
            TypeId::of::<Self>()
        }

        fn measure(&self, constraints: Constraints) -> Size {
            constraints.constrain(Size::new(10.0, 5.0))
        }

        fn layout(&mut self, bounds: Rect) -> LayoutResult {
            LayoutResult {
                size: Size::new(bounds.width, bounds.height),
            }
        }

        fn paint(&self, _canvas: &mut dyn Canvas) {}

        fn event(&mut self, _event: &Event) -> Option<Box<dyn Any + Send>> {
            None
        }

        fn children(&self) -> &[Box<dyn Widget>] {
            &[]
        }

        fn children_mut(&mut self) -> &mut [Box<dyn Widget>] {
            &mut []
        }
    }

    #[test]
    fn test_tui_app_with_failing_widget() {
        let widget = FailingWidget;
        let app = TuiApp::new(widget);
        // Should be Ok since we only check assertions on creation, not verify()
        assert!(app.is_ok());
    }

    #[test]
    fn test_tui_config_all_fields() {
        let config = TuiConfig {
            tick_rate_ms: 100,
            enable_mouse: true,
            color_mode: Some(ColorMode::Color16),
            skip_verification: true,
            target_fps: 30,
        };

        assert_eq!(config.tick_rate_ms, 100);
        assert!(config.enable_mouse);
        assert_eq!(config.color_mode, Some(ColorMode::Color16));
        assert!(config.skip_verification);
        assert_eq!(config.target_fps, 30);
    }

    #[test]
    fn test_frame_metrics_all_fields() {
        let metrics = FrameMetrics {
            verify_time: Duration::from_millis(1),
            measure_time: Duration::from_millis(2),
            layout_time: Duration::from_millis(3),
            paint_time: Duration::from_millis(4),
            total_time: Duration::from_millis(10),
            frame_count: 42,
        };

        assert_eq!(metrics.verify_time, Duration::from_millis(1));
        assert_eq!(metrics.measure_time, Duration::from_millis(2));
        assert_eq!(metrics.layout_time, Duration::from_millis(3));
        assert_eq!(metrics.paint_time, Duration::from_millis(4));
        assert_eq!(metrics.total_time, Duration::from_millis(10));
        assert_eq!(metrics.frame_count, 42);
    }

    #[test]
    fn test_tui_app_skip_verification_config() {
        let widget = TestWidget::new();
        let app = TuiApp::new(widget).unwrap();

        let config = TuiConfig {
            skip_verification: true,
            ..Default::default()
        };

        let app = app.with_config(config);
        assert!(app.config.skip_verification);
    }

    #[test]
    fn test_tui_app_enable_mouse_config() {
        let widget = TestWidget::new();
        let app = TuiApp::new(widget).unwrap();

        let config = TuiConfig {
            enable_mouse: true,
            ..Default::default()
        };

        let app = app.with_config(config);
        assert!(app.config.enable_mouse);
    }

    #[test]
    fn test_render_frame_zero_size_buffer() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        // Test with minimal buffer size
        let mut buffer = CellBuffer::new(1, 1);
        app.render_frame(&mut buffer);
        // Should not panic
    }

    #[test]
    fn test_render_frame_metrics_populated() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();
        let mut buffer = CellBuffer::new(80, 24);

        app.render_frame(&mut buffer);

        // All timing metrics should be non-negative (possibly zero for fast operations)
        assert!(app.metrics.measure_time >= Duration::ZERO);
        assert!(app.metrics.layout_time >= Duration::ZERO);
        assert!(app.metrics.paint_time >= Duration::ZERO);
    }

    #[test]
    fn test_tui_config_color_modes() {
        // Test all color modes
        for mode in [
            ColorMode::TrueColor,
            ColorMode::Color256,
            ColorMode::Color16,
            ColorMode::Mono,
        ] {
            let widget = TestWidget::new();
            let app = TuiApp::new(widget).unwrap();

            let config = TuiConfig {
                color_mode: Some(mode),
                ..Default::default()
            };

            let app = app.with_config(config);
            assert_eq!(app.color_mode, mode);
        }
    }

    #[test]
    fn test_test_widget_brick_methods() {
        let widget = TestWidget::new();

        assert_eq!(widget.brick_name(), "test_widget");
        assert!(!widget.assertions().is_empty());
        assert!(widget.verify().is_valid());
        assert!(widget.to_html().is_empty());
        assert!(widget.to_css().is_empty());
    }

    #[test]
    fn test_test_widget_widget_methods() {
        let mut widget = TestWidget::new();

        // measure
        let size = widget.measure(Constraints::loose(Size::new(100.0, 100.0)));
        assert!(size.width > 0.0);
        assert!(size.height > 0.0);

        // layout
        let bounds = Rect::new(0.0, 0.0, 50.0, 25.0);
        let result = widget.layout(bounds);
        assert_eq!(result.size.width, 50.0);
        assert_eq!(result.size.height, 25.0);

        // event
        let event = Event::KeyDown {
            key: presentar_core::Key::Enter,
        };
        assert!(widget.event(&event).is_none());

        // children
        assert!(widget.children().is_empty());
        assert!(widget.children_mut().is_empty());
    }

    #[test]
    fn test_tui_app_multiple_render_frames() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();
        let mut buffer = CellBuffer::new(80, 24);

        // Render multiple frames to ensure stability
        for _ in 0..10 {
            app.render_frame(&mut buffer);
        }

        // Should complete without panic
    }

    // Mock terminal for testing run/run_loop

    use std::cell::RefCell;
    use std::collections::VecDeque;

    struct MockTerminal {
        size: (u16, u16),
        events: RefCell<VecDeque<CrosstermEvent>>,
        poll_results: RefCell<VecDeque<bool>>,
        entered: RefCell<bool>,
        left: RefCell<bool>,
        mouse_enabled: RefCell<bool>,
        flush_count: RefCell<u32>,
    }

    impl MockTerminal {
        fn new(width: u16, height: u16) -> Self {
            Self {
                size: (width, height),
                events: RefCell::new(VecDeque::new()),
                poll_results: RefCell::new(VecDeque::new()),
                entered: RefCell::new(false),
                left: RefCell::new(false),
                mouse_enabled: RefCell::new(false),
                flush_count: RefCell::new(0),
            }
        }

        fn with_events(mut self, events: Vec<CrosstermEvent>) -> Self {
            self.events = RefCell::new(events.into());
            self
        }

        fn with_polls(mut self, polls: Vec<bool>) -> Self {
            self.poll_results = RefCell::new(polls.into());
            self
        }
    }

    impl Terminal for MockTerminal {
        fn enter(&mut self) -> Result<(), TuiError> {
            *self.entered.borrow_mut() = true;
            Ok(())
        }

        fn leave(&mut self) -> Result<(), TuiError> {
            *self.left.borrow_mut() = true;
            Ok(())
        }

        fn size(&self) -> Result<(u16, u16), TuiError> {
            Ok(self.size)
        }

        fn poll(&self, _timeout: Duration) -> Result<bool, TuiError> {
            Ok(self.poll_results.borrow_mut().pop_front().unwrap_or(false))
        }

        fn read_event(&self) -> Result<CrosstermEvent, TuiError> {
            self.events
                .borrow_mut()
                .pop_front()
                .ok_or_else(|| TuiError::Io(io::Error::new(io::ErrorKind::Other, "no event")))
        }

        fn flush(
            &mut self,
            _buffer: &mut CellBuffer,
            _renderer: &mut DiffRenderer,
        ) -> Result<(), TuiError> {
            *self.flush_count.borrow_mut() += 1;
            Ok(())
        }

        fn enable_mouse(&mut self) -> Result<(), TuiError> {
            *self.mouse_enabled.borrow_mut() = true;
            Ok(())
        }

        fn disable_mouse(&mut self) -> Result<(), TuiError> {
            *self.mouse_enabled.borrow_mut() = false;
            Ok(())
        }
    }

    #[test]
    fn test_run_with_terminal_quit_on_q() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let terminal = MockTerminal::new(80, 24)
            .with_polls(vec![true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
        assert!(app.should_quit);
    }

    #[test]
    fn test_run_with_terminal_ctrl_c() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let terminal = MockTerminal::new(80, 24)
            .with_polls(vec![true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('c'),
                crossterm::event::KeyModifiers::CONTROL,
            ))]);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
        assert!(app.should_quit);
    }

    #[test]
    fn test_run_with_terminal_mouse_enabled() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();
        app.config.enable_mouse = true;

        let terminal = MockTerminal::new(80, 24)
            .with_polls(vec![true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_with_terminal_skip_verification() {
        let widget = FailingWidget;
        let mut app = TuiApp::new(widget).unwrap();
        app.config.skip_verification = true;

        let terminal = MockTerminal::new(80, 24)
            .with_polls(vec![true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);

        // Should succeed because verification is skipped
        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_with_terminal_verification_failure() {
        let widget = FailingWidget;
        let mut app = TuiApp::new(widget).unwrap();

        let terminal = MockTerminal::new(80, 24).with_polls(vec![false]);

        // Should fail verification
        let result = app.run_with_terminal(terminal);
        assert!(result.is_err());
        assert!(matches!(result, Err(TuiError::VerificationFailed(_))));
    }

    #[test]
    fn test_run_with_terminal_no_events() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();
        app.quit(); // Pre-set quit to exit immediately

        let terminal = MockTerminal::new(80, 24).with_polls(vec![false]);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_with_terminal_other_key() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let terminal = MockTerminal::new(80, 24)
            .with_polls(vec![true, true])
            .with_events(vec![
                CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                    KeyCode::Enter,
                    crossterm::event::KeyModifiers::NONE,
                )),
                CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                    KeyCode::Char('q'),
                    crossterm::event::KeyModifiers::NONE,
                )),
            ]);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_with_terminal_frame_count() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let terminal = MockTerminal::new(80, 24)
            .with_polls(vec![false, false, true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
        assert!(app.metrics.frame_count >= 1);
    }

    #[test]
    fn test_crossterm_backend_new() {
        let backend = CrosstermBackend::new();
        // Just verify it can be created
        let _ = backend;
    }

    #[test]
    fn test_crossterm_backend_default() {
        let backend = CrosstermBackend::default();
        let _ = backend;
    }

    // Mock backend for testing GenericTerminal
    struct MockBackend {
        size: (u16, u16),
        events: RefCell<VecDeque<CrosstermEvent>>,
        poll_results: RefCell<VecDeque<bool>>,
        raw_mode: RefCell<bool>,
        alternate_screen: RefCell<bool>,
        cursor_hidden: RefCell<bool>,
        mouse_captured: RefCell<bool>,
    }

    impl MockBackend {
        fn new(width: u16, height: u16) -> Self {
            Self {
                size: (width, height),
                events: RefCell::new(VecDeque::new()),
                poll_results: RefCell::new(VecDeque::new()),
                raw_mode: RefCell::new(false),
                alternate_screen: RefCell::new(false),
                cursor_hidden: RefCell::new(false),
                mouse_captured: RefCell::new(false),
            }
        }

        fn with_events(self, events: Vec<CrosstermEvent>) -> Self {
            *self.events.borrow_mut() = events.into();
            self
        }

        fn with_polls(self, polls: Vec<bool>) -> Self {
            *self.poll_results.borrow_mut() = polls.into();
            self
        }
    }

    impl TerminalBackend for MockBackend {
        fn enable_raw_mode(&mut self) -> Result<(), TuiError> {
            *self.raw_mode.borrow_mut() = true;
            Ok(())
        }
        fn disable_raw_mode(&mut self) -> Result<(), TuiError> {
            *self.raw_mode.borrow_mut() = false;
            Ok(())
        }
        fn enter_alternate_screen(&mut self) -> Result<(), TuiError> {
            *self.alternate_screen.borrow_mut() = true;
            Ok(())
        }
        fn leave_alternate_screen(&mut self) -> Result<(), TuiError> {
            *self.alternate_screen.borrow_mut() = false;
            Ok(())
        }
        fn hide_cursor(&mut self) -> Result<(), TuiError> {
            *self.cursor_hidden.borrow_mut() = true;
            Ok(())
        }
        fn show_cursor(&mut self) -> Result<(), TuiError> {
            *self.cursor_hidden.borrow_mut() = false;
            Ok(())
        }
        fn size(&self) -> Result<(u16, u16), TuiError> {
            Ok(self.size)
        }
        fn poll(&self, _timeout: Duration) -> Result<bool, TuiError> {
            Ok(self.poll_results.borrow_mut().pop_front().unwrap_or(false))
        }
        fn read_event(&self) -> Result<CrosstermEvent, TuiError> {
            self.events
                .borrow_mut()
                .pop_front()
                .ok_or_else(|| TuiError::Io(io::Error::new(io::ErrorKind::Other, "no event")))
        }
        fn write_flush(
            &mut self,
            _buffer: &mut CellBuffer,
            _renderer: &mut DiffRenderer,
        ) -> Result<(), TuiError> {
            Ok(())
        }
        fn enable_mouse_capture(&mut self) -> Result<(), TuiError> {
            *self.mouse_captured.borrow_mut() = true;
            Ok(())
        }
        fn disable_mouse_capture(&mut self) -> Result<(), TuiError> {
            *self.mouse_captured.borrow_mut() = false;
            Ok(())
        }
    }

    #[test]
    fn test_generic_terminal_enter_leave() {
        let backend = MockBackend::new(80, 24);
        let mut terminal = GenericTerminal::new(backend);

        terminal.enter().unwrap();
        assert!(*terminal.backend.raw_mode.borrow());
        assert!(*terminal.backend.alternate_screen.borrow());
        assert!(*terminal.backend.cursor_hidden.borrow());

        terminal.leave().unwrap();
        assert!(!*terminal.backend.raw_mode.borrow());
        assert!(!*terminal.backend.alternate_screen.borrow());
        assert!(!*terminal.backend.cursor_hidden.borrow());
    }

    #[test]
    fn test_generic_terminal_size() {
        let backend = MockBackend::new(100, 50);
        let terminal = GenericTerminal::new(backend);
        let (w, h) = terminal.size().unwrap();
        assert_eq!(w, 100);
        assert_eq!(h, 50);
    }

    #[test]
    fn test_generic_terminal_poll_read() {
        let backend = MockBackend::new(80, 24)
            .with_polls(vec![true, false])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Enter,
                crossterm::event::KeyModifiers::NONE,
            ))]);
        let terminal = GenericTerminal::new(backend);

        assert!(terminal.poll(Duration::from_millis(10)).unwrap());
        let event = terminal.read_event().unwrap();
        assert!(matches!(event, CrosstermEvent::Key(_)));

        assert!(!terminal.poll(Duration::from_millis(10)).unwrap());
    }

    #[test]
    fn test_generic_terminal_mouse() {
        let backend = MockBackend::new(80, 24);
        let mut terminal = GenericTerminal::new(backend);

        assert!(!*terminal.backend.mouse_captured.borrow());
        terminal.enable_mouse().unwrap();
        assert!(*terminal.backend.mouse_captured.borrow());
        terminal.disable_mouse().unwrap();
        assert!(!*terminal.backend.mouse_captured.borrow());
    }

    #[test]
    fn test_generic_terminal_flush() {
        let backend = MockBackend::new(80, 24);
        let mut terminal = GenericTerminal::new(backend);
        let mut buffer = CellBuffer::new(80, 24);
        let mut renderer = DiffRenderer::new();

        terminal.flush(&mut buffer, &mut renderer).unwrap();
    }

    #[test]
    fn test_run_with_generic_terminal() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let backend = MockBackend::new(80, 24)
            .with_polls(vec![true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);
        let terminal = GenericTerminal::new(backend);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
        assert!(app.should_quit);
    }

    #[test]
    fn test_mock_terminal_enter_leave() {
        let mut terminal = MockTerminal::new(80, 24);
        assert!(!*terminal.entered.borrow());
        terminal.enter().unwrap();
        assert!(*terminal.entered.borrow());

        assert!(!*terminal.left.borrow());
        terminal.leave().unwrap();
        assert!(*terminal.left.borrow());
    }

    #[test]
    fn test_mock_terminal_mouse() {
        let mut terminal = MockTerminal::new(80, 24);
        assert!(!*terminal.mouse_enabled.borrow());
        terminal.enable_mouse().unwrap();
        assert!(*terminal.mouse_enabled.borrow());
        terminal.disable_mouse().unwrap();
        assert!(!*terminal.mouse_enabled.borrow());
    }

    #[test]
    fn test_mock_terminal_size() {
        let terminal = MockTerminal::new(100, 50);
        let (w, h) = terminal.size().unwrap();
        assert_eq!(w, 100);
        assert_eq!(h, 50);
    }

    #[test]
    fn test_run_with_terminal_resize() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        // Create terminal that simulates a size change by having different initial size
        let terminal = MockTerminal::new(40, 12)
            .with_polls(vec![true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_with_terminal_mouse_event() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let terminal = MockTerminal::new(80, 24)
            .with_polls(vec![true, true])
            .with_events(vec![
                CrosstermEvent::Mouse(crossterm::event::MouseEvent {
                    kind: crossterm::event::MouseEventKind::Down(
                        crossterm::event::MouseButton::Left,
                    ),
                    column: 10,
                    row: 5,
                    modifiers: crossterm::event::KeyModifiers::NONE,
                }),
                CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                    KeyCode::Char('q'),
                    crossterm::event::KeyModifiers::NONE,
                )),
            ]);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_with_terminal_non_key_event_then_quit() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let terminal = MockTerminal::new(80, 24)
            .with_polls(vec![true, true])
            .with_events(vec![
                CrosstermEvent::Resize(100, 50),
                CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                    KeyCode::Char('q'),
                    crossterm::event::KeyModifiers::NONE,
                )),
            ]);

        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
    }

    #[test]
    fn test_app_runner_metrics_update() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let terminal = MockTerminal::new(80, 24)
            .with_polls(vec![false, true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);

        app.run_with_terminal(terminal).unwrap();

        // Metrics should be populated
        assert!(app.metrics.frame_count >= 1);
    }

    // =====================================================
    // TestableBackend tests - TTY mocking with escape sequences
    // =====================================================

    #[test]
    fn test_testable_backend_new() {
        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 80, 24);
        assert_eq!(backend.size, (80, 24));
        assert!(!backend.raw_mode);
        assert!(!backend.alternate_screen);
        assert!(!backend.cursor_hidden);
        assert!(!backend.mouse_captured);
    }

    #[test]
    fn test_testable_backend_with_events() {
        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 80, 24).with_events(vec![CrosstermEvent::Key(
            crossterm::event::KeyEvent::new(
                KeyCode::Char('a'),
                crossterm::event::KeyModifiers::NONE,
            ),
        )]);
        assert_eq!(backend.events.borrow().len(), 1);
    }

    #[test]
    fn test_testable_backend_with_polls() {
        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 80, 24).with_polls(vec![true, false, true]);
        assert_eq!(backend.poll_results.borrow().len(), 3);
    }

    #[test]
    fn test_testable_backend_enable_raw_mode() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);
        assert!(!backend.is_raw_mode());
        backend.enable_raw_mode().unwrap();
        assert!(backend.is_raw_mode());
    }

    #[test]
    fn test_testable_backend_disable_raw_mode() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);
        backend.enable_raw_mode().unwrap();
        assert!(backend.is_raw_mode());
        backend.disable_raw_mode().unwrap();
        assert!(!backend.is_raw_mode());
    }

    #[test]
    fn test_testable_backend_enter_alternate_screen() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);
        assert!(!backend.is_alternate_screen());
        backend.enter_alternate_screen().unwrap();
        assert!(backend.is_alternate_screen());
        // Verify escape sequence was written
        let output = backend.into_writer();
        assert!(!output.is_empty());
        // EnterAlternateScreen is \x1b[?1049h
        assert!(output.starts_with(b"\x1b["));
    }

    #[test]
    fn test_testable_backend_leave_alternate_screen() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);
        backend.enter_alternate_screen().unwrap();
        backend.leave_alternate_screen().unwrap();
        assert!(!backend.is_alternate_screen());
    }

    #[test]
    fn test_testable_backend_hide_cursor() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);
        assert!(!backend.is_cursor_hidden());
        backend.hide_cursor().unwrap();
        assert!(backend.is_cursor_hidden());
        // Verify escape sequence was written
        let output = backend.into_writer();
        assert!(!output.is_empty());
    }

    #[test]
    fn test_testable_backend_show_cursor() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);
        backend.hide_cursor().unwrap();
        backend.show_cursor().unwrap();
        assert!(!backend.is_cursor_hidden());
    }

    #[test]
    fn test_testable_backend_size() {
        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 120, 40);
        assert_eq!(backend.size().unwrap(), (120, 40));
    }

    #[test]
    fn test_testable_backend_poll() {
        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 80, 24).with_polls(vec![true, false]);
        assert!(backend.poll(Duration::from_millis(100)).unwrap());
        assert!(!backend.poll(Duration::from_millis(100)).unwrap());
        // Default when empty
        assert!(!backend.poll(Duration::from_millis(100)).unwrap());
    }

    #[test]
    fn test_testable_backend_read_event() {
        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 80, 24).with_events(vec![CrosstermEvent::Key(
            crossterm::event::KeyEvent::new(
                KeyCode::Char('x'),
                crossterm::event::KeyModifiers::NONE,
            ),
        )]);
        let event = backend.read_event().unwrap();
        assert!(matches!(event, CrosstermEvent::Key(_)));
    }

    #[test]
    fn test_testable_backend_read_event_empty() {
        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 80, 24);
        let result = backend.read_event();
        assert!(result.is_err());
    }

    #[test]
    fn test_testable_backend_enable_mouse_capture() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);
        assert!(!backend.is_mouse_captured());
        backend.enable_mouse_capture().unwrap();
        assert!(backend.is_mouse_captured());
        // Verify escape sequence was written
        let output = backend.into_writer();
        assert!(!output.is_empty());
    }

    #[test]
    fn test_testable_backend_disable_mouse_capture() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);
        backend.enable_mouse_capture().unwrap();
        backend.disable_mouse_capture().unwrap();
        assert!(!backend.is_mouse_captured());
    }

    #[test]
    fn test_testable_backend_write_flush() {
        use crate::direct::Cell;

        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);
        let mut buffer = CellBuffer::new(80, 24);
        let mut renderer = DiffRenderer::new();

        // Write something to the buffer using the Cell API
        let mut cell_a = Cell::default();
        cell_a.update(
            "A",
            presentar_core::Color::WHITE,
            presentar_core::Color::BLACK,
            crate::direct::Modifiers::empty(),
        );
        buffer.set(0, 0, cell_a);

        let mut cell_b = Cell::default();
        cell_b.update(
            "B",
            presentar_core::Color::WHITE,
            presentar_core::Color::BLACK,
            crate::direct::Modifiers::empty(),
        );
        buffer.set(1, 0, cell_b);

        buffer.mark_all_dirty();
        backend.write_flush(&mut buffer, &mut renderer).unwrap();

        // Verify output was written
        let output = backend.into_writer();
        assert!(!output.is_empty());
    }

    #[test]
    fn test_testable_backend_full_lifecycle() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);

        // Enter
        backend.enable_raw_mode().unwrap();
        backend.enter_alternate_screen().unwrap();
        backend.hide_cursor().unwrap();

        assert!(backend.is_raw_mode());
        assert!(backend.is_alternate_screen());
        assert!(backend.is_cursor_hidden());

        // Leave
        backend.show_cursor().unwrap();
        backend.leave_alternate_screen().unwrap();
        backend.disable_raw_mode().unwrap();

        assert!(!backend.is_raw_mode());
        assert!(!backend.is_alternate_screen());
        assert!(!backend.is_cursor_hidden());
    }

    #[test]
    fn test_testable_backend_escape_sequences() {
        let buf: Vec<u8> = Vec::new();
        let mut backend = TestableBackend::new(buf, 80, 24);

        backend.enter_alternate_screen().unwrap();
        backend.hide_cursor().unwrap();
        backend.enable_mouse_capture().unwrap();

        let output = backend.into_writer();
        let output_str = String::from_utf8_lossy(&output);

        // Check for ANSI escape sequences (CSI = \x1b[)
        assert!(
            output_str.contains("\x1b["),
            "Expected ANSI escape sequences"
        );
    }

    #[test]
    fn test_generic_terminal_with_testable_backend() {
        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 80, 24)
            .with_polls(vec![true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);

        let mut terminal = GenericTerminal::new(backend);

        terminal.enter().unwrap();
        assert_eq!(terminal.size().unwrap(), (80, 24));

        // Poll and read
        assert!(terminal.poll(Duration::from_millis(10)).unwrap());
        let event = terminal.read_event().unwrap();
        assert!(matches!(event, CrosstermEvent::Key(_)));

        terminal.leave().unwrap();
    }

    #[test]
    fn test_testable_backend_with_tui_app() {
        let widget = TestWidget::new();
        let mut app = TuiApp::new(widget).unwrap();

        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 80, 24)
            .with_polls(vec![true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);

        let terminal = GenericTerminal::new(backend);
        let result = app.run_with_terminal(terminal);
        assert!(result.is_ok());
    }

    #[test]
    fn test_testable_backend_captures_render_output() {
        let widget = TestWidget::new();
        let _app = TuiApp::new(widget).unwrap();

        let buf: Vec<u8> = Vec::new();
        let backend = TestableBackend::new(buf, 40, 10)
            .with_polls(vec![true])
            .with_events(vec![CrosstermEvent::Key(crossterm::event::KeyEvent::new(
                KeyCode::Char('q'),
                crossterm::event::KeyModifiers::NONE,
            ))]);

        let mut terminal = GenericTerminal::new(backend);
        terminal.enter().unwrap();

        // Get terminal size
        let (width, height) = terminal.size().unwrap();
        assert_eq!((width, height), (40, 10));

        terminal.leave().unwrap();
    }
}