jackdaw 0.3.0

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

use bevy::{ecs::system::SystemParam, input_focus::InputFocus, prelude::*};

use crate::colors;
use crate::{
    commands::CommandHistory,
    draw_brush::{CreateBrushCommand, brush_data_from_entity},
    keybinds::{EditorAction, KeybindRegistry},
    selection::{Selected, Selection},
    viewport::{MainViewportCamera, SceneViewport},
    viewport_util::{point_in_polygon_2d, point_to_segment_dist, window_to_viewport_cursor},
};

const MIN_EXTRUDE_DEPTH: f32 = 0.01;

use super::hull::rebuild_brush_from_vertices;
use super::{BrushEditMode, BrushMeshCache, BrushSelection, EditMode, SetBrush};
use jackdaw_geometry::{
    EPSILON, brush_planes_to_world, compute_brush_geometry, compute_face_tangent_axes,
    point_inside_all_planes,
};
use jackdaw_jsn::{Brush, BrushFaceData, BrushGroup, BrushPlane};

/// Bundled keyboard + keybind input to keep system parameter counts under the 16-param limit.
#[derive(SystemParam)]
pub(super) struct KeyboardInput<'w> {
    pub keyboard: Res<'w, ButtonInput<KeyCode>>,
    pub keybinds: Res<'w, KeybindRegistry>,
}

pub(super) fn handle_edit_mode_keys(
    input_focus: Res<InputFocus>,
    input: KeyboardInput,
    selection: Res<Selection>,
    mut edit_mode: ResMut<EditMode>,
    mut brush_selection: ResMut<BrushSelection>,
    modal: Res<crate::modal_transform::ModalTransformState>,
    brushes: Query<(), With<Brush>>,
    face_drag: Res<BrushDragState>,
    vertex_drag: Res<VertexDragState>,
    edge_drag: Res<EdgeDragState>,
    clip_state: Res<ClipState>,
) {
    let keyboard = &input.keyboard;
    let keybinds = &input.keybinds;
    if input_focus.0.is_some() || modal.active.is_some() {
        return;
    }

    // Exit brush edit mode if the brush entity gets deselected
    if let EditMode::BrushEdit(_) = *edit_mode {
        if let Some(brush_entity) = brush_selection.entity {
            if selection.primary() != Some(brush_entity) {
                // Save last selected face for extend-to-brush fallback
                if !brush_selection.faces.is_empty() {
                    brush_selection.last_face_entity = Some(brush_entity);
                    brush_selection.last_face_index = brush_selection.faces.last().copied();
                }
                *edit_mode = EditMode::Object;
                brush_selection.entity = None;
                brush_selection.faces.clear();
                brush_selection.vertices.clear();
                brush_selection.edges.clear();
            }
        }
    }

    // Don't switch modes while any drag is active
    if face_drag.active || vertex_drag.active || edge_drag.active {
        return;
    }
    if face_drag.pending.is_some() || vertex_drag.pending.is_some() || edge_drag.pending.is_some() {
        return;
    }

    // 1/2/3/4 toggle brush sub-element modes
    let pressed_mode = if keybinds.just_pressed(EditorAction::VertexMode, keyboard) {
        Some(BrushEditMode::Vertex)
    } else if keybinds.just_pressed(EditorAction::EdgeMode, keyboard) {
        Some(BrushEditMode::Edge)
    } else if keybinds.just_pressed(EditorAction::FaceMode, keyboard) {
        Some(BrushEditMode::Face)
    } else if keybinds.just_pressed(EditorAction::ClipMode, keyboard) {
        Some(BrushEditMode::Clip)
    } else {
        None
    };

    if let Some(target_mode) = pressed_mode {
        if let EditMode::BrushEdit(current) = *edit_mode {
            if current == target_mode {
                // Same key again: toggle off to Object
                *edit_mode = EditMode::Object;
                brush_selection.entity = None;
                brush_selection.faces.clear();
                brush_selection.vertices.clear();
                brush_selection.edges.clear();
            } else {
                // Switch sub-mode, clear sub-element selections
                *edit_mode = EditMode::BrushEdit(target_mode);
                brush_selection.faces.clear();
                brush_selection.vertices.clear();
                brush_selection.edges.clear();
            }
        } else {
            // From Object mode: enter edit on primary if it's a brush
            if let Some(entity) = selection.primary().filter(|&e| brushes.contains(e)) {
                *edit_mode = EditMode::BrushEdit(target_mode);
                brush_selection.entity = Some(entity);
                brush_selection.faces.clear();
                brush_selection.vertices.clear();
                brush_selection.edges.clear();
            }
        }
        return;
    }

    // Escape: exit to Object (unless Clip mode with pending points)
    if keybinds.just_pressed(EditorAction::ExitEditMode, keyboard) {
        if let EditMode::BrushEdit(BrushEditMode::Clip) = *edit_mode {
            if !clip_state.points.is_empty() {
                // Let clip mode's own Escape handler clear the points first
                return;
            }
        }
        if matches!(*edit_mode, EditMode::BrushEdit(_)) {
            *edit_mode = EditMode::Object;
            brush_selection.entity = None;
            brush_selection.faces.clear();
            brush_selection.vertices.clear();
            brush_selection.edges.clear();
        }
    }
}

