quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
//! `Dialog` primitive: a modal message box with a title, body, and
//! action buttons. Used for confirmations, error reports, and anything
//! else that needs the user to acknowledge or choose before continuing.
//!
//! A `Dialog` is a modal overlay with a fixed layout: title row + body
//! text + bottom-right-aligned button row. Backends render it as a
//! centered overlay box; modal-vs-base hit precedence is arbitrated by
//! [`crate::ModalStack`], not by this primitive.
//!
//! # Backend contract
//!
//! **Modal overlay — intercept all clicks.** Clicks outside the dialog
//! either dismiss (emit `Cancelled`) or are swallowed — app policy.
//! Click on a button emits `ButtonClicked { id }`. Enter activates the
//! default button (the first whose `is_default = true`); Escape emits
//! `Cancelled` unconditionally.
//!
//! # Two-way reference with `backend.rs`
//!
//! [`native_dialog_options`] imports [`MessageDialogButton`] and
//! [`MessageDialogOptions`] from `crate::backend` — the first import
//! from `crate::backend` in `src/primitives/`. `backend.rs` imports
//! [`Dialog`] and [`DialogSeverity`] from here, creating a two-way
//! reference between the files. This inverts the one-directional
//! primitives→backend layering but stays within `ARCHITECTURE.md`'s
//! rules: [`MessageDialogOptions`] is a plain data type, not a backend
//! crate type, and serves as the mapping from `Dialog` descriptor to
//! native options — a pure function, unit-testable with no live surface.

use crate::backend::{MessageDialogButton, MessageDialogOptions};
use crate::event::Rect;
use crate::primitives::layout_metrics::TextMeasure;
use crate::primitives::toolbar::{Toolbar, ToolbarHit, ToolbarItemMeasure, ToolbarLayout};
use crate::types::{Color, StyledText, WidgetId};
use serde::{Deserialize, Serialize};

/// A 2-D data table embedded inside a [`Dialog`] body.
///
/// Rendered between the body text lines and the [`DialogInput`] slot.
/// Columns are separated by ` │ `. When `headers` is `Some`, a header row
/// is drawn above a `─┼─` separator row.
///
/// # Column widths
///
/// `column_widths` is an optional explicit hint (in *character cells* for TUI,
/// in *pixels* for pixel backends). When `None` every backend auto-sizes each
/// column to fit its widest cell.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DialogTable {
    /// Optional column header labels.
    pub headers: Option<Vec<String>>,
    /// Data rows; each row is a `Vec` of cell strings, one per column.
    pub rows: Vec<Vec<String>>,
    /// Explicit column widths (TUI: char cells; pixel backends: pixels).
    /// `None` → auto-size.
    #[serde(default)]
    pub column_widths: Option<Vec<u16>>,
}

impl DialogTable {
    /// Number of columns derived from the widest row / header.
    pub fn num_cols(&self) -> usize {
        let from_rows = self.rows.iter().map(|r| r.len()).max().unwrap_or(0);
        let from_headers = self.headers.as_ref().map(|h| h.len()).unwrap_or(0);
        from_rows.max(from_headers)
    }

    /// Auto-compute column char-widths from content (TUI helper).
    ///
    /// Returns a `Vec` of length [`Self::num_cols`]; each entry is the
    /// maximum character count seen in that column across headers + rows.
    /// If `column_widths` is `Some`, those values are used as a *minimum*
    /// (content may still be wider).
    pub fn auto_col_widths(&self) -> Vec<usize> {
        let ncols = self.num_cols();
        let mut widths = vec![0usize; ncols];

        if let Some(explicit) = &self.column_widths {
            for (j, &w) in explicit.iter().enumerate() {
                if j < ncols {
                    widths[j] = w as usize;
                }
            }
        }

        if let Some(headers) = &self.headers {
            for (j, h) in headers.iter().enumerate() {
                if j < ncols {
                    widths[j] = widths[j].max(h.chars().count());
                }
            }
        }
        for row in &self.rows {
            for (j, cell) in row.iter().enumerate() {
                if j < ncols {
                    widths[j] = widths[j].max(cell.chars().count());
                }
            }
        }
        widths
    }

    /// Total rendered width in character cells (TUI).
    ///
    /// Columns are separated by ` │ ` (3 chars). Returns 0 when there are no
    /// columns.
    pub fn tui_total_width(&self) -> usize {
        let col_widths = self.auto_col_widths();
        if col_widths.is_empty() {
            return 0;
        }
        let sum: usize = col_widths.iter().sum();
        sum + 3 * col_widths.len().saturating_sub(1)
    }

    /// Total height in TUI rows: data rows + header row + separator row (when
    /// headers present).
    pub fn tui_total_height(&self) -> usize {
        let header_rows = if self.headers.is_some() { 2 } else { 0 };
        header_rows + self.rows.len()
    }
}

/// Declarative description of a dialog.
///
/// # Examples
///
/// ```
/// use quadraui::{
///     Dialog, DialogButton, DialogHit, DialogMeasure, Rect, StyledText, ToolbarItemMeasure,
///     WidgetId,
/// };
///
/// let dialog = Dialog {
///     id: WidgetId::new("dialog:confirm_close"),
///     title: StyledText::plain("Unsaved changes"),
///     body: vec![StyledText::plain("Close without saving?")],
///     buttons: vec![DialogButton {
///         id: WidgetId::new("dialog:ok"),
///         label: "OK".to_string(),
///         is_default: true,
///         is_cancel: false,
///         tint: None,
///     }],
///     severity: None,
///     vertical_buttons: false,
///     table: None,
///     input: None,
/// };
///
/// let measure = DialogMeasure {
///     width: 40.0,
///     title_height: 1.0,
///     body_height: 1.0,
///     table_height: 0.0,
///     input_height: 0.0,
///     button_row_height: 1.0,
///     button_width: 10.0,
///     button_gap: 1.0,
///     padding: 1.0,
/// };
///
/// let viewport = Rect::new(0.0, 0.0, 80.0, 24.0);
/// // `input` is `None` above, so `layout` never calls this closure — it's
/// // only reached by the `DialogInput::Toolbar` body variant.
/// let layout = dialog.layout(viewport, measure, |_| ToolbarItemMeasure::new(10.0));
/// let ok = layout.visible_buttons[0].bounds;
/// assert_eq!(layout.hit_test(ok.x, ok.y), DialogHit::Button(dialog.buttons[0].id.clone()));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Dialog {
    pub id: WidgetId,
    pub title: StyledText,
    /// Body content lines. Each entry is one line rendered top-to-bottom.
    /// Supports per-line styled spans for keybinding references, help
    /// text, and other multi-line content.
    pub body: Vec<StyledText>,
    pub buttons: Vec<DialogButton>,
    /// Optional severity tint — backends may add an icon or edge
    /// accent. `None` = neutral.
    #[serde(default)]
    pub severity: Option<DialogSeverity>,
    /// When true, buttons are stacked vertically (useful for narrow
    /// dialogs or many-choice dialogs like code-action pickers). When
    /// false, buttons are horizontal, right-aligned.
    #[serde(default)]
    pub vertical_buttons: bool,
    /// Optional structured table rendered between the body text and the
    /// [`DialogInput`] slot. Used for keybindings grids, comparison
    /// tables, etc.
    ///
    /// Layout order: title → body → **table** → input → buttons.
    #[serde(default)]
    pub table: Option<DialogTable>,
    /// Optional content rendered between the table and the button row.
    ///
    /// - [`DialogInput::TextInput`] — single-line text field; used for
    ///   rename prompts, input-required confirms.
    /// - [`DialogInput::Toolbar`] — horizontal action strip; used when
    ///   the dialog wants an inline action bar (e.g. "Preview / Skip /
    ///   Apply") in addition to the modal OK/Cancel buttons.
    ///
    /// Apps own the value; interactions resolve via [`DialogLayout::hit_test`]
    /// / [`DialogHit`].
    #[serde(default)]
    pub input: Option<DialogInput>,
}

/// Content of the slot rendered between the body text and the button row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DialogInput {
    /// Single-line text field (rename prompts, input-required confirms).
    TextInput(DialogTextInput),
    /// Inline horizontal action strip. Backends render this by calling their
    /// `draw_toolbar` equivalent inside the body slot. Clicks resolve as
    /// [`DialogHit::BodyToolbarButton`].
    Toolbar(Toolbar),
}

/// Single-line text input embedded in a dialog body slot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DialogTextInput {
    /// Current input value.
    pub value: String,
    /// Placeholder text shown when `value` is empty.
    #[serde(default)]
    pub placeholder: String,
    /// Cursor byte offset. `None` renders the input without a cursor.
    #[serde(default)]
    pub cursor: Option<usize>,
}

/// Severity of a `Dialog`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DialogSeverity {
    Info,
    Question,
    Warning,
    Error,
}

/// One button on a dialog.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DialogButton {
    pub id: WidgetId,
    pub label: String,
    /// When true, Enter activates this button (and backends typically
    /// style it as the primary). Only one button should be default;
    /// if multiple, the first wins.
    #[serde(default)]
    pub is_default: bool,
    /// When true, Escape activates this button (cancel-button
    /// convention). Only one button should have this.
    #[serde(default)]
    pub is_cancel: bool,
    /// Override colour for destructive actions ("Delete", "Discard").
    /// `None` = theme default.
    #[serde(default)]
    pub tint: Option<Color>,
}

// ── D6 Layout API ───────────────────────────────────────────────────────────

/// Measurements for dialog sub-regions.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DialogMeasure {
    /// Full dialog box width.
    pub width: f32,
    /// Height reserved for the title row (may be 0 if title is empty).
    pub title_height: f32,
    /// Height of the body content.
    pub body_height: f32,
    /// Height reserved for the table slot (0 when `dialog.table` is `None`).
    /// Set by the backend to `row_count * row_height` (including header +
    /// separator rows when headers are present).
    pub table_height: f32,
    /// Height reserved for the input row (0 when dialog has no input).
    pub input_height: f32,
    /// Height reserved for the button row.
    pub button_row_height: f32,
    /// Width of each button (uniform, for simplicity).
    pub button_width: f32,
    /// Horizontal gap between buttons.
    pub button_gap: f32,
    /// Padding inside the dialog (between content and box edges).
    pub padding: f32,
}

impl DialogMeasure {
    pub fn total_height(&self) -> f32 {
        self.title_height
            + self.body_height
            + self.table_height
            + self.input_height
            + self.button_row_height
            + self.padding * 2.0
    }
}

/// Resolved position of one button.
#[derive(Debug, Clone, PartialEq)]
pub struct VisibleDialogButton {
    pub button_idx: usize,
    pub id: WidgetId,
    pub bounds: Rect,
}

/// Classification of a hit-test result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DialogHit {
    /// Click landed on a button.
    Button(WidgetId),
    /// Click landed on an enabled action button inside the body toolbar
    /// ([`DialogInput::Toolbar`]).
    BodyToolbarButton(WidgetId),
    /// Click landed on the dialog box (not a button) — apps typically
    /// swallow this so it doesn't dismiss.
    Body,
    /// Click landed outside the dialog box — apps may dismiss on this.
    Outside,
}

/// Fully-resolved dialog layout.
#[derive(Debug, Clone, PartialEq)]
pub struct DialogLayout {
    /// Full dialog box bounds.
    pub bounds: Rect,
    /// Title row bounds (if `measure.title_height > 0`).
    pub title_bounds: Option<Rect>,
    /// Body content bounds.
    pub body_bounds: Rect,
    /// Bounds of the table slot when `dialog.table` is `Some` and
    /// `measure.table_height > 0`. Rasterisers render the table inside
    /// this rectangle.
    pub table_bounds: Option<Rect>,
    /// Bounds of the input slot (text input or toolbar), when present
    /// and `measure.input_height > 0`. Rasterisers use this to position
    /// whichever kind of input the dialog carries.
    pub input_bounds: Option<Rect>,
    /// Pre-computed [`ToolbarLayout`] for the body-slot toolbar, when
    /// the dialog carries a [`DialogInput::Toolbar`]. `None` for all
    /// other input kinds. Rasterisers use this to paint the toolbar
    /// and route click events.
    pub body_toolbar_layout: Option<ToolbarLayout>,
    /// Button row bounds.
    pub button_row_bounds: Rect,
    pub visible_buttons: Vec<VisibleDialogButton>,
    pub hit_regions: Vec<(Rect, DialogHit)>,
}

impl DialogLayout {
    pub fn hit_test(&self, x: f32, y: f32) -> DialogHit {
        let inside = x >= self.bounds.x
            && x < self.bounds.x + self.bounds.width
            && y >= self.bounds.y
            && y < self.bounds.y + self.bounds.height;
        if !inside {
            return DialogHit::Outside;
        }
        // Check toolbar hit regions first (finer-grained than the body
        // slot bounding box in `hit_regions`).
        if let Some(ref tl) = self.body_toolbar_layout {
            match tl.hit_test(x, y) {
                ToolbarHit::Button(id) => return DialogHit::BodyToolbarButton(id),
                ToolbarHit::Empty => {}
            }
        }
        for (rect, hit) in &self.hit_regions {
            if x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height {
                return hit.clone();
            }
        }
        DialogHit::Body
    }
}

impl Dialog {
    /// Compute dialog layout.
    ///
    /// # Arguments
    ///
    /// - `viewport` — parent surface bounds; the dialog is centered
    ///   within this.
    /// - `measure` — sub-region widths/heights. Backends measure the
    ///   body text (wrapping to `measure.width`) and set
    ///   `body_height` accordingly; ditto for title and buttons.
    ///   `input_height` is used for both the text-input and toolbar
    ///   variants — set it to the desired slot height regardless of
    ///   which [`DialogInput`] kind is present.
    /// - `measure_toolbar_item` — per-item width callback for the
    ///   toolbar variant. When `self.input` is not
    ///   [`DialogInput::Toolbar`], this callback is never called and
    ///   may be `|_| ToolbarItemMeasure::new(0.0)`.
    ///
    /// # Centering
    ///
    /// The dialog box is placed at the viewport's horizontal + vertical
    /// center. Button row is at the bottom of the box, right-aligned
    /// (horizontal) or stretched (vertical).
    pub fn layout<F>(
        &self,
        viewport: Rect,
        measure: DialogMeasure,
        measure_toolbar_item: F,
    ) -> DialogLayout
    where
        F: Fn(&crate::primitives::toolbar::ToolbarButton) -> ToolbarItemMeasure,
    {
        // A vertical button stack reserves one row per button; total_height()
        // budgets only a single button row, so swap in the full block height.
        let button_block_h = if self.vertical_buttons {
            measure.button_row_height * self.buttons.len().max(1) as f32
        } else {
            measure.button_row_height
        };
        let total_h = measure.total_height() - measure.button_row_height + button_block_h;
        let box_x = viewport.x + (viewport.width - measure.width) * 0.5;
        let box_y = viewport.y + (viewport.height - total_h) * 0.5;
        let bounds = Rect::new(box_x, box_y, measure.width, total_h);

        let content_x = box_x + measure.padding;
        let content_w = (measure.width - measure.padding * 2.0).max(0.0);
        let mut cursor_y = box_y + measure.padding;

        let title_bounds = if measure.title_height > 0.0 {
            let b = Rect::new(content_x, cursor_y, content_w, measure.title_height);
            cursor_y += measure.title_height;
            Some(b)
        } else {
            None
        };

        let body_bounds = Rect::new(content_x, cursor_y, content_w, measure.body_height);
        cursor_y += measure.body_height;

        let table_bounds = if self.table.is_some() && measure.table_height > 0.0 {
            let b = Rect::new(content_x, cursor_y, content_w, measure.table_height);
            cursor_y += measure.table_height;
            Some(b)
        } else {
            None
        };

        let (input_bounds, body_toolbar_layout) =
            if self.input.is_some() && measure.input_height > 0.0 {
                let b = Rect::new(content_x, cursor_y, content_w, measure.input_height);
                cursor_y += measure.input_height;

                let tl = match &self.input {
                    Some(DialogInput::Toolbar(toolbar)) => {
                        Some(toolbar.layout(b.x, b.y, b.width, b.height, &measure_toolbar_item))
                    }
                    _ => None,
                };
                (Some(b), tl)
            } else {
                (None, None)
            };

        let button_row_bounds = Rect::new(content_x, cursor_y, content_w, button_block_h);

        let mut visible_buttons: Vec<VisibleDialogButton> = Vec::new();
        let mut hit_regions: Vec<(Rect, DialogHit)> = Vec::new();

        if self.vertical_buttons {
            // Stack vertically, one full row per button, full content width,
            // starting at the button-row origin and growing downward.
            let btn_h = measure.button_row_height;
            for (i, btn) in self.buttons.iter().enumerate() {
                let y = cursor_y + (i as f32) * btn_h;
                let b = Rect::new(content_x, y, content_w, btn_h);
                visible_buttons.push(VisibleDialogButton {
                    button_idx: i,
                    id: btn.id,
                    bounds: b,
                });
                hit_regions.push((b, DialogHit::Button(btn.id)));
            }
        } else {
            // Right-aligned horizontal row.
            let total_btns_w = self.buttons.len() as f32 * measure.button_width
                + (self.buttons.len().saturating_sub(1)) as f32 * measure.button_gap;
            let start_x = content_x + content_w - total_btns_w;
            for (i, btn) in self.buttons.iter().enumerate() {
                let x = start_x + (i as f32) * (measure.button_width + measure.button_gap);
                let b = Rect::new(x, cursor_y, measure.button_width, measure.button_row_height);
                visible_buttons.push(VisibleDialogButton {
                    button_idx: i,
                    id: btn.id,
                    bounds: b,
                });
                hit_regions.push((b, DialogHit::Button(btn.id)));
            }
        }

        DialogLayout {
            bounds,
            title_bounds,
            body_bounds,
            table_bounds,
            input_bounds,
            body_toolbar_layout,
            button_row_bounds,
            visible_buttons,
            hit_regions,
        }
    }

    /// Convenience: find the default button's id (first with
    /// `is_default = true`, or the last button as a fallback).
    pub fn default_button_id(&self) -> Option<&WidgetId> {
        self.buttons
            .iter()
            .find(|b| b.is_default)
            .map(|b| &b.id)
            .or_else(|| self.buttons.last().map(|b| &b.id))
    }

    /// Convenience: find the cancel button's id (first with
    /// `is_cancel = true`).
    pub fn cancel_button_id(&self) -> Option<&WidgetId> {
        self.buttons.iter().find(|b| b.is_cancel).map(|b| &b.id)
    }

    /// Derive a [`DialogMeasure`] from `char_width` and `line_height`
    /// without real text measurement. This is the char-cell approximation
    /// used where `char_width == line_height == 1.0` on TUI (one character
    /// cell) and the backend's real glyph metrics on pixel backends.
    ///
    /// `border_chrome_inset` optionally shrinks the resulting `width` to
    /// leave room for a border the rasteriser draws *outside*
    /// [`DialogLayout::bounds`] rather than inside it — e.g. a TUI backend
    /// whose box-drawing glyphs live one cell past the content box, the
    /// same convention `tui::context_menu::draw_context_menu` (behind the
    /// `tui` feature) already uses for `ContextMenu`. Pass `0.0` when the
    /// border is painted *inside* the returned bounds — this crate's own
    /// `tui::dialog::draw_dialog` and every pixel backend do this.
    ///
    /// Does not measure [`Self::table`] or [`Self::buttons`]' rendered pixel
    /// width beyond the char-cell approximation above; callers with real
    /// text measurement available should prefer [`Self::measure_generic_measured`].
    pub fn measure_generic(
        &self,
        char_width: f32,
        line_height: f32,
        viewport: Rect,
        border_chrome_inset: f32,
    ) -> DialogMeasure {
        self.measure_generic_inner(char_width, line_height, viewport, border_chrome_inset, None)
    }

    /// Like [`Self::measure_generic`], but sizes [`DialogMeasure::button_width`]
    /// from each [`DialogButton::label`]'s real rendered width through
    /// `measure` instead of the fixed `char_width * 8.0` estimate — the
    /// widest button sets a uniform width for the row (`button_width` is
    /// shared by every button; see [`DialogMeasure::button_width`]'s doc),
    /// plus 2 char-widths of horizontal padding, floored at the original
    /// `char_width * 8.0` so a row of short labels ("OK" / "No") doesn't
    /// shrink below what every existing caller of [`Self::measure_generic`]
    /// already renders.
    ///
    /// Every other field is identical to [`Self::measure_generic`] — only
    /// the button row's width changes.
    pub fn measure_generic_measured(
        &self,
        char_width: f32,
        line_height: f32,
        viewport: Rect,
        border_chrome_inset: f32,
        measure: &dyn TextMeasure,
    ) -> DialogMeasure {
        self.measure_generic_inner(
            char_width,
            line_height,
            viewport,
            border_chrome_inset,
            Some(measure),
        )
    }

    fn measure_generic_inner(
        &self,
        char_width: f32,
        line_height: f32,
        viewport: Rect,
        border_chrome_inset: f32,
        measure: Option<&dyn TextMeasure>,
    ) -> DialogMeasure {
        let table = self.table.as_ref();
        let table_total_h = table
            .map(|t| t.tui_total_height() as f32 * line_height)
            .unwrap_or(0.0);
        // Preferred table width: char cells × char_width + 2 char-widths
        // of padding.
        let table_preferred_w = table
            .map(|t| t.tui_total_width() as f32 * char_width + char_width * 2.0)
            .unwrap_or(0.0);

        let title_h = if self.title.spans.iter().any(|s| !s.text.is_empty()) {
            line_height
        } else {
            0.0
        };
        let body_h = self.body.len() as f32 * line_height;
        let input_h = if self.input.is_some() {
            line_height
        } else {
            0.0
        };

        let min_w = char_width * 30.0; // ≈ 30 char-widths
        let max_w = char_width * 60.0; // ≈ 60 char-widths
        let default_w = (viewport.width * 0.5).clamp(min_w, max_w);
        let dialog_w = default_w
            .max(table_preferred_w)
            .min(viewport.width - char_width * 4.0 - border_chrome_inset * 2.0);

        let estimated_button_w = char_width * 8.0;
        let button_width = match measure {
            Some(m) => self
                .buttons
                .iter()
                .map(|b| m.width_of(&b.label) + char_width * 2.0)
                .fold(estimated_button_w, f32::max),
            None => estimated_button_w,
        };

        DialogMeasure {
            width: dialog_w,
            title_height: title_h,
            body_height: body_h,
            table_height: table_total_h,
            input_height: input_h,
            button_row_height: line_height,
            button_width,
            button_gap: char_width * 2.0,
            padding: line_height,
        }
    }
}

/// Flatten a [`StyledText`] to plain text. Native alert facilities carry
/// no per-span styling, so this discards it the same way `gtk::dialog`
/// and `tui::dialog`'s private `flatten` helpers do for the in-canvas
/// rasterisers.
fn flatten(text: &StyledText) -> String {
    text.spans.iter().map(|s| s.text.as_str()).collect()
}

/// Map a [`Dialog`] descriptor to the options
/// [`crate::backend::PlatformServices::show_message_dialog`] needs, or
/// `None` when `d` is not natively expressible.
///
/// Not natively expressible today: `d.table.is_some() || d.input.is_some()`
/// — no native alert facility hosts a table or a text field, so callers
/// must fall back to `draw_dialog` (the in-canvas primitive) for those.
/// This decision lives here, as a pure function of the descriptor, so
/// callers never grow their own hand-written list of "which dialogs can
/// go native" — the same reasoning behind keeping `gtk::minimap::render_mode`
/// pure and unit-testable with no live surface.
///
/// `DialogButton::tint` has no equivalent in [`MessageDialogButton`] (no
/// native alert facility exposes per-button colour) and is silently
/// dropped — every other field maps straight across.
///
/// `d.buttons` is passed through as-is, including when empty — this
/// function does not enforce "a dialog must declare at least one
/// button". Every native alert facility (GTK's `AlertDialog`, macOS's
/// `NSAlert`, Win32's `MessageBoxEx`) expects at least one, so a caller
/// building a `Dialog` for native display should always populate
/// `buttons`; `Dialog`'s own doc doesn't currently state that invariant
/// either.
pub fn native_dialog_options(d: &Dialog) -> Option<MessageDialogOptions> {
    if d.table.is_some() || d.input.is_some() {
        return None;
    }
    Some(MessageDialogOptions {
        title: flatten(&d.title),
        body: d.body.iter().map(flatten).collect::<Vec<_>>().join("\n"),
        buttons: d
            .buttons
            .iter()
            .map(|b| MessageDialogButton {
                id: b.id,
                label: b.label.clone(),
                is_default: b.is_default,
                is_cancel: b.is_cancel,
            })
            .collect(),
        severity: d.severity,
    })
}

// PaintSurface Phase 4: shared paint implementation written against
// [`crate::paint_surface::PaintSurface`] instead of any one backend's
// API. Pre-migration per-backend implementations had substantive drift,
// resolved by picking one implementation and documenting divergences:
//
// - **Font role.** The whole primitive is classified as chrome — one font
//   for the entire box. Pre-migration, only macOS did this; GTK swapped
//   fonts mid-paint (title/buttons in chrome, body/table/input in editor
//   monospace), and Windows used only the editor font. `paint` takes a
//   single `surface` already constructed against the chrome font by its
//   caller, so the whole dialog now renders in chrome everywhere.
//   `DialogInput::Toolbar` is the exception: `paint` does not render it.
// - **Per-button border stroke.** Windows alone stroked `theme.border_fg`
//   around every button; GTK/macOS filled the default button's
//   selected-bg but never stroked a border. `paint` strokes every button.
// - **`DialogButton::tint`.** Override colour for destructive actions.
//   Windows was the only backend that read it; GTK/macOS always painted
//   labels in `theme.surface_fg`. `paint` reads tint on every backend.
// - **Button label vertical centring.** GTK/macOS centre each label;
//   Windows left labels at the top. `paint` centres on every backend.
// - **`DialogTextInput` vertical centring.** Same drift: GTK/macOS
//   centred display text; Windows passed the box's full height uncentred.
// - **`DialogTable` explicit `column_widths`.** GTK/macOS honour widths
//   as per-column minimum; Windows never read the field.
// - **`DialogTable` header-separator dash count.** GTK/macOS divide by
//   approximate char width; Windows divided by plain `line_height`,
//   causing the separator row to undershoot actual content width.
//
// `DialogInput::Toolbar` is not painted by `paint` — it still renders
// through each backend's own `super::toolbar::draw_toolbar` (GTK/macOS)
// or inline Direct2D code (Windows), called by the wrapper after `paint`
// returns. Porting the toolbar rasteriser onto `PaintSurface` is a
// separate future change. This skips nothing a caller observes: every
// backend's `dialog_layout.input_bounds` position is unaffected.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(dead_code)]
pub(crate) mod native_surface_paint {
    use super::{Dialog, DialogInput, DialogLayout, DialogTable};
    use crate::paint_surface::PaintSurface;
    use crate::style::Style;
    use crate::theme::Theme;
    use crate::types::Color;
    use crate::{Point, Rect};

    /// Approximate monospace character width ratio: converts
    /// [`DialogTable::column_widths`] char-cell hints to pixels.
    const APPROX_CHAR_WIDTH_RATIO: f32 = 0.6;

    /// Horizontal gap reserved between two columns for the 1px separator
    /// line drawn through its middle — replaces the ` │ ` text-run
    /// separator with a drawn rule on GUI backends; the TUI painter is
    /// untouched and keeps drawing the glyph.
    const COLUMN_SEP_GAP: f32 = 16.0;

    /// Paint a [`DialogTable`] at `(bounds.x, bounds.y)`, top-left
    /// anchored. Column widths are auto-computed from content via
    /// [`PaintSurface::surface_measure_text`], honouring
    /// `table.column_widths` as a per-column minimum. A header row
    /// (when present) is followed by a drawn 1px rule — no `┼`
    /// junction, matching every backend's pre-migration simplification.
    /// Column separators and the header rule are drawn as 1px lines
    /// rather than the ` │ ` / `─` glyphs the TUI painter still emits —
    /// those glyphs read as terminal affordances on a pixel canvas.
    fn draw_table(
        surface: &mut dyn PaintSurface,
        table: &DialogTable,
        bounds: Rect,
        line_height: f32,
        fg: crate::Color,
        border: crate::Color,
    ) {
        let ncols = table.num_cols();
        if ncols == 0 {
            return;
        }

        let measure_w = |surface: &dyn PaintSurface, s: &str| surface.surface_measure_text(s).0;

        let mut col_w = vec![0.0f32; ncols];
        if let Some(headers) = &table.headers {
            for (j, h) in headers.iter().enumerate().take(ncols) {
                col_w[j] = col_w[j].max(measure_w(surface, h));
            }
        }
        for row in &table.rows {
            for (j, cell) in row.iter().enumerate().take(ncols) {
                col_w[j] = col_w[j].max(measure_w(surface, cell));
            }
        }

        if let Some(explicit) = &table.column_widths {
            for (j, &w) in explicit.iter().enumerate() {
                if j < ncols {
                    let px = w as f32 * (line_height * APPROX_CHAR_WIDTH_RATIO);
                    col_w[j] = col_w[j].max(px);
                }
            }
        }

        let mut col_x = vec![0.0f32; ncols];
        let mut cursor_x = bounds.x;
        for j in 0..ncols {
            col_x[j] = cursor_x;
            cursor_x += col_w[j];
            if j + 1 < ncols {
                cursor_x += COLUMN_SEP_GAP;
            }
        }

        let mut row_y = bounds.y;
        let row_rect = |x: f32, y: f32, w: f32| Rect::new(x, y, w.max(1.0), line_height);
        let draw_col_separators = |surface: &mut dyn PaintSurface, row_y: f32| {
            for j in 0..ncols.saturating_sub(1) {
                let sep_x = col_x[j] + col_w[j] + COLUMN_SEP_GAP / 2.0;
                surface.surface_draw_line(
                    Point::new(sep_x, row_y + 1.0),
                    Point::new(sep_x, row_y + line_height - 1.0),
                    border,
                    1.0,
                );
            }
        };

        if let Some(headers) = &table.headers {
            for (j, h) in headers.iter().enumerate().take(ncols) {
                surface.surface_draw_text_run(row_rect(col_x[j], row_y, col_w[j]), h, fg);
            }
            draw_col_separators(surface, row_y);
            row_y += line_height;

            let total_w = col_x[ncols - 1] + col_w[ncols - 1] - bounds.x;
            let rule_y = row_y + line_height / 2.0;
            surface.surface_draw_line(
                Point::new(bounds.x, rule_y),
                Point::new(bounds.x + total_w, rule_y),
                border,
                1.0,
            );
            row_y += line_height;
        }

        for row in &table.rows {
            for (j, cell) in row.iter().enumerate().take(ncols) {
                surface.surface_draw_text_run(row_rect(col_x[j], row_y, col_w[j]), cell, fg);
            }
            draw_col_separators(surface, row_y);
            row_y += line_height;
        }
    }

    /// Paint a [`Dialog`] at its resolved `dialog_layout` onto `surface`
    /// — background, border, title, body, optional table, optional
    /// [`DialogInput::TextInput`] slot, and buttons (selected-bg fill +
    /// border stroke + tint-aware label). Returns the per-button hit
    /// rectangles in `dialog_layout.visible_buttons` order, matching
    /// [`crate::Backend::draw_dialog`]'s contract.
    ///
    /// `surface` must already be constructed against the **chrome**
    /// font — see this module's doc for why the whole dialog paints in
    /// one font now. `DialogInput::Toolbar` is deliberately not painted
    /// here; see the module doc. `style` supplies the
    /// corner radius/border width/shadow elevation the box paints with
    /// — callers pass `&self.style()`.
    pub(crate) fn paint(
        dialog: &Dialog,
        dialog_layout: &DialogLayout,
        line_height: f32,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        style: &Style,
    ) -> Vec<Rect> {
        let bounds = dialog_layout.bounds;
        if bounds.width <= 0.0 || bounds.height <= 0.0 {
            return Vec::new();
        }

        // Modal dialogs get the heaviest shadow elevation of the
        // overlays this issue wires up — matching VS Code's own modal
        // tier.
        surface.surface_draw_shadow(
            bounds,
            style.corner_radius,
            style.shadow_elevation.max(3),
            Color::rgba(0, 0, 0, 120),
        );
        surface.surface_fill_rounded_rect(bounds, style.corner_radius, theme.surface_bg);
        surface.surface_stroke_rounded_rect(
            bounds,
            style.corner_radius,
            theme.border_fg,
            style.border_width,
        );

        if let Some(title_rect) = dialog_layout.title_bounds {
            surface.surface_draw_text_run(
                title_rect,
                &super::flatten(&dialog.title),
                theme.title_fg,
            );
        }

        let body_b = dialog_layout.body_bounds;
        for (i, line) in dialog.body.iter().enumerate() {
            let row_y = body_b.y + i as f32 * line_height;
            if row_y + line_height > body_b.y + body_b.height {
                break;
            }
            let row_rect = Rect::new(body_b.x, row_y, body_b.width, line_height);
            surface.surface_draw_text_run(row_rect, &super::flatten(line), theme.surface_fg);
        }

        if let (Some(table_b), Some(table)) = (dialog_layout.table_bounds, dialog.table.as_ref()) {
            draw_table(
                surface,
                table,
                table_b,
                line_height,
                theme.surface_fg,
                theme.border_fg,
            );
        }

        if let (Some(input_b), Some(DialogInput::TextInput(input))) =
            (dialog_layout.input_bounds, dialog.input.as_ref())
        {
            surface.surface_fill_rect(input_b, theme.input_bg);
            surface.surface_stroke_rect(input_b, theme.border_fg, 1.0);
            let display = if input.value.is_empty() {
                format!(" {}", input.placeholder)
            } else {
                format!(" {}", input.value)
            };
            let (_, ih) = surface.surface_measure_text(&display);
            let text_rect = Rect::new(
                input_b.x + 2.0,
                input_b.y + (input_b.height - ih) / 2.0,
                (input_b.width - 2.0).max(0.0),
                ih.max(1.0),
            );
            surface.surface_draw_text_run(text_rect, &display, theme.surface_fg);
        }
        // DialogInput::Toolbar is intentionally not painted here — see
        // this module's doc.

        let mut rects = Vec::with_capacity(dialog_layout.visible_buttons.len());
        for vis in &dialog_layout.visible_buttons {
            let btn = &dialog.buttons[vis.button_idx];
            rects.push(vis.bounds);

            if btn.is_default {
                surface.surface_fill_rect(vis.bounds, theme.selected_bg);
            }
            surface.surface_stroke_rect(vis.bounds, theme.border_fg, 1.0);

            // The default button's style (selected_bg fill + border) is
            // the marker on GUI — no leading glyph needed (the TUI
            // painter still prefixes "▸ " since it has no fill
            // affordance to lean on).
            let label = btn.label.clone();
            let label_fg = btn.tint.unwrap_or(theme.surface_fg);
            let (lw, lh) = surface.surface_measure_text(&label);
            let label_x = if dialog.vertical_buttons {
                vis.bounds.x + 8.0
            } else {
                vis.bounds.x + (vis.bounds.width - lw) / 2.0
            };
            let label_y = vis.bounds.y + (vis.bounds.height - lh) / 2.0;
            surface.surface_draw_text_run(
                Rect::new(label_x, label_y, lw.max(1.0), lh.max(1.0)),
                &label,
                label_fg,
            );
        }

        rects
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::event::Viewport;
        use crate::primitives::dialog::{DialogButton, VisibleDialogButton};
        use crate::types::{Color, StyledText, WidgetId};
        use crate::Image;

        /// Records every drawing verb issued by `draw_table` / `paint` —
        /// mirrors every other primitive's `RecordingSurface` test
        /// double (e.g. `primitives::form`, `primitives::pipeline_view`).
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            strokes: Vec<(Rect, Color, f32)>,
            text_runs: Vec<(Rect, String, Color)>,
            lines: Vec<(Point, Point, Color, f32)>,
        }

        impl PaintSurface for RecordingSurface {
            fn surface_begin_frame(&mut self, _viewport: Viewport) {}
            fn surface_end_frame(&mut self) {}
            fn surface_viewport(&self) -> Viewport {
                Viewport::new(300.0, 200.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                14.0
            }
            fn surface_char_width(&self) -> f32 {
                7.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (text.chars().count() as f32 * 7.0, 12.0)
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_fill_rounded_rect(&mut self, rect: Rect, _radius: f32, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_stroke_rect(&mut self, rect: Rect, color: Color, stroke_width: f32) {
                self.strokes.push((rect, color, stroke_width));
            }
            fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: Color) {
                self.text_runs.push((rect, text.to_string(), color));
            }
            fn surface_draw_line(
                &mut self,
                from: crate::Point,
                to: crate::Point,
                color: Color,
                stroke_width: f32,
            ) {
                self.lines.push((from, to, color, stroke_width));
            }
            fn surface_push_clip(&mut self, _rect: Rect) {}
            fn surface_pop_clip(&mut self) {}
            fn surface_draw_image(&mut self, _rect: Rect, _image: &Image) -> ImagePaintResult {
                ImagePaintResult::Unsupported
            }
        }

        /// Column separators and the header rule paint as 1px lines,
        /// never the ` │ ` / `─` glyphs the TUI painter still emits.
        #[test]
        fn draw_table_paints_lines_not_separator_glyphs() {
            let table = DialogTable {
                headers: Some(vec!["Key".to_string(), "Action".to_string()]),
                rows: vec![vec!["Ctrl+S".to_string(), "Save".to_string()]],
                column_widths: None,
            };
            let mut surface = RecordingSurface::default();
            draw_table(
                &mut surface,
                &table,
                Rect::new(0.0, 0.0, 200.0, 42.0),
                14.0,
                Color::rgb(255, 255, 255),
                Color::rgb(128, 128, 128),
            );

            assert!(
                !surface
                    .text_runs
                    .iter()
                    .any(|(_, t, _)| t.contains('│') || t.contains('─')),
                "no ` │ ` / `─` glyph should be painted; text runs were {:?}",
                surface.text_runs,
            );
            // One column separator per row (header + data row) plus the
            // header rule below it = 3 lines.
            assert_eq!(
                surface.lines.len(),
                3,
                "expected 2 column separators + 1 header rule; lines were {:?}",
                surface.lines,
            );
        }

        /// The default button's marker is the selected-bg fill +
        /// border, not a leading `▸ ` glyph.
        #[test]
        fn default_button_has_no_leading_glyph() {
            let dialog = Dialog {
                id: WidgetId::new("dialog:confirm"),
                title: StyledText::plain("Confirm"),
                body: vec![],
                buttons: vec![DialogButton {
                    id: WidgetId::new("dialog:ok"),
                    label: "OK".to_string(),
                    is_default: true,
                    is_cancel: false,
                    tint: None,
                }],
                severity: None,
                vertical_buttons: true,
                table: None,
                input: None,
            };
            let dlayout = DialogLayout {
                bounds: Rect::new(0.0, 0.0, 100.0, 60.0),
                title_bounds: None,
                body_bounds: Rect::new(0.0, 0.0, 0.0, 0.0),
                table_bounds: None,
                input_bounds: None,
                body_toolbar_layout: None,
                button_row_bounds: Rect::new(0.0, 40.0, 100.0, 20.0),
                visible_buttons: vec![VisibleDialogButton {
                    button_idx: 0,
                    id: dialog.buttons[0].id.clone(),
                    bounds: Rect::new(10.0, 40.0, 40.0, 16.0),
                }],
                hit_regions: vec![],
            };
            let mut surface = RecordingSurface::default();
            paint(
                &dialog,
                &dlayout,
                14.0,
                &mut surface,
                &Theme::default(),
                &crate::style::Style::default(),
            );

            assert!(
                surface.text_runs.iter().any(|(_, t, _)| t == "OK"),
                "the button label itself must still be painted; text runs \
                 were {:?}",
                surface.text_runs,
            );
            assert!(
                !surface.text_runs.iter().any(|(_, t, _)| t.contains('▸')),
                "no leading glyph should be painted on the default button; \
                 text runs were {:?}",
                surface.text_runs,
            );
            let theme = Theme::default();
            assert!(
                surface.fills.iter().any(|(_, c)| *c == theme.selected_bg),
                "the default button must still fill selected_bg as its \
                 marker; fills were {:?}",
                surface.fills,
            );
        }
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::toolbar::{Toolbar, ToolbarButton};
    use crate::types::WidgetId;

    fn no_measure(_: &crate::primitives::toolbar::ToolbarButton) -> ToolbarItemMeasure {
        ToolbarItemMeasure::new(0.0)
    }

    fn viewport() -> Rect {
        Rect::new(0.0, 0.0, 400.0, 300.0)
    }

    fn measure_no_input() -> DialogMeasure {
        DialogMeasure {
            width: 200.0,
            title_height: 20.0,
            body_height: 20.0,
            table_height: 0.0,
            input_height: 0.0,
            button_row_height: 20.0,
            button_width: 60.0,
            button_gap: 8.0,
            padding: 10.0,
        }
    }

    fn measure_with_input() -> DialogMeasure {
        DialogMeasure {
            input_height: 20.0,
            ..measure_no_input()
        }
    }

    fn btn(id: &str) -> DialogButton {
        DialogButton {
            id: WidgetId::new(id),
            label: id.to_string(),
            is_default: false,
            is_cancel: false,
            tint: None,
        }
    }

    fn base_dialog(input: Option<DialogInput>) -> Dialog {
        Dialog {
            id: WidgetId::new("d"),
            title: crate::types::StyledText::plain("Title"),
            body: vec![crate::types::StyledText::plain("Body")],
            buttons: vec![btn("ok")],
            severity: None,
            vertical_buttons: false,
            table: None,
            input,
        }
    }

    // ── DialogInput::TextInput serde round-trip ───────────────────────────

    #[test]
    fn serde_dialog_text_input_round_trip() {
        let input = DialogInput::TextInput(DialogTextInput {
            value: "hello".into(),
            placeholder: "type here".into(),
            cursor: Some(5),
        });
        let json = serde_json::to_string(&input).unwrap();
        let back: DialogInput = serde_json::from_str(&json).unwrap();
        assert_eq!(input, back);
    }

    // ── DialogInput::Toolbar serde round-trip ─────────────────────────────

    #[test]
    fn serde_dialog_toolbar_round_trip() {
        let input = DialogInput::Toolbar(Toolbar {
            id: WidgetId::new("body-tb"),
            buttons: vec![
                ToolbarButton::Action {
                    id: WidgetId::new("preview"),
                    label: "Preview".into(),
                    icon: None,
                    key_hint: None,
                    enabled: true,
                    is_active: false,
                    tooltip: String::new(),
                },
                ToolbarButton::Separator,
                ToolbarButton::Action {
                    id: WidgetId::new("apply"),
                    label: "Apply".into(),
                    icon: None,
                    key_hint: None,
                    enabled: true,
                    is_active: false,
                    tooltip: String::new(),
                },
            ],
            bg: None,
            focused_index: None,
        });
        let json = serde_json::to_string(&input).unwrap();
        let back: DialogInput = serde_json::from_str(&json).unwrap();
        assert_eq!(input, back);
    }

    // ── Toolbar variant creates body_toolbar_layout ───────────────────────

    #[test]
    fn layout_toolbar_variant_sets_body_toolbar_layout() {
        let d = base_dialog(Some(DialogInput::Toolbar(Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Action {
                id: WidgetId::new("a"),
                label: "A".into(),
                icon: None,
                key_hint: None,
                enabled: true,
                is_active: false,
                tooltip: String::new(),
            }],
            bg: None,
            focused_index: None,
        })));
        let layout = d.layout(viewport(), measure_with_input(), |_| {
            ToolbarItemMeasure::new(10.0)
        });
        assert!(
            layout.input_bounds.is_some(),
            "input_bounds should be Some for Toolbar variant"
        );
        assert!(
            layout.body_toolbar_layout.is_some(),
            "body_toolbar_layout should be Some for Toolbar variant"
        );
        assert!(
            layout
                .body_toolbar_layout
                .as_ref()
                .unwrap()
                .visible_items
                .len()
                == 1
        );
    }

    #[test]
    fn layout_text_input_variant_does_not_set_body_toolbar_layout() {
        let d = base_dialog(Some(DialogInput::TextInput(DialogTextInput {
            value: "x".into(),
            placeholder: String::new(),
            cursor: None,
        })));
        let layout = d.layout(viewport(), measure_with_input(), no_measure);
        assert!(layout.input_bounds.is_some());
        assert!(
            layout.body_toolbar_layout.is_none(),
            "body_toolbar_layout should be None for TextInput variant"
        );
    }

    // ── BodyToolbarButton hit routing ─────────────────────────────────────

    #[test]
    fn hit_test_body_toolbar_button_routes_correctly() {
        let d = base_dialog(Some(DialogInput::Toolbar(Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Action {
                id: WidgetId::new("preview"),
                label: "Preview".into(),
                icon: None,
                key_hint: None,
                enabled: true,
                is_active: false,
                tooltip: String::new(),
            }],
            bg: None,
            focused_index: None,
        })));
        let layout = d.layout(viewport(), measure_with_input(), |_| {
            ToolbarItemMeasure::new(60.0)
        });
        let tl = layout.body_toolbar_layout.as_ref().unwrap();
        let vis = &tl.visible_items[0];
        // Click inside the toolbar button bounds.
        let cx = vis.bounds.x + 1.0;
        let cy = vis.bounds.y;
        match layout.hit_test(cx, cy) {
            DialogHit::BodyToolbarButton(id) => {
                assert_eq!(id.as_str(), "preview");
            }
            other => panic!("expected BodyToolbarButton, got {:?}", other),
        }
    }

    #[test]
    fn hit_test_no_toolbar_no_body_toolbar_hit() {
        let d = base_dialog(None);
        let layout = d.layout(viewport(), measure_no_input(), no_measure);
        // Click inside dialog body — should be Body, not BodyToolbarButton.
        let cx = layout.body_bounds.x + 5.0;
        let cy = layout.body_bounds.y + 5.0;
        assert_eq!(layout.hit_test(cx, cy), DialogHit::Body);
    }

    // ── DialogTable ──────────────────────────────────────────────────────────

    fn table_dialog() -> Dialog {
        Dialog {
            id: WidgetId::new("d"),
            title: crate::types::StyledText::plain("Keybindings"),
            body: vec![],
            buttons: vec![btn("close")],
            severity: None,
            vertical_buttons: false,
            table: Some(DialogTable {
                headers: Some(vec!["Key".into(), "Action".into()]),
                rows: vec![
                    vec!["Ctrl+S".into(), "Save".into()],
                    vec!["Ctrl+Z".into(), "Undo".into()],
                ],
                column_widths: None,
            }),
            input: None,
        }
    }

    #[test]
    fn dialog_table_num_cols() {
        let t = DialogTable {
            headers: Some(vec!["A".into(), "B".into(), "C".into()]),
            rows: vec![vec!["x".into(), "y".into()]],
            column_widths: None,
        };
        assert_eq!(t.num_cols(), 3, "headers win when wider than rows");
    }

    #[test]
    fn dialog_table_auto_col_widths() {
        let t = DialogTable {
            headers: Some(vec!["Key".into(), "Action".into()]),
            rows: vec![
                vec!["Ctrl+S".into(), "Save".into()],
                vec!["Ctrl+Shift+Z".into(), "Redo".into()],
            ],
            column_widths: None,
        };
        let widths = t.auto_col_widths();
        assert_eq!(widths.len(), 2);
        assert_eq!(widths[0], "Ctrl+Shift+Z".chars().count()); // 12
        assert_eq!(widths[1], "Action".chars().count()); // 6
    }

    #[test]
    fn dialog_table_tui_total_width() {
        let t = DialogTable {
            headers: Some(vec!["Key".into(), "Action".into()]),
            rows: vec![vec!["Ctrl+S".into(), "Save".into()]],
            column_widths: None,
        };
        // col0=6 ("Ctrl+S"), col1=6 ("Action"), sep=" │ "=3 → total=6+3+6=15
        assert_eq!(t.tui_total_width(), 15);
    }

    #[test]
    fn dialog_table_tui_total_height_with_headers() {
        let t = DialogTable {
            headers: Some(vec!["Key".into()]),
            rows: vec![vec!["a".into()], vec!["b".into()]],
            column_widths: None,
        };
        // 2 header rows (header + separator) + 2 data rows = 4
        assert_eq!(t.tui_total_height(), 4);
    }

    #[test]
    fn dialog_table_tui_total_height_no_headers() {
        let t = DialogTable {
            headers: None,
            rows: vec![vec!["a".into()], vec!["b".into()], vec!["c".into()]],
            column_widths: None,
        };
        assert_eq!(t.tui_total_height(), 3);
    }

    #[test]
    fn layout_with_table_creates_table_bounds() {
        let d = table_dialog();
        // table: 2 header rows + 2 data rows = 4 rows → table_height=4*20=80
        let measure = DialogMeasure {
            width: 200.0,
            title_height: 20.0,
            body_height: 0.0,
            table_height: 80.0,
            input_height: 0.0,
            button_row_height: 20.0,
            button_width: 60.0,
            button_gap: 8.0,
            padding: 10.0,
        };
        let layout = d.layout(viewport(), measure, no_measure);
        assert!(
            layout.table_bounds.is_some(),
            "table_bounds should be Some when table is set"
        );
        let tb = layout.table_bounds.unwrap();
        assert_eq!(tb.height, 80.0);
    }

    #[test]
    fn layout_without_table_has_no_table_bounds() {
        let d = base_dialog(None);
        let layout = d.layout(viewport(), measure_no_input(), no_measure);
        assert!(
            layout.table_bounds.is_none(),
            "table_bounds should be None when table is None"
        );
    }

    #[test]
    fn layout_table_placed_below_body() {
        let d = table_dialog();
        let measure = DialogMeasure {
            width: 200.0,
            title_height: 10.0,
            body_height: 0.0,
            table_height: 40.0,
            input_height: 0.0,
            button_row_height: 10.0,
            button_width: 60.0,
            button_gap: 8.0,
            padding: 5.0,
        };
        let layout = d.layout(viewport(), measure, no_measure);
        let body_bottom = layout.body_bounds.y + layout.body_bounds.height;
        let table_top = layout.table_bounds.unwrap().y;
        assert_eq!(
            table_top, body_bottom,
            "table starts immediately after body"
        );
    }

    #[test]
    fn serde_dialog_table_round_trip() {
        let t = DialogTable {
            headers: Some(vec!["Key".into(), "Action".into()]),
            rows: vec![vec!["Ctrl+S".into(), "Save".into()]],
            column_widths: Some(vec![10, 20]),
        };
        let json = serde_json::to_string(&t).unwrap();
        let back: DialogTable = serde_json::from_str(&json).unwrap();
        assert_eq!(t, back);
    }

    #[test]
    fn serde_dialog_with_table_round_trip() {
        let d = table_dialog();
        let json = serde_json::to_string(&d).unwrap();
        let back: Dialog = serde_json::from_str(&json).unwrap();
        assert_eq!(d, back);
    }

    #[test]
    fn serde_dialog_without_table_defaults_to_none() {
        // A JSON blob that doesn't contain the "table" key should deserialise
        // with table = None (backward-compat — old serialised dialogs keep working).
        let json = r#"{"id":"d","title":{"spans":[{"text":"T","fg":null,"bg":null,"bold":false,"italic":false,"underline":false,"strike":false}]},"body":[],"buttons":[]}"#;
        let d: Dialog = serde_json::from_str(json).unwrap();
        assert!(d.table.is_none());
    }

    // ── native_dialog_options ─────────────────────────────────────────────

    fn dialog_with_buttons() -> Dialog {
        Dialog {
            id: WidgetId::new("d"),
            title: crate::types::StyledText::plain("Unsaved Changes"),
            body: vec![
                crate::types::StyledText::plain("Do you want to save?"),
                crate::types::StyledText::plain("Changes will be lost."),
            ],
            buttons: vec![
                DialogButton {
                    id: WidgetId::new("save"),
                    label: "Save".into(),
                    is_default: true,
                    is_cancel: false,
                    tint: None,
                },
                DialogButton {
                    id: WidgetId::new("cancel"),
                    label: "Cancel".into(),
                    is_default: false,
                    is_cancel: true,
                    tint: None,
                },
            ],
            severity: Some(DialogSeverity::Warning),
            vertical_buttons: false,
            table: None,
            input: None,
        }
    }

    #[test]
    fn native_dialog_options_maps_title_body_buttons_default_cancel_severity() {
        let d = dialog_with_buttons();
        let opts =
            native_dialog_options(&d).expect("no table/input — must be natively expressible");
        assert_eq!(opts.title, "Unsaved Changes");
        assert_eq!(opts.body, "Do you want to save?\nChanges will be lost.");
        assert_eq!(opts.buttons.len(), 2);
        assert_eq!(opts.buttons[0].id.as_str(), "save");
        assert_eq!(opts.buttons[0].label, "Save");
        assert!(opts.buttons[0].is_default);
        assert!(!opts.buttons[0].is_cancel);
        assert_eq!(opts.buttons[1].id.as_str(), "cancel");
        assert_eq!(opts.buttons[1].label, "Cancel");
        assert!(opts.buttons[1].is_cancel);
        assert!(!opts.buttons[1].is_default);
        assert_eq!(opts.severity, Some(DialogSeverity::Warning));
    }

    #[test]
    fn native_dialog_options_passes_through_none_severity() {
        let mut d = dialog_with_buttons();
        d.severity = None;
        let opts =
            native_dialog_options(&d).expect("no table/input — must be natively expressible");
        assert_eq!(opts.severity, None);
    }

    #[test]
    fn native_dialog_options_none_for_table() {
        let d = table_dialog();
        assert!(
            native_dialog_options(&d).is_none(),
            "no native alert facility hosts a DialogTable"
        );
    }

    #[test]
    fn native_dialog_options_none_for_input() {
        let d = base_dialog(Some(DialogInput::TextInput(DialogTextInput {
            value: "x".into(),
            placeholder: String::new(),
            cursor: None,
        })));
        assert!(
            native_dialog_options(&d).is_none(),
            "no native alert facility hosts a DialogInput text field"
        );
    }

    // ── Dialog primitive tests ────────────────────────────────────────

    fn mk_dialog_button(id: &str, label: &str) -> DialogButton {
        DialogButton {
            id: WidgetId::new(id),
            label: label.to_string(),
            is_default: false,
            is_cancel: false,
            tint: None,
        }
    }

    #[test]
    fn dialog_layout_centered_horizontal_buttons() {
        let mut ok = mk_dialog_button("ok", "OK");
        ok.is_default = true;
        let mut cancel = mk_dialog_button("cancel", "Cancel");
        cancel.is_cancel = true;
        let d = Dialog {
            id: WidgetId::new("confirm"),
            title: StyledText::plain("Close unsaved file?"),
            body: vec![StyledText::plain("You have unsaved changes. Close anyway?")],
            buttons: vec![cancel, ok],
            severity: Some(DialogSeverity::Question),
            vertical_buttons: false,
            table: None,
            input: None,
        };
        let viewport = Rect::new(0.0, 0.0, 800.0, 600.0);
        let measure = DialogMeasure {
            width: 400.0,
            title_height: 24.0,
            body_height: 40.0,
            table_height: 0.0,
            input_height: 0.0,
            button_row_height: 32.0,
            button_width: 80.0,
            button_gap: 8.0,
            padding: 16.0,
        };
        let layout = d.layout(viewport, measure, |_| {
            crate::primitives::toolbar::ToolbarItemMeasure::new(0.0)
        });

        // Centered: x = (800 - 400)/2 = 200
        assert_eq!(layout.bounds.x, 200.0);
        // total_h = 24 + 40 + 32 + 32 = 128; y = (600 - 128)/2 = 236
        assert_eq!(layout.bounds.y, 236.0);

        assert!(layout.title_bounds.is_some());
        assert_eq!(layout.visible_buttons.len(), 2);
        // Right-aligned: last button's right edge = content right edge.
        let last = &layout.visible_buttons[1];
        assert_eq!(
            last.bounds.x + last.bounds.width,
            layout.bounds.x + measure.width - measure.padding
        );
    }

    #[test]
    fn dialog_layout_vertical_buttons() {
        let d = Dialog {
            id: WidgetId::new("code-actions"),
            title: StyledText::plain("Code actions"),
            body: vec![StyledText::default()],
            buttons: vec![
                mk_dialog_button("a1", "Add import"),
                mk_dialog_button("a2", "Use fully qualified path"),
                mk_dialog_button("a3", "Ignore"),
            ],
            severity: None,
            vertical_buttons: true,
            table: None,
            input: None,
        };
        let viewport = Rect::new(0.0, 0.0, 800.0, 600.0);
        let measure = DialogMeasure {
            width: 300.0,
            title_height: 20.0,
            body_height: 0.0,
            table_height: 0.0,
            input_height: 0.0,
            button_row_height: 90.0,
            button_width: 280.0,
            button_gap: 0.0,
            padding: 10.0,
        };
        let layout = d.layout(viewport, measure, |_| {
            crate::primitives::toolbar::ToolbarItemMeasure::new(0.0)
        });
        assert_eq!(layout.visible_buttons.len(), 3);
        // Stacked: each one full button row tall (button_row_height = 90);
        // widths equal content_w = 300-20 = 280.
        for b in &layout.visible_buttons {
            assert_eq!(b.bounds.width, 280.0);
            assert_eq!(b.bounds.height, 90.0);
        }
        // Button 0 y < button 1 y < button 2 y.
        assert!(layout.visible_buttons[0].bounds.y < layout.visible_buttons[1].bounds.y);
    }

    #[test]
    fn dialog_hit_test_on_button_returns_id() {
        let d = Dialog {
            id: WidgetId::new("confirm"),
            title: StyledText::plain("T"),
            body: vec![StyledText::plain("B")],
            buttons: vec![
                mk_dialog_button("cancel", "Cancel"),
                mk_dialog_button("ok", "OK"),
            ],
            severity: None,
            vertical_buttons: false,
            table: None,
            input: None,
        };
        let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
        let measure = DialogMeasure {
            width: 200.0,
            title_height: 20.0,
            body_height: 20.0,
            table_height: 0.0,
            input_height: 0.0,
            button_row_height: 20.0,
            button_width: 60.0,
            button_gap: 10.0,
            padding: 10.0,
        };
        let layout = d.layout(viewport, measure, |_| {
            crate::primitives::toolbar::ToolbarItemMeasure::new(0.0)
        });
        // Click on the second (right) button — OK.
        let ok_btn = &layout.visible_buttons[1];
        let cx = ok_btn.bounds.x + ok_btn.bounds.width / 2.0;
        let cy = ok_btn.bounds.y + ok_btn.bounds.height / 2.0;
        match layout.hit_test(cx, cy) {
            DialogHit::Button(id) => assert_eq!(id.as_str(), "ok"),
            _ => panic!(),
        }
        // Click on body (not on button) → Body.
        assert_eq!(
            layout.hit_test(layout.body_bounds.x + 5.0, layout.body_bounds.y + 5.0),
            DialogHit::Body
        );
        // Click outside dialog → Outside.
        assert_eq!(layout.hit_test(0.0, 0.0), DialogHit::Outside);
    }

    #[test]
    fn dialog_with_input_field_layout() {
        // Rename-style dialog: title + short body + input + buttons.
        let ok = mk_dialog_button("ok", "OK");
        let cancel = mk_dialog_button("cancel", "Cancel");
        let d = Dialog {
            id: WidgetId::new("rename"),
            title: StyledText::plain("Rename"),
            body: vec![StyledText::plain("New name:")],
            buttons: vec![cancel, ok],
            severity: None,
            vertical_buttons: false,
            table: None,
            input: Some(DialogInput::TextInput(DialogTextInput {
                value: "old_name.rs".to_string(),
                placeholder: String::new(),
                cursor: Some(11),
            })),
        };
        let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
        let measure = DialogMeasure {
            width: 200.0,
            title_height: 20.0,
            body_height: 20.0,
            table_height: 0.0,
            input_height: 24.0,
            button_row_height: 20.0,
            button_width: 60.0,
            button_gap: 10.0,
            padding: 10.0,
        };
        let layout = d.layout(viewport, measure, |_| {
            crate::primitives::toolbar::ToolbarItemMeasure::new(0.0)
        });
        assert!(layout.input_bounds.is_some());
        let ib = layout.input_bounds.unwrap();
        // Input sits between body and buttons.
        assert_eq!(ib.y, layout.body_bounds.y + layout.body_bounds.height);
        assert_eq!(ib.height, 24.0);
        // Buttons pushed down by input_height.
        assert_eq!(layout.button_row_bounds.y, ib.y + ib.height);
    }

    #[test]
    fn dialog_default_and_cancel_resolution() {
        let mut ok = mk_dialog_button("ok", "OK");
        ok.is_default = true;
        let mut cancel = mk_dialog_button("cancel", "Cancel");
        cancel.is_cancel = true;
        let d = Dialog {
            id: WidgetId::new("d"),
            title: StyledText::default(),
            body: vec![StyledText::default()],
            buttons: vec![cancel, ok],
            severity: None,
            vertical_buttons: false,
            table: None,
            input: None,
        };
        assert_eq!(d.default_button_id().unwrap().as_str(), "ok");
        assert_eq!(d.cancel_button_id().unwrap().as_str(), "cancel");
    }

    // ── Dialog::measure_generic ───────────────────────────────────────────

    #[test]
    fn measure_generic_tui_shaped_matches_hand_rolled_formula() {
        // char_width == line_height == 1.0, mirroring TUI metrics —
        // reproduces the formula every caller currently hand-rolls.
        let d = table_dialog();
        let viewport = Rect::new(0.0, 0.0, 100.0, 30.0);
        let m = d.measure_generic(1.0, 1.0, viewport, 0.0);

        assert_eq!(m.title_height, 1.0, "non-empty title reserves one line");
        assert_eq!(m.body_height, 0.0, "table_dialog() has no body lines");
        let table = d.table.as_ref().unwrap();
        assert_eq!(m.table_height, table.tui_total_height() as f32);
        assert_eq!(m.button_row_height, 1.0);
        assert_eq!(m.button_width, 8.0);
        assert_eq!(m.button_gap, 2.0);
        assert_eq!(m.padding, 1.0);
        assert_eq!(m.input_height, 0.0, "no DialogInput on table_dialog()");
    }

    #[test]
    fn measure_generic_empty_title_reserves_no_height() {
        let mut d = base_dialog(None);
        d.title = StyledText::default();
        let viewport = Rect::new(0.0, 0.0, 100.0, 30.0);
        let m = d.measure_generic(1.0, 1.0, viewport, 0.0);
        assert_eq!(m.title_height, 0.0);
    }

    #[test]
    fn measure_generic_input_present_reserves_one_line() {
        let d = base_dialog(Some(DialogInput::TextInput(DialogTextInput {
            value: "x".into(),
            placeholder: String::new(),
            cursor: None,
        })));
        let viewport = Rect::new(0.0, 0.0, 100.0, 30.0);
        let m = d.measure_generic(1.0, 1.0, viewport, 0.0);
        assert_eq!(m.input_height, 1.0);
    }

    #[test]
    fn measure_generic_widens_for_wide_table() {
        // A table wide enough to force the dialog beyond its default
        // preferred width.
        let wide_table_dialog = Dialog {
            id: WidgetId::new("wide"),
            title: StyledText::plain("Wide"),
            body: vec![],
            buttons: vec![btn("close")],
            severity: None,
            vertical_buttons: false,
            table: Some(DialogTable {
                headers: None,
                rows: vec![vec!["x".repeat(80)]],
                column_widths: None,
            }),
            input: None,
        };
        let viewport = Rect::new(0.0, 0.0, 200.0, 50.0);
        let m = wide_table_dialog.measure_generic(1.0, 1.0, viewport, 0.0);
        // Table content alone needs 80 + 2 padding chars = 82, well past
        // the ≈30-60 char default preferred width.
        assert!(
            m.width >= 82.0,
            "width {} should fit the wide table",
            m.width
        );
    }

    #[test]
    fn measure_generic_border_chrome_inset_shrinks_width_when_viewport_bound() {
        // Narrow viewport so the `viewport.width - 4*char_width -
        // 2*inset` clamp is the binding constraint, not the table or
        // the 30-60 char-width default band.
        let d = base_dialog(None);
        let viewport = Rect::new(0.0, 0.0, 20.0, 30.0);
        let no_inset = d.measure_generic(1.0, 1.0, viewport, 0.0);
        let with_inset = d.measure_generic(1.0, 1.0, viewport, 2.0);
        assert_eq!(
            with_inset.width,
            no_inset.width - 4.0,
            "border_chrome_inset shrinks width by 2x the inset"
        );
    }

    // ── Dialog::measure_generic_measured ──────────────────────────────────

    /// Fixed-width stand-in for a real font: `6.0` px per char. Mirrors
    /// `layout_metrics`'s `FakeMeasure`, giving this a platform-independent
    /// regression test instead of depending on a real backend's glyph
    /// metrics.
    struct FakeMeasure;
    impl crate::primitives::layout_metrics::TextMeasure for FakeMeasure {
        fn width_of(&self, text: &str) -> f32 {
            text.chars().count() as f32 * 6.0
        }
    }

    #[test]
    fn measure_generic_measured_uses_real_label_width_not_the_estimate() {
        let mut d = base_dialog(None);
        d.buttons = vec![btn("a-very-long-button-label")];
        let viewport = Rect::new(0.0, 0.0, 200.0, 30.0);
        let char_width = 1.0;
        let line_height = 1.0;

        let estimated = d.measure_generic(char_width, line_height, viewport, 0.0);
        let measured =
            d.measure_generic_measured(char_width, line_height, viewport, 0.0, &FakeMeasure);

        assert_eq!(
            estimated.button_width, 8.0,
            "measure_generic always uses the flat char_width * 8.0 estimate"
        );
        let label_w = FakeMeasure.width_of("a-very-long-button-label");
        assert_eq!(
            measured.button_width,
            label_w + char_width * 2.0,
            "measured button_width tracks the real label width + padding, \
             not the flat estimate"
        );
        assert!(measured.button_width > estimated.button_width);
    }

    #[test]
    fn measure_generic_measured_floors_at_the_char_width_estimate() {
        // Short labels must not shrink the button row below what
        // measure_generic already renders for every existing caller.
        struct NarrowMeasure;
        impl crate::primitives::layout_metrics::TextMeasure for NarrowMeasure {
            fn width_of(&self, text: &str) -> f32 {
                text.chars().count() as f32 * 1.0
            }
        }

        let d = base_dialog(None); // buttons: [btn("ok")]
        let viewport = Rect::new(0.0, 0.0, 200.0, 30.0);
        let char_width = 1.0;
        let line_height = 1.0;

        let measured =
            d.measure_generic_measured(char_width, line_height, viewport, 0.0, &NarrowMeasure);
        assert_eq!(measured.button_width, char_width * 8.0);
    }

    #[test]
    fn measure_generic_measured_matches_estimate_for_other_fields() {
        let d = table_dialog();
        let viewport = Rect::new(0.0, 0.0, 100.0, 30.0);
        let estimated = d.measure_generic(1.0, 1.0, viewport, 0.0);
        let measured = d.measure_generic_measured(1.0, 1.0, viewport, 0.0, &FakeMeasure);

        assert_eq!(measured.width, estimated.width);
        assert_eq!(measured.title_height, estimated.title_height);
        assert_eq!(measured.body_height, estimated.body_height);
        assert_eq!(measured.table_height, estimated.table_height);
        assert_eq!(measured.input_height, estimated.input_height);
        assert_eq!(measured.button_row_height, estimated.button_row_height);
        assert_eq!(measured.button_gap, estimated.button_gap);
        assert_eq!(measured.padding, estimated.padding);
    }
}