mahbot 0.4.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
//! Shared dashboard widgets: styled pick_list, PickOption type, FileTree state struct
//! and build_tree_panel for shared file-tree panel rendering.

use std::collections::HashSet;
use std::path::Path;
use std::time::Duration;

use iced::keyboard;
use iced::widget::{
    self, Column, Row, Space, button, column, container, pick_list, row, scrollable, stack, text,
    text_editor, text_input, tooltip,
};
use iced::{Alignment, Color, Element, Length, Padding, Task};

use iced_selection;

use super::theme;
use iced_fonts::lucide;

/// An option for [`fn@pick_list`] with separate value and display label.
///
/// Equality is determined by `value` only — two `PickOption`s with the same
/// `value` are considered equal regardless of label. This lets [`fn@pick_list`]
/// highlight the correct option even when the selected value is constructed
/// independently of the options list.
#[derive(Debug, Clone)]
pub struct PickOption {
    pub value: String,
    pub label: String,
}

impl PartialEq for PickOption {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl Eq for PickOption {}

impl std::fmt::Display for PickOption {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.label)
    }
}

/// Flexoki-dark themed style for [`fn@pick_list`] widgets.
#[must_use]
pub fn pick_list_style(_theme: &iced::Theme, _status: pick_list::Status) -> pick_list::Style {
    pick_list::Style {
        text_color: theme::TEXT_PRIMARY,
        placeholder_color: theme::TEXT_MUTED,
        handle_color: theme::TEXT_MUTED,
        background: iced::Background::Color(theme::BG_ELEVATED),
        border: iced::Border {
            radius: 4.0.into(),
            width: 1.0,
            color: theme::BORDER_STRONG,
        },
    }
}

/// Flexoki-dark themed style for [`fn@text_input`] widgets.
/// Matches [`pick_list_style`] for visual consistency.
#[must_use]
pub fn text_input_style(_theme: &iced::Theme, _status: text_input::Status) -> text_input::Style {
    text_input::Style {
        background: iced::Background::Color(theme::BG_ELEVATED),
        border: iced::Border {
            radius: 4.0.into(),
            width: 1.0,
            color: theme::BORDER_STRONG,
        },
        icon: theme::TEXT_MUTED,
        placeholder: theme::TEXT_MUTED,
        value: theme::TEXT_PRIMARY,
        selection: theme::ACCENT,
    }
}

/// Highlighted [`fn@text_input`] style for fields that need attention (e.g.
/// the provider API key while unset): an accent border plus a subtle accent
/// background tint. Identical to [`text_input_style`] otherwise.
#[must_use]
pub fn text_input_highlight_style(
    _theme: &iced::Theme,
    _status: text_input::Status,
) -> text_input::Style {
    text_input::Style {
        background: iced::Background::Color(theme::ACCENT.scale_alpha(0.07)),
        border: iced::Border {
            radius: 4.0.into(),
            width: 1.5,
            color: theme::ACCENT,
        },
        icon: theme::TEXT_MUTED,
        placeholder: theme::TEXT_MUTED,
        value: theme::TEXT_PRIMARY,
        selection: theme::ACCENT,
    }
}

/// Render a styled error banner for dashboard panels.
#[must_use]
pub fn error_banner<'a, Message: 'a>(err: &'a str) -> Element<'a, Message> {
    container(text(err).size(13).color(theme::STATUS_ERROR))
        .padding(8)
        .style(theme::pill_style(theme::STATUS_ERROR.scale_alpha(0.08)))
        .into()
}

/// Standardized "Loading..." placeholder label for load-state scaffolding.
#[must_use]
pub fn loading_text<'a, Message: 'a>() -> Element<'a, Message> {
    text("Loading...").size(14).color(theme::TEXT_MUTED).into()
}

/// Push an [`error_banner`] plus trailing 8px spacer onto `col` when `err` is present.
#[must_use]
pub fn push_error_banner<'a, Message: 'a>(
    mut col: Column<'a, Message>,
    err: Option<&'a str>,
) -> Column<'a, Message> {
    if let Some(err) = err {
        col = col.push(error_banner(err));
        col = col.push(Space::new().height(8));
    }
    col
}

/// Render a centered empty-state placeholder with a lucide icon and label.
#[must_use]
pub fn empty_state_placeholder<'a, Message: 'a>(
    icon: iced::widget::Text<'a, iced::Theme, iced::Renderer>,
    label: &'a str,
) -> Element<'a, Message> {
    container(
        column![
            icon.size(48).color(theme::TEXT_MUTED),
            text(label).size(14).color(theme::TEXT_MUTED),
        ]
        .spacing(12)
        .align_x(Alignment::Center),
    )
    .width(Length::Fill)
    .height(Length::Fill)
    .center_x(Length::Fill)
    .center_y(Length::Fill)
    .into()
}

/// Badge pill with an opaque background; `colors` is a `(background, text)` tuple.
#[must_use]
pub fn badge_pill<'a, Message: 'a>(
    label: String,
    colors: (Color, Color),
    text_size: u32,
    padding: [u16; 2],
) -> Element<'a, Message> {
    container(text(label).size(text_size).color(colors.1))
        .padding(padding)
        .style(theme::pill_style(colors.0))
        .into()
}

/// Role badge pill: a container with the role name, caller-specified padding,
/// and the translucent role-colored pill background (canonical 4px radius).
///
/// Takes the role as an owned `String` (not `&str`) because the sessions
/// transcript renders move a loop-local String into an Element that outlives
/// the iteration — a borrowed parameter would not compile there; call sites
/// that only have a borrow pay a trivial `.clone()`.
///
/// `colors` is the `(foreground, background)` tuple from
/// [`theme::role_badge_color`] / [`theme::role_badge_color_for`]; the
/// background member (always the foreground at 0.1 alpha — that math lives
/// in exactly one place, `theme::badge_bg`) feeds [`theme::pill_style`].
///
/// `padding` is the container padding `[vertical, horizontal]`, passed
/// through to the container's padding builder; the board comment rows use
/// the enlarged `[2, 12]` so the role stands out while scrolling, while the
/// sessions transcript and tool-failure metadata rows keep the compact
/// `[1, 6]`.
///
/// `selectable` chooses between plain [`text`] and [`selectable_text`]: both
/// arms coerce into `Element` via `.into()`, but plain `text` is cheaper (no
/// selection machinery) while `selectable_text` lets the role name be
/// selected/copied from the UI. The sessions transcript uses selectable text
/// so a whole line can be copied in one drag; the board comment rows and
/// tool-failure metadata rows use plain text.
#[must_use]
pub fn role_badge<'a, Message: 'a>(
    role: String,
    colors: (Color, Color),
    text_size: u32,
    padding: [u16; 2],
    selectable: bool,
) -> Element<'a, Message> {
    let label: Element<'a, Message> = if selectable {
        selectable_text(role, colors.0).size(text_size).into()
    } else {
        text(role).size(text_size).color(colors.0).into()
    };
    container(label)
        .padding(padding)
        .style(theme::pill_style(colors.1))
        .into()
}

/// "Maint ON/OFF" badge shared by the sidebar Maintainer toggle and the
/// Settings workspace-row Maintainer toggle; the wrapping toggle button
/// stays with each caller.
#[must_use]
pub fn maint_badge<'a, Message: 'a>(enabled: bool) -> Column<'a, Message> {
    column![
        text("Maint").size(8).color(theme::TEXT_MUTED),
        text(if enabled { "ON" } else { "OFF" })
            .size(9)
            .color(if enabled {
                theme::ACCENT
            } else {
                theme::TEXT_MUTED
            }),
    ]
    .spacing(0)
    .align_x(Alignment::Center)
}

/// Create a selectable text widget with the given color.
///
/// Accepts both borrowed (`&str`) and owned (`String`) text content.
pub fn selectable_text<'a>(
    content: impl iced_selection::text::IntoFragment<'a>,
    color: Color,
) -> iced_selection::text::Text<'a, iced::Theme, iced::Renderer> {
    iced_selection::text::Text::new(content).style(move |_theme| iced_selection::text::Style {
        color: Some(color),
        selection: theme::ACCENT_DIM,
    })
}

/// Close button for editor/shell tab bars: a 12px lucide X colored by tab
/// active state (secondary vs faint text).
#[must_use]
pub fn tab_close_button<'a, Message: Clone + 'a>(
    is_active: bool,
    on_press: Message,
) -> widget::Button<'a, Message> {
    widget::button(
        lucide::x::<iced::Theme, iced::Renderer>()
            .size(12)
            .color(if is_active {
                theme::TEXT_SECONDARY
            } else {
                theme::TEXT_FAINT
            }),
    )
    .on_press(on_press)
    .style(theme::button_transparent)
    .padding(0)
}

/// Wrap a tab strip in the shared scrollable + surface-container chrome.
/// `scroll_id` is optional — the editor passes one for scroll-to-active-tab.
/// `on_scroll` is optional — the editor passes a closure tracking the
/// [`scrollable::Viewport`] so its reveal logic can decide whether the
/// active tab is visible; the shell passes `None` (its strip never needs
/// programmatic reveal).
#[must_use]
pub fn tab_scrollable<'a, Message: 'a>(
    tab_buttons: Vec<Element<'a, Message>>,
    scroll_id: Option<widget::Id>,
    on_scroll: Option<impl Fn(scrollable::Viewport) -> Message + 'a>,
) -> Element<'a, Message> {
    let mut sc = scrollable(row(tab_buttons).spacing(0).width(Length::Fill))
        .direction(theme::horizontal_scrollbar())
        .style(theme::scrollbar_style)
        .width(Length::Fill)
        .height(Length::Shrink);
    if let Some(id) = scroll_id {
        sc = sc.id(id);
    }
    if let Some(on_scroll) = on_scroll {
        sc = sc.on_scroll(on_scroll);
    }
    container(sc)
        .style(theme::surface_container_style)
        .width(Length::Fill)
        .into()
}