pub(super) fn brush_face_interact(
    mut edit_mode: ResMut<EditMode>,
    mouse: Res<ButtonInput<MouseButton>>,
    input: KeyboardInput,
    windows: Query<&Window>,
    camera_query: Query<(&Camera, &GlobalTransform), With<MainViewportCamera>>,
    viewport_query: Query<(&ComputedNode, &UiGlobalTransform), With<SceneViewport>>,
    face_entities: Query<(Entity, &super::BrushFaceEntity, &GlobalTransform)>,
    mut brush_selection: ResMut<BrushSelection>,
    brush_caches: Query<&BrushMeshCache>,
    selection: Res<Selection>,
    mut brushes: Query<(&mut Brush, &GlobalTransform)>,
    mut drag_state: ResMut<BrushDragState>,
    input_focus: Res<InputFocus>,
    mut history: ResMut<CommandHistory>,
    mut commands: Commands,
    snap_settings: Res<crate::snapping::SnapSettings>,
) {
    let keyboard = &input.keyboard;
    let keybinds = &input.keybinds;
    let in_face_edit = matches!(*edit_mode, EditMode::BrushEdit(BrushEditMode::Face));

    // PageUp/PageDown: nudge selected face vertices vertically (gabling)
    if in_face_edit
        && !drag_state.active
        && drag_state.pending.is_none()
        && !brush_selection.faces.is_empty()
    {
        if let Some(brush_entity) = brush_selection.entity {
            let nudge_dir = if keybinds.key_just_pressed(EditorAction::NudgeUp, keyboard) {
                Some(1.0)
            } else if keybinds.key_just_pressed(EditorAction::NudgeDown, keyboard) {
                Some(-1.0)
            } else {
                None
            };
            if let Some(dir) = nudge_dir {
                let grid = snap_settings.grid_size();
                if let Ok(cache) = brush_caches.get(brush_entity) {
                    if let Ok((mut brush, _)) = brushes.get_mut(brush_entity) {
                        let old = brush.clone();
                        let offset = Vec3::new(0.0, dir * grid, 0.0);
                        let mut new_verts = cache.vertices.clone();
                        // Collect unique vertex indices from all selected faces
                        let mut affected: HashSet<usize> = HashSet::new();
                        for &fi in &brush_selection.faces {
                            if let Some(poly) = cache.face_polygons.get(fi) {
                                affected.extend(poly.iter().copied());
                            }
                        }
                        for vi in &affected {
                            if *vi < new_verts.len() {
                                new_verts[*vi] += offset;
                            }
                        }
                        if let Some((new_brush, old_to_new)) = rebuild_brush_from_vertices(
                            &old,
                            &cache.vertices,
                            &cache.face_polygons,
                            &new_verts,
                        ) {
                            *brush = new_brush;
                            // Remap face selection to match new face ordering
                            brush_selection.faces = brush_selection
                                .faces
                                .iter()
                                .filter_map(|&fi| old_to_new.get(fi).copied())
                                .collect();
                            let cmd = SetBrush {
                                entity: brush_entity,
                                old,
                                new: brush.clone(),
                                label: "Nudge brush face".to_string(),
                            };
                            history.undo_stack.push(Box::new(cmd));
                            history.redo_stack.clear();
                        }
                    }
                }
                return;
            }
        }
    }

    if !in_face_edit && drag_state.pending.is_none() && !drag_state.active {
        // Not in face mode. Shift+click or Alt+click enters quick face edit
        let shift = keyboard.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight]);
        let alt = keyboard.any_pressed([KeyCode::AltLeft, KeyCode::AltRight]);
        if !(shift || alt) || !mouse.just_pressed(MouseButton::Left) {
            return;
        }
        // Fall through to face picking below
    }

    if input_focus.0.is_some() && !in_face_edit {
        return;
    }

    let Ok(window) = windows.single() else {
        return;
    };
    let Some(cursor_pos) = window.cursor_position() else {
        return;
    };
    let Ok((camera, cam_tf)) = camera_query.single() else {
        return;
    };
    let Some(viewport_cursor) = window_to_viewport_cursor(cursor_pos, camera, &viewport_query)
    else {
        return;
    };

    let ctrl = keyboard.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]);
    let alt = keyboard.any_pressed([KeyCode::AltLeft, KeyCode::AltRight]);

    // Cancel active drag on Escape or right-click
    if drag_state.active {
        if keybinds.just_pressed(EditorAction::ExitEditMode, keyboard)
            || mouse.just_pressed(MouseButton::Right)
        {
            match drag_state.extrude_mode {
                FaceExtrudeMode::Merge => {
                    // Revert brush to start state
                    if let Some(brush_entity) = brush_selection.entity {
                        if let Some(ref start) = drag_state.start_brush {
                            if let Ok((mut brush, _)) = brushes.get_mut(brush_entity) {
                                *brush = start.clone();
                            }
                        }
                    }
                }
                FaceExtrudeMode::Extend => {
                    // Original brush was never modified, just clear state
                }
            }
            drag_state.active = false;
            drag_state.pending = None;
            drag_state.extend_face_polygon.clear();
            drag_state.extend_depth = 0.0;
            if drag_state.quick_action {
                *edit_mode = EditMode::Object;
                brush_selection.entity = None;
                brush_selection.faces.clear();
                brush_selection.vertices.clear();
                brush_selection.edges.clear();
                drag_state.quick_action = false;
            }
            return;
        }
    }

    // Release: commit drag
    if mouse.just_released(MouseButton::Left) {
        if drag_state.active {
            match drag_state.extrude_mode {
                FaceExtrudeMode::Merge => {
                    if let Some(brush_entity) = brush_selection.entity {
                        if let Some(ref start) = drag_state.start_brush {
                            if let Ok((brush, _)) = brushes.get(brush_entity) {
                                let cmd = SetBrush {
                                    entity: brush_entity,
                                    old: start.clone(),
                                    new: brush.clone(),
                                    label: "Move brush face".to_string(),
                                };
                                history.undo_stack.push(Box::new(cmd));
                                history.redo_stack.clear();
                            }
                        }
                    }
                }
                FaceExtrudeMode::Extend => {
                    if drag_state.extend_depth.abs() > MIN_EXTRUDE_DEPTH {
                        spawn_extruded_brush(
                            &drag_state.extend_face_polygon,
                            drag_state.extend_face_normal,
                            drag_state.extend_depth,
                            &mut commands,
                        );
                    }
                }
            }
            drag_state.active = false;
            drag_state.extend_face_polygon.clear();
            drag_state.extend_depth = 0.0;
        }
        let was_quick = drag_state.quick_action;
        drag_state.pending = None;
        if was_quick {
            *edit_mode = EditMode::Object;
            brush_selection.entity = None;
            brush_selection.faces.clear();
            brush_selection.vertices.clear();
            brush_selection.edges.clear();
            drag_state.quick_action = false;
        }
        return;
    }

    // Pending → active promotion (5px threshold)
    if let Some(ref pending) = drag_state.pending {
        if mouse.pressed(MouseButton::Left) && !drag_state.active {
            let dist = (cursor_pos - pending.click_pos).length();
            if dist > 5.0 {
                // Promote to active drag
                if let Some(brush_entity) = brush_selection.entity {
                    if let Ok((brush, brush_global)) = brushes.get(brush_entity) {
                        drag_state.active = true;
                        drag_state.start_cursor = viewport_cursor;
                        // Use the first selected face's normal
                        if let Some(&face_idx) = brush_selection.faces.first() {
                            if face_idx < brush.faces.len() {
                                drag_state.drag_face_normal = brush.faces[face_idx].plane.normal;
                            }
                        }

                        match drag_state.extrude_mode {
                            FaceExtrudeMode::Merge => {
                                drag_state.start_brush = Some(brush.clone());
                            }
                            FaceExtrudeMode::Extend => {
                                // Capture world-space face polygon vertices for preview
                                let (_, brush_rot, _) =
                                    brush_global.to_scale_rotation_translation();
                                drag_state.extend_face_normal =
                                    (brush_rot * drag_state.drag_face_normal).normalize();
                                if let Ok(cache) = brush_caches.get(brush_entity) {
                                    if let Some(&face_idx) = brush_selection.faces.first() {
                                        let polygon = &cache.face_polygons[face_idx];
                                        drag_state.extend_face_polygon = polygon
                                            .iter()
                                            .map(|&vi| {
                                                brush_global.transform_point(cache.vertices[vi])
                                            })
                                            .collect();
                                    }
                                }
                                drag_state.extend_depth = 0.0;
                            }
                        }
                    }
                }
            }
        }
    }

    // Continue active drag
    if drag_state.active {
        let Some(brush_entity) = brush_selection.entity else {
            drag_state.active = false;
            return;
        };

        match drag_state.extrude_mode {
            FaceExtrudeMode::Merge => {
                // Adjust face plane distance (push/pull)
                let Ok((mut brush, brush_global)) = brushes.get_mut(brush_entity) else {
                    drag_state.active = false;
                    return;
                };
                let Some(ref start) = drag_state.start_brush else {
                    drag_state.active = false;
                    return;
                };

                let brush_pos = brush_global.translation();
                let Ok(origin_screen) = camera.world_to_viewport(cam_tf, brush_pos) else {
                    return;
                };
                let Ok(normal_screen) =
                    camera.world_to_viewport(cam_tf, brush_pos + drag_state.drag_face_normal)
                else {
                    return;
                };
                let screen_dir = (normal_screen - origin_screen).normalize_or_zero();
                let mouse_delta = viewport_cursor - drag_state.start_cursor;
                let projected = mouse_delta.dot(screen_dir);

                let cam_dist = (cam_tf.translation() - brush_pos).length();
                let drag_amount = projected * cam_dist * 0.003;
                let drag_amount = if snap_settings.translate_active(ctrl)
                    && snap_settings.translate_increment > 0.0
                {
                    (drag_amount / snap_settings.translate_increment).round()
                        * snap_settings.translate_increment
                } else {
                    drag_amount
                };

                for &face_idx in &brush_selection.faces {
                    if face_idx < start.faces.len() && face_idx < brush.faces.len() {
                        brush.faces[face_idx].plane.distance =
                            start.faces[face_idx].plane.distance + drag_amount;
                    }
                }
            }
            FaceExtrudeMode::Extend => {
                // Compute extend depth from mouse projection, don't modify original brush
                if drag_state.extend_face_polygon.is_empty() {
                    drag_state.active = false;
                    return;
                }

                let face_centroid: Vec3 = drag_state.extend_face_polygon.iter().sum::<Vec3>()
                    / drag_state.extend_face_polygon.len() as f32;
                let world_normal = drag_state.extend_face_normal;

                let Ok(origin_screen) = camera.world_to_viewport(cam_tf, face_centroid) else {
                    return;
                };
                let Ok(normal_screen) =
                    camera.world_to_viewport(cam_tf, face_centroid + world_normal)
                else {
                    return;
                };
                let screen_dir = (normal_screen - origin_screen).normalize_or_zero();
                let mouse_delta = viewport_cursor - drag_state.start_cursor;
                let projected = mouse_delta.dot(screen_dir);

                let cam_dist = (cam_tf.translation() - face_centroid).length();
                let raw_depth = projected * cam_dist * 0.003;
                drag_state.extend_depth = if snap_settings.translate_active(ctrl)
                    && snap_settings.translate_increment > 0.0
                {
                    (raw_depth / snap_settings.translate_increment).round()
                        * snap_settings.translate_increment
                } else {
                    raw_depth
                };
            }
        }
        return;
    }

    // Mouse press: pick face and start pending drag
    if !mouse.just_pressed(MouseButton::Left) {
        return;
    }

    // Determine which brush entity to work with
    let brush_entity = if in_face_edit {
        brush_selection.entity
    } else {
        selection.primary().filter(|&e| brushes.contains(e))
    };
    let Some(brush_entity) = brush_entity else {
        return;
    };

    let Ok(cache) = brush_caches.get(brush_entity) else {
        return;
    };

    // Find face whose screen-space polygon contains the cursor.
    // When multiple faces overlap (e.g. back-face behind front-face),
    // pick the one whose centroid is closest to the camera.
    let mut best_face = None;
    let mut best_depth = f32::MAX;

    for (_, face_ent, face_global) in &face_entities {
        if face_ent.brush_entity != brush_entity {
            continue;
        }
        let face_idx = face_ent.face_index;
        let polygon = &cache.face_polygons[face_idx];
        if polygon.len() < 3 {
            continue;
        }

        let brush_tf = face_global;

        // Project face polygon vertices to screen space
        let screen_verts: Vec<Vec2> = polygon
            .iter()
            .filter_map(|&vi| {
                let world = brush_tf.transform_point(cache.vertices[vi]);
                camera.world_to_viewport(cam_tf, world).ok()
            })
            .collect();
        if screen_verts.len() < 3 {
            continue;
        }

        if point_in_polygon_2d(viewport_cursor, &screen_verts) {
            // Use depth of centroid to resolve overlapping faces
            let centroid: Vec3 =
                polygon.iter().map(|&vi| cache.vertices[vi]).sum::<Vec3>() / polygon.len() as f32;
            let world_centroid = brush_tf.transform_point(centroid);
            let depth = (cam_tf.translation() - world_centroid).length_squared();
            if depth < best_depth {
                best_depth = depth;
                best_face = Some(face_idx);
            }
        }
    }

    if let Some(face_idx) = best_face {
        // Auto-enter face edit mode if not already in it
        if !in_face_edit {
            *edit_mode = EditMode::BrushEdit(BrushEditMode::Face);
            brush_selection.entity = Some(brush_entity);
            brush_selection.faces.clear();
            brush_selection.vertices.clear();
            brush_selection.edges.clear();
            drag_state.quick_action = true;
        }

        if in_face_edit && ctrl {
            // Ctrl+click in face mode: toggle multi-select (no drag)
            if let Some(pos) = brush_selection.faces.iter().position(|&f| f == face_idx) {
                brush_selection.faces.remove(pos);
            } else {
                brush_selection.faces.push(face_idx);
            }
        } else {
            brush_selection.faces = vec![face_idx];
            // Determine extrude mode:
            // - From Object mode: Shift = Merge (push/pull), Alt = Extend (new brush)
            // - In face mode: plain drag = Merge
            if !in_face_edit {
                drag_state.extrude_mode = if alt {
                    FaceExtrudeMode::Extend
                } else {
                    FaceExtrudeMode::Merge
                };
            } else {
                drag_state.extrude_mode = FaceExtrudeMode::Merge;
                drag_state.quick_action = false;
            }
            // Record pending drag
            drag_state.pending = Some(PendingSubDrag {
                click_pos: cursor_pos,
            });
        }
    } else if in_face_edit && !ctrl {
        // Click outside any face: exit to Object mode
        *edit_mode = EditMode::Object;
        brush_selection.entity = None;
        brush_selection.faces.clear();
        brush_selection.vertices.clear();
        brush_selection.edges.clear();
    }
}

fn spawn_extruded_brush(
    face_polygon_world: &[Vec3],
    world_normal: Vec3,
    depth: f32,
    commands: &mut Commands,
) {
    if face_polygon_world.len() < 3 || depth.abs() < MIN_EXTRUDE_DEPTH {
        return;
    }

    let face_polygon = face_polygon_world.to_vec();
    let normal = world_normal;

    commands.queue(move |world: &mut World| {
        // Compute volume center = face centroid + normal * depth/2
        let face_centroid: Vec3 = face_polygon.iter().sum::<Vec3>() / face_polygon.len() as f32;
        let center = face_centroid + normal * depth / 2.0;

        // Build rotation: local Y = face normal (same pattern as spawn_drawn_brush)
        let rotation = if normal == Vec3::Y {
            Quat::IDENTITY
        } else if normal == Vec3::NEG_Y {
            Quat::from_rotation_x(std::f32::consts::PI)
        } else {
            let (u, _v) = compute_face_tangent_axes(normal);
            let target_mat = Mat3::from_cols(u, normal, -normal.cross(u).normalize());
            Quat::from_mat3(&target_mat)
        };
        let inv_rotation = rotation.inverse();

        // Convert polygon vertices to local space (centered at `center`)
        let local_verts: Vec<Vec3> = face_polygon
            .iter()
            .map(|&v| inv_rotation * (v - center))
            .collect();

        let Some(mut brush) = Brush::prism(&local_verts, Vec3::Y, depth) else {
            return;
        };

        // Apply last-used material
        let last_mat = world.resource::<super::LastUsedMaterial>().material.clone();
        if let Some(ref mat) = last_mat {
            for face in &mut brush.faces {
                face.material = mat.clone();
            }
        }

        let entity = world
            .spawn((
                Name::new("Brush"),
                brush,
                Transform {
                    translation: center,
                    rotation,
                    scale: Vec3::ONE,
                },
                Visibility::default(),
            ))
            .id();

        // Select the new brush
        {
            let selection = world.resource::<Selection>();
            let old_selected: Vec<Entity> = selection.entities.clone();
            for &e in &old_selected {
                if let Ok(mut ec) = world.get_entity_mut(e) {
                    ec.remove::<Selected>();
                }
            }
            let mut selection = world.resource_mut::<Selection>();
            selection.entities = vec![entity];
            world.entity_mut(entity).insert(Selected);
        }

        // Store brush data for undo
        let cmd = CreateBrushCommand {
            data: brush_data_from_entity(world, entity),
        };
        let mut history = world.resource_mut::<CommandHistory>();
        history.undo_stack.push(Box::new(cmd));
        history.redo_stack.clear();
    });
}

pub(super) fn brush_vertex_interact(
    mut edit_mode: ResMut<EditMode>,
    mouse: Res<ButtonInput<MouseButton>>,
    input: KeyboardInput,
    windows: Query<&Window>,
    camera_query: Query<(&Camera, &GlobalTransform), With<MainViewportCamera>>,
    viewport_query: Query<(&ComputedNode, &UiGlobalTransform), With<SceneViewport>>,
    brush_transforms: Query<&GlobalTransform>,
    mut brush_selection: ResMut<BrushSelection>,
    brush_caches: Query<&BrushMeshCache>,
    mut brushes: Query<&mut Brush>,
    mut drag_state: ResMut<VertexDragState>,
    input_focus: Res<InputFocus>,
    mut history: ResMut<CommandHistory>,
    snap_settings: Res<crate::snapping::SnapSettings>,
) {
    let keyboard = &input.keyboard;
    let keybinds = &input.keybinds;
    let EditMode::BrushEdit(BrushEditMode::Vertex) = *edit_mode else {
        drag_state.active = false;
        drag_state.pending = None;
        return;
    };
    if input_focus.0.is_some() {
        return;
    }

    let Some(brush_entity) = brush_selection.entity else {
        return;
    };

    // PageUp/PageDown: nudge selected vertices vertically (no cursor needed)
    if !drag_state.active && drag_state.pending.is_none() && !brush_selection.vertices.is_empty() {
        let nudge_dir = if keybinds.key_just_pressed(EditorAction::NudgeUp, keyboard) {
            Some(1.0)
        } else if keybinds.key_just_pressed(EditorAction::NudgeDown, keyboard) {
            Some(-1.0)
        } else {
            None
        };
        if let Some(dir) = nudge_dir {
            let grid = snap_settings.grid_size();
            if let Ok(cache) = brush_caches.get(brush_entity) {
                if let Ok(mut brush) = brushes.get_mut(brush_entity) {
                    let old = brush.clone();
                    let offset = Vec3::new(0.0, dir * grid, 0.0);
                    let mut new_verts = cache.vertices.clone();
                    for &vi in &brush_selection.vertices {
                        if vi < new_verts.len() {
                            new_verts[vi] += offset;
                        }
                    }
                    if let Some((new_brush, _)) = rebuild_brush_from_vertices(
                        &old,
                        &cache.vertices,
                        &cache.face_polygons,
                        &new_verts,
                    ) {
                        *brush = new_brush;
                        let cmd = SetBrush {
                            entity: brush_entity,
                            old,
                            new: brush.clone(),
                            label: "Nudge brush vertex".to_string(),
                        };
                        history.undo_stack.push(Box::new(cmd));
                        history.redo_stack.clear();
                    }
                }
            }
            return;
        }
    }

    let Ok(window) = windows.single() else {
        return;
    };
    let Some(cursor_pos) = window.cursor_position() else {
        return;
    };
    let Ok((camera, cam_tf)) = camera_query.single() else {
        return;
    };
    let Some(viewport_cursor) = window_to_viewport_cursor(cursor_pos, camera, &viewport_query)
    else {
        return;
    };

    // Axis constraint toggle during active drag
    if drag_state.active {
        if keybinds.just_pressed(EditorAction::ConstrainX, keyboard) {
            drag_state.constraint = if drag_state.constraint == VertexDragConstraint::AxisX {
                VertexDragConstraint::Free
            } else {
                VertexDragConstraint::AxisX
            };
        } else if keybinds.just_pressed(EditorAction::ConstrainY, keyboard) {
            drag_state.constraint = if drag_state.constraint == VertexDragConstraint::AxisY {
                VertexDragConstraint::Free
            } else {
                VertexDragConstraint::AxisY
            };
        } else if keybinds.just_pressed(EditorAction::ConstrainZ, keyboard) {
            drag_state.constraint = if drag_state.constraint == VertexDragConstraint::AxisZ {
                VertexDragConstraint::Free
            } else {
                VertexDragConstraint::AxisZ
            };
        }
    }

    // Cancel active drag on Escape or right-click
    if drag_state.active {
        if keybinds.just_pressed(EditorAction::ExitEditMode, keyboard)
            || mouse.just_pressed(MouseButton::Right)
        {
            if let Some(ref start) = drag_state.start_brush {
                if let Ok(mut brush) = brushes.get_mut(brush_entity) {
                    *brush = start.clone();
                }
            }
            drag_state.active = false;
            drag_state.pending = None;
            drag_state.constraint = VertexDragConstraint::Free;
            drag_state.split_vertex = None;
            return;
        }
    }

    // Release: commit drag
    if mouse.just_released(MouseButton::Left) {
        if drag_state.active {
            if let Some(ref start) = drag_state.start_brush {
                if let Ok(brush) = brushes.get(brush_entity) {
                    let label = if drag_state.split_vertex.is_some() {
                        "Split brush vertex"
                    } else {
                        "Move brush vertex"
                    };
                    let cmd = SetBrush {
                        entity: brush_entity,
                        old: start.clone(),
                        new: brush.clone(),
                        label: label.to_string(),
                    };
                    history.undo_stack.push(Box::new(cmd));
                    history.redo_stack.clear();
                }
            }
            drag_state.active = false;
            drag_state.constraint = VertexDragConstraint::Free;
        }
        drag_state.pending = None;
        drag_state.split_vertex = None;
        return;
    }

    // Pending → active promotion (5px threshold)
    if let Some(ref pending) = drag_state.pending {
        if mouse.pressed(MouseButton::Left) && !drag_state.active {
            let dist = (cursor_pos - pending.click_pos).length();
            if dist > 5.0 {
                if let Ok(cache) = brush_caches.get(brush_entity) {
                    if let Ok(brush) = brushes.get(brush_entity) {
                        drag_state.active = true;
                        drag_state.constraint = VertexDragConstraint::Free;
                        drag_state.start_brush = Some(brush.clone());
                        drag_state.start_cursor = viewport_cursor;

                        // Build start vertices, possibly with split vertex appended
                        let mut all_verts = cache.vertices.clone();
                        if let Some(split_pos) = drag_state.split_vertex {
                            all_verts.push(split_pos);
                        }

                        drag_state.start_vertex_positions = brush_selection
                            .vertices
                            .iter()
                            .map(|&vi| all_verts.get(vi).copied().unwrap_or(Vec3::ZERO))
                            .collect();
                        drag_state.start_all_vertices = all_verts;
                        drag_state.start_face_polygons = cache.face_polygons.clone();
                    }
                }
            }
        }
    }

    // Continue active drag
    if drag_state.active {
        let Ok(mut brush) = brushes.get_mut(brush_entity) else {
            drag_state.active = false;
            return;
        };
        let Some(ref start) = drag_state.start_brush else {
            drag_state.active = false;
            return;
        };
        let Ok(brush_global) = brush_transforms.get(brush_entity) else {
            return;
        };

        let mouse_delta = viewport_cursor - drag_state.start_cursor;
        let Some(local_offset) = compute_brush_drag_offset(
            drag_state.constraint,
            mouse_delta,
            cam_tf,
            camera,
            brush_global,
        ) else {
            return;
        };

        let mut new_verts = drag_state.start_all_vertices.clone();
        for (sel_idx, &vert_idx) in brush_selection.vertices.iter().enumerate() {
            if sel_idx < drag_state.start_vertex_positions.len() && vert_idx < new_verts.len() {
                new_verts[vert_idx] = drag_state.start_vertex_positions[sel_idx] + local_offset;
            }
        }

        if let Some((new_brush, _)) = rebuild_brush_from_vertices(
            start,
            &drag_state.start_all_vertices,
            &drag_state.start_face_polygons,
            &new_verts,
        ) {
            *brush = new_brush;
        }
        return;
    }

    // Mouse press: pick vertex and start pending drag
    if !mouse.just_pressed(MouseButton::Left) {
        return;
    }

    let Ok(cache) = brush_caches.get(brush_entity) else {
        return;
    };
    let Ok(brush_global) = brush_transforms.get(brush_entity) else {
        return;
    };

    let shift = keyboard.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight]);
    let ctrl = keyboard.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]);

    // Shift+click: pick edge midpoint or face center for vertex split
    if shift && !ctrl {
        // Collect unique edges from face polygons
        let mut unique_edges: Vec<(usize, usize)> = Vec::new();
        for polygon in &cache.face_polygons {
            if polygon.len() < 2 {
                continue;
            }
            for i in 0..polygon.len() {
                let a = polygon[i];
                let b = polygon[(i + 1) % polygon.len()];
                let edge = (a.min(b), a.max(b));
                if !unique_edges.contains(&edge) {
                    unique_edges.push(edge);
                }
            }
        }

        let mut best_split: Option<Vec3> = None;
        let mut best_dist = 20.0_f32;

        // Try edge midpoints first
        for &(a, b) in &unique_edges {
            let midpoint = (cache.vertices[a] + cache.vertices[b]) * 0.5;
            let world_pos = brush_global.transform_point(midpoint);
            if let Ok(screen_pos) = camera.world_to_viewport(cam_tf, world_pos) {
                let dist = (screen_pos - viewport_cursor).length();
                if dist < best_dist {
                    best_dist = dist;
                    best_split = Some(midpoint);
                }
            }
        }

        // Fallback: face centers
        if best_split.is_none() {
            best_dist = 20.0;
            for polygon in &cache.face_polygons {
                if polygon.len() < 3 {
                    continue;
                }
                let centroid: Vec3 = polygon.iter().map(|&vi| cache.vertices[vi]).sum::<Vec3>()
                    / polygon.len() as f32;
                let world_pos = brush_global.transform_point(centroid);
                if let Ok(screen_pos) = camera.world_to_viewport(cam_tf, world_pos) {
                    let dist = (screen_pos - viewport_cursor).length();
                    if dist < best_dist {
                        best_dist = dist;
                        best_split = Some(centroid);
                    }
                }
            }
        }

        if let Some(split_pos) = best_split {
            let new_idx = cache.vertices.len();
            brush_selection.vertices = vec![new_idx];
            drag_state.split_vertex = Some(split_pos);
            drag_state.pending = Some(PendingSubDrag {
                click_pos: cursor_pos,
            });
        }
        return;
    }

    // Normal vertex picking
    let mut best_vert = None;
    let mut best_dist = 20.0_f32;

    for (vi, v) in cache.vertices.iter().enumerate() {
        let world_pos = brush_global.transform_point(*v);
        if let Ok(screen_pos) = camera.world_to_viewport(cam_tf, world_pos) {
            let dist = (screen_pos - viewport_cursor).length();
            if dist < best_dist {
                best_dist = dist;
                best_vert = Some(vi);
            }
        }
    }

    if let Some(vi) = best_vert {
        if ctrl {
            // Ctrl+click: toggle multi-select, no drag
            if let Some(pos) = brush_selection.vertices.iter().position(|&v| v == vi) {
                brush_selection.vertices.remove(pos);
            } else {
                brush_selection.vertices.push(vi);
            }
        } else {
            brush_selection.vertices = vec![vi];
            // Record pending drag
            drag_state.pending = Some(PendingSubDrag {
                click_pos: cursor_pos,
            });
        }
    } else if !ctrl {
        // Click outside any vertex: exit to Object mode
        *edit_mode = EditMode::Object;
        brush_selection.entity = None;
        brush_selection.faces.clear();
        brush_selection.vertices.clear();
        brush_selection.edges.clear();
    }
}

pub(super) fn brush_edge_interact(
    mut edit_mode: ResMut<EditMode>,
    mouse: Res<ButtonInput<MouseButton>>,
    input: KeyboardInput,
    windows: Query<&Window>,
    camera_query: Query<(&Camera, &GlobalTransform), With<MainViewportCamera>>,
    viewport_query: Query<(&ComputedNode, &UiGlobalTransform), With<SceneViewport>>,
    brush_transforms: Query<&GlobalTransform>,
    mut brush_selection: ResMut<BrushSelection>,
    brush_caches: Query<&BrushMeshCache>,
    mut brushes: Query<&mut Brush>,
    mut drag_state: ResMut<EdgeDragState>,
    input_focus: Res<InputFocus>,
    mut history: ResMut<CommandHistory>,
    snap_settings: Res<crate::snapping::SnapSettings>,
) {
    let keyboard = &input.keyboard;
    let keybinds = &input.keybinds;
    let EditMode::BrushEdit(BrushEditMode::Edge) = *edit_mode else {
        drag_state.active = false;
        drag_state.pending = None;
        return;
    };
    if input_focus.0.is_some() {
        return;
    }

    let Some(brush_entity) = brush_selection.entity else {
        return;
    };

    // PageUp/PageDown: nudge selected edge vertices vertically (no cursor needed)
    if !drag_state.active && drag_state.pending.is_none() && !brush_selection.edges.is_empty() {
        let nudge_dir = if keybinds.key_just_pressed(EditorAction::NudgeUp, keyboard) {
            Some(1.0)
        } else if keybinds.key_just_pressed(EditorAction::NudgeDown, keyboard) {
            Some(-1.0)
        } else {
            None
        };
        if let Some(dir) = nudge_dir {
            let grid = snap_settings.grid_size();
            if let Ok(cache) = brush_caches.get(brush_entity) {
                if let Ok(mut brush) = brushes.get_mut(brush_entity) {
                    let old = brush.clone();
                    let offset = Vec3::new(0.0, dir * grid, 0.0);
                    let mut new_verts = cache.vertices.clone();
                    let mut seen = HashSet::new();
                    for &(a, b) in &brush_selection.edges {
                        if seen.insert(a) && a < new_verts.len() {
                            new_verts[a] += offset;
                        }
                        if seen.insert(b) && b < new_verts.len() {
                            new_verts[b] += offset;
                        }
                    }
                    if let Some((new_brush, _)) = rebuild_brush_from_vertices(
                        &old,
                        &cache.vertices,
                        &cache.face_polygons,
                        &new_verts,
                    ) {
                        *brush = new_brush;
                        let cmd = SetBrush {
                            entity: brush_entity,
                            old,
                            new: brush.clone(),
                            label: "Nudge brush edge".to_string(),
                        };
                        history.undo_stack.push(Box::new(cmd));
                        history.redo_stack.clear();
                    }
                }
            }
            return;
        }
    }

    let Ok(window) = windows.single() else {
        return;
    };
    let Some(cursor_pos) = window.cursor_position() else {
        return;
    };
    let Ok((camera, cam_tf)) = camera_query.single() else {
        return;
    };
    let Some(viewport_cursor) = window_to_viewport_cursor(cursor_pos, camera, &viewport_query)
    else {
        return;
    };

    // Axis constraint toggle during active drag
    if drag_state.active {
        if keybinds.just_pressed(EditorAction::ConstrainX, keyboard) {
            drag_state.constraint = if drag_state.constraint == VertexDragConstraint::AxisX {
                VertexDragConstraint::Free
            } else {
                VertexDragConstraint::AxisX
            };
        } else if keybinds.just_pressed(EditorAction::ConstrainY, keyboard) {
            drag_state.constraint = if drag_state.constraint == VertexDragConstraint::AxisY {
                VertexDragConstraint::Free
            } else {
                VertexDragConstraint::AxisY
            };
        } else if keybinds.just_pressed(EditorAction::ConstrainZ, keyboard) {
            drag_state.constraint = if drag_state.constraint == VertexDragConstraint::AxisZ {
                VertexDragConstraint::Free
            } else {
                VertexDragConstraint::AxisZ
            };
        }
    }

    // Cancel active drag on Escape or right-click
    if drag_state.active {
        if keybinds.just_pressed(EditorAction::ExitEditMode, keyboard)
            || mouse.just_pressed(MouseButton::Right)
        {
            if let Some(ref start) = drag_state.start_brush {
                if let Ok(mut brush) = brushes.get_mut(brush_entity) {
                    *brush = start.clone();
                }
            }
            drag_state.active = false;
            drag_state.pending = None;
            drag_state.constraint = VertexDragConstraint::Free;
            return;
        }
    }

    // Release: commit drag
    if mouse.just_released(MouseButton::Left) {
        if drag_state.active {
            if let Some(ref start) = drag_state.start_brush {
                if let Ok(brush) = brushes.get(brush_entity) {
                    let cmd = SetBrush {
                        entity: brush_entity,
                        old: start.clone(),
                        new: brush.clone(),
                        label: "Move brush edge".to_string(),
                    };
                    history.undo_stack.push(Box::new(cmd));
                    history.redo_stack.clear();
                }
            }
            drag_state.active = false;
            drag_state.constraint = VertexDragConstraint::Free;
        }
        drag_state.pending = None;
        return;
    }

    // Pending → active promotion (5px threshold)
    if let Some(ref pending) = drag_state.pending {
        if mouse.pressed(MouseButton::Left) && !drag_state.active {
            let dist = (cursor_pos - pending.click_pos).length();
            if dist > 5.0 {
                if let Ok(cache) = brush_caches.get(brush_entity) {
                    if let Ok(brush) = brushes.get(brush_entity) {
                        drag_state.active = true;
                        drag_state.constraint = VertexDragConstraint::Free;
                        drag_state.start_brush = Some(brush.clone());
                        drag_state.start_cursor = viewport_cursor;
                        drag_state.start_all_vertices = cache.vertices.clone();
                        drag_state.start_face_polygons = cache.face_polygons.clone();

                        let mut seen = HashSet::new();
                        let mut edge_verts = Vec::new();
                        for &(a, b) in &brush_selection.edges {
                            if seen.insert(a) {
                                let pos = cache.vertices.get(a).copied().unwrap_or(Vec3::ZERO);
                                edge_verts.push((a, pos));
                            }
                            if seen.insert(b) {
                                let pos = cache.vertices.get(b).copied().unwrap_or(Vec3::ZERO);
                                edge_verts.push((b, pos));
                            }
                        }
                        drag_state.start_edge_vertices = edge_verts;
                    }
                }
            }
        }
    }

    // Continue active drag
    if drag_state.active {
        let Ok(mut brush) = brushes.get_mut(brush_entity) else {
            drag_state.active = false;
            return;
        };
        let Some(ref start) = drag_state.start_brush else {
            drag_state.active = false;
            return;
        };
        let Ok(brush_global) = brush_transforms.get(brush_entity) else {
            return;
        };

        let mouse_delta = viewport_cursor - drag_state.start_cursor;
        let Some(local_offset) = compute_brush_drag_offset(
            drag_state.constraint,
            mouse_delta,
            cam_tf,
            camera,
            brush_global,
        ) else {
            return;
        };

        let mut new_verts = drag_state.start_all_vertices.clone();
        for &(vi, start_pos) in &drag_state.start_edge_vertices {
            if vi < new_verts.len() {
                new_verts[vi] = start_pos + local_offset;
            }
        }

        if let Some((new_brush, _)) = rebuild_brush_from_vertices(
            start,
            &drag_state.start_all_vertices,
            &drag_state.start_face_polygons,
            &new_verts,
        ) {
            *brush = new_brush;
        }
        return;
    }

    // Mouse press: pick edge and start pending drag
    if !mouse.just_pressed(MouseButton::Left) {
        return;
    }

    let Ok(cache) = brush_caches.get(brush_entity) else {
        return;
    };
    let Ok(brush_global) = brush_transforms.get(brush_entity) else {
        return;
    };

    // Collect unique edges from face polygons
    let mut unique_edges: Vec<(usize, usize)> = Vec::new();
    for polygon in &cache.face_polygons {
        if polygon.len() < 2 {
            continue;
        }
        for i in 0..polygon.len() {
            let a = polygon[i];
            let b = polygon[(i + 1) % polygon.len()];
            let edge = (a.min(b), a.max(b));
            if !unique_edges.contains(&edge) {
                unique_edges.push(edge);
            }
        }
    }

    let mut best_edge = None;
    let mut best_dist = 20.0_f32;

    for &(a, b) in &unique_edges {
        let wa = brush_global.transform_point(cache.vertices[a]);
        let wb = brush_global.transform_point(cache.vertices[b]);
        let Ok(sa) = camera.world_to_viewport(cam_tf, wa) else {
            continue;
        };
        let Ok(sb) = camera.world_to_viewport(cam_tf, wb) else {
            continue;
        };
        let dist = point_to_segment_dist(viewport_cursor, sa, sb);
        if dist < best_dist {
            best_dist = dist;
            best_edge = Some((a, b));
        }
    }

    let ctrl = keyboard.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]);
    if let Some(edge) = best_edge {
        if ctrl {
            // Ctrl+click: toggle multi-select, no drag
            if let Some(pos) = brush_selection.edges.iter().position(|e| *e == edge) {
                brush_selection.edges.remove(pos);
            } else {
                brush_selection.edges.push(edge);
            }
        } else {
            brush_selection.edges = vec![edge];
            // Record pending drag
            drag_state.pending = Some(PendingSubDrag {
                click_pos: cursor_pos,
            });
        }
    } else if !ctrl {
        // Click outside any edge: exit to Object mode
        *edit_mode = EditMode::Object;
        brush_selection.entity = None;
        brush_selection.faces.clear();
        brush_selection.vertices.clear();
        brush_selection.edges.clear();
    }
}

pub(crate) struct PendingSubDrag {
    pub click_pos: Vec2,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub(crate) enum FaceExtrudeMode {
    #[default]
    Merge, // Push/pull existing face plane
    Extend, // Create new brush from face extrusion
}

#[derive(Resource, Default)]
pub(crate) struct BrushDragState {
    pub pending: Option<PendingSubDrag>,
    pub active: bool,
    pub extrude_mode: FaceExtrudeMode,
    /// When true, exits to Object mode when drag completes or is cancelled.
    pub quick_action: bool,
    start_brush: Option<Brush>,
    start_cursor: Vec2,
    drag_face_normal: Vec3,
    /// World-space face polygon vertices for extend preview.
    pub extend_face_polygon: Vec<Vec3>,
    /// World-space face normal for extend preview.
    pub extend_face_normal: Vec3,
    /// Current extrude depth during extend drag.
    pub extend_depth: f32,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub(crate) enum VertexDragConstraint {
    #[default]
    Free,
    AxisX,
    AxisY,
    AxisZ,
}

#[derive(Resource, Default)]
pub(crate) struct VertexDragState {
    pub pending: Option<PendingSubDrag>,
    pub active: bool,
    pub constraint: VertexDragConstraint,
    start_brush: Option<Brush>,
    start_cursor: Vec2,
    start_vertex_positions: Vec<Vec3>,
    /// Full vertex list at drag start (for hull rebuild).
    start_all_vertices: Vec<Vec3>,
    /// Per-face polygon indices at drag start (for hull rebuild).
    start_face_polygons: Vec<Vec<usize>>,
    /// New vertex position for Shift+drag split (edge midpoint or face center).
    split_vertex: Option<Vec3>,
}

/// Compute a local-space offset for brush vertex/edge drag based on mouse movement.
fn compute_brush_drag_offset(
    constraint: VertexDragConstraint,
    mouse_delta: Vec2,
    cam_tf: &GlobalTransform,
    camera: &Camera,
    brush_global: &GlobalTransform,
) -> Option<Vec3> {
    let brush_pos = brush_global.translation();
    let cam_dist = (cam_tf.translation() - brush_pos).length();
    let scale = cam_dist * 0.003;

    let offset = match constraint {
        VertexDragConstraint::Free => {
            let cam_right = cam_tf.right().as_vec3();
            let cam_up = cam_tf.up().as_vec3();
            let world_offset =
                cam_right * mouse_delta.x * scale + cam_up * (-mouse_delta.y) * scale;
            let (_, brush_rot, _) = brush_global.to_scale_rotation_translation();
            brush_rot.inverse() * world_offset
        }
        constraint => {
            let axis_dir = match constraint {
                VertexDragConstraint::AxisX => Vec3::X,
                VertexDragConstraint::AxisY => Vec3::Y,
                VertexDragConstraint::AxisZ => Vec3::Z,
                VertexDragConstraint::Free => unreachable!(),
            };
            let origin_screen = camera.world_to_viewport(cam_tf, brush_pos).ok()?;
            let (_, brush_rot, _) = brush_global.to_scale_rotation_translation();
            let world_axis = brush_rot * axis_dir;
            let axis_screen = camera
                .world_to_viewport(cam_tf, brush_pos + world_axis)
                .ok()?;
            let screen_axis = (axis_screen - origin_screen).normalize_or_zero();
            let projected = mouse_delta.dot(screen_axis);
            axis_dir * projected * scale
        }
    };
    Some(offset)
}

#[derive(Resource, Default)]
pub(crate) struct EdgeDragState {
    pub pending: Option<PendingSubDrag>,
    pub active: bool,
    pub constraint: VertexDragConstraint,
    start_brush: Option<Brush>,
    start_cursor: Vec2,
    /// Start positions for each selected edge's two endpoints (vertex indices + positions).
    start_edge_vertices: Vec<(usize, Vec3)>,
    /// Full vertex list at drag start (for hull rebuild).
    start_all_vertices: Vec<Vec3>,
    /// Per-face polygon indices at drag start (for hull rebuild).
    start_face_polygons: Vec<Vec<usize>>,
}

pub(super) fn handle_brush_delete(
    edit_mode: Res<EditMode>,
    input: KeyboardInput,
    input_focus: Res<InputFocus>,
    mut brush_selection: ResMut<BrushSelection>,
    mut brushes: Query<&mut Brush>,
    brush_caches: Query<&BrushMeshCache>,
    mut history: ResMut<CommandHistory>,
    vertex_drag: Res<VertexDragState>,
    edge_drag: Res<EdgeDragState>,
    face_drag: Res<BrushDragState>,
) {
    let keyboard = &input.keyboard;
    let keybinds = &input.keybinds;

    let EditMode::BrushEdit(mode) = *edit_mode else {
        return;
    };
    if input_focus.0.is_some() {
        return;
    }
    if !keybinds.just_pressed(EditorAction::DeleteBrushElement, keyboard) {
        return;
    }
    // Don't delete while dragging
    if vertex_drag.active || edge_drag.active || face_drag.active {
        return;
    }

    let Some(brush_entity) = brush_selection.entity else {
        return;
    };
    let Ok(mut brush) = brushes.get_mut(brush_entity) else {
        return;
    };

    match mode {
        BrushEditMode::Vertex => {
            if brush_selection.vertices.is_empty() {
                return;
            }
            let Ok(cache) = brush_caches.get(brush_entity) else {
                return;
            };
            let remove_set: HashSet<usize> = brush_selection.vertices.iter().copied().collect();
            let remaining: Vec<Vec3> = cache
                .vertices
                .iter()
                .enumerate()
                .filter(|(i, _)| !remove_set.contains(i))
                .map(|(_, v)| *v)
                .collect();
            if remaining.len() < 4 {
                return; // need at least a tetrahedron
            }
            let old = brush.clone();
            if let Some((new_brush, _)) =
                rebuild_brush_from_vertices(&old, &cache.vertices, &cache.face_polygons, &remaining)
            {
                *brush = new_brush;
                let cmd = SetBrush {
                    entity: brush_entity,
                    old,
                    new: brush.clone(),
                    label: "Remove brush vertex".to_string(),
                };
                history.undo_stack.push(Box::new(cmd));
                history.redo_stack.clear();
                brush_selection.vertices.clear();
            }
        }
        BrushEditMode::Edge => {
            if brush_selection.edges.is_empty() {
                return;
            }
            let Ok(cache) = brush_caches.get(brush_entity) else {
                return;
            };
            let mut remove_set = HashSet::new();
            for &(a, b) in &brush_selection.edges {
                remove_set.insert(a);
                remove_set.insert(b);
            }
            let remaining: Vec<Vec3> = cache
                .vertices
                .iter()
                .enumerate()
                .filter(|(i, _)| !remove_set.contains(i))
                .map(|(_, v)| *v)
                .collect();
            if remaining.len() < 4 {
                return;
            }
            let old = brush.clone();
            if let Some((new_brush, _)) =
                rebuild_brush_from_vertices(&old, &cache.vertices, &cache.face_polygons, &remaining)
            {
                *brush = new_brush;
                let cmd = SetBrush {
                    entity: brush_entity,
                    old,
                    new: brush.clone(),
                    label: "Remove brush edge".to_string(),
                };
                history.undo_stack.push(Box::new(cmd));
                history.redo_stack.clear();
                brush_selection.edges.clear();
            }
        }
        BrushEditMode::Face => {
            if brush_selection.faces.is_empty() {
                return;
            }
            let remaining = brush.faces.len() - brush_selection.faces.len();
            if remaining < 4 {
                return;
            }
            let old = brush.clone();
            let remove_set: HashSet<usize> = brush_selection.faces.iter().copied().collect();
            let new_faces: Vec<BrushFaceData> = brush
                .faces
                .iter()
                .enumerate()
                .filter(|(i, _)| !remove_set.contains(i))
                .map(|(_, f)| f.clone())
                .collect();
            brush.faces = new_faces;
            let cmd = SetBrush {
                entity: brush_entity,
                old,
                new: brush.clone(),
                label: "Remove brush face".to_string(),
            };
            history.undo_stack.push(Box::new(cmd));
            history.redo_stack.clear();
            brush_selection.faces.clear();
        }
        _ => {}
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum ClipMode {
    #[default]
    KeepFront,
    KeepBack,
    Split,
}

#[derive(Resource, Default)]
pub(crate) struct ClipState {
    pub points: Vec<Vec3>,
    pub preview_plane: Option<BrushPlane>,
    pub mode: ClipMode,
}

pub(super) fn handle_clip_mode(
    edit_mode: Res<EditMode>,
    input: KeyboardInput,
    mouse: Res<ButtonInput<MouseButton>>,
    input_focus: Res<InputFocus>,
    windows: Query<&Window>,
    viewport_query: Query<(&ComputedNode, &UiGlobalTransform), With<SceneViewport>>,
    camera_query: Query<(&Camera, &GlobalTransform), With<MainViewportCamera>>,
    brush_selection: Res<BrushSelection>,
    mut brushes: Query<&mut Brush>,
    brush_transforms: Query<&GlobalTransform>,
    brush_caches: Query<&BrushMeshCache>,
    mut clip_state: ResMut<ClipState>,
    mut history: ResMut<CommandHistory>,
    snap_settings: Res<crate::snapping::SnapSettings>,
    mut commands: Commands,
    mut gizmos: Gizmos,
) {
    let keyboard = &input.keyboard;
    let keybinds = &input.keybinds;
    let EditMode::BrushEdit(BrushEditMode::Clip) = *edit_mode else {
        // Clear clip state when not in clip mode
        if !clip_state.points.is_empty() || clip_state.mode != ClipMode::KeepFront {
            clip_state.points.clear();
            clip_state.preview_plane = None;
            clip_state.mode = ClipMode::KeepFront;
        }
        return;
    };
    if input_focus.0.is_some() {
        return;
    }

    let Some(brush_entity) = brush_selection.entity else {
        return;
    };
    let Ok(brush_global) = brush_transforms.get(brush_entity) else {
        return;
    };

    let Ok(window) = windows.single() else {
        return;
    };
    let Ok((camera, cam_tf)) = camera_query.single() else {
        return;
    };

    // Escape clears clip points and resets mode
    if keybinds.just_pressed(EditorAction::ClipClear, keyboard) {
        clip_state.points.clear();
        clip_state.preview_plane = None;
        clip_state.mode = ClipMode::KeepFront;
        return;
    }

    // Tab cycles clip mode when preview plane exists
    if keybinds.just_pressed(EditorAction::ClipCycleMode, keyboard)
        && clip_state.preview_plane.is_some()
    {
        clip_state.mode = match clip_state.mode {
            ClipMode::KeepFront => ClipMode::KeepBack,
            ClipMode::KeepBack => ClipMode::Split,
            ClipMode::Split => ClipMode::KeepFront,
        };
    }

    // Left click: add point by raycasting to brush surface
    if mouse.just_pressed(MouseButton::Left) && clip_state.points.len() < 3 {
        let Some(cursor_pos) = window.cursor_position() else {
            return;
        };
        let Some(viewport_cursor) = window_to_viewport_cursor(cursor_pos, camera, &viewport_query)
        else {
            return;
        };

        // Cast ray from camera through cursor
        let Ok(ray) = camera.viewport_to_world(cam_tf, viewport_cursor) else {
            return;
        };

        let Ok(cache) = brush_caches.get(brush_entity) else {
            return;
        };

        // Find closest intersection with any brush face
        let (_, brush_rot, brush_trans) = brush_global.to_scale_rotation_translation();
        let mut best_t = f32::MAX;
        let mut best_point = None;

        for (face_idx, polygon) in cache.face_polygons.iter().enumerate() {
            if polygon.len() < 3 {
                continue;
            }
            let Ok(brush_ref) = brushes.get(brush_entity) else {
                return;
            };
            let face = &brush_ref.faces[face_idx];
            let world_normal = brush_rot * face.plane.normal;
            let face_centroid: Vec3 =
                polygon.iter().map(|&vi| cache.vertices[vi]).sum::<Vec3>() / polygon.len() as f32;
            let world_centroid = brush_global.transform_point(face_centroid);

            let denom = world_normal.dot(*ray.direction);
            if denom.abs() < EPSILON {
                continue;
            }
            let t = (world_centroid - ray.origin).dot(world_normal) / denom;
            if t > 0.0 && t < best_t {
                let hit = ray.origin + *ray.direction * t;
                // Verify hit is roughly on the brush (within face polygon bounds)
                let local_hit = brush_rot.inverse() * (hit - brush_trans);
                if point_inside_all_planes(local_hit, &brush_ref.faces) {
                    best_t = t;
                    best_point = Some(local_hit);
                }
            }
        }

        if let Some(mut point) = best_point {
            // Grid snap the clip point
            let world_point = brush_global.transform_point(point);
            let ctrl = keyboard.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]);
            let snapped = snap_settings.snap_translate_vec3_if(world_point, ctrl);
            let (_, brush_rot, brush_trans) = brush_global.to_scale_rotation_translation();
            point = brush_rot.inverse() * (snapped - brush_trans);
            clip_state.points.push(point);
        }
    }

    // Compute preview plane from collected points
    clip_state.preview_plane = match clip_state.points.len() {
        2 => {
            // Two points + camera forward for orientation
            let dir = clip_state.points[1] - clip_state.points[0];
            let (_, brush_rot, _) = brush_global.to_scale_rotation_translation();
            let local_cam_fwd = brush_rot.inverse() * cam_tf.forward().as_vec3();
            let normal = dir.cross(local_cam_fwd).normalize_or_zero();
            if normal.length_squared() > 0.5 {
                let distance = normal.dot(clip_state.points[0]);
                Some(BrushPlane { normal, distance })
            } else {
                None
            }
        }
        3 => {
            let a = clip_state.points[0];
            let b = clip_state.points[1];
            let c = clip_state.points[2];
            let normal = (b - a).cross(c - a).normalize_or_zero();
            if normal.length_squared() > 0.5 {
                let distance = normal.dot(a);
                Some(BrushPlane { normal, distance })
            } else {
                None
            }
        }
        _ => None,
    };

    // Enter: apply clip plane based on mode
    if keybinds.just_pressed(EditorAction::ClipApply, keyboard) {
        if let Some(ref plane) = clip_state.preview_plane {
            let Ok(mut brush) = brushes.get_mut(brush_entity) else {
                return;
            };
            let (clip_u, clip_v) = compute_face_tangent_axes(plane.normal);
            let clip_face = BrushFaceData {
                plane: plane.clone(),
                uv_offset: Vec2::ZERO,
                uv_scale: Vec2::ONE,
                uv_rotation: 0.0,
                uv_u_axis: clip_u,
                uv_v_axis: clip_v,
                ..default()
            };
            let (flip_u, flip_v) = compute_face_tangent_axes(-plane.normal);
            let flipped_face = BrushFaceData {
                plane: BrushPlane {
                    normal: -plane.normal,
                    distance: -plane.distance,
                },
                uv_u_axis: flip_u,
                uv_v_axis: flip_v,
                ..clip_face.clone()
            };

            match clip_state.mode {
                ClipMode::KeepFront => {
                    let old = brush.clone();
                    brush.faces.push(clip_face);
                    let cmd = SetBrush {
                        entity: brush_entity,
                        old,
                        new: brush.clone(),
                        label: "Clip brush (keep front)".to_string(),
                    };
                    history.undo_stack.push(Box::new(cmd));
                    history.redo_stack.clear();
                }
                ClipMode::KeepBack => {
                    let old = brush.clone();
                    brush.faces.push(flipped_face);
                    let cmd = SetBrush {
                        entity: brush_entity,
                        old,
                        new: brush.clone(),
                        label: "Clip brush (keep back)".to_string(),
                    };
                    history.undo_stack.push(Box::new(cmd));
                    history.redo_stack.clear();
                }
                ClipMode::Split => {
                    let old = brush.clone();
                    // Front half: apply clip plane to original
                    let mut front = old.clone();
                    front.faces.push(clip_face);
                    // Back half: apply flipped clip plane
                    let mut back = old.clone();
                    back.faces.push(flipped_face);

                    // Update original entity to front half
                    *brush = front.clone();
                    let set_cmd = SetBrush {
                        entity: brush_entity,
                        old,
                        new: front,
                        label: "Clip brush (split - front)".to_string(),
                    };

                    // Spawn back half as new entity
                    let back_brush = back;
                    let (_, brush_rot, brush_trans) = brush_global.to_scale_rotation_translation();
                    let spawn_transform = Transform {
                        translation: brush_trans,
                        rotation: brush_rot,
                        scale: Vec3::ONE,
                    };
                    let back_owned = back_brush.clone();
                    let transform_owned = spawn_transform;
                    commands.queue(move |world: &mut World| {
                        let parent_group = world
                            .get::<ChildOf>(brush_entity)
                            .map(|c| c.0)
                            .filter(|&p| world.get::<BrushGroup>(p).is_some());

                        let actual_transform = if parent_group.is_some() {
                            *world.get::<Transform>(brush_entity).unwrap()
                        } else {
                            transform_owned
                        };

                        let mut spawner = world.spawn((
                            Name::new("Brush"),
                            back_owned,
                            actual_transform,
                            Visibility::default(),
                        ));
                        if let Some(parent) = parent_group {
                            spawner.insert(ChildOf(parent));
                        }
                        let entity = spawner.id();
                        crate::scene_io::register_entity_in_ast(world, entity);

                        let create_cmd = CreateBrushCommand {
                            data: brush_data_from_entity(world, entity),
                        };

                        let group = crate::commands::CommandGroup {
                            commands: vec![Box::new(set_cmd), Box::new(create_cmd)],
                            label: "Split brush".to_string(),
                        };
                        let mut history = world.resource_mut::<CommandHistory>();
                        history.undo_stack.push(Box::new(group));
                        history.redo_stack.clear();
                    });
                    clip_state.points.clear();
                    clip_state.preview_plane = None;
                    clip_state.mode = ClipMode::KeepFront;
                    return;
                }
            }

            clip_state.points.clear();
            clip_state.preview_plane = None;
            clip_state.mode = ClipMode::KeepFront;
        }
    }

    // Draw clip points and preview
    for (i, point) in clip_state.points.iter().enumerate() {
        let world_pos = brush_global.transform_point(*point);
        let color = colors::CLIP_POINT;
        gizmos.sphere(Isometry3d::from_translation(world_pos), 0.06, color);
        // Draw connecting lines between points
        if i > 0 {
            let prev_world = brush_global.transform_point(clip_state.points[i - 1]);
            gizmos.line(prev_world, world_pos, color);
        }
    }

    // Draw clipped geometry preview
    if let Some(ref plane) = clip_state.preview_plane {
        let Ok(brush_ref) = brushes.get(brush_entity) else {
            return;
        };
        let (_, brush_rot, brush_trans) = brush_global.to_scale_rotation_translation();
        let world_normal = brush_rot * plane.normal;
        let center = brush_global.transform_point(plane.normal * plane.distance);

        let world_faces = brush_planes_to_world(&brush_ref.faces, brush_rot, brush_trans);

        // Transform clip plane to world space (same formula as brush_planes_to_world)
        let world_clip_normal = (brush_rot * plane.normal).normalize();
        let world_clip_distance = plane.distance + world_clip_normal.dot(brush_trans);

        // Front half faces (brush + clip plane)
        let front_clip = BrushFaceData {
            plane: BrushPlane {
                normal: world_clip_normal,
                distance: world_clip_distance,
            },
            uv_scale: Vec2::ONE,
            ..default()
        };
        let mut front_faces = world_faces.clone();
        front_faces.push(front_clip);

        // Back half faces (brush + flipped clip plane)
        let back_clip = BrushFaceData {
            plane: BrushPlane {
                normal: -world_clip_normal,
                distance: -world_clip_distance,
            },
            uv_scale: Vec2::ONE,
            ..default()
        };
        let mut back_faces = world_faces;
        back_faces.push(back_clip);

        let (front_color, back_color) = match clip_state.mode {
            ClipMode::KeepFront => (colors::CLIP_KEEP, colors::CLIP_DISCARD),
            ClipMode::KeepBack => (colors::CLIP_DISCARD, colors::CLIP_KEEP),
            ClipMode::Split => (colors::CLIP_KEEP, colors::CLIP_SPLIT_BACK),
        };

        // Draw front half wireframe
        let (verts, polys) = compute_brush_geometry(&front_faces);
        if verts.len() >= 4 {
            for polygon in &polys {
                for i in 0..polygon.len() {
                    let a = verts[polygon[i]];
                    let b = verts[polygon[(i + 1) % polygon.len()]];
                    gizmos.line(a, b, front_color);
                }
            }
        }

        // Draw back half wireframe
        let (verts, polys) = compute_brush_geometry(&back_faces);
        if verts.len() >= 4 {
            for polygon in &polys {
                for i in 0..polygon.len() {
                    let a = verts[polygon[i]];
                    let b = verts[polygon[(i + 1) % polygon.len()]];
                    gizmos.line(a, b, back_color);
                }
            }
        }

        // Draw normal arrow (direction reflects mode)
        let arrow_dir = match clip_state.mode {
            ClipMode::KeepBack => -world_normal,
            _ => world_normal,
        };
        gizmos.arrow(center, center + arrow_dir * 0.5, colors::CLIP_NORMAL_ARROW);
    }
}

/// Pick the closest face under the cursor on a given brush entity.
fn pick_face_under_cursor(
    viewport_cursor: Vec2,
    brush_entity: Entity,
    camera: &Camera,
    cam_tf: &GlobalTransform,
    cache: &BrushMeshCache,
    face_entities: &Query<(Entity, &super::BrushFaceEntity, &GlobalTransform)>,
) -> Option<usize> {
    let mut best_face = None;
    let mut best_depth = f32::MAX;

    for (_, face_ent, face_global) in face_entities {
        if face_ent.brush_entity != brush_entity {
            continue;
        }
        let face_idx = face_ent.face_index;
        let polygon = &cache.face_polygons[face_idx];
        if polygon.len() < 3 {
            continue;
        }
        let screen_verts: Vec<Vec2> = polygon
            .iter()
            .filter_map(|&vi| {
                let world = face_global.transform_point(cache.vertices[vi]);
                camera.world_to_viewport(cam_tf, world).ok()
            })
            .collect();
        if screen_verts.len() < 3 {
            continue;
        }
        if point_in_polygon_2d(viewport_cursor, &screen_verts) {
            let centroid: Vec3 =
                polygon.iter().map(|&vi| cache.vertices[vi]).sum::<Vec3>() / polygon.len() as f32;
            let world_centroid = face_global.transform_point(centroid);
            let depth = (cam_tf.translation() - world_centroid).length_squared();
            if depth < best_depth {
                best_depth = depth;
                best_face = Some(face_idx);
            }
        }
    }
    best_face
}

/// Updates the hover resource each frame to track which face the cursor is over.
pub(super) fn brush_face_hover(
    edit_mode: Res<EditMode>,
    input: KeyboardInput,
    windows: Query<&Window>,
    camera_query: Query<(&Camera, &GlobalTransform), With<MainViewportCamera>>,
    viewport_query: Query<(&ComputedNode, &UiGlobalTransform), With<SceneViewport>>,
    face_entities: Query<(Entity, &super::BrushFaceEntity, &GlobalTransform)>,
    brush_selection: Res<BrushSelection>,
    brush_caches: Query<&BrushMeshCache>,
    selection: Res<Selection>,
    drag_state: Res<BrushDragState>,
    mut hover: ResMut<super::BrushFaceHover>,
    brushes: Query<(), With<Brush>>,
) {
    let keyboard = &input.keyboard;
    let in_face_edit = matches!(*edit_mode, EditMode::BrushEdit(BrushEditMode::Face));
    let shift = keyboard.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight]);
    let alt = keyboard.any_pressed([KeyCode::AltLeft, KeyCode::AltRight]);

    // Clear hover during active drag
    if drag_state.active {
        hover.entity = None;
        hover.face_index = None;
        return;
    }

    // Determine if we should show hover
    let should_hover = in_face_edit || (*edit_mode == EditMode::Object && (shift || alt));

    if !should_hover {
        hover.entity = None;
        hover.face_index = None;
        return;
    }

    let intent = if alt {
        super::HoverIntent::Extend
    } else {
        super::HoverIntent::PushPull
    };

    let Ok(window) = windows.single() else {
        hover.entity = None;
        hover.face_index = None;
        return;
    };
    let Some(cursor_pos) = window.cursor_position() else {
        hover.entity = None;
        hover.face_index = None;
        return;
    };
    let Ok((camera, cam_tf)) = camera_query.single() else {
        hover.entity = None;
        hover.face_index = None;
        return;
    };
    let Some(viewport_cursor) = window_to_viewport_cursor(cursor_pos, camera, &viewport_query)
    else {
        hover.entity = None;
        hover.face_index = None;
        return;
    };

    let brush_entity = if in_face_edit {
        brush_selection.entity
    } else {
        selection.primary().filter(|&e| brushes.contains(e))
    };

    let Some(brush_entity) = brush_entity else {
        hover.entity = None;
        hover.face_index = None;
        return;
    };

    let Ok(cache) = brush_caches.get(brush_entity) else {
        hover.entity = None;
        hover.face_index = None;
        return;
    };

    if let Some(face_idx) = pick_face_under_cursor(
        viewport_cursor,
        brush_entity,
        camera,
        cam_tf,
        cache,
        &face_entities,
    ) {
        hover.entity = Some(brush_entity);
        hover.face_index = Some(face_idx);
        hover.intent = intent;
    } else {
        hover.entity = None;
        hover.face_index = None;
    }
}