deckhand 0.1.0

Present markdown slide decks as a TUI — live embedded terminals, a 2-D slide grid, presenter notes, and a wasm presenter for the browser
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
//! The platform-independent presenter.
//!
//! `Presenter` owns everything every presentation context shares:
//! navigation across the 2-D grid, slide layout, the overview with jump
//! codes, theming, terminal focus/selection, and drawing — all into a
//! ratatui `Buffer`, so it runs anywhere.
//!
//! What it *can't* know is how live terminals work in a given context.
//! That's a `TerminalProvider`: native supplies real PTYs, the wasm build
//! supplies placeholders, and other embeddings (ssh, containers,
//! recordings…) can supply their own. The presenter draws all the chrome
//! — borders, pane numbers, focus hints, scrollbars — and delegates only
//! the inside of the box.
//!
//! Events arrive as platform-neutral [`KeyPress`] / [`Mouse`] values;
//! each front end translates its own event source into them.

use std::collections::HashMap;

use anyhow::{Context, Result};
use ratatui::buffer::Buffer;
use ratatui::layout::{Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{
    Block, Borders, Clear, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState,
    StatefulWidget, Widget,
};

use crate::deck::{Deck, Segment, Slide, TermBlock};
use crate::hints::{JUMP_KEYS, jump_codes};
use crate::markdown;
use crate::theme::{HAlign, Theme, ThemeConfig, VAlign};

// ----------------------------------------------------------------- events

/// A platform-independent key, as translated by each front end from its
/// own event source (crossterm, DOM `KeyboardEvent`, …).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Key {
    /// A printable character (already case/shift-resolved).
    Char(char),
    /// Return / enter.
    Enter,
    /// Escape.
    Esc,
    /// Backspace.
    Backspace,
    /// Tab.
    Tab,
    /// Shift-tab.
    BackTab,
    /// Arrow up.
    Up,
    /// Arrow down.
    Down,
    /// Arrow left.
    Left,
    /// Arrow right.
    Right,
    /// Home.
    Home,
    /// End.
    End,
    /// Page up.
    PageUp,
    /// Page down.
    PageDown,
    /// Insert.
    Insert,
    /// Forward delete.
    Delete,
    /// A function key (`F(1)` ..= `F(12)` are encodable).
    F(u8),
}

/// A [`Key`] plus its modifier state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyPress {
    /// The key itself.
    pub key: Key,
    /// Control held.
    pub ctrl: bool,
    /// Alt/option held.
    pub alt: bool,
    /// Shift held.
    pub shift: bool,
}

impl KeyPress {
    /// A press of `key` with no modifiers.
    pub fn plain(key: Key) -> Self {
        KeyPress {
            key,
            ctrl: false,
            alt: false,
            shift: false,
        }
    }
}

/// What a mouse event did, in presenter terms.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MouseAction {
    /// Left button pressed.
    LeftClick,
    /// Wheel scrolled up (away from the user).
    ScrollUp,
    /// Wheel scrolled down (toward the user).
    ScrollDown,
}

/// A mouse event in screen cell coordinates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Mouse {
    /// Column of the affected cell.
    pub x: u16,
    /// Row of the affected cell.
    pub y: u16,
    /// What happened.
    pub action: MouseAction,
}

/// Encode a key press as the bytes a terminal would send — used to feed
/// input to a focused terminal, whatever the provider behind it is.
pub fn encode_key(key: &KeyPress) -> Option<Vec<u8>> {
    let mut out: Vec<u8> = Vec::new();
    if key.alt {
        out.push(0x1b);
    }
    match key.key {
        Key::Char(c) => {
            if key.ctrl {
                let b = match c {
                    'a'..='z' => c as u8 - b'a' + 1,
                    'A'..='Z' => c.to_ascii_lowercase() as u8 - b'a' + 1,
                    '@' | ' ' => 0,
                    '[' => 27,
                    '\\' => 28,
                    ']' => 29,
                    '^' => 30,
                    '_' | '/' => 31,
                    _ => return None,
                };
                out.push(b);
            } else {
                let mut buf = [0u8; 4];
                out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
            }
        }
        Key::Enter => out.push(b'\r'),
        Key::Backspace => out.push(0x7f),
        Key::Tab => out.push(b'\t'),
        Key::BackTab => out.extend_from_slice(b"\x1b[Z"),
        Key::Esc => out.push(0x1b),
        Key::Up => out.extend_from_slice(b"\x1b[A"),
        Key::Down => out.extend_from_slice(b"\x1b[B"),
        Key::Right => out.extend_from_slice(b"\x1b[C"),
        Key::Left => out.extend_from_slice(b"\x1b[D"),
        Key::Home => out.extend_from_slice(b"\x1b[H"),
        Key::End => out.extend_from_slice(b"\x1b[F"),
        Key::PageUp => out.extend_from_slice(b"\x1b[5~"),
        Key::PageDown => out.extend_from_slice(b"\x1b[6~"),
        Key::Insert => out.extend_from_slice(b"\x1b[2~"),
        Key::Delete => out.extend_from_slice(b"\x1b[3~"),
        Key::F(n) => {
            let seq: &[u8] = match n {
                1 => b"\x1bOP",
                2 => b"\x1bOQ",
                3 => b"\x1bOR",
                4 => b"\x1bOS",
                5 => b"\x1b[15~",
                6 => b"\x1b[17~",
                7 => b"\x1b[18~",
                8 => b"\x1b[19~",
                9 => b"\x1b[20~",
                10 => b"\x1b[21~",
                11 => b"\x1b[23~",
                12 => b"\x1b[24~",
                _ => return None,
            };
            out.extend_from_slice(seq);
        }
    }
    Some(out)
}

// -------------------------------------------------------------- providers

/// What a terminal block is doing right now, per its provider.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TermState {
    /// The terminal is live and accepting input.
    Running {
        /// How far into history the view is (0 = live).
        scroll_offset: usize,
        /// Total history lines available.
        scroll_total: usize,
    },
    /// The process ended; `R` restarts it.
    Exited,
    /// The terminal couldn't start; the message is shown in the box.
    Failed(String),
    /// This context can't run terminals but is showing a capture baked
    /// in by `deckhand compile --snapshots`.
    Snapshot,
    /// The block hasn't been approved to run yet: its command is shown
    /// and the presenter confirms with `t`, then `y`.
    Disabled,
    /// This context can't run terminals (e.g. the browser).
    Unavailable,
}

/// Supplies the live, context-dependent innards of terminal blocks.
///
/// The presenter draws all chrome (borders, titles, pane numbering,
/// hints, scrollbars) and calls the provider for the inside of the box.
pub trait TerminalProvider {
    /// Called for each visible terminal every frame with its inner size;
    /// spawn or resize as needed.
    fn prepare(&mut self, block: &TermBlock, cols: u16, rows: u16);
    /// What this block is doing right now; drives border/hint chrome.
    fn state(&self, block: &TermBlock) -> TermState;
    /// Draw the terminal's contents into `inner`.
    fn draw(&mut self, block: &TermBlock, inner: Rect, buf: &mut Buffer);
    /// Bytes typed while this terminal is focused.
    fn input(&mut self, id: usize, bytes: &[u8]);
    /// Move the scrollback view; positive = further into history.
    fn scroll(&mut self, id: usize, delta: isize);
    /// Half-page scroll needs the viewport height; default derives it.
    fn scroll_page(&mut self, id: usize, up: bool, viewport_rows: u16) {
        let half = (viewport_rows / 2).max(1) as isize;
        self.scroll(id, if up { half } else { -half });
    }
    /// Kill and forget these terminals so they respawn (the `R` key).
    fn restart(&mut self, ids: &[usize]);
    /// The deck was replaced and its terminal blocks changed: drop all
    /// live terminal state so blocks start cleanly. Default: no-op.
    fn reset(&mut self) {}
    /// The presenter confirmed running this [`TermState::Disabled`]
    /// block (the in-deck `y` confirmation). Default: no-op.
    fn enable(&mut self, _id: usize) {}
    /// Stop this terminal and withdraw its approval — it returns to
    /// [`TermState::Disabled`] (the `s` key). Default: no-op.
    fn stop(&mut self, _id: usize) {}
    /// Whether terminals can be focused and typed into in this context.
    fn interactive(&self) -> bool {
        true
    }
}

// -------------------------------------------------------------- presenter

/// All terminal blocks in deck order; two decks with equal lists have
/// identical terminal ids, so live sessions can safely carry over.
fn term_blocks(deck: &Deck) -> Vec<&TermBlock> {
    deck.columns
        .iter()
        .flat_map(|c| &c.slides)
        .flat_map(|s| s.leaf_segments())
        .filter_map(|seg| match seg {
            Segment::Terminal(b) => Some(b),
            _ => None,
        })
        .collect()
}

/// Columns of blank space between row cells.
const ROW_GAP: u16 = 2;

/// First visible index for a one-axis viewport of `vis` slots over
/// `total` items: keeps `sel` one slot in from the trailing edge while
/// more items exist beyond it, so the neighbor you're heading toward
/// is always in view.
fn viewport_offset(sel: usize, total: usize, vis: usize) -> usize {
    if total <= vis {
        return 0;
    }
    (sel + 2).saturating_sub(vis).min(total - vis).min(sel)
}

/// If markdown source opens with a heading (blank lines aside), split
/// it off: (heading line, everything after). Feeds `pin_title`.
fn split_leading_heading(src: &str) -> Option<(String, String)> {
    let mut consumed = 0usize;
    for part in src.split_inclusive('\n') {
        let t = part.trim();
        consumed += part.len();
        if t.is_empty() {
            continue;
        }
        if t.starts_with('#') {
            return Some((t.to_string(), src[consumed..].to_string()));
        }
        return None;
    }
    None
}

/// One fixed-height piece of a row cell (or a full-width segment —
/// the same builder serves both).
enum CellItem {
    Text(Text<'static>),
    Term(TermBlock),
}

/// Render segments into fixed-height items at `w` columns. Inside
/// cells, fill terminals fall back to their fixed row count — "the
/// rest of the slide" isn't a height a side-by-side cell can claim.
fn build_cell_items(
    segments: &[Segment],
    w: u16,
    box_h: u16,
    theme: &Theme,
) -> Vec<(u16, CellItem)> {
    let mut items = Vec::new();
    for seg in segments {
        match seg {
            Segment::Markdown(src) => {
                let text = markdown::render(src, w, theme);
                let h = text.height() as u16;
                if h > 0 {
                    items.push((h, CellItem::Text(text)));
                }
            }
            Segment::Terminal(b) => items.push((b.rows + 2, CellItem::Term(b.clone()))),
            Segment::Qr(q) => {
                let text = qr_text(q, w, theme);
                items.push((text.height() as u16, CellItem::Text(text)));
            }
            Segment::Image(img) => {
                let text = match &img.data {
                    Some(data) => crate::ascii_image::render(data, w, box_h),
                    None => image_placeholder(img, theme),
                };
                items.push((text.height() as u16, CellItem::Text(text)));
            }
            // The parser keeps rows one level deep.
            Segment::Row(_) => {}
        }
    }
    items
}

/// A QR block as centered lines, colored by the theme's
/// `qr_dark`/`qr_light` — true black-on-white by default, because
/// scanners want a dark code on a light background and a themed
/// terminal guarantees neither. Themes that override this own its
/// scannability.
fn qr_text(q: &crate::deck::QrBlock, w: u16, theme: &Theme) -> Text<'static> {
    let qw = q.rows.first().map(|r| r.chars().count()).unwrap_or(0);
    if qw > w as usize {
        return Text::from(Line::from(Span::styled(
            format!("[qr code needs {qw} columns]"),
            Style::default()
                .fg(theme.muted)
                .add_modifier(Modifier::ITALIC),
        )));
    }
    let style = Style::default().fg(theme.qr_dark).bg(theme.qr_light);
    let pad = " ".repeat((w as usize - qw) / 2);
    Text::from(
        q.rows
            .iter()
            .map(|row| {
                Line::from(vec![
                    Span::raw(pad.clone()),
                    Span::styled(row.clone(), style),
                ])
            })
            .collect::<Vec<_>>(),
    )
}

/// What an image block shows when its pixels aren't loaded: alt text,
/// plus the reason (load failure natively, no filesystem on the web).
fn image_placeholder(img: &crate::deck::ImageBlock, theme: &Theme) -> Text<'static> {
    let muted = Style::default().fg(theme.muted);
    let label = if img.alt.is_empty() {
        img.path.as_str()
    } else {
        img.alt.as_str()
    };
    let mut lines = vec![Line::from(Span::styled(format!("▦ image: {label}"), muted))];
    let detail = match &img.error {
        Some(e) => e.clone(),
        None => format!(
            "{} — renders as ASCII art in the native presenter",
            img.path
        ),
    };
    lines.push(Line::from(Span::styled(
        format!("  {detail}"),
        muted.add_modifier(Modifier::ITALIC),
    )));
    Text::from(lines)
}

/// Resolve per-slide theme overrides against the base config stack.
fn resolve_slide_themes(
    deck: &Deck,
    base: &[ThemeConfig],
) -> Result<HashMap<(usize, usize), Theme>> {
    let mut out = HashMap::new();
    for (c, column) in deck.columns.iter().enumerate() {
        for (r, slide) in column.slides.iter().enumerate() {
            if let Some(cfg) = &slide.theme {
                let mut cfgs = base.to_vec();
                cfgs.push(cfg.clone());
                let resolved = Theme::resolve(cfgs)
                    .with_context(|| format!("theme for slide {}.{}", c + 1, r + 1))?;
                out.insert((c, r), resolved);
            }
        }
    }
    Ok(out)
}

#[derive(Clone, Copy, PartialEq)]
enum Mode {
    Slide,
    Overview { sel: (usize, usize) },
    Help,
}

/// The shared presentation state machine and renderer. See the
/// [module docs](self) for the division of labor with providers.
pub struct Presenter<P: TerminalProvider> {
    /// The context's terminal provider, reachable for lifecycle calls
    /// (e.g. the native front end kills its PTYs on shutdown).
    pub provider: P,
    deck: Deck,
    theme: Theme,
    slide_themes: HashMap<(usize, usize), Theme>,
    col: usize,
    row: usize,
    depth_memory: Vec<usize>,
    mode: Mode,
    focus: Option<usize>,
    selected: HashMap<(usize, usize), usize>,
    term_rects: Vec<(usize, Rect)>,
    overview_rects: Vec<((usize, usize), Rect)>,
    status: Option<String>,
    jump_input: String,
    /// A disabled terminal awaiting the presenter's `y` to run.
    pending_enable: Option<usize>,
    /// Extra line shown at the bottom of the help overlay (the native
    /// front end uses it for the notes-socket hint).
    pub help_footer: Option<String>,
    quit: bool,
}

impl<P: TerminalProvider> Presenter<P> {
    /// `theme_cfgs` are merged lowest-precedence-first (e.g. user config,
    /// then the deck's own theme).
    pub fn new(deck: Deck, theme_cfgs: Vec<ThemeConfig>, provider: P) -> Result<Self> {
        anyhow::ensure!(!deck.columns.is_empty(), "deck contains no slides");
        let theme = Theme::resolve(theme_cfgs.clone())?;
        let slide_themes = resolve_slide_themes(&deck, &theme_cfgs)?;
        let ncols = deck.columns.len();
        Ok(Presenter {
            provider,
            deck,
            theme,
            slide_themes,
            col: 0,
            row: 0,
            depth_memory: vec![0; ncols],
            mode: Mode::Slide,
            focus: None,
            selected: HashMap::new(),
            term_rects: Vec::new(),
            overview_rects: Vec::new(),
            status: None,
            jump_input: String::new(),
            pending_enable: None,
            help_footer: None,
            quit: false,
        })
    }

    /// The deck being presented.
    pub fn deck(&self) -> &Deck {
        &self.deck
    }

    /// Current (column, depth), 0-based.
    pub fn position(&self) -> (usize, usize) {
        (self.col, self.row)
    }

    /// The slide currently displayed.
    pub fn current_slide(&self) -> &Slide {
        self.deck.slide(self.col, self.row)
    }

    /// Whether the user asked to quit (`q` / ctrl-c).
    pub fn should_quit(&self) -> bool {
        self.quit
    }

    /// Show a transient message in the status bar (cleared on the next
    /// key press). Front ends use it for live-reload feedback.
    pub fn set_status(&mut self, message: impl Into<String>) {
        self.status = Some(message.into());
    }

    /// Swap in a rebuilt deck — e.g. after its files changed on disk —
    /// preserving position (clamped) and, when the terminal blocks are
    /// unchanged, live terminal state and focus. When they changed, the
    /// provider is [`reset`](TerminalProvider::reset) so ids can't attach
    /// to the wrong sessions.
    pub fn replace_deck(&mut self, deck: Deck, theme_cfgs: Vec<ThemeConfig>) -> Result<()> {
        anyhow::ensure!(!deck.columns.is_empty(), "deck contains no slides");
        let theme = Theme::resolve(theme_cfgs.clone())?;
        let slide_themes = resolve_slide_themes(&deck, &theme_cfgs)?;

        let same_terms = term_blocks(&self.deck) == term_blocks(&deck);
        if !same_terms {
            self.provider.reset();
            self.focus = None;
            self.selected.clear();
        }

        self.deck = deck;
        self.theme = theme;
        self.slide_themes = slide_themes;

        let ncols = self.deck.columns.len();
        self.depth_memory.resize(ncols, 0);
        for (c, depth) in self.depth_memory.iter_mut().enumerate() {
            *depth = (*depth).min(self.deck.columns[c].slides.len() - 1);
        }
        self.col = self.col.min(ncols - 1);
        self.row = self.row.min(self.deck.columns[self.col].slides.len() - 1);
        if let Mode::Overview { sel: (c, r) } = self.mode {
            let c = c.min(ncols - 1);
            let r = r.min(self.deck.columns[c].slides.len() - 1);
            self.mode = Mode::Overview { sel: (c, r) };
        }
        self.jump_input.clear();
        self.pending_enable = None;
        Ok(())
    }

    // -------------------------------------------------------------- nav

    fn current_ids(&self) -> Vec<usize> {
        self.deck.slide(self.col, self.row).term_ids()
    }

    fn current_theme(&self) -> Theme {
        self.slide_themes
            .get(&(self.col, self.row))
            .copied()
            .unwrap_or(self.theme)
    }

    /// Jump to a slide; out-of-range coordinates clamp.
    pub fn goto(&mut self, col: usize, row: usize) {
        let col = col.min(self.deck.columns.len() - 1);
        let row = row.min(self.deck.columns[col].slides.len() - 1);
        if (col, row) != (self.col, self.row) {
            self.col = col;
            self.row = row;
            self.depth_memory[col] = row;
            self.focus = None;
            self.pending_enable = None;
        }
    }

    fn next(&mut self) {
        if self.row + 1 < self.deck.columns[self.col].slides.len() {
            self.goto(self.col, self.row + 1);
        } else if self.col + 1 < self.deck.columns.len() {
            self.goto(self.col + 1, 0);
        }
    }

    fn prev(&mut self) {
        if self.row > 0 {
            self.goto(self.col, self.row - 1);
        } else if self.col > 0 {
            let c = self.col - 1;
            self.goto(c, self.deck.columns[c].slides.len() - 1);
        }
    }

    // ------------------------------------------------------------- input

    /// Handle a key press: navigation, mode changes, terminal focus, or
    /// (while a terminal is focused) input forwarded to the provider.
    pub fn on_key(&mut self, key: KeyPress) {
        self.status = None;

        // A disabled terminal is awaiting confirmation: `y` runs it,
        // anything else cancels (take() clears the pending state) and
        // is then handled normally.
        if let Some(id) = self.pending_enable.take()
            && matches!(key.key, Key::Char('y') | Key::Char('Y'))
        {
            self.provider.enable(id);
            self.focus = Some(id);
            return;
        }

        if let Some(id) = self.focus {
            if key.key == Key::Char('q') && key.ctrl {
                self.focus = None;
                return;
            }
            match self.provider.state(&self.block_by_id(id)) {
                TermState::Running { .. } => {}
                _ => {
                    self.focus = None;
                    return;
                }
            }
            if key.shift {
                let rows = self.block_by_id(id).rows;
                match key.key {
                    Key::PageUp => return self.provider.scroll_page(id, true, rows),
                    Key::PageDown => return self.provider.scroll_page(id, false, rows),
                    Key::Up => return self.provider.scroll(id, 1),
                    Key::Down => return self.provider.scroll(id, -1),
                    _ => {}
                }
            }
            if let Some(bytes) = encode_key(&key) {
                self.provider.input(id, &bytes);
            }
            return;
        }

        match self.mode {
            Mode::Help => self.mode = Mode::Slide,
            Mode::Overview { sel } => self.on_key_overview(key, sel),
            Mode::Slide => self.on_key_slide(key),
        }
    }

    fn block_by_id(&self, id: usize) -> TermBlock {
        for column in &self.deck.columns {
            for slide in &column.slides {
                for seg in slide.leaf_segments() {
                    if let Segment::Terminal(b) = seg
                        && b.id == id
                    {
                        return b.clone();
                    }
                }
            }
        }
        unreachable!("terminal id {id} not in deck")
    }

    fn on_key_slide(&mut self, key: KeyPress) {
        match key.key {
            Key::Char('c') if key.ctrl => self.quit = true,
            Key::Char('q') => self.quit = true,
            Key::Char(' ') if key.shift => self.prev(),
            Key::Char(' ') | Key::Char('n') | Key::PageDown => self.next(),
            Key::Backspace | Key::Char('p') | Key::PageUp => self.prev(),
            Key::Left | Key::Char('h') => {
                if self.col > 0 {
                    self.goto(self.col - 1, self.depth_memory[self.col - 1]);
                }
            }
            Key::Right | Key::Char('l') => {
                if self.col + 1 < self.deck.columns.len() {
                    self.goto(self.col + 1, self.depth_memory[self.col + 1]);
                }
            }
            Key::Down | Key::Char('j') => self.goto(self.col, self.row + 1),
            Key::Up | Key::Char('k') => self.goto(self.col, self.row.saturating_sub(1)),
            Key::Char('g') | Key::Home => self.goto(0, 0),
            Key::Char('G') | Key::End => self.goto(self.deck.columns.len() - 1, 0),
            Key::Char('o') => {
                self.jump_input.clear();
                self.mode = Mode::Overview {
                    sel: (self.col, self.row),
                };
            }
            Key::Char('?') => self.mode = Mode::Help,
            Key::Enter | Key::Char('t') => self.focus_terminal(),
            Key::Char(c @ '1'..='9') => self.select_terminal(c as usize - '0' as usize),
            Key::Char('s') => self.stop_terminal(),
            Key::Char('R') => self.restart_terminal(),
            _ => {}
        }
    }

    /// The terminal `t` will focus on this slide.
    fn selected_terminal(&self) -> Option<usize> {
        let ids = self.current_ids();
        self.selected
            .get(&(self.col, self.row))
            .copied()
            .filter(|id| ids.contains(id))
            .or_else(|| ids.first().copied())
    }

    fn select_terminal(&mut self, n: usize) {
        if !self.provider.interactive() {
            return;
        }
        let ids = self.current_ids();
        if ids.is_empty() {
            self.status = Some("no terminal on this slide".to_string());
            return;
        }
        match ids.get(n - 1) {
            Some(&id) => {
                self.selected.insert((self.col, self.row), id);
            }
            None => {
                self.status = Some(format!("no terminal {n} here ({} available)", ids.len()));
            }
        }
    }

    fn focus_terminal(&mut self) {
        if !self.provider.interactive() {
            self.status = Some("terminals run when presenting in a real terminal".to_string());
            return;
        }
        let Some(id) = self.selected_terminal() else {
            self.status = Some("no terminal on this slide".to_string());
            return;
        };
        self.selected.insert((self.col, self.row), id);
        // Unapproved blocks ask before running anything.
        if self.provider.state(&self.block_by_id(id)) == TermState::Disabled {
            let command = self.block_label(id);
            self.pending_enable = Some(id);
            self.status = Some(format!(
                "run `{command}`? y confirms · any other key cancels"
            ));
            return;
        }
        self.focus = Some(id);
    }

    fn block_label(&self, id: usize) -> String {
        let block = self.block_by_id(id);
        block
            .command
            .as_deref()
            .and_then(|c| c.lines().next())
            .unwrap_or("shell")
            .to_string()
    }

    fn stop_terminal(&mut self) {
        let Some(id) = self.selected_terminal() else {
            return;
        };
        match self.provider.state(&self.block_by_id(id)) {
            TermState::Running { .. } | TermState::Exited | TermState::Failed(_) => {
                self.provider.stop(id);
                self.focus = None;
                self.status = Some(format!("stopped `{}`", self.block_label(id)));
            }
            _ => {}
        }
    }

    fn restart_terminal(&mut self) {
        let Some(id) = self.selected_terminal() else {
            return;
        };
        match self.provider.state(&self.block_by_id(id)) {
            TermState::Running { .. } | TermState::Exited | TermState::Failed(_) => {
                self.provider.restart(&[id]);
                self.status = Some(format!("restarted `{}`", self.block_label(id)));
            }
            TermState::Disabled => {
                self.status = Some("not running — t runs it".to_string());
            }
            _ => {}
        }
    }

    fn overview_codes(&self) -> Vec<((usize, usize), String)> {
        let flat = self.deck.flat();
        let codes = jump_codes(flat.len());
        flat.into_iter().zip(codes).collect()
    }

    fn on_key_overview(&mut self, key: KeyPress, sel: (usize, usize)) {
        if let Key::Char(ch) = key.key
            && JUMP_KEYS.contains(&ch)
        {
            self.jump_input.push(ch);
            let codes = self.overview_codes();
            let hit = codes
                .iter()
                .find(|(_, code)| *code == self.jump_input)
                .map(|(target, _)| *target);
            if let Some(target) = hit {
                self.jump_input.clear();
                self.mode = Mode::Slide;
                self.goto(target.0, target.1);
            } else if !codes
                .iter()
                .any(|(_, code)| code.starts_with(self.jump_input.as_str()))
            {
                self.jump_input.clear();
            }
            return;
        }
        let had_pending = !self.jump_input.is_empty();
        self.jump_input.clear();

        let (mut c, mut r) = sel;
        match key.key {
            Key::Esc if had_pending => return,
            Key::Esc | Key::Char('o') => {
                self.mode = Mode::Slide;
                return;
            }
            Key::Char('q') => {
                self.quit = true;
                return;
            }
            Key::Enter => {
                self.mode = Mode::Slide;
                self.goto(c, r);
                return;
            }
            Key::Left | Key::Char('h') => c = c.saturating_sub(1),
            Key::Right | Key::Char('l') => c = (c + 1).min(self.deck.columns.len() - 1),
            Key::Up | Key::Char('k') => r = r.saturating_sub(1),
            Key::Down | Key::Char('j') => r += 1,
            _ => {}
        }
        r = r.min(self.deck.columns[c].slides.len() - 1);
        self.mode = Mode::Overview { sel: (c, r) };
    }

    /// Handle a mouse event: click to focus/release terminals or jump in
    /// the overview, wheel to scroll terminal history.
    pub fn on_mouse(&mut self, m: Mouse) {
        let pos = Position::new(m.x, m.y);
        let term_at = |rects: &[(usize, Rect)]| {
            rects
                .iter()
                .find(|(_, r)| r.contains(pos))
                .map(|(id, _)| *id)
        };
        match self.mode {
            Mode::Help => {
                if m.action == MouseAction::LeftClick {
                    self.mode = Mode::Slide;
                }
            }
            Mode::Overview { .. } => {
                if m.action == MouseAction::LeftClick
                    && let Some(&(target, _)) =
                        self.overview_rects.iter().find(|(_, r)| r.contains(pos))
                {
                    self.mode = Mode::Slide;
                    self.goto(target.0, target.1);
                }
            }
            Mode::Slide => match m.action {
                MouseAction::LeftClick => {
                    if !self.provider.interactive() {
                        return;
                    }
                    self.pending_enable = None;
                    match term_at(&self.term_rects) {
                        Some(id) => {
                            self.selected.insert((self.col, self.row), id);
                            if self.provider.state(&self.block_by_id(id)) == TermState::Disabled {
                                let command = self.block_label(id);
                                self.pending_enable = Some(id);
                                self.status = Some(format!(
                                    "run `{command}`? y confirms · any other key cancels"
                                ));
                            } else {
                                self.focus = Some(id);
                            }
                        }
                        None => self.focus = None,
                    }
                }
                MouseAction::ScrollUp | MouseAction::ScrollDown => {
                    if let Some(id) = term_at(&self.term_rects) {
                        let delta = if m.action == MouseAction::ScrollUp {
                            3
                        } else {
                            -3
                        };
                        self.provider.scroll(id, delta);
                    }
                }
            },
        }
    }

    // -------------------------------------------------------------- draw

    /// Render the current frame (slide or overview, plus status bar and
    /// overlays) into `buf`. Also records hit-test regions for mouse
    /// events and gives the provider its per-frame `prepare` calls.
    pub fn draw(&mut self, area: Rect, buf: &mut Buffer) {
        self.term_rects.clear();
        self.overview_rects.clear();
        if area.height < 2 {
            return;
        }
        let content = Rect {
            height: area.height - 1,
            ..area
        };
        let status = Rect {
            y: area.y + area.height - 1,
            height: 1,
            ..area
        };
        match self.mode {
            Mode::Overview { .. } => self.draw_overview(content, buf),
            _ => self.draw_slide(content, buf),
        }
        if self.mode == Mode::Help {
            self.draw_help(content, buf);
        }
        self.draw_status(status, buf);
    }

    fn draw_slide(&mut self, area: Rect, buf: &mut Buffer) {
        let theme = self.current_theme();

        // One content box, two axes, same rules on both: margins are
        // minimum air (they always win), caps bound everything drawn,
        // and alignment only places what's left.
        let usable = Rect {
            x: area.x + theme.margin_x.min(area.width / 2),
            y: area.y + theme.margin_y.min(area.height / 2),
            width: area.width.saturating_sub(theme.margin_x.saturating_mul(2)),
            height: area.height.saturating_sub(theme.margin_y.saturating_mul(2)),
        };
        let w = usable.width.min(theme.max_width);
        if w < 10 || usable.height < 1 {
            return;
        }
        let x = usable.x
            + match theme.align_x {
                HAlign::Left => 0,
                HAlign::Center => (usable.width - w) / 2,
                HAlign::Right => usable.width - w,
            };

        // Pinned title: carve the leading heading off the first
        // segment and anchor it to the top of the usable area; the
        // body below still follows `align_y`.
        let mut title: Option<Text<'static>> = None;
        let mut first_md_body: Option<String> = None;
        if theme.pin_title
            && let Some(Segment::Markdown(src)) =
                self.deck.slide(self.col, self.row).segments.first()
            && let Some((head, rest)) = split_leading_heading(src)
        {
            title = Some(markdown::render(&head, w, &theme));
            first_md_body = Some(rest);
        }
        let title_h = title
            .as_ref()
            .map(|t| (t.height() as u16).min(usable.height))
            .unwrap_or(0);
        if let Some(t) = title {
            let rect = Rect {
                x,
                y: usable.y,
                width: w,
                height: title_h,
            };
            Paragraph::new(t).render(rect, buf);
        }
        // The body lays out below the title and its gap; the height
        // cap covers title, gap, and body together.
        let carved = if title_h > 0 {
            title_h + theme.title_gap
        } else {
            0
        };
        let body = Rect {
            y: usable.y + carved.min(usable.height),
            height: usable.height.saturating_sub(carved),
            ..usable
        };
        if body.height == 0 {
            return;
        }

        enum RenderItem {
            Text(Text<'static>),
            Term(TermBlock),
            /// Side-by-side cells, each a fixed-height stack.
            Row(Vec<Vec<(u16, CellItem)>>, u16),
        }
        let box_h = body
            .height
            .min(theme.max_height.saturating_sub(carved).max(1));
        let mut items: Vec<(Option<u16>, RenderItem)> = Vec::new();
        for (i, seg) in self
            .deck
            .slide(self.col, self.row)
            .segments
            .iter()
            .enumerate()
        {
            if i == 0
                && let Some(rest) = &first_md_body
            {
                let text = markdown::render(rest, w, &theme);
                let h = text.height() as u16;
                if h > 0 {
                    items.push((Some(h), RenderItem::Text(text)));
                }
                continue;
            }
            match seg {
                // Fill sizing only exists at the top level; everything
                // else routes through the shared cell builder.
                Segment::Terminal(b) if b.fill => {
                    items.push((None, RenderItem::Term(b.clone())));
                }
                Segment::Row(cells) => {
                    let n = cells.len().max(1) as u16;
                    let cw = (w.saturating_sub(ROW_GAP * (n - 1)) / n).max(10);
                    let built: Vec<Vec<(u16, CellItem)>> = cells
                        .iter()
                        .map(|cell| build_cell_items(cell, cw, box_h, &theme))
                        .collect();
                    let height = built
                        .iter()
                        .map(|cell| {
                            cell.iter()
                                .map(|(h, _)| h + 1)
                                .sum::<u16>()
                                .saturating_sub(1)
                        })
                        .max()
                        .unwrap_or(0);
                    if height > 0 {
                        items.push((Some(height), RenderItem::Row(built, cw)));
                    }
                }
                other => {
                    for (h, item) in build_cell_items(std::slice::from_ref(other), w, box_h, &theme)
                    {
                        let item = match item {
                            CellItem::Text(t) => RenderItem::Text(t),
                            CellItem::Term(b) => RenderItem::Term(b),
                        };
                        items.push((Some(h), item));
                    }
                }
            }
        }
        if items.is_empty() {
            return;
        }

        let gaps = items.len().saturating_sub(1) as u16;
        let fixed: u16 = items.iter().filter_map(|(h, _)| *h).sum();
        let nfill = items.iter().filter(|(h, _)| h.is_none()).count() as u16;
        let fill_h = box_h
            .saturating_sub(fixed + gaps)
            .checked_div(nfill)
            .map_or(0, |h| h.max(7));
        let heights: Vec<u16> = items.iter().map(|(h, _)| h.unwrap_or(fill_h)).collect();
        let total: u16 = heights.iter().sum::<u16>() + gaps;
        let visible = total.min(box_h);
        let mut y = body.y
            + match theme.align_y {
                VAlign::Top => 0,
                VAlign::Center => body.height.saturating_sub(visible) / 2,
                VAlign::Bottom => body.height.saturating_sub(visible),
            };
        let bottom = y + visible;
        for ((_, item), h) in items.into_iter().zip(heights) {
            if y >= bottom {
                break;
            }
            let h = h.min(bottom - y);
            let rect = Rect {
                x,
                y,
                width: w,
                height: h,
            };
            match item {
                RenderItem::Text(text) => Paragraph::new(text).render(rect, buf),
                RenderItem::Term(block) => {
                    self.provider.prepare(
                        &block,
                        w.saturating_sub(2).max(4),
                        h.saturating_sub(2).max(1),
                    );
                    self.term_rects.push((block.id, rect));
                    self.draw_term(rect, &block, &theme, buf);
                }
                RenderItem::Row(cells, cw) => {
                    let mut cx = rect.x;
                    for cell in cells {
                        let mut cy = rect.y;
                        let cell_bottom = rect.y + rect.height;
                        for (ih, item) in cell {
                            if cy >= cell_bottom {
                                break;
                            }
                            let ih = ih.min(cell_bottom - cy);
                            let r = Rect {
                                x: cx,
                                y: cy,
                                width: cw,
                                height: ih,
                            };
                            match item {
                                CellItem::Text(text) => Paragraph::new(text).render(r, buf),
                                CellItem::Term(block) => {
                                    self.provider.prepare(
                                        &block,
                                        cw.saturating_sub(2).max(4),
                                        ih.saturating_sub(2).max(1),
                                    );
                                    self.term_rects.push((block.id, r));
                                    self.draw_term(r, &block, &theme, buf);
                                }
                            }
                            cy += ih + 1;
                        }
                        cx += cw + ROW_GAP;
                    }
                }
            }
            y += h + 1;
        }
    }

    /// All terminal chrome; the provider draws the inside of the box.
    fn draw_term(&mut self, rect: Rect, block: &TermBlock, theme: &Theme, buf: &mut Buffer) {
        let focused = self.focus == Some(block.id);
        let state = self.provider.state(block);

        let label: String = block
            .command
            .as_deref()
            .and_then(|c| c.lines().next())
            .unwrap_or("shell")
            .chars()
            .take(40)
            .collect();

        let ids = self.current_ids();
        let idx = ids.iter().position(|i| *i == block.id).unwrap_or(0);
        let is_next = self.selected_terminal() == Some(block.id);
        let numbered = ids.len() > 1 && self.provider.interactive();
        let title = if numbered {
            let marker = if is_next && !focused { "▸ " } else { "" };
            format!(" {marker}{} · {label} ", idx + 1)
        } else {
            format!(" {label} ")
        };

        let hint = match &state {
            TermState::Failed(_) => "spawn failed".to_string(),
            TermState::Exited => "exited · R restarts".to_string(),
            TermState::Snapshot => "snapshot · runs live in the real TUI".to_string(),
            TermState::Disabled if self.pending_enable == Some(block.id) => {
                "run? y confirms · any other key cancels".to_string()
            }
            TermState::Disabled => "t to run".to_string(),
            TermState::Unavailable => "runs live in the real TUI".to_string(),
            TermState::Running { scroll_offset, .. } if *scroll_offset > 0 => {
                format!("history -{scroll_offset} · shift-pgdn returns")
            }
            TermState::Running { .. } if focused => {
                "Ctrl-q releases · shift-pgup history".to_string()
            }
            TermState::Running { .. } if is_next => "t interacts · s stops".to_string(),
            TermState::Running { .. } => format!("{} selects", idx + 1),
        };

        let border_style = if focused {
            Style::default().fg(theme.accent)
        } else if state == TermState::Snapshot {
            Style::default().fg(theme.snapshot_border())
        } else {
            Style::default().fg(theme.term_border)
        };
        let title_style = if focused {
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD)
        } else if is_next && numbered {
            Style::default().fg(theme.accent)
        } else {
            Style::default().fg(theme.muted)
        };

        let outer = Block::default()
            .borders(Borders::ALL)
            .border_type(theme.border_type)
            .border_style(border_style)
            .title(Line::from(title).style(title_style))
            .title_bottom(
                Line::from(format!(" {hint} "))
                    .style(Style::default().fg(theme.muted))
                    .right_aligned(),
            );
        let inner = outer.inner(rect);
        outer.render(rect, buf);
        if inner.width == 0 || inner.height == 0 {
            return;
        }

        if let TermState::Failed(msg) = &state {
            Paragraph::new(msg.as_str())
                .style(Style::default().fg(Color::Red))
                .render(inner, buf);
            return;
        }
        self.provider.draw(block, inner, buf);

        if let TermState::Running {
            scroll_offset,
            scroll_total,
        } = state
            && scroll_total > 0
            && rect.height > 3
        {
            let viewport = inner.height as usize;
            let mut sb = ScrollbarState::new(scroll_total + viewport)
                .viewport_content_length(viewport)
                .position(scroll_total - scroll_offset.min(scroll_total));
            let thumb = if focused { theme.accent } else { theme.muted };
            StatefulWidget::render(
                Scrollbar::default()
                    .orientation(ScrollbarOrientation::VerticalRight)
                    .begin_symbol(None)
                    .end_symbol(None)
                    .track_style(border_style)
                    .thumb_style(Style::default().fg(thumb)),
                rect.inner(ratatui::layout::Margin {
                    vertical: 1,
                    horizontal: 0,
                }),
                buf,
                &mut sb,
            );
        }
    }

    fn draw_overview(&mut self, area: Rect, buf: &mut Buffer) {
        let Mode::Overview { sel } = self.mode else {
            return;
        };
        let bw: u16 = 26;
        let bh: u16 = 4;

        let mut header = vec![
            Span::styled(" overview ", Style::default().add_modifier(Modifier::BOLD)),
            Span::styled(
                " — type a code or ↵ to jump · esc back",
                Style::default().fg(self.theme.muted),
            ),
        ];
        if !self.jump_input.is_empty() {
            header.push(Span::styled(
                format!("  {}…", self.jump_input),
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ));
        }
        Paragraph::new(Line::from(header)).render(Rect { height: 1, ..area }, buf);
        let codes: HashMap<(usize, usize), String> = self.overview_codes().into_iter().collect();

        // One row under the grid is always reserved for the clip bar
        // (markers for slides scrolled out of view) so the grid never
        // reflows when scrolling starts.
        let grid = Rect {
            x: area.x,
            y: area.y + 1,
            width: area.width,
            height: area.height.saturating_sub(2),
        };
        if grid.width < bw || grid.height < bh {
            return;
        }
        let vis_cols = (grid.width / bw).max(1) as usize;
        let vis_rows = (grid.height / bh).max(1) as usize;
        let n_cols = self.deck.columns.len();
        let max_depth = self
            .deck
            .columns
            .iter()
            .map(|c| c.slides.len())
            .max()
            .unwrap_or(0);
        let off_c = viewport_offset(sel.0, n_cols, vis_cols);
        let off_r = viewport_offset(sel.1, max_depth, vis_rows);

        for (ci, column) in self.deck.columns.iter().enumerate() {
            if ci < off_c || ci >= off_c + vis_cols {
                continue;
            }
            for (ri, slide) in column.slides.iter().enumerate() {
                if ri < off_r || ri >= off_r + vis_rows {
                    continue;
                }
                let rect = Rect {
                    x: grid.x + ((ci - off_c) as u16) * bw,
                    y: grid.y + ((ri - off_r) as u16) * bh,
                    width: bw - 1,
                    height: bh - 1,
                };
                self.overview_rects.push(((ci, ri), rect));
                let selected = (ci, ri) == sel;
                let current = (ci, ri) == (self.col, self.row);
                let border_style = if selected {
                    Style::default()
                        .fg(self.theme.accent)
                        .add_modifier(Modifier::BOLD)
                } else if current {
                    Style::default().fg(Color::Yellow)
                } else {
                    Style::default().fg(self.theme.muted)
                };
                let mut title_spans = Vec::new();
                if let Some(code) = codes.get(&(ci, ri)) {
                    let candidate =
                        self.jump_input.is_empty() || code.starts_with(self.jump_input.as_str());
                    let code_style = if candidate {
                        Style::default()
                            .fg(Color::Yellow)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(self.theme.muted)
                    };
                    title_spans.push(Span::styled(format!(" {code} "), code_style));
                }
                title_spans.push(Span::styled(
                    format!("{}.{} ", ci + 1, ri + 1),
                    border_style,
                ));
                if current {
                    title_spans.push(Span::styled("● ", border_style));
                }
                let block = Block::default()
                    .borders(Borders::ALL)
                    .border_type(self.theme.border_type)
                    .border_style(border_style)
                    .title(Line::from(title_spans));
                let inner = block.inner(rect);
                block.render(rect, buf);

                let mut label: String = slide.title.chars().take((bw as usize) - 4).collect();
                if !slide.term_ids().is_empty() {
                    label.push_str(" ⌨");
                }
                Paragraph::new(label).render(inner, buf);
            }
        }

        // Clip bar: how many slides are scrolled out of view, per
        // direction, sitting right under the drawn rows. Depth counts
        // only consider visible columns — a column you can't see
        // shouldn't advertise its deep slides.
        let hidden_left = off_c;
        let hidden_right = n_cols.saturating_sub(off_c + vis_cols);
        let hidden_above = off_r;
        let vis_depth = self
            .deck
            .columns
            .iter()
            .skip(off_c)
            .take(vis_cols)
            .map(|c| c.slides.len())
            .max()
            .unwrap_or(0);
        let hidden_below = vis_depth.saturating_sub(off_r + vis_rows);
        if hidden_left + hidden_right + hidden_above + hidden_below == 0 {
            return;
        }
        let rows_drawn = vis_depth.saturating_sub(off_r).clamp(1, vis_rows) as u16;
        let bar = Rect {
            x: grid.x,
            y: grid.y + rows_drawn * bh,
            width: grid.width,
            height: 1,
        };
        let style = Style::default()
            .fg(self.theme.accent)
            .add_modifier(Modifier::BOLD);
        if hidden_left > 0 {
            Paragraph::new(Span::styled(format!("◂ {hidden_left}"), style)).render(bar, buf);
        }
        if hidden_right > 0 {
            Paragraph::new(Line::from(Span::styled(format!("{hidden_right} ▸"), style)))
                .alignment(ratatui::layout::Alignment::Right)
                .render(bar, buf);
        }
        if hidden_above + hidden_below > 0 {
            let mut mid = String::new();
            if hidden_above > 0 {
                mid.push_str(&format!("▴ {hidden_above}"));
            }
            if hidden_below > 0 {
                if !mid.is_empty() {
                    mid.push_str(" · ");
                }
                mid.push_str(&format!("▾ {hidden_below}"));
            }
            Paragraph::new(Line::from(Span::styled(mid, style)))
                .alignment(ratatui::layout::Alignment::Center)
                .render(bar, buf);
        }
    }

    fn draw_help(&self, area: Rect, buf: &mut Buffer) {
        let dim = Style::default().fg(self.theme.muted);
        let key = Style::default()
            .fg(self.theme.accent)
            .add_modifier(Modifier::BOLD);
        let row = |k: &str, desc: &str| {
            Line::from(vec![
                Span::styled(format!("  {k:<14}"), key),
                Span::raw(desc.to_string()),
            ])
        };
        let mut lines = vec![
            Line::from(Span::styled(" navigation", dim)),
            row("←/h  →/l", "previous / next column"),
            row("↓/j  ↑/k", "deeper / shallower"),
            row("space, n", "next slide (depth-first)"),
            row("shift-space", "previous slide (also bksp, p)"),
            row("g / G", "first / last column"),
            Line::default(),
        ];
        if self.provider.interactive() {
            lines.extend([
                Line::from(Span::styled(" terminals", dim)),
                row("1-9", "select terminal pane"),
                row("t, enter", "run (after y) / focus the selected terminal"),
                row("click", "same as t, on the clicked terminal"),
                row("ctrl-q", "release terminal focus (or click outside)"),
                row("shift-pgup/dn", "scroll terminal history (or wheel)"),
                row("s / R", "stop / restart the selected terminal"),
                Line::default(),
            ]);
        }
        lines.extend([
            Line::from(Span::styled(" modes", dim)),
            row("o", "overview (type a slide's code to jump)"),
            row("?", "this help"),
            row("q", "quit"),
        ]);
        if let Some(footer) = &self.help_footer {
            lines.push(Line::default());
            lines.push(Line::from(vec![
                Span::styled(" ", dim),
                Span::raw(footer.clone()),
            ]));
        }
        let w = 66.min(area.width);
        let h = (lines.len() as u16 + 2).min(area.height);
        let rect = Rect {
            x: area.x + (area.width - w) / 2,
            y: area.y + (area.height - h) / 2,
            width: w,
            height: h,
        };
        Clear.render(rect, buf);
        Paragraph::new(lines)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(self.theme.border_type)
                    .border_style(Style::default().fg(self.theme.accent))
                    .title(" help "),
            )
            .render(rect, buf);
    }

    fn draw_status(&self, area: Rect, buf: &mut Buffer) {
        let bar = Style::default()
            .bg(self.theme.status_bg)
            .fg(self.theme.status_fg);
        let depth = self.deck.columns[self.col].slides.len();
        let flat = self.deck.flat();
        let idx = flat
            .iter()
            .position(|&p| p == (self.col, self.row))
            .unwrap_or(0);

        let mut left = format!(" {} · {}.{}", self.deck.title, self.col + 1, self.row + 1);
        if depth > 1 {
            left.push_str(&format!(" · depth {}/{}", self.row + 1, depth));
        }
        left.push_str(&format!(" · {}/{}", idx + 1, flat.len()));
        if let Some(status) = &self.status {
            left.push_str(&format!("  —  {status}"));
        }
        Paragraph::new(left).style(bar).render(area, buf);

        let right = if self.focus.is_some() {
            Span::styled(
                " TERMINAL · ctrl-q releases ",
                Style::default()
                    // Indexed(16) is true black; ANSI Black gets remapped
                    // near-background by schemes like solarized.
                    .fg(Color::Indexed(16))
                    .bg(self.theme.accent)
                    .add_modifier(Modifier::BOLD),
            )
        } else if self.provider.interactive() {
            Span::styled(" space next · o overview · ? help ", bar)
        } else {
            Span::styled(" space next · o overview ", bar)
        };
        Paragraph::new(Line::from(right).right_aligned()).render(area, buf);
    }
}

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

    /// A provider with no terminals at all, for exercising the core.
    struct NullProvider;
    impl TerminalProvider for NullProvider {
        fn prepare(&mut self, _: &TermBlock, _: u16, _: u16) {}
        fn state(&self, _: &TermBlock) -> TermState {
            TermState::Unavailable
        }
        fn draw(&mut self, _: &TermBlock, _: Rect, _: &mut Buffer) {}
        fn input(&mut self, _: usize, _: &[u8]) {}
        fn scroll(&mut self, _: usize, _: isize) {}
        fn restart(&mut self, _: &[usize]) {}
        fn interactive(&self) -> bool {
            false
        }
    }

    fn presenter() -> Presenter<NullProvider> {
        let deck = crate::deck::parse("# a\n---\n# b\n--\n# b2\n---\n# c\n", "t").unwrap();
        Presenter::new(deck, vec![], NullProvider).unwrap()
    }

    #[test]
    fn navigation_walks_the_grid() {
        let mut p = presenter();
        p.on_key(KeyPress::plain(Key::Char(' ')));
        assert_eq!(p.position(), (1, 0));
        p.on_key(KeyPress::plain(Key::Char(' ')));
        assert_eq!(p.position(), (1, 1));
        p.on_key(KeyPress {
            shift: true,
            ..KeyPress::plain(Key::Char(' '))
        });
        assert_eq!(p.position(), (1, 0));
        p.on_key(KeyPress::plain(Key::Char('G')));
        assert_eq!(p.position(), (2, 0));
    }

    #[test]
    fn viewport_offset_keeps_a_margin() {
        // Fits: never scrolls.
        assert_eq!(viewport_offset(3, 4, 4), 0);
        // Selection stays one slot in from the trailing edge…
        assert_eq!(viewport_offset(3, 10, 4), 1);
        assert_eq!(viewport_offset(5, 10, 4), 3);
        // …except at the very ends, where there's nothing beyond.
        assert_eq!(viewport_offset(0, 10, 4), 0);
        assert_eq!(viewport_offset(9, 10, 4), 6);
        // Degenerate one-slot viewport still shows the selection.
        assert_eq!(viewport_offset(7, 10, 1), 7);
    }

    #[test]
    fn overview_clip_bar_counts_hidden_slides() {
        // 8 columns; the first is 3 deep. 60x14 fits 2 columns × 2 rows
        // of boxes (26x4 each) plus header and clip bar.
        let mut src = String::from("# c1\n--\n# c1b\n--\n# c1c\n");
        for i in 2..=8 {
            src.push_str(&format!("---\n# c{i}\n"));
        }
        let deck = crate::deck::parse(&src, "t").unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        p.on_key(KeyPress::plain(Key::Char('o')));
        let area = Rect::new(0, 0, 60, 14);
        let screen = |p: &mut Presenter<NullProvider>| {
            let mut buf = Buffer::empty(area);
            p.draw(area, &mut buf);
            (0..area.height)
                .map(|y| {
                    (0..area.width)
                        .map(|x| buf[(x, y)].symbol().to_string())
                        .collect::<String>()
                })
                .collect::<Vec<_>>()
                .join("\n")
        };

        // At the start: 6 columns hidden right, 1 slide hidden below.
        let s = screen(&mut p);
        assert!(s.contains("6 ▸"), "screen:\n{s}");
        assert!(s.contains("▾ 1"), "screen:\n{s}");
        assert!(!s.contains('◂'), "screen:\n{s}");

        // At the last column: everything hidden is to the left, and the
        // shallow visible columns advertise no hidden depth.
        p.on_key(KeyPress::plain(Key::Esc));
        p.on_key(KeyPress::plain(Key::Char('G')));
        p.on_key(KeyPress::plain(Key::Char('o')));
        let s = screen(&mut p);
        assert!(s.contains("◂ 6"), "screen:\n{s}");
        assert!(!s.contains('▸'), "screen:\n{s}");
        assert!(!s.contains('▾'), "screen:\n{s}");
    }

    #[test]
    fn overview_clip_bar_absent_when_everything_fits() {
        let deck = crate::deck::parse("# a\n---\n# b\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        p.on_key(KeyPress::plain(Key::Char('o')));
        let area = Rect::new(0, 0, 60, 14);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        let mut screen = String::new();
        for y in 0..area.height {
            for x in 0..area.width {
                screen.push_str(buf[(x, y)].symbol());
            }
        }
        for glyph in ["◂", "▸", "▴", "▾"] {
            assert!(!screen.contains(glyph), "unexpected {glyph}");
        }
    }

    #[test]
    fn overview_jump_codes_navigate() {
        let mut p = presenter();
        p.on_key(KeyPress::plain(Key::Char('o')));
        // 4 slides → single-letter codes; 'd' is the third (column 2 deep)
        p.on_key(KeyPress::plain(Key::Char('d')));
        assert_eq!(p.position(), (1, 1));
        assert!(matches!(p.mode, Mode::Slide));
    }

    #[test]
    fn qr_slide_draws_black_on_white() {
        let deck = crate::deck::parse("```qr\nhttps://deckhand.sh\n```\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        let area = Rect::new(0, 0, 80, 40);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        let cells = (0..area.height)
            .flat_map(|y| (0..area.width).map(move |x| (x, y)))
            .map(|pos| &buf[pos]);
        assert!(
            cells
                .clone()
                .any(|c| c.bg == Color::Indexed(231) && c.fg == Color::Indexed(16)),
            "no black-on-white QR cells drawn"
        );
        assert!(cells.clone().any(|c| c.symbol().contains('█')));
    }

    #[test]
    fn qr_colors_follow_slide_theme() {
        let deck = crate::deck::parse(
            "```theme\nqr_dark: red\nqr_light: white\n```\n```qr\nhi\n```\n",
            "t",
        )
        .unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        let area = Rect::new(0, 0, 40, 20);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        let themed = (0..area.height)
            .flat_map(|y| (0..area.width).map(move |x| (x, y)))
            .any(|pos| buf[pos].fg == Color::Red && buf[pos].bg == Color::White);
        assert!(themed, "qr_dark/qr_light overrides not applied");
    }

    #[test]
    fn pinned_title_sticks_while_body_centers() {
        let deck =
            crate::deck::parse("```theme\npin_title: true\n```\n# TITLE\n\nbody\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        let area = Rect::new(0, 0, 40, 20);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        let row = |y: u16| {
            (0..area.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        };
        // Heading anchored to the very top…
        assert!(row(0).contains("TITLE"), "row 0: {:?}", row(0));
        // …while the body centers in the space below (19 content rows,
        // title+underline+gap = 3, one body row → y = 3 + 15/2 = 10).
        let body_y = (0..19).find(|&y| row(y).contains("body")).unwrap();
        assert!(
            (8..=12).contains(&body_y),
            "body at y={body_y}, expected centered"
        );

        // Without pin_title the title floats down with the body.
        let deck = crate::deck::parse("# TITLE\n\nbody\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        let row = |y: u16| {
            (0..area.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        };
        let title_y = (0..19).find(|&y| row(y).contains("TITLE")).unwrap();
        assert!(
            title_y > 3,
            "unpinned title at y={title_y}, expected floating"
        );
    }

    #[test]
    fn box_model_composes_margins_caps_and_pin() {
        // pin_title + margin_y + title_gap + max_height, all at once:
        // margins inset the title, the gap spaces the body, and the
        // cap bounds title+gap+body together.
        let deck = crate::deck::parse(
            "```theme\npin_title: true\nmargin_y: 2\ntitle_gap: 2\nmax_height: 9\nalign_y: top\n```\n# TITLE\n\na\n\nb\n\nc\n\nd\n\ne\n",
            "t",
        )
        .unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        let area = Rect::new(0, 0, 40, 24);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        let row = |y: u16| {
            (0..area.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        };
        // Title at margin_y, not row 0.
        assert!(!row(0).contains("TITLE"));
        assert!(row(2).contains("TITLE"), "row 2: {:?}", row(2));
        // title_gap: 2 → body starts at y = 2 (margin) + 2 (title) + 2.
        assert!(row(6).contains('a'), "row 6: {:?}", row(6));
        // max_height 9 bounds title(2)+gap(2)+body → body ≤ 5 rows:
        // "a", blank, "b", blank, "c" fit; "d" (row 12) does not.
        assert!(row(10).contains('c'), "row 10: {:?}", row(10));
        assert!(
            !(0..24).any(|y| row(y).contains('d')),
            "cap should clip past max_height"
        );
    }

    #[test]
    fn align_x_and_bottom_place_the_box() {
        let deck = crate::deck::parse(
            "```theme\nalign_x: right\nalign_y: bottom\nmargin: 0\nmax_width: 20\n```\nhi\n",
            "t",
        )
        .unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        let row = |y: u16| {
            (0..area.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        };
        // Content box is 20 wide, right-aligned in 60 → "hi" at x=40;
        // one row tall, bottom-aligned in 9 content rows → y=8.
        assert!(row(8).contains("hi"), "row 8: {:?}", row(8));
        assert!(row(8).find("hi").unwrap() >= 40);
        assert!(!(0..8).any(|y| row(y).contains("hi")));
    }

    #[test]
    fn row_draws_cells_side_by_side() {
        let deck =
            crate::deck::parse("````row\n```qr\nhi\n```\n||\n```qr\nhi\n```\n````\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        let area = Rect::new(0, 0, 80, 30);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        // Two QR codes on the same line: white-bg cells in both the
        // left and right halves of some row.
        let qr_cols: Vec<u16> = (0..area.width)
            .filter(|&x| (0..area.height).any(|y| buf[(x, y)].bg == Color::Indexed(231)))
            .collect();
        assert!(!qr_cols.is_empty(), "no QR cells drawn");
        assert!(
            qr_cols.iter().any(|&x| x < 40) && qr_cols.iter().any(|&x| x >= 40),
            "QR cells all on one side: {qr_cols:?}"
        );
    }

    #[test]
    fn row_terminals_are_focusable_and_hit_testable() {
        let deck = crate::deck::parse(
            "````row\n```terminal\n```\n||\n```terminal\n```\n````\n",
            "t",
        )
        .unwrap();
        let mut p = Presenter::new(deck, vec![], FakeTerms { resets: 0 }).unwrap();
        let area = Rect::new(0, 0, 80, 24);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        assert_eq!(p.term_rects.len(), 2);
        let (left, right) = (p.term_rects[0].1, p.term_rects[1].1);
        assert_eq!(left.y, right.y, "cells should share a row");
        assert!(left.x + left.width <= right.x, "cells should not overlap");
        // Focus cycles across both cells.
        p.on_key(KeyPress::plain(Key::Char('t')));
        p.on_key(KeyPress::plain(Key::Char('y')));
        assert_eq!(p.focus, Some(0));
    }

    #[test]
    fn image_slide_draws_ascii_and_placeholder() {
        let mut deck = crate::deck::parse("![pic](p.png)\n", "t").unwrap();
        // Placeholder first (no pixels loaded)…
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        let area = Rect::new(0, 0, 60, 20);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        let row = |buf: &Buffer, y: u16| {
            (0..area.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        };
        let screen = (0..area.height)
            .map(|y| row(&buf, y))
            .collect::<Vec<_>>()
            .join("\n");
        assert!(screen.contains("image: pic"), "screen:\n{screen}");

        // …then real pixels render as a colored ramp.
        deck = crate::deck::parse("![pic](p.png)\n", "t").unwrap();
        if let crate::deck::Segment::Image(img) = &mut deck.columns[0].slides[0].segments[0] {
            img.data = Some(crate::ascii_image::ImageData {
                width: 8,
                height: 8,
                rgba: [200u8, 200, 200, 255].repeat(64),
            });
        }
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        let screen = (0..area.height)
            .map(|y| row(&buf, y))
            .collect::<Vec<_>>()
            .join("\n");
        // Luminance 200/255 lands on '#' in the ramp.
        assert!(screen.contains('#'), "no ramp glyphs drawn:\n{screen}");
    }

    #[test]
    fn non_interactive_context_refuses_focus() {
        let deck = crate::deck::parse("```terminal\n```\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], NullProvider).unwrap();
        p.on_key(KeyPress::plain(Key::Char('t')));
        assert!(p.focus.is_none());
    }

    /// A provider that runs "terminals" only enough to test focus and
    /// reset behavior.
    struct FakeTerms {
        resets: usize,
    }
    impl TerminalProvider for FakeTerms {
        fn prepare(&mut self, _: &TermBlock, _: u16, _: u16) {}
        fn state(&self, _: &TermBlock) -> TermState {
            TermState::Running {
                scroll_offset: 0,
                scroll_total: 0,
            }
        }
        fn draw(&mut self, _: &TermBlock, _: Rect, _: &mut Buffer) {}
        fn input(&mut self, _: usize, _: &[u8]) {}
        fn scroll(&mut self, _: usize, _: isize) {}
        fn restart(&mut self, _: &[usize]) {}
        fn reset(&mut self) {
            self.resets += 1;
        }
    }

    #[test]
    fn replace_deck_clamps_position_and_keeps_place() {
        let mut p = presenter();
        p.on_key(KeyPress::plain(Key::Char('G'))); // column 3
        assert_eq!(p.position(), (2, 0));

        // Same shape: position survives.
        let same = crate::deck::parse("# a2\n---\n# b\n--\n# b2\n---\n# c\n", "t").unwrap();
        p.replace_deck(same, vec![]).unwrap();
        assert_eq!(p.position(), (2, 0));

        // Deck shrank to one column: position clamps.
        let smaller = crate::deck::parse("# only\n", "t").unwrap();
        p.replace_deck(smaller, vec![]).unwrap();
        assert_eq!(p.position(), (0, 0));
    }

    /// A provider with per-block consent, like the native PtyProvider.
    #[derive(Default)]
    struct GatedTerms {
        approved: std::collections::HashSet<usize>,
        stopped: Vec<usize>,
    }
    impl TerminalProvider for GatedTerms {
        fn prepare(&mut self, _: &TermBlock, _: u16, _: u16) {}
        fn state(&self, block: &TermBlock) -> TermState {
            if self.approved.contains(&block.id) {
                TermState::Running {
                    scroll_offset: 0,
                    scroll_total: 0,
                }
            } else {
                TermState::Disabled
            }
        }
        fn draw(&mut self, _: &TermBlock, _: Rect, _: &mut Buffer) {}
        fn input(&mut self, _: usize, _: &[u8]) {}
        fn scroll(&mut self, _: usize, _: isize) {}
        fn restart(&mut self, _: &[usize]) {}
        fn enable(&mut self, id: usize) {
            self.approved.insert(id);
        }
        fn stop(&mut self, id: usize) {
            self.approved.remove(&id);
            self.stopped.push(id);
        }
    }

    #[test]
    fn disabled_terminals_need_in_deck_confirmation() {
        let deck = crate::deck::parse("```terminal\nhtop\n```\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], GatedTerms::default()).unwrap();

        // t arms the confirmation but runs nothing.
        p.on_key(KeyPress::plain(Key::Char('t')));
        assert_eq!(p.focus, None);
        assert!(p.provider.approved.is_empty());

        // y approves and focuses.
        p.on_key(KeyPress::plain(Key::Char('y')));
        assert!(p.provider.approved.contains(&0));
        assert_eq!(p.focus, Some(0));
    }

    #[test]
    fn any_other_key_cancels_the_confirmation() {
        let deck = crate::deck::parse("```terminal\nhtop\n```\n---\n# b\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], GatedTerms::default()).unwrap();

        p.on_key(KeyPress::plain(Key::Char('t')));
        // Space cancels — and still navigates.
        p.on_key(KeyPress::plain(Key::Char(' ')));
        assert!(p.provider.approved.is_empty());
        assert_eq!(p.position(), (1, 0));
        // A later y is just an inert key, not an approval.
        p.on_key(KeyPress::plain(Key::Char('y')));
        assert!(p.provider.approved.is_empty());
    }

    #[test]
    fn stop_withdraws_approval() {
        let deck = crate::deck::parse("```terminal\nhtop\n```\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], GatedTerms::default()).unwrap();
        p.on_key(KeyPress::plain(Key::Char('t')));
        p.on_key(KeyPress::plain(Key::Char('y')));
        assert_eq!(p.focus, Some(0));

        p.on_key(KeyPress {
            ctrl: true,
            ..KeyPress::plain(Key::Char('q'))
        });
        p.on_key(KeyPress::plain(Key::Char('s')));
        assert_eq!(p.provider.stopped, vec![0]);
        assert_eq!(p.focus, None);
        // Back to Disabled: running again requires re-confirmation.
        p.on_key(KeyPress::plain(Key::Char('t')));
        assert_eq!(p.focus, None);
    }

    #[test]
    fn replace_deck_resets_terminals_only_when_they_change() {
        let deck = crate::deck::parse("```terminal\nhtop\n```\n", "t").unwrap();
        let mut p = Presenter::new(deck, vec![], FakeTerms { resets: 0 }).unwrap();
        p.on_key(KeyPress::plain(Key::Char('t')));
        assert_eq!(p.focus, Some(0));

        // Markdown-only edit: terminals identical → focus and sessions live on.
        let same_terms = crate::deck::parse("new words\n```terminal\nhtop\n```\n", "t").unwrap();
        p.replace_deck(same_terms, vec![]).unwrap();
        assert_eq!(p.provider.resets, 0);
        assert_eq!(p.focus, Some(0));

        // Command changed: provider resets, focus drops.
        let changed = crate::deck::parse("```terminal\nbtop\n```\n", "t").unwrap();
        p.replace_deck(changed, vec![]).unwrap();
        assert_eq!(p.provider.resets, 1);
        assert_eq!(p.focus, None);
    }

    #[test]
    fn draws_without_panicking() {
        let mut p = presenter();
        let area = Rect::new(0, 0, 80, 24);
        let mut buf = Buffer::empty(area);
        p.draw(area, &mut buf);
        p.on_key(KeyPress::plain(Key::Char('o')));
        p.draw(area, &mut buf);
        p.on_key(KeyPress::plain(Key::Char('?')));
        p.draw(area, &mut buf);
    }
}