/// Options for [`chat_composer`] that differ between the Home and Board
/// pages. Bundled so the shared signature does not grow with page-specific
/// knobs.
pub struct ChatComposerOptions<'a, M> {
    /// A send is in flight — button disabled.
    pub sending: bool,
    /// Editor min/max heights in px.
    pub min_height: f32,
    pub max_height: f32,
    /// Right-edge controls rendered above the send button (Home role/mic
    /// column; empty for the plain Board composer).
    pub controls: Vec<Element<'a, M>>,
    /// Grey the send button while the input is empty/whitespace-only.
    /// Home enables this (empty-input affordance); Board keeps its legacy
    /// always-active look.
    pub grey_on_empty: bool,
    /// Tooltip text for the send button — surface-specific wording
    /// ("send text message" on Home, "send comment" on the Board ticket
    /// modal). Shown on hover even while the button is disabled.
    pub send_tooltip: &'a str,
}

/// Shared chat composer: text editor with Enter-to-send and Cmd+Z intercept,
/// a floating send button, and the overlay stack. `on_action`/`send_msg`
/// parameterize the page's messages; callers supply the placeholder and an
/// [`ChatComposerOptions`] bundle (editor min/max heights, the sending flag,
/// optional right-edge controls, and whether the send button greys on empty
/// input).
#[must_use]
pub fn chat_composer<'a, M: Clone + 'a>(
    content: &'a text_editor::Content,
    on_action: impl Fn(text_editor::Action) -> M + 'a,
    send_msg: M,
    placeholder: &'a str,
    options: ChatComposerOptions<'a, M>,
) -> Element<'a, M> {
    let send_msg_btn = send_msg.clone();
    let mut input_editor = text_editor(content)
        .on_action(on_action)
        .placeholder(placeholder)
        .min_height(options.min_height)
        .max_height(options.max_height)
        .style(|_theme: &iced::Theme, status| {
            let is_focused = matches!(status, text_editor::Status::Focused { .. });
            text_editor::Style {
                background: iced::Background::Color(theme::BG_ELEVATED),
                border: iced::Border {
                    radius: 8.0.into(),
                    width: if is_focused { 1.0 } else { 0.0 },
                    color: if is_focused {
                        theme::ACCENT
                    } else {
                        iced::Color::TRANSPARENT
                    },
                },
                placeholder: theme::TEXT_MUTED,
                value: theme::TEXT_PRIMARY,
                selection: theme::ACCENT_DIM,
            }
        })
        .key_binding(move |key_press| {
            // Intercept Cmd+Z / Cmd+Shift+Z — handled by the keyboard
            // subscription; on macOS only Cmd+Z triggers undo (Ctrl+Z is the
            // terminal SUSP character and should insert 'z').
            let km = super::detect_keyboard_mods(key_press.modifiers);
            if km.is_shortcut_platform_mod()
                && matches!(
                    &key_press.key,
                    keyboard::Key::Character(c) if c == "z"
                )
            {
                return None;
            }
            if key_press.key == keyboard::Key::Named(keyboard::key::Named::Enter)
                && !key_press.modifiers.shift()
            {
                Some(text_editor::Binding::Custom(send_msg.clone()))
            } else {
                text_editor::Binding::from_key_press(key_press)
            }
        });

    // Keep the text clear of the right-edge control column when present.
    // Preserve the text_editor's default 5px padding on the other edges.
    if !options.controls.is_empty() {
        input_editor = input_editor.padding(iced::Padding::new(5.0).right(38.0));
    }

    // Whitespace-only input counts as empty (greys the send button).
    // The emptiness check is gated on grey_on_empty so Board (legacy look)
    // never allocates content.text() per frame.
    let send_disabled = options.sending
        || (options.grey_on_empty && (content.is_empty() || content.text().trim().is_empty()));
    let send_btn = tooltip(
        button(
            lucide::send::<iced::Theme, iced::Renderer>()
                .size(14)
                .color(if send_disabled {
                    theme::TEXT_MUTED
                } else {
                    theme::ACCENT
                }),
        )
        .style(theme::icon_button_style(send_disabled))
        .on_press_maybe(if send_disabled {
            None
        } else {
            Some(send_msg_btn)
        })
        .padding(4),
        text(options.send_tooltip).size(11),
        tooltip::Position::Top,
    )
    .style(theme::tooltip_style);

    // Right-edge overlay: controls column (when present) above the send button.
    let mut col = Column::new().spacing(6).align_x(Alignment::End);
    for c in options.controls {
        col = col.push(c);
    }
    let overlay: Element<'_, M> = container(col.push(send_btn))
        .width(Length::Fill)
        .height(Length::Fill)
        .align_x(Alignment::End)
        .align_y(Alignment::End)
        .padding(iced::Padding::default().right(8.0).bottom(8.0))
        .into();

    // Stack the editor with the send button overlaid at bottom-right.
    container(stack([input_editor.into(), overlay]))
        .padding(8)
        .style(theme::base_container_style)
        .into()
}

/// Render formatted diff stats (+X/−Y) matching ticket card style.
///
/// Returns a [`Row`] showing only non-zero sides with a `/` separator.
/// Returns an empty [`Row`] when both `added` and `removed` are zero.
///
/// Callers typically wrap this in a styled [`button()`] with an appropriate
/// action message.
#[must_use]
pub fn diff_stats_row<'a, Message: 'a>(added: i64, removed: i64, size: f32) -> Row<'a, Message> {
    let mut parts: Vec<Element<'a, Message>> = Vec::new();
    if added > 0 {
        parts.push(
            text(format!("+{added}"))
                .size(size)
                .color(theme::STATUS_SUCCESS)
                .into(),
        );
    }
    if added > 0 && removed > 0 {
        parts.push(text("/").size(size).color(theme::TEXT_MUTED).into());
    }
    if removed > 0 {
        parts.push(
            text(format!("\u{2212}{removed}"))
                .size(size)
                .color(theme::STATUS_ERROR)
                .into(),
        );
    }
    Row::with_children(parts)
        .spacing(0)
        .align_y(Alignment::Center)
}

// ── Debounce helpers ───────────────────────────────────────────────

/// Spawn a sleep task that returns `generation` after `ms` milliseconds.
///
/// Used by `DebounceState` to implement
/// debounced refresh: increment a generation counter, spawn this task
/// with the new generation, and check the returned generation against
/// the current counter in the response handler.
pub async fn debounce_sleep(ms: u64, generation: u64) -> u64 {
    tokio::time::sleep(Duration::from_millis(ms)).await;
    generation
}

// ── File tree ───────────────────────────────────────────────────────

/// A node in a shared file-tree sidebar.
#[derive(Debug, Clone)]
pub struct TreeNode {
    /// Display name (directory or file name component).
    pub name: String,
    /// Full relative path from workspace/repo root.
    pub full_path: String,
    /// Whether this is a directory node.
    pub is_dir: bool,
    /// Children (only populated for expanded directory nodes).
    pub children: Vec<TreeNode>,
    /// Error message if this entry couldn't be inspected (broken symlink, etc.).
    pub error: Option<String>,
}

/// Direction for navigating the file tree (arrow-key vertical movement).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TreeNavDirection {
    Up,
    Down,
}

/// Shared file-tree state used by both the editor and diff dashboard pages.
pub struct FileTree {
    /// The hierarchical tree nodes.
    pub nodes: Vec<TreeNode>,
    /// Which directories are expanded (by `full_path`).
    pub expanded_dirs: HashSet<String>,
    /// Whether keyboard focus is in the file tree.
    pub tree_focused: bool,
    /// Index into `visible_tree_nodes` of the focused entry.
    pub tree_focus_index: usize,
    /// Flattened visible tree entries: (full_path, is_dir).
    pub visible_tree_nodes: Vec<(String, bool)>,
    /// Scrollable ID for the tree panel (for scroll-into-view).
    pub tree_scroll_id: iced::widget::Id,
    /// Current vertical scroll offset of the tree panel viewport.
    /// Updated via `on_scroll` on the scrollable widget.
    pub scroll_y: f32,
    /// Visible height of the tree panel viewport.
    /// `None` until the first scroll event fires, at which point it becomes
    /// `Some(viewport_h)`. When `None`, [`scroll_to_tree_focus`] with
    /// [`ScrollMode::ScrollIntoView`] falls back to [`ScrollMode::SnapToTop`].
    pub viewport_h: Option<f32>,
}

impl FileTree {
    /// Create a new empty `FileTree` with the given scrollable ID.
    #[must_use]
    pub fn new(scroll_id: iced::widget::Id) -> Self {
        Self {
            nodes: Vec::new(),
            expanded_dirs: HashSet::new(),
            tree_focused: false,
            tree_focus_index: 0,
            visible_tree_nodes: Vec::new(),
            tree_scroll_id: scroll_id,
            scroll_y: 0.0,
            viewport_h: None,
        }
    }

    /// Rebuild the flattened list of visible tree nodes for keyboard navigation.
    pub fn rebuild_visible(&mut self) {
        self.visible_tree_nodes.clear();
        Self::flatten_tree_nodes(
            &self.nodes,
            &self.expanded_dirs,
            &mut self.visible_tree_nodes,
        );
        if self.visible_tree_nodes.is_empty() {
            self.tree_focus_index = 0;
        } else {
            self.tree_focus_index = self.tree_focus_index.min(self.visible_tree_nodes.len() - 1);
        }
    }

    /// Move focus up one visible node. Returns `true` if focus moved.
    ///
    /// No-op when the tree is not focused, or when already at the top.
    #[must_use]
    pub fn nav_up(&mut self) -> bool {
        if self.tree_focused && self.tree_focus_index > 0 {
            self.tree_focus_index -= 1;
            true
        } else {
            false
        }
    }

    /// Move focus down one visible node. Returns `true` if focus moved.
    ///
    /// No-op when the tree is not focused, or when already at the bottom.
    #[must_use]
    pub fn nav_down(&mut self) -> bool {
        if self.tree_focused && self.tree_focus_index + 1 < self.visible_tree_nodes.len() {
            self.tree_focus_index += 1;
            true
        } else {
            false
        }
    }

    /// Recursively flatten tree nodes, respecting expanded state.
    fn flatten_tree_nodes(
        nodes: &[TreeNode],
        expanded: &HashSet<String>,
        out: &mut Vec<(String, bool)>,
    ) {
        for node in nodes {
            out.push((node.full_path.clone(), node.is_dir));
            if node.is_dir && expanded.contains(&node.full_path) && !node.children.is_empty() {
                Self::flatten_tree_nodes(&node.children, expanded, out);
            }
        }
    }

    /// Sort tree nodes: directories first, then case-insensitive alphabetical.
    /// Applied recursively so subdirectory children are also sorted.
    pub fn sort_nodes(nodes: &mut [TreeNode]) {
        nodes.sort_by(|a, b| {
            if a.is_dir != b.is_dir {
                return b.is_dir.cmp(&a.is_dir);
            }
            a.name.to_lowercase().cmp(&b.name.to_lowercase())
        });
        for node in nodes {
            Self::sort_nodes(&mut node.children);
        }
    }

    /// Set the focus index to the visible-tree position of `path`, if found.
    ///
    /// Returns the found position, or [`None`] if `path` is not in the visible tree.
    /// The caller can use the returned position for additional logic (e.g. advancing
    /// focus past a directory to its first child).
    pub fn focus_path(&mut self, path: &str) -> Option<usize> {
        let pos = self
            .visible_tree_nodes
            .iter()
            .position(|(p, _)| p == path)?;
        self.tree_focus_index = pos;
        Some(pos)
    }

    /// Expand a directory and move keyboard focus to its first child.
    ///
    /// Caller must have already inserted `path` into [`expanded_dirs`](Self::expanded_dirs)
    /// and updated [`nodes`](Self::nodes). This method rebuilds the visible tree, locates
    /// the directory in the new flattened list via [`Self::focus_path`], advances focus
    /// to the entry immediately after it (the first child), and returns a scroll-into-view
    /// task.
    ///
    /// Returns [`Task::none()`] if the directory is no longer in the visible tree or has
    /// no children — focus stays on the directory itself in that case.
    pub fn expand_dir_and_focus_first_child<Message: 'static>(
        &mut self,
        path: &str,
    ) -> Task<Message> {
        debug_assert!(
            self.expanded_dirs.contains(path),
            "expand_dir_and_focus_first_child: path must be in expanded_dirs before calling"
        );
        self.rebuild_visible();
        if let Some(dir_idx) = self.focus_path(path) {
            if dir_idx + 1 < self.visible_tree_nodes.len() {
                self.tree_focus_index = dir_idx + 1;
                return scroll_to_tree_focus(self, ScrollMode::SnapToTop);
            }
        }
        Task::none()
    }

    /// Collapse an expanded directory and keep keyboard focus on it.
    ///
    /// Caller must have already removed `path` from [`expanded_dirs`](Self::expanded_dirs)
    /// and updated [`nodes`](Self::nodes). This method rebuilds the visible tree,
    /// re-focuses the now-collapsed directory via [`Self::focus_path`], and returns a
    /// scroll-into-view task.
    ///
    /// Returns [`Task::none()`] if the directory is no longer in the visible tree —
    /// focus is left at whatever position it ended up at after rebuilding.
    pub fn collapse_dir_and_keep_focus<Message: 'static>(&mut self, path: &str) -> Task<Message> {
        debug_assert!(
            !self.expanded_dirs.contains(path),
            "collapse_dir_and_keep_focus: path must have been removed from expanded_dirs \
             before calling"
        );
        self.rebuild_visible();
        if self.focus_path(path).is_some() {
            return scroll_to_tree_focus(self, ScrollMode::SnapToTop);
        }
        Task::none()
    }

    /// Move focus to the parent of the focused node (ArrowLeft on a collapsed
    /// directory or file). Returns a snap-to-top scroll task, or [`Task::none()`]
    /// when the focused item has no parent in the visible tree.
    pub fn focus_parent<Message: 'static>(&mut self) -> Task<Message> {
        match self.focused_parent_path() {
            Some(ref p) if self.focus_path(p).is_some() => {
                scroll_to_tree_focus(self, ScrollMode::SnapToTop)
            }
            // Root-level item has no parent — no-op.
            _ => Task::none(),
        }
    }

    /// Move focus to the row after `idx` (the first child of an expanded
    /// directory), if it exists. Returns a snap-to-top scroll task.
    ///
    /// `idx` is the already-clamped focused index from [`Self::focused_tree_node`];
    /// keeping it a parameter preserves the caller's bounds-check view even if a
    /// tree rebuild re-clamped `tree_focus_index`.
    pub fn focus_next_row<Message: 'static>(&mut self, idx: usize) -> Task<Message> {
        if idx + 1 < self.visible_tree_nodes.len() {
            self.tree_focus_index = idx + 1;
            scroll_to_tree_focus(self, ScrollMode::SnapToTop)
        } else {
            Task::none()
        }
    }

    /// Move focus one visible node in `direction` and scroll it into view.
    ///
    /// Returns [`Task::none()`] when the tree is not focused or focus is already
    /// at the boundary.
    pub fn nav_and_scroll<Message: 'static>(
        &mut self,
        direction: TreeNavDirection,
    ) -> Task<Message> {
        let moved = match direction {
            TreeNavDirection::Up => self.nav_up(),
            TreeNavDirection::Down => self.nav_down(),
        };
        if moved {
            scroll_to_tree_focus(self, ScrollMode::ScrollIntoView)
        } else {
            Task::none()
        }
    }

    /// Return the focused visible tree node, if the tree has focus and is non-empty.
    ///
    /// Returns `None` when the tree is not focused or there are no visible nodes.
    /// Otherwise returns `(clamped_index, path, is_dir)` where `clamped_index` is
    /// `tree_focus_index` clamped to `visible_tree_nodes.len() - 1`. The clamped
    /// index is returned (rather than the raw `tree_focus_index`) so callers can
    /// safely use it for subsequent adjacency checks (e.g. `idx + 1` bounds check
    /// in `TreeNavRight`).
    #[must_use]
    pub fn focused_tree_node(&self) -> Option<(usize, String, bool)> {
        if !self.tree_focused || self.visible_tree_nodes.is_empty() {
            return None;
        }
        let idx = self.tree_focus_index.min(self.visible_tree_nodes.len() - 1);
        let path = self.visible_tree_nodes[idx].0.clone();
        let is_dir = self.visible_tree_nodes[idx].1;
        Some((idx, path, is_dir))
    }

    /// Returns `true` when the focused node is a directory and is currently expanded.
    ///
    /// This is a read-only inspection helper that centralises the common
    /// `is_dir && expanded_dirs.contains(path)` check that appears in tree-navigation
    /// keyboard handlers.  Returns `false` when the tree is not focused, empty, or
    /// the focused node is a file or a collapsed directory.
    #[must_use]
    pub fn focused_is_expanded_dir(&self) -> bool {
        self.focused_tree_node()
            .is_some_and(|(_, ref path, is_dir)| is_dir && self.expanded_dirs.contains(path))
    }

    /// Returns the parent path of the focused node, or [`None`] for root-level items.
    ///
    /// Computes the parent by calling [`std::path::Path::parent`] on the focused
    /// node's full path.  Returns [`None`] when the tree is not focused, empty, or
    /// the focused node is already at the root (no parent).
    ///
    /// This is a read-only helper that replaces the repeated
    /// `Path::new(&path).parent().map(|p| p.to_string_lossy().to_string())`
    /// pattern in tree-navigation keyboard handlers.
    #[must_use]
    pub fn focused_parent_path(&self) -> Option<String> {
        let (_idx, path, _is_dir) = self.focused_tree_node()?;
        let parent = Path::new(&path).parent()?;
        let parent_str = parent.to_string_lossy().to_string();
        if parent_str.is_empty() {
            None
        } else {
            Some(parent_str)
        }
    }
}

/// Font size for file tree item labels and connector guides.
pub const TREE_FONT_SIZE: f32 = 14.0;

/// Icon size for directory nodes in the file tree (slightly larger than
/// [`TREE_FONT_SIZE`] to compensate for lucide icons appearing smaller
/// at the same nominal point size).
pub const TREE_ICON_SIZE: f32 = 15.0;

/// Minimum width of the auto-sizing file-tree panel — the tree never gets
/// narrower than this (matches the previous fixed 260px width).
pub const TREE_MIN_WIDTH: f32 = 260.0;

/// Maximum width cap of the auto-sizing file-tree panel. The cap guarantees
/// sibling panels (editor content, diff content) keep a sane minimum width
/// at the smallest supported window size.
pub const TREE_MAX_WIDTH: f32 = 400.0;

/// Right-side room reserved in the auto-sized panel width so the 6px overlay
/// scrollbar (see [`super::theme::thin_scrollbar`]) never covers the widest
/// visible row's content: 6px scrollbar + 4px breathing room.
pub const TREE_SCROLLBAR_ALLOWANCE: f32 = 10.0;

/// Horizontal padding of every tree row (`.padding([0, 8])` in the editor
/// and diff row renderers). The panel width computation adds both sides.
pub const TREE_ROW_H_PADDING: f32 = 8.0;

/// Glyph advance of JetBrains Mono as a fraction of em. Every glyph the tree
/// rows render — ASCII, box-drawing (`│ ├ └`), `⚠`, `…`, digits — measures
/// exactly 0.6em in both the Regular and Bold faces (verified from the TTFs
/// in `src/gui/`), so `chars × size × 0.6` is an exact width, not an
/// estimate. The dashboard default font is JetBrains Mono
/// (see [`super::JETBRAINS_MONO`]), so `text()` widgets without an explicit
/// font (diff ± counts, `[⚠]` suffixes) use it too.
pub const JETBRAINS_MONO_ADVANCE: f32 = 0.6;

/// Glyph advance of the lucide icon font as a fraction of em (verified from
/// the lucide TTF). Every icon in the tree measures exactly 1.0em, so an
/// icon rendered via `.size(s)` is `s` px wide.
pub const LUCIDE_ADVANCE: f32 = 1.0;

/// Width in px of `chars` glyphs of JetBrains Mono at `size` px.
///
/// Exact for every glyph the tree renders — see [`JETBRAINS_MONO_ADVANCE`].
#[must_use]
#[expect(clippy::cast_precision_loss)] // usize glyph count → px width
pub fn mono_text_width(chars: usize, size: f32) -> f32 {
    chars as f32 * size * JETBRAINS_MONO_ADVANCE
}

/// Natural content width of a rendered tree row, excluding the row's
/// horizontal padding (added by [`tree_panel_width`]).
///
/// Replicates the exact row composition in the editor and diff renderers:
/// `guide_chars` box-drawing guide glyphs (14px) + a lucide icon at
/// `icon_size` px + a 4px gap + the name label at `name_size` px, an optional
/// `name_suffix` segment preceded by another 4px gap (editor error file rows
/// render `[⚠]` at 11px), and — for diff file rows — the ± change counts at
/// 10px followed by a 6px trailing gap.
///
/// `counts` is `Some((add, remove))` for diff file rows (either string may be
/// empty; the 6px trailing gap is part of the row either way) and `None` for
/// every other row type. When both strings are non-empty they render as
/// `"{add} {remove}"` — one separating space at 10px.
///
/// JetBrains Mono is monospace with a single advance for all weights, so the
/// bold name of selected rows and the regular name of unselected rows measure
/// identically.
#[must_use]
pub fn tree_row_natural_width(
    guide_chars: usize,
    icon_size: f32,
    name: &str,
    name_size: f32,
    name_suffix: Option<(&str, f32)>,
    counts: Option<(&str, &str)>,
) -> f32 {
    let mut w = mono_text_width(guide_chars, TREE_FONT_SIZE)
        + icon_size * LUCIDE_ADVANCE
        + 4.0
        + mono_text_width(name.chars().count(), name_size);
    if let Some((suffix, size)) = name_suffix {
        w += 4.0 + mono_text_width(suffix.chars().count(), size);
    }
    if let Some((add, rem)) = counts {
        let counts_chars = if add.is_empty() {
            rem.chars().count()
        } else if rem.is_empty() {
            add.chars().count()
        } else {
            add.chars().count() + 1 + rem.chars().count()
        };
        w += mono_text_width(counts_chars, 10.0) + 6.0;
    }
    w
}

/// Collect the natural content width of every rendered tree row, in render
/// order (one entry per row — the same DFS order as the recursive node
/// renderers, which may nest multiple rows per root element).
///
/// Mirrors the render walk: a directory row is followed by its children's
/// rows when the directory is expanded. `row_width` computes one row's
/// width from the node and its nesting `depth` (0 = root).
pub fn collect_tree_row_widths(
    nodes: &[TreeNode],
    expanded: &HashSet<String>,
    row_width: impl Fn(&TreeNode, usize) -> f32,
) -> Vec<f32> {
    fn walk(
        nodes: &[TreeNode],
        expanded: &HashSet<String>,
        row_width: &impl Fn(&TreeNode, usize) -> f32,
        depth: usize,
        out: &mut Vec<f32>,
    ) {
        for node in nodes {
            out.push(row_width(node, depth));
            if node.is_dir && expanded.contains(&node.full_path) {
                walk(&node.children, expanded, row_width, depth + 1, out);
            }
        }
    }
    let mut out = Vec::new();
    walk(nodes, expanded, &row_width, 0, &mut out);
    out
}

/// Compute the auto-sized width of the tree panel from the natural content
/// width of every rendered row (in render order — see
/// [`collect_tree_row_widths`]).
///
/// Only rows currently visible in the viewport are measured. The visible
/// range is derived from [`FileTree::scroll_y`] / [`FileTree::viewport_h`]
/// with [`ESTIMATED_TREE_ROW_HEIGHT`] row spacing, extended by one row on
/// each side to absorb height-estimate drift (over-measuring is safe; the
/// result is clamped either way).
///
/// Before the first scroll event — and for trees whose content fits without
/// scrolling, where Iced never fires `on_scroll` (see
/// [`FileTree::viewport_h`]) — `viewport_h` is `None` and all rows are
/// measured: the documented fallback.
///
/// The result is the widest measured row's natural content width plus the
/// row's horizontal padding on both sides and
/// [`TREE_SCROLLBAR_ALLOWANCE`], clamped to
/// [`TREE_MIN_WIDTH`]..=[`TREE_MAX_WIDTH`]. A tree whose rows all fit at the
/// minimum width stays at [`TREE_MIN_WIDTH`].
#[must_use]
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // viewport px → row index
pub fn tree_panel_width(file_tree: &FileTree, row_widths: &[f32]) -> f32 {
    let widest = match file_tree.viewport_h {
        Some(viewport_h) if viewport_h > 0.0 => {
            let row_h = ESTIMATED_TREE_ROW_HEIGHT;
            let first = (file_tree.scroll_y / row_h).floor().max(0.0) as usize;
            let last = ((file_tree.scroll_y + viewport_h) / row_h).ceil() as usize + 1;
            row_widths
                .iter()
                .enumerate()
                .skip(first.saturating_sub(1))
                .take(last - first + 2)
                .map(|(_, w)| *w)
                .fold(0.0f32, f32::max)
        }
        // Viewport unknown — measure everything (first frame / non-scrolling
        // tree, where every row is visible anyway).
        _ => row_widths.iter().copied().fold(0.0f32, f32::max),
    };
    (widest + 2.0 * TREE_ROW_H_PADDING + TREE_SCROLLBAR_ALLOWANCE)
        .clamp(TREE_MIN_WIDTH, TREE_MAX_WIDTH)
}

/// Controls whether [`scroll_to_tree_focus`] snaps to the focused row or
/// uses viewport-aware scroll-into-view logic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollMode {
    /// Scroll so that the focused row is at the top of the viewport.
    SnapToTop,
    /// Only scroll when the focused row is outside the visible viewport.
    /// Requires [`FileTree::viewport_h`] to be `Some`; falls back to
    /// [`SnapToTop`](ScrollMode::SnapToTop) when unknown.
    ScrollIntoView,
}

/// Estimated height per tree row for scroll-into-view on keyboard navigation.
/// Derived from [`TREE_FONT_SIZE`] × Iced's default relative line height (1.3)
/// for a close approximation of actual rendered row height. File entries are
/// ~18.2 px; directory entries (with [`TREE_ICON_SIZE`] 15 pt icons) are
/// ~19.5 px.
///
/// This constant is used directly by [`scroll_to_tree_focus`] to compute
/// row positions for keyboard-navigation scroll-into-view logic.
pub const ESTIMATED_TREE_ROW_HEIGHT: f32 = TREE_FONT_SIZE * 1.3;

/// Scroll the tree panel to bring the focused row into view.
///
/// Behaviour depends on [`ScrollMode`]:
///
/// * [`SnapToTop`](ScrollMode::SnapToTop): absolute offset to
///   `tree_focus_index * ESTIMATED_TREE_ROW_HEIGHT`.
/// * [`ScrollIntoView`](ScrollMode::ScrollIntoView): only scrolls when the
///   focused row is not fully visible — for rows above the viewport the
///   row is brought to the top, for rows below the viewport the view
///   advances by one row height. Falls back to [`ScrollMode::SnapToTop`] when the
///   viewport height is unknown ([`FileTree::viewport_h`] is `None`).
///
/// Row height is approximated by [`ESTIMATED_TREE_ROW_HEIGHT`], derived
/// from [`TREE_FONT_SIZE`] × Iced's default relative line height (1.3).
///
/// This method updates [`FileTree::scroll_y`] directly so that consecutive
/// calls during the same frame see an accurate scroll offset even before the
/// `on_scroll` callback fires.
#[expect(clippy::cast_precision_loss)]
pub fn scroll_to_tree_focus<Message: 'static>(
    file_tree: &mut FileTree,
    mode: ScrollMode,
) -> Task<Message> {
    if file_tree.visible_tree_nodes.is_empty() {
        return Task::none();
    }

    let focus_y = file_tree.tree_focus_index as f32 * ESTIMATED_TREE_ROW_HEIGHT;

    match mode {
        ScrollMode::SnapToTop => absolute_scroll_to(file_tree, focus_y),
        ScrollMode::ScrollIntoView => match file_tree.viewport_h {
            None => {
                // Viewport size unknown — fall back to snap-to-top.
                absolute_scroll_to(file_tree, focus_y)
            }
            Some(viewport_h) => {
                // A row is considered "above viewport" when the bottom edge
                // of the row is above the viewport top. This avoids redundant
                // scrolling when a row is partially visible at the top edge
                // after non-row-aligned mouse-wheel scrolling.
                let row_bottom = focus_y + ESTIMATED_TREE_ROW_HEIGHT;
                let viewport_bottom = file_tree.scroll_y + viewport_h;

                if row_bottom <= file_tree.scroll_y {
                    // Focus is above the visible area — bring it to the top.
                    absolute_scroll_to(file_tree, focus_y)
                } else if focus_y >= viewport_bottom {
                    // Focus is below the visible area — advance by one row
                    // and update scroll_y directly so the next key event
                    // sees accurate state even before on_scroll fires.
                    file_tree.scroll_y = (file_tree.scroll_y + ESTIMATED_TREE_ROW_HEIGHT).max(0.0);
                    iced::widget::operation::scroll_by(
                        file_tree.tree_scroll_id.clone(),
                        iced::widget::operation::AbsoluteOffset {
                            x: 0.0,
                            y: ESTIMATED_TREE_ROW_HEIGHT,
                        },
                    )
                } else {
                    // Row is within the viewport (fully or partially visible).
                    // Partially-visible rows at the bottom edge
                    // (focus_y < viewport_bottom but row_bottom > viewport_bottom)
                    // are intentionally not scrolled — only rows whose top edge
                    // is entirely outside the viewport trigger a scroll.
                    Task::none()
                }
            }
        },
    }
}

/// Helper: absolute scroll to `y` offset and update [`FileTree::scroll_y`].
fn absolute_scroll_to<Message: 'static>(file_tree: &mut FileTree, y: f32) -> Task<Message> {
    // Best-guess update of the tracked scroll offset so that subsequent
    // ScrollIntoView checks within the same frame use a plausible value.
    file_tree.scroll_y = y.max(0.0);
    iced::widget::operation::scroll_to(
        file_tree.tree_scroll_id.clone(),
        iced::widget::operation::AbsoluteOffset { x: 0.0, y },
    )
}

/// Build a file-tree panel widget.
///
/// Renders a scrollable, auto-width column wrapping the pre-built
/// `tree_rows` elements. The panel width adapts to the widest currently
/// visible row (see [`tree_panel_width`]); a focus border is applied when
/// `file_tree.tree_focused` is true.
///
/// `row_widths` holds the natural content width of every rendered row in
/// render order — one entry per row, in the same DFS order as the recursive
/// node renderers (which may nest multiple rows per root element). See
/// [`collect_tree_row_widths`].
///
/// `on_scroll` is attached to the inner [`widget::scrollable()`] via
/// `on_scroll` and fires whenever the viewport changes
/// (scrollbar drag, mouse wheel, programmatic scroll). The caller should
/// produce a message that updates [`FileTree::scroll_y`] and
/// [`FileTree::viewport_h`] from the [`iced::widget::scrollable::Viewport`] data.
pub fn build_tree_panel<'a, Message: 'a>(
    file_tree: &'a FileTree,
    tree_rows: Vec<Element<'a, Message>>,
    row_widths: &[f32],
    on_scroll: impl Fn(scrollable::Viewport) -> Message + 'a,
) -> Element<'a, Message> {
    let panel_width = tree_panel_width(file_tree, row_widths);

    let tree_body = widget::scrollable(column(tree_rows).spacing(0))
        .id(file_tree.tree_scroll_id.clone())
        .on_scroll(on_scroll)
        .width(Length::Fill)
        .height(Length::Fill)
        .direction(theme::vertical_scrollbar())
        .style(theme::scrollbar_style);

    let tree_inner: Element<'_, Message> = container(tree_body)
        .width(Length::Fixed(panel_width))
        .height(Length::Fill)
        .style(theme::surface_container_style)
        .into();

    if file_tree.tree_focused {
        container(tree_inner)
            .style(|_t: &iced::Theme| container::Style {
                border: iced::Border {
                    color: theme::ACCENT_LIGHT,
                    width: 2.0,
                    radius: 0.0.into(),
                },
                ..Default::default()
            })
            .into()
    } else {
        tree_inner
    }
}

// ── Tree node helpers ──────────────────────────────────────────────

/// Build the guide-line prefix string for a tree node.
///
/// Returns box-drawing characters that visually connect tree siblings:
///
/// | Character | Meaning |
/// |---|---|
/// | `│` | Vertical continuation — the ancestor at this depth has more siblings below |
/// | `├` | T-junction — this node has at least one more sibling after it |
/// | `└` | Corner — this node is the last child of its parent |
/// | ` `  | No continuation at this ancestor level |
///
/// Each depth level uses exactly two characters (guide char + one space), so
/// the total visual width per level closely matches the existing 14 px indent.
///
/// `ancestor_mask` has bit `d` set iff the ancestor at depth `d` has more
/// siblings after it (requiring a vertical continuation line at that column).
/// `depth` is the current nesting depth (0 = root, which gets no prefix).
/// `is_last` is true when this node is the last child of its parent.
///
/// # Panics
///
/// Panics in debug builds when `depth >= 64` (the u64 bitmask would overflow).
#[must_use]
pub fn tree_guide_prefix(ancestor_mask: u64, depth: usize, is_last: bool) -> String {
    debug_assert!(
        depth < 64,
        "tree_guide_prefix: depth {depth} exceeds u64 bit limit (max 63)"
    );
    let mut s = String::new();
    for d in 0..depth.saturating_sub(1) {
        if ancestor_mask & (1u64 << d) != 0 {
            s.push('');
        } else {
            s.push(' ');
        }
        s.push(' ');
    }
    if depth > 0 {
        if is_last {
            s.push('');
        } else {
            s.push('');
        }
        s.push(' ');
    }
    s
}

/// Recursively render children of a tree node, computing the correct
/// continuation mask and `is_last` state for each child.
///
/// `render_node` is called for each child with `(child, depth+1, child_mask, child_is_last)`.
/// The returned elements share the lifetime `'a` of the tree nodes.
/// Returns a `Vec` of child elements, one per child, in order.
///
/// This exists to avoid duplicating the child-iteration + mask-computation
/// logic across the two render paths (editor and diff file trees).
pub fn render_tree_children<'a, Message>(
    children: &'a [TreeNode],
    depth: usize,
    ancestor_mask: u64,
    is_last: bool,
    render_node: impl Fn(&'a TreeNode, usize, u64, bool) -> Element<'a, Message>,
) -> Vec<Element<'a, Message>> {
    let child_count = children.len();
    let cont_bit = if !is_last { 1u64 << depth } else { 0u64 };
    let child_mask = ancestor_mask | cont_bit;
    children
        .iter()
        .enumerate()
        .map(|(i, child)| {
            let child_is_last = i == child_count - 1;
            render_node(child, depth + 1, child_mask, child_is_last)
        })
        .collect()
}

/// Dispatch a file-tree node to its dir or file renderer.
///
/// Shared by the editor and diff file trees so the `is_dir` branching lives
/// in one place; exactly one of the two closures is invoked.
pub fn render_tree_node<'a, Message>(
    is_dir: bool,
    render_dir: impl FnOnce() -> Element<'a, Message>,
    render_file: impl FnOnce() -> Element<'a, Message>,
) -> Element<'a, Message> {
    if is_dir { render_dir() } else { render_file() }
}

/// Check whether a tree node at the given path is currently focused
/// in the file tree's keyboard navigation.
#[must_use]
pub fn tree_node_focused(tree: &FileTree, node_path: &str) -> bool {
    tree.tree_focused
        && tree.tree_focus_index < tree.visible_tree_nodes.len()
        && tree.visible_tree_nodes[tree.tree_focus_index].0 == node_path
}

/// Return a button style closure for tree node entries.
/// When `is_highlighted` is true, uses [`theme::HOVER_STRONG`]; otherwise
/// hover gets [`theme::HOVER`], and default is transparent.
fn tree_node_button_style(
    is_highlighted: bool,
) -> impl Fn(&iced::Theme, button::Status) -> button::Style {
    move |_t: &iced::Theme, status| {
        let bg = if is_highlighted {
            theme::HOVER_STRONG
        } else if status == button::Status::Hovered {
            theme::HOVER
        } else {
            iced::Color::TRANSPARENT
        };
        button::Style {
            background: Some(iced::Background::Color(bg)),
            ..Default::default()
        }
    }
}

/// Build a tree-node button from a content row, highlight state, and
/// optional press message. Uses `tree_node_button_style` internally
/// and spans full width.
///
/// This returns only the button element — callers that need context menus
/// (e.g., the editor page) must wrap the result themselves.
pub fn tree_node_button<'a, Message: Clone + 'a>(
    content: impl Into<Element<'a, Message>>,
    is_highlighted: bool,
    on_press: Option<Message>,
) -> Element<'a, Message> {
    let mut btn = widget::button(content)
        .style(tree_node_button_style(is_highlighted))
        .width(Length::Fill)
        .padding(Padding::ZERO);
    if let Some(msg) = on_press {
        btn = btn.on_press(msg);
    }
    btn.into()
}

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

    /// Helper to create a FileTree with known visible_tree_nodes for testing.
    fn make_tree(nodes: Vec<(&str, bool)>) -> FileTree {
        let mut tree = FileTree::new(iced::widget::Id::new("test"));
        tree.visible_tree_nodes = nodes
            .into_iter()
            .map(|(p, is_dir)| (p.to_string(), is_dir))
            .collect();
        tree
    }

    #[test]
    #[expect(clippy::type_complexity)]
    fn focus_path_cases() {
        // (name, nodes, path, expected return, expected focus index)
        #[rustfmt::skip]
        let cases: &[(&str, &[(&str, bool)], &str, Option<usize>, usize)] = &[
            ("found", &[("src", true), ("src/main.rs", false), ("Cargo.toml", false)], "src/main.rs", Some(1), 1),
            ("empty_tree", &[], "anything", None, 0),
            ("first_node", &[("src", true), ("src/main.rs", false)], "src", Some(0), 0),
        ];
        for &(name, nodes, path, expected, expected_index) in cases {
            let mut tree = make_tree(nodes.to_vec());
            assert_eq!(tree.focus_path(path), expected, "case: {name}");
            assert_eq!(
                tree.tree_focus_index, expected_index,
                "case: {name} (index)"
            );
        }
    }

    #[test]
    fn focus_path_not_found() {
        let mut tree = make_tree(vec![("src", true), ("Cargo.toml", false)]);
        tree.tree_focus_index = 42;
        assert_eq!(tree.focus_path("nonexistent"), None);
        assert_eq!(tree.tree_focus_index, 42);
    }

    #[test]
    fn focus_path_updates_index_no_residual() {
        let mut tree = make_tree(vec![("a", false), ("b", false), ("c", false)]);
        // Focus on "c", then re-focus on "a" — should end up at index 0.
        tree.focus_path("c");
        assert_eq!(tree.tree_focus_index, 2);
        tree.focus_path("a");
        assert_eq!(tree.tree_focus_index, 0);
    }

    #[test]
    #[expect(clippy::type_complexity)]
    fn focused_tree_node_cases() {
        // (name, nodes, focused, focus index, expected node)
        #[rustfmt::skip]
        let cases: &[(&str, &[(&str, bool)], bool, usize, Option<(usize, &str, bool)>)] = &[
            // Tree is not focused (default).
            ("not_focused", &[("src", true), ("src/main.rs", false)], false, 0, None),
            ("empty_visible_nodes", &[], true, 0, None),
            // Set index beyond bounds — method should clamp.
            ("clamps_index", &[("a", false), ("b", false)], true, 10, Some((1, "b", false))),
            ("returns_correct_node", &[("src", true), ("src/main.rs", false), ("Cargo.toml", false)], true, 1, Some((1, "src/main.rs", false))),
            ("returns_directory", &[("src", true), ("src/main.rs", false)], true, 0, Some((0, "src", true))),
        ];
        for &(name, nodes, focused, focus_index, expected) in cases {
            let mut tree = make_tree(nodes.to_vec());
            tree.tree_focused = focused;
            tree.tree_focus_index = focus_index;
            assert_eq!(
                tree.focused_tree_node(),
                expected.map(|(i, p, d)| (i, p.to_string(), d)),
                "case: {name}"
            );
        }
    }

    // ── nav_up / nav_down tests ──────────────────────────────────────

    #[test]
    fn nav_cases() {
        // (name, direction, focused, start index, expected moved, expected index)
        let cases: &[(&str, &str, bool, usize, bool, usize)] = &[
            ("up_at_top_clamped", "up", true, 0, false, 0),
            ("down_at_bottom_clamped", "down", true, 1, false, 1),
            ("up_moves_focus", "up", true, 1, true, 0),
            ("down_moves_focus", "down", true, 0, true, 1),
            ("ignored_when_not_focused_up", "up", false, 0, false, 0),
            ("ignored_when_not_focused_down", "down", false, 0, false, 0),
        ];
        for &(name, dir, focused, start, expected_moved, expected_index) in cases {
            let mut tree = make_tree(vec![("a", false), ("b", false)]);
            tree.tree_focused = focused;
            tree.tree_focus_index = start;
            let moved = if dir == "up" {
                tree.nav_up()
            } else {
                tree.nav_down()
            };
            assert_eq!(moved, expected_moved, "case: {name}");
            assert_eq!(
                tree.tree_focus_index, expected_index,
                "case: {name} (index)"
            );
        }
    }

    // ── rebuild_visible clamping tests ────────────────────────────────

    #[test]
    fn rebuild_visible_clamps_high_focus_index() {
        let mut tree = FileTree::new(iced::widget::Id::new("test"));
        tree.nodes = vec![
            TreeNode {
                name: "a".into(),
                full_path: "a".into(),
                is_dir: false,
                children: vec![],
                error: None,
            },
            TreeNode {
                name: "b".into(),
                full_path: "b".into(),
                is_dir: false,
                children: vec![],
                error: None,
            },
            TreeNode {
                name: "c".into(),
                full_path: "c".into(),
                is_dir: false,
                children: vec![],
                error: None,
            },
        ];
        tree.rebuild_visible();
        assert_eq!(tree.visible_tree_nodes.len(), 3);
        tree.tree_focus_index = 999;
        tree.rebuild_visible();
        assert_eq!(tree.tree_focus_index, 2);
    }

    #[test]
    fn rebuild_visible_empty_tree_resets_focus_index() {
        let mut tree = make_tree(vec![("a", false)]);
        tree.tree_focus_index = 0;
        tree.nodes.clear();
        tree.expanded_dirs.clear();
        tree.rebuild_visible();
        assert!(tree.visible_tree_nodes.is_empty());
        assert_eq!(tree.tree_focus_index, 0);
    }

    // ── focused_is_expanded_dir tests ────────────────────────────────

    #[test]
    #[expect(clippy::type_complexity)]
    fn focused_is_expanded_dir_cases() {
        // (name, nodes, focused, expanded dir, expected)
        #[rustfmt::skip]
        let cases: &[(&str, &[(&str, bool)], bool, Option<&str>, bool)] = &[
            // Tree is not focused.
            ("not_focused", &[("src", true)], false, None, false),
            ("empty_tree", &[], true, None, false),
            ("file", &[("main.rs", false)], true, None, false),
            // "src" is a directory but not in expanded_dirs.
            ("collapsed_directory", &[("src", true)], true, None, false),
            ("expanded_directory", &[("src", true)], true, Some("src"), true),
        ];
        for &(name, nodes, focused, expanded, expected) in cases {
            let mut tree = make_tree(nodes.to_vec());
            tree.tree_focused = focused;
            if let Some(dir) = expanded {
                tree.expanded_dirs.insert(dir.into());
            }
            assert_eq!(tree.focused_is_expanded_dir(), expected, "case: {name}");
        }
    }

    // ── focused_parent_path tests ────────────────────────────────────

    #[test]
    fn focused_parent_path_cases() {
        // (name, nodes, focused, expected)
        #[rustfmt::skip]
        #[expect(clippy::type_complexity)] // focused_parent_path case table
        let cases: &[(&str, &[(&str, bool)], bool, Option<&str>)] = &[
            ("not_focused", &[("src/main.rs", false)], false, None),
            ("empty_tree", &[], true, None),
            // Root-level item — no parent.
            ("root_item", &[("src", true)], true, None),
            ("nested", &[("src/main.rs", false)], true, Some("src")),
            ("deep_nested", &[("a/b/c/file.rs", false)], true, Some("a/b/c")),
        ];
        for &(name, nodes, focused, expected) in cases {
            let mut tree = make_tree(nodes.to_vec());
            tree.tree_focused = focused;
            assert_eq!(
                tree.focused_parent_path(),
                expected.map(str::to_string),
                "case: {name}"
            );
        }
    }

    // ── tree_guide_prefix tests ────────────────────────────────────────────

    /// A single test case for [`tree_guide_prefix`].
    struct GuidePrefixCase {
        /// Human-readable name for failure diagnostics.
        name: &'static str,
        /// Which ancestor depths have continuation markers.
        mask: u64,
        /// Depth of the current node.
        depth: usize,
        /// Whether this is the last child at its depth.
        is_last: bool,
        /// Expected guide prefix string.
        expected: &'static str,
    }

    #[expect(clippy::too_many_lines)]
    #[test]
    fn tree_guide_prefix_cases() {
        let cases = [
            // Root-level nodes have no guide lines regardless of mask or is_last.
            GuidePrefixCase {
                name: "root, mask=0, not last",
                mask: 0,
                depth: 0,
                is_last: false,
                expected: "",
            },
            GuidePrefixCase {
                name: "root, mask=0, last",
                mask: 0,
                depth: 0,
                is_last: true,
                expected: "",
            },
            GuidePrefixCase {
                name: "root, mask=all, not last",
                mask: 0b_1111,
                depth: 0,
                is_last: false,
                expected: "",
            },
            // Depth 1, no ancestor continuation.
            GuidePrefixCase {
                name: "depth 1, mask=0, not last",
                mask: 0,
                depth: 1,
                is_last: false,
                expected: "",
            },
            GuidePrefixCase {
                name: "depth 1, mask=0, last",
                mask: 0,
                depth: 1,
                is_last: true,
                expected: "",
            },
            // Depth 1, ancestor at depth 0 continues.
            GuidePrefixCase {
                name: "depth 1, mask=0b01, not last",
                mask: 0b_01,
                depth: 1,
                is_last: false,
                expected: "",
            },
            GuidePrefixCase {
                name: "depth 1, mask=0b01, last",
                mask: 0b_01,
                depth: 1,
                is_last: true,
                expected: "",
            },
            // Depth 2: ancestor depth 0 continues, depth 1 does not.
            GuidePrefixCase {
                name: "depth 2, mask=0b01, not last",
                mask: 0b_01,
                depth: 2,
                is_last: false,
                expected: "│ ├ ",
            },
            // Depth 2: both ancestors continue.
            GuidePrefixCase {
                name: "depth 2, mask=0b11, not last",
                mask: 0b_11,
                depth: 2,
                is_last: false,
                expected: "│ ├ ",
            },
            GuidePrefixCase {
                name: "depth 2, mask=0b11, last",
                mask: 0b_11,
                depth: 2,
                is_last: true,
                expected: "│ └ ",
            },
            // Depth 2: neither ancestor continues.
            GuidePrefixCase {
                name: "depth 2, mask=0, not last",
                mask: 0,
                depth: 2,
                is_last: false,
                expected: "",
            },
            GuidePrefixCase {
                name: "depth 2, mask=0, last",
                mask: 0,
                depth: 2,
                is_last: true,
                expected: "",
            },
            // Depth 5: ancestors at 0,1,3 continue; 2 does not.
            GuidePrefixCase {
                name: "depth 5, mask=0b1011, not last",
                mask: 0b_1011,
                depth: 5,
                is_last: false,
                expected: "│ │   │ ├ ",
            },
            GuidePrefixCase {
                name: "depth 5, mask=0b1011, last",
                mask: 0b_1011,
                depth: 5,
                is_last: true,
                expected: "│ │   │ └ ",
            },
            // Bits beyond depth should be ignored.
            GuidePrefixCase {
                name: "high bits, mask=0x100, not last",
                mask: 0b1_0000_0000,
                depth: 1,
                is_last: false,
                expected: "",
            },
            GuidePrefixCase {
                name: "high bits, mask=0x100, last",
                mask: 0b1_0000_0000,
                depth: 1,
                is_last: true,
                expected: "",
            },
        ];

        for case in &cases {
            assert_eq!(
                tree_guide_prefix(case.mask, case.depth, case.is_last),
                case.expected,
                "case '{}' failed",
                case.name
            );
        }
    }

    #[test]
    #[should_panic(expected = "exceeds u64 bit limit")]
    fn guide_prefix_depth_overflow_debug() {
        // debug_assert fires at depth >= 64 in debug builds.
        let _ = tree_guide_prefix(0, 64, false);
    }

    // ── Auto-sizing tree panel width tests ───────────────────────────
    //
    // These are pure-arithmetic tests of the geometry constants (0.6em mono
    // advance, 1.0em lucide, 4px gaps, 10px counts, 6px trailing gap) — they
    // do not touch the global font system, so the expected values are exact.

    #[test]
    fn mono_text_width_uses_06em_advance() {
        assert!(close(mono_text_width(0, 14.0), 0.0));
        assert!(close(mono_text_width(1, 14.0), 8.4));
        assert!(close(mono_text_width(10, 14.0), 84.0));
        // "binary" count label at 10px.
        assert!(close(mono_text_width(6, 10.0), 36.0));
    }

    #[test]
    fn tree_row_natural_width_plain_file_row() {
        // Depth 1 (guide 2 chars) + 14px icon + 4px gap + 11-char name.
        let w =
            tree_row_natural_width(2, TREE_FONT_SIZE, "src/main.rs", TREE_FONT_SIZE, None, None);
        assert!(close(w, 127.2));
    }

    #[test]
    fn tree_row_natural_width_dir_loading_suffix() {
        // Root dir row: 15px icon + 4px gap + "src  Loading…" (13 glyphs).
        let w = tree_row_natural_width(
            0,
            TREE_ICON_SIZE,
            "src  Loading…",
            TREE_FONT_SIZE,
            None,
            None,
        );
        assert!(close(w, 128.2));
    }

    #[test]
    fn tree_row_natural_width_error_file_suffix() {
        // Error file row: name + 4px gap + "[⚠]" at 11px.
        let w = tree_row_natural_width(
            0,
            TREE_FONT_SIZE,
            "broken.txt",
            TREE_FONT_SIZE,
            Some(("[⚠]", 11.0)),
            None,
        );
        assert!(close(w, 125.8));
    }

    #[test]
    fn tree_row_natural_width_diff_counts() {
        // Diff file row: name + "+123 -45" at 10px + 6px trailing gap.
        let w = tree_row_natural_width(
            0,
            TREE_FONT_SIZE,
            "lib.rs",
            TREE_FONT_SIZE,
            None,
            Some(("+123", "-45")),
        );
        assert!(close(w, 122.4));
    }

    #[test]
    fn tree_row_natural_width_diff_binary_count() {
        // 8-char name + "binary" at 10px + 6px trailing gap.
        let w = tree_row_natural_width(
            0,
            TREE_FONT_SIZE,
            "data.bin",
            TREE_FONT_SIZE,
            None,
            Some(("binary", "")),
        );
        assert!(close(w, 127.2));
    }

    /// Epsilon-equality for the pure-arithmetic width tests (0.001px is far
    /// below any visible difference; the formulas use `f32` accumulation).
    fn close(a: f32, b: f32) -> bool {
        (a - b).abs() < 0.001
    }

    /// Build a FileTree with a known viewport for panel-width tests.
    fn tree_with_panel_viewport(scroll_y: f32, viewport_h: Option<f32>) -> FileTree {
        let mut tree = FileTree::new(iced::widget::Id::new("width_test"));
        tree.scroll_y = scroll_y;
        tree.viewport_h = viewport_h;
        tree
    }

    #[test]
    fn tree_panel_width_clamps_to_minimum() {
        // Short rows → widest 68.4 + 26 = 94.4 < 260 → stays at minimum.
        let tree = tree_with_panel_viewport(0.0, Some(400.0));
        let widths = vec![68.4, 100.0, 50.0];
        assert!(close(tree_panel_width(&tree, &widths), TREE_MIN_WIDTH));
    }

    #[test]
    fn tree_panel_width_clamps_to_maximum() {
        // 50-char name → natural 438 → 464 → clamped to the 400px cap.
        let tree = tree_with_panel_viewport(0.0, Some(400.0));
        let long_name = "x".repeat(50);
        let widths = vec![tree_row_natural_width(
            0,
            TREE_FONT_SIZE,
            &long_name,
            TREE_FONT_SIZE,
            None,
            None,
        )];
        assert!(close(tree_panel_width(&tree, &widths), TREE_MAX_WIDTH));
    }

    #[test]
    fn tree_panel_width_scales_with_widest_row() {
        // 27-char name → 261.6 natural → 287.6 panel (within the bounds).
        let tree = tree_with_panel_viewport(0.0, Some(400.0));
        let wide = tree_row_natural_width(
            2,
            TREE_FONT_SIZE,
            "some_really_long_file_name.rs",
            TREE_FONT_SIZE,
            None,
            None,
        );
        let widths = vec![68.4, wide, 50.0];
        assert!(close(
            tree_panel_width(&tree, &widths),
            wide + 2.0 * TREE_ROW_H_PADDING + TREE_SCROLLBAR_ALLOWANCE
        ));
    }

    #[test]
    fn tree_panel_width_measures_all_rows_without_viewport() {
        // viewport_h None (first frame / non-scrolling fallback): all rows count.
        let tree = tree_with_panel_viewport(0.0, None);
        let long_name = "y".repeat(40);
        let wide =
            tree_row_natural_width(0, TREE_FONT_SIZE, &long_name, TREE_FONT_SIZE, None, None);
        let widths = vec![50.0, wide, 60.0];
        assert!(close(
            tree_panel_width(&tree, &widths),
            (wide + 2.0 * TREE_ROW_H_PADDING + TREE_SCROLLBAR_ALLOWANCE)
                .clamp(TREE_MIN_WIDTH, TREE_MAX_WIDTH)
        ));
    }

    #[test]
    fn tree_panel_width_filters_out_of_viewport_rows() {
        // Viewport 200px tall at scroll 0 → rows ~0..14 measured.
        let tree = tree_with_panel_viewport(0.0, Some(200.0));
        let mut widths = vec![68.4; 50];
        widths[40] = 500.0; // below the fold → must not inflate the width
        assert!(close(tree_panel_width(&tree, &widths), TREE_MIN_WIDTH));
        widths[2] = 500.0; // visible → inflates to the cap
        assert!(close(tree_panel_width(&tree, &widths), TREE_MAX_WIDTH));
    }

    #[test]
    fn tree_panel_width_scrolled_viewport_measures_mid_rows() {
        // scroll_y 400, viewport 200 → rows ~20..35 measured.
        let tree = tree_with_panel_viewport(400.0, Some(200.0));
        let mut widths = vec![68.4; 60];
        widths[10] = 500.0; // above the fold → ignored
        assert!(close(tree_panel_width(&tree, &widths), TREE_MIN_WIDTH));
        widths[30] = 500.0; // visible → inflates to the cap
        assert!(close(tree_panel_width(&tree, &widths), TREE_MAX_WIDTH));
    }

    #[test]
    fn tree_panel_width_empty_tree_stays_at_minimum() {
        let tree = tree_with_panel_viewport(0.0, None);
        assert!(close(tree_panel_width(&tree, &[]), TREE_MIN_WIDTH));
    }

    #[test]
    #[expect(clippy::cast_precision_loss)] // test-only encoding closure (depth, name length)
    fn collect_tree_row_widths_mirrors_render_order() {
        // src (dir, expanded) → src/main.rs, src/lib.rs; Cargo.toml at root.
        let mut tree = FileTree::new(iced::widget::Id::new("w"));
        tree.nodes = vec![
            TreeNode {
                name: "src".into(),
                full_path: "src".into(),
                is_dir: true,
                children: vec![
                    TreeNode {
                        name: "main.rs".into(),
                        full_path: "src/main.rs".into(),
                        is_dir: false,
                        children: vec![],
                        error: None,
                    },
                    TreeNode {
                        name: "lib.rs".into(),
                        full_path: "src/lib.rs".into(),
                        is_dir: false,
                        children: vec![],
                        error: None,
                    },
                ],
                error: None,
            },
            TreeNode {
                name: "Cargo.toml".into(),
                full_path: "Cargo.toml".into(),
                is_dir: false,
                children: vec![],
                error: None,
            },
        ];
        tree.expanded_dirs.insert("src".to_string());

        // Closure encodes depth and name length so the order is observable.
        let widths = collect_tree_row_widths(&tree.nodes, &tree.expanded_dirs, |node, depth| {
            depth as f32 * 10.0 + node.name.chars().count() as f32
        });
        assert_eq!(widths, vec![3.0, 17.0, 16.0, 10.0]);

        // Collapsed src → only the two root rows remain.
        tree.expanded_dirs.clear();
        let widths = collect_tree_row_widths(&tree.nodes, &tree.expanded_dirs, |node, depth| {
            depth as f32 * 10.0 + node.name.chars().count() as f32
        });
        assert_eq!(widths, vec![3.0, 10.0]);
    }

    // ── expand_dir_and_focus_first_child / collapse_dir_and_keep_focus tests ──

    /// Build a `FileTree` with a `src/` directory containing `lib.rs` and `main.rs`.
    /// The returned tree has `nodes` populated (pre-sorted) and `visible_tree_nodes`
    /// initially empty. Callers expand/collapse `"src"` as needed and call the helpers.
    fn tree_with_src_dir() -> FileTree {
        let mut tree = FileTree::new(iced::widget::Id::new("test"));
        tree.nodes = vec![TreeNode {
            name: "src".into(),
            full_path: "src".into(),
            is_dir: true,
            children: vec![
                TreeNode {
                    name: "lib.rs".into(),
                    full_path: "src/lib.rs".into(),
                    is_dir: false,
                    children: vec![],
                    error: None,
                },
                TreeNode {
                    name: "main.rs".into(),
                    full_path: "src/main.rs".into(),
                    is_dir: false,
                    children: vec![],
                    error: None,
                },
            ],
            error: None,
        }];
        tree
    }

    #[test]
    fn expand_dir_advances_to_first_child() {
        let mut tree = tree_with_src_dir();
        tree.expanded_dirs.insert("src".into());
        // No visible nodes yet — rebuild is part of the helper.
        assert!(tree.visible_tree_nodes.is_empty());

        let _task = tree.expand_dir_and_focus_first_child::<()>("src");

        // Rebuilt visible tree: src, src/lib.rs, src/main.rs
        assert_eq!(tree.visible_tree_nodes.len(), 3);
        assert_eq!(tree.visible_tree_nodes[0].0, "src");
        assert_eq!(tree.visible_tree_nodes[1].0, "src/lib.rs");
        assert_eq!(tree.visible_tree_nodes[2].0, "src/main.rs");
        // Focus advances to the first child (right after "src").
        assert_eq!(tree.tree_focus_index, 1);
    }

    #[test]
    fn expand_dir_no_children_stays_on_dir() {
        let mut tree = tree_with_src_dir();
        tree.expanded_dirs.insert("src".into());
        // Remove children so the directory has no expandable content.
        tree.nodes[0].children.clear();

        let _task = tree.expand_dir_and_focus_first_child::<()>("src");

        // Only "src" in the visible tree.
        assert_eq!(tree.visible_tree_nodes.len(), 1);
        assert_eq!(tree.visible_tree_nodes[0].0, "src");
        // Focus stays on "src" because there is no child to advance to.
        assert_eq!(tree.tree_focus_index, 0);
    }

    #[test]
    fn expand_dir_not_in_expanded_dirs_panics_in_debug() {
        let mut tree = tree_with_src_dir();
        // Intentionally NOT inserting into expanded_dirs — the debug_assert
        // should fire. Use a catch_unwind to avoid test failure in release builds.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _task = tree.expand_dir_and_focus_first_child::<()>("src");
        }));
        // In debug builds this panics; in release builds it doesn't.
        #[cfg(debug_assertions)]
        assert!(
            result.is_err(),
            "debug_assert should fire when path not in expanded_dirs"
        );
        #[cfg(not(debug_assertions))]
        assert!(result.is_ok(), "no panic expected in release builds");
    }

    #[test]
    fn collapse_dir_keeps_focus_on_directory() {
        let mut tree = tree_with_src_dir();
        // Pre-expand so collapsing has an effect.
        tree.expanded_dirs.insert("src".into());
        tree.rebuild_visible();
        assert_eq!(tree.visible_tree_nodes.len(), 3); // src, lib.rs, main.rs

        // Now collapse — remove from expanded_dirs and call the helper.
        tree.expanded_dirs.remove("src");
        let _task = tree.collapse_dir_and_keep_focus::<()>("src");

        // Collapsed: only "src" visible.
        assert_eq!(tree.visible_tree_nodes.len(), 1);
        assert_eq!(tree.visible_tree_nodes[0].0, "src");
        // Focus stays on "src".
        assert_eq!(tree.tree_focus_index, 0);
    }

    #[test]
    fn collapse_dir_not_in_visible_tree_still_finds_it() {
        let mut tree = tree_with_src_dir();
        // "src" has been removed from expanded_dirs and visible_tree_nodes is empty.
        // Even without an explicit rebuild_visible first, the helper should
        // rebuild and find "src" since it's still in nodes.
        let _task = tree.collapse_dir_and_keep_focus::<()>("src");

        // After rebuild_visible, "src" should appear (it's in nodes).
        assert_eq!(tree.visible_tree_nodes.len(), 1);
        assert_eq!(tree.visible_tree_nodes[0].0, "src");
        assert_eq!(tree.tree_focus_index, 0);
    }

    #[test]
    fn collapse_dir_still_in_expanded_dirs_panics_in_debug() {
        let mut tree = tree_with_src_dir();
        tree.expanded_dirs.insert("src".into());
        // Call without removing from expanded_dirs first — debug_assert fires.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _task = tree.collapse_dir_and_keep_focus::<()>("src");
        }));
        #[cfg(debug_assertions)]
        assert!(
            result.is_err(),
            "debug_assert should fire when path still in expanded_dirs"
        );
        #[cfg(not(debug_assertions))]
        assert!(result.is_ok(), "no panic expected in release builds");
    }

    // ── scroll_to_tree_focus / ScrollIntoView tests ──────────────────

    /// Helper: build a FileTree with `n` flat file entries, a known viewport
    /// height, and `scroll_y` set to a given offset.
    fn tree_with_viewport(n: usize, scroll_y: f32, viewport_h: f32) -> FileTree {
        let mut tree = FileTree::new(iced::widget::Id::new("scroll_test"));
        tree.visible_tree_nodes = (0..n).map(|i| (format!("file_{i}.rs"), false)).collect();
        tree.scroll_y = scroll_y;
        tree.viewport_h = Some(viewport_h);
        tree
    }

    #[test]
    fn scroll_into_view_row_fully_visible_no_scroll() {
        // Viewport: y=40..440 (400px tall, starting at row index ~2)
        // Focus on index 3. Row spans y=54..72 (3 * 18 = 54).
        // Viewport bottom is 440. Row is fully within 40..440.
        let mut tree = tree_with_viewport(30, 40.0, 400.0);
        tree.tree_focus_index = 3; // 3 * ~18.2 = ~54.6

        let _task = scroll_to_tree_focus::<()>(&mut tree, ScrollMode::ScrollIntoView);

        // scroll_y unchanged — no scroll needed.
        assert!(
            (tree.scroll_y - 40.0).abs() < 0.01,
            "scroll_y should remain 40"
        );
    }

    #[test]
    fn scroll_into_view_row_below_viewport_advances_one_row() {
        // Viewport: y=0..200 (200px tall)
        // Focus on index 15 (y~273). Row bottom ~291.2.
        // Row is below viewport bottom (200).
        let mut tree = tree_with_viewport(30, 0.0, 200.0);
        tree.tree_focus_index = 15; // 15 * ~18.2 = ~273

        let _task = scroll_to_tree_focus::<()>(&mut tree, ScrollMode::ScrollIntoView);

        // scroll_y advanced by one row height (~18.2px).
        assert!(
            (tree.scroll_y - 18.2_f32).abs() < 0.01,
            "scroll_y should advance by ~18.2, got {}",
            tree.scroll_y
        );
    }

    #[test]
    fn scroll_into_view_row_above_viewport_brings_to_top() {
        // Viewport: y=100..500 (400px tall)
        // Focus on index 3 (y~54.6). Row bottom ~72.8.
        // Row bottom (~72.8) is above viewport top (100).
        let mut tree = tree_with_viewport(30, 100.0, 400.0);
        tree.tree_focus_index = 3; // 3 * ~18.2 = ~54.6

        let _task = scroll_to_tree_focus::<()>(&mut tree, ScrollMode::ScrollIntoView);

        // scroll_y set to focus_y (~54.6) — bring row to top.
        assert!(
            (tree.scroll_y - 54.6).abs() < 0.01,
            "scroll_y should be ~54.6, got {}",
            tree.scroll_y
        );
    }

    #[test]
    fn scroll_into_view_partially_visible_at_top_edge_no_scroll() {
        // Viewport: y=50..450 (400px tall)
        // Focus on index 2 (y~36.4). Row bottom ~54.6.
        // Row bottom (~54.6) is below viewport top (50) → partially visible.
        let mut tree = tree_with_viewport(30, 50.0, 400.0);
        tree.tree_focus_index = 2; // 2 * ~18.2 = ~36.4

        let _task = scroll_to_tree_focus::<()>(&mut tree, ScrollMode::ScrollIntoView);

        // scroll_y unchanged — row is partially visible at top edge.
        assert!(
            (tree.scroll_y - 50.0).abs() < 0.01,
            "scroll_y should remain 50, got {}",
            tree.scroll_y
        );
    }

    #[test]
    fn scroll_into_view_unknown_viewport_falls_back_to_snap() {
        // viewport_h is None — should fall back to SnapToTop.
        let mut tree = tree_with_viewport(30, 10.0, 0.0);
        tree.viewport_h = None;
        tree.tree_focus_index = 10; // 10 * ~18.2 = ~182

        let _task = scroll_to_tree_focus::<()>(&mut tree, ScrollMode::ScrollIntoView);

        // Falls back to absolute scroll: scroll_y = focus_y ≈ 182.
        assert!(
            (tree.scroll_y - 182.0).abs() < 0.01,
            "scroll_y should snap to ~182, got {}",
            tree.scroll_y
        );
    }

    #[test]
    fn scroll_snap_to_top_sets_scroll_y() {
        let mut tree = tree_with_viewport(30, 0.0, 400.0);
        tree.tree_focus_index = 8; // 8 * ~18.2 = ~145.6

        let _task = scroll_to_tree_focus::<()>(&mut tree, ScrollMode::SnapToTop);

        // SnapToTop sets scroll_y to focus_y.
        assert!(
            (tree.scroll_y - 145.6).abs() < 0.01,
            "scroll_y should be ~145.6, got {}",
            tree.scroll_y
        );
    }

    #[test]
    fn scroll_into_view_empty_tree_noop() {
        let mut tree = FileTree::new(iced::widget::Id::new("scroll_test"));
        tree.viewport_h = Some(400.0);

        // Must bind (not discard) because iced::Task is #[must_use].
        let _task = scroll_to_tree_focus::<()>(&mut tree, ScrollMode::ScrollIntoView);

        // The task type is opaque, but we can verify it's not panicking
        // and that scroll_y stays at its default.
        assert!((tree.scroll_y - 0.0).abs() < 0.01);
        // The function returns Task::none() for empty trees.
        // We can't easily inspect Task contents, so we just check no crash.
    }
}