flatland-client-lib 0.2.32

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

use std::collections::BTreeSet;

use flatland_protocol::{
    ItemStack, NpcView, PlacedContainerView, ResourceNodeView, WorkerRouteKindView,
    WorkerRouteStopView, WorkerRouteView,
};

/// One outbound travel waypoint for a harvest loop route.
#[derive(Debug, Clone, PartialEq)]
pub struct WorkerRouteWaypoint {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

/// One typed stop in an ordered worker route. Mirrors the sim `WorkerRouteStop`.
#[derive(Debug, Clone, PartialEq)]
pub enum WorkerRouteStop {
    Waypoint { x: f32, y: f32, z: f32 },
    HarvestNode { node_id: String },
    DepositAt {
        container_id: String,
        /// When set, deposit only these templates (lets a worker keep tools across loops).
        filter: Option<Vec<String>>,
    },
    /// Travel to an NPC and sell `template` (whole stack when `sell_all`).
    /// `npc_id: None` → auto-pick the nearest NPC that buys `template`.
    TradeWith {
        npc_id: Option<String>,
        template: String,
        sell_all: bool,
    },
    /// Withdraw specific items from an owned storage container.
    WithdrawFrom {
        container_id: String,
        items: Vec<WorkerRouteWithdrawItem>,
    },
    /// Craft `blueprint` at `device` (or `"hand"`). `qty: None` = until inputs exhausted.
    CraftAt {
        device: String,
        blueprint: String,
        qty: Option<u32>,
    },
    CultivatePlot { plot_id: uuid::Uuid },
    PlantPlot {
        plot_id: uuid::Uuid,
        seed_template: String,
    },
    HarvestPlot { plot_id: uuid::Uuid },
    RestIfNeeded,
    Wait { wait_ticks: u64 },
}

/// One withdraw line for a `WithdrawFrom` editor stop.
#[derive(Debug, Clone, PartialEq)]
pub struct WorkerRouteWithdrawItem {
    pub template: String,
    /// `None` = take every stack of this template (carry-capped; the worker
    /// loops back for the rest). `Some(n)` = hold up to n (top-up each loop).
    pub qty: Option<u32>,
}

impl WorkerRouteStop {
    pub fn summary(&self) -> String {
        self.summary_resolved(|id| short_id(id), |id| id.to_string(), |id| id.to_string())
    }

    /// Human-facing summary using friendly labels for containers / NPCs / nodes.
    pub fn summary_resolved(
        &self,
        container_label: impl Fn(&str) -> String,
        npc_label: impl Fn(&str) -> String,
        node_label: impl Fn(&str) -> String,
    ) -> String {
        match self {
            Self::Waypoint { x, y, .. } => format!("waypoint ({x:.0}, {y:.0})"),
            Self::HarvestNode { node_id } => format!("harvest {}", node_label(node_id)),
            Self::DepositAt { container_id, filter } => {
                let f = filter
                    .as_ref()
                    .map(|f| format!(" only {}", f.join(",")))
                    .unwrap_or_default();
                format!("deposit at {}{f}", container_label(container_id))
            }
            Self::TradeWith { npc_id, template, .. } => {
                let who = npc_id
                    .as_deref()
                    .map(|id| npc_label(id))
                    .unwrap_or_else(|| "nearest buyer".into());
                format!("sell {template} to {who}")
            }
            Self::WithdrawFrom { container_id, items } => {
                let what = items
                    .iter()
                    .map(|i| match i.qty {
                        None => format!("all {}", i.template),
                        Some(q) => format!("up to {q} {}", i.template),
                    })
                    .collect::<Vec<_>>()
                    .join(" + ");
                format!("withdraw {what} from {}", container_label(container_id))
            }
            Self::CraftAt { blueprint, .. } => format!("craft {blueprint}"),
            Self::CultivatePlot { plot_id } => {
                format!("cultivate plot {}", &plot_id.to_string()[..8])
            }
            Self::PlantPlot {
                plot_id,
                seed_template,
            } => format!("plant {seed_template} on {}", &plot_id.to_string()[..8]),
            Self::HarvestPlot { plot_id } => {
                format!("harvest plot {}", &plot_id.to_string()[..8])
            }
            Self::RestIfNeeded => "rest at lodging (if needed)".into(),
            Self::Wait { wait_ticks } => format!("wait {wait_ticks}t"),
        }
    }

    /// Short label for the editor list (without the stop index).
    pub fn kind_label(&self) -> &'static str {
        match self {
            Self::Waypoint { .. } => "waypoint",
            Self::HarvestNode { .. } => "harvest",
            Self::DepositAt { .. } => "deposit",
            Self::TradeWith { .. } => "sell",
            Self::WithdrawFrom { .. } => "withdraw",
            Self::CraftAt { .. } => "craft",
            Self::CultivatePlot { .. } => "cultivate",
            Self::PlantPlot { .. } => "plant",
            Self::HarvestPlot { .. } => "harvest-plot",
            Self::RestIfNeeded => "rest",
            Self::Wait { .. } => "wait",
        }
    }
}

fn short_id(id: &str) -> String {
    id.rsplit('-')
        .next()
        .filter(|s| !s.is_empty())
        .unwrap_or(id)
        .to_string()
}

/// Whitespace-separated AND tokens for long picker lists.
///
/// Text tokens match if any `fields` string contains the token (case-insensitive).
/// A token ending in `m` (e.g. `50m`) is a max distance in meters when `dist_m` is set.
pub fn list_filter_row_matches(filter: &str, dist_m: Option<f32>, fields: &[&str]) -> bool {
    let tokens: Vec<&str> = filter.split_whitespace().filter(|t| !t.is_empty()).collect();
    if tokens.is_empty() {
        return true;
    }
    let hay: Vec<String> = fields.iter().map(|f| f.to_ascii_lowercase()).collect();
    for tok in tokens {
        let t = tok.to_ascii_lowercase();
        if let Some(rest) = t.strip_suffix('m') {
            if let Ok(max) = rest.parse::<f32>() {
                if let Some(d) = dist_m {
                    if d > max {
                        return false;
                    }
                    continue;
                }
            }
        }
        if !hay.iter().any(|h| h.contains(&t)) {
            return false;
        }
    }
    true
}

// ---- sheets (per-stop setup screens, `plans/33`) -------------------

/// Tri-state of one withdraw line draft: not included, take all, take qty.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WithdrawLineMode {
    Off,
    All,
    Qty(u32),
}

/// One editable withdraw line inside the `WithdrawItems` sheet.
#[derive(Debug, Clone, PartialEq)]
pub struct WithdrawLineDraft {
    pub template: String,
    /// Total quantity currently in the chosen container (0 = no longer there).
    pub available: u32,
    pub mode: WithdrawLineMode,
}

/// Farm plot action for the route-editor plot picker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FarmPlotAction {
    Cultivate,
    Plant,
    Harvest,
}

impl WithdrawLineDraft {
    /// Cycle Off → All → Qty → Off (Enter/Space on the row).
    pub fn cycle(&mut self) {
        self.mode = match self.mode {
            WithdrawLineMode::Off => WithdrawLineMode::All,
            WithdrawLineMode::All => WithdrawLineMode::Qty(self.available.clamp(1, 10)),
            WithdrawLineMode::Qty(_) => WithdrawLineMode::Off,
        };
    }

    /// Nudge the quantity; switches the line into `Qty` mode when needed.
    pub fn adjust_qty(&mut self, delta: i32) {
        let cur = match self.mode {
            WithdrawLineMode::Off => self.available.clamp(1, 10),
            WithdrawLineMode::All => self.available.clamp(1, 10),
            WithdrawLineMode::Qty(q) => q,
        };
        let next = (cur as i32 + delta).clamp(1, self.available.max(1) as i32) as u32;
        self.mode = WithdrawLineMode::Qty(next);
    }
}

/// Which sheet (sub-screen) the route editor is showing.
#[derive(Debug, Clone, PartialEq)]
pub enum RouteEditorSheet {
    /// Root: the ordered stop list.
    Stops,
    /// "Add stop" menu — choose a stop type.
    AddMenu { index: usize },
    /// Waypoint submenu (player position / map click).
    WaypointMenu { index: usize },
    /// "Click the map to place the waypoint" transient mode.
    WaypointMapPick,
    /// Pick harvest node(s) from the region list (`picked` → Done row).
    /// `nodes` is frozen when the sheet opens so the list does not reshuffle while navigating.
    HarvestPicker {
        index: usize,
        picked: BTreeSet<String>,
        nodes: Vec<NodeCandidate>,
    },
    /// Withdraw step 1: pick the source container.
    WithdrawContainers { index: usize },
    /// Withdraw step 2: choose items + All/qty within the container.
    WithdrawItems {
        container_id: String,
        lines: Vec<WithdrawLineDraft>,
        index: usize,
    },
    /// Deposit step 1: pick the target container.
    DepositContainers { index: usize },
    /// Deposit step 2: optional "only these templates" filter.
    DepositFilter {
        container_id: String,
        /// (template, chosen) rows; empty selection = deposit everything.
        rows: Vec<(String, bool)>,
        index: usize,
    },
    /// Sell step 1: pick the merchant (or auto).
    SellNpcs { index: usize },
    /// Sell step 2: pick item template(s) (+ sell-all toggle, `picked` → Done).
    SellItem {
        npc_id: Option<String>,
        templates: Vec<String>,
        index: usize,
        sell_all: bool,
        picked: BTreeSet<String>,
    },
    /// Craft: pick a blueprint (at `hand`).
    CraftBlueprint { index: usize },
    /// Wait stop: adjust ticks.
    WaitEntry { ticks: u64 },
    /// Pick the rest bed (lodging).
    BedPicker { index: usize },
    /// Pick a farmable property plot for cultivate / plant / harvest stops.
    FarmPlotPicker {
        index: usize,
        action: FarmPlotAction,
    },
    /// Plant-plot step 2: pick seed template after choosing a plot.
    FarmPlantSeed {
        plot_id: uuid::Uuid,
        seeds: Vec<String>,
        index: usize,
    },
}

/// Mouse actions produced by the gfx overlay and applied on the net thread.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RouteEditorClick {
    /// Click a stop row: select it and focus the stop list.
    SelectStop(usize),
    /// Click the rest-bed header row: open the bed picker.
    OpenBedPicker,
    /// Click a sheet row: move the sheet cursor there and activate (Enter).
    SheetRow(usize),
    /// Toggle between the full panel and the minimized map-friendly bar.
    TogglePanel,
}

/// Add-menu entries in display order.
pub const ADD_MENU: &[&str] = &[
    "Waypoint",
    "Harvest node",
    "Withdraw from storage",
    "Deposit to storage",
    "Sell to merchant",
    "Craft (at hand)",
    "Rest if needed",
    "Wait",
    "Cultivate plot",
    "Plant plot",
    "Harvest plot",
];

/// Waypoint submenu entries in display order.
pub const WAYPOINT_MENU: &[&str] = &["At player position", "Pick on map (click)"];

// ---- picker candidate snapshots ------------------------------------

/// One owned container row for the withdraw/deposit container pickers.
#[derive(Debug, Clone, PartialEq)]
pub struct ContainerCandidate {
    pub id: String,
    pub name: String,
    pub is_lodging: bool,
    /// e.g. `oak_log ×12 · lumber ×4` or `(empty)`.
    pub summary: String,
    pub dist: f32,
}

/// Summarize container contents as `oak_log ×12 · lumber ×4` (or `(empty)`).
pub fn summarize_contents(contents: &[ItemStack]) -> String {
    let mut totals: Vec<(String, u32)> = Vec::new();
    for s in contents {
        if s.template_id.is_empty() {
            continue;
        }
        match totals.iter_mut().find(|(t, _)| t == &s.template_id) {
            Some((_, q)) => *q += s.quantity,
            None => totals.push((s.template_id.clone(), s.quantity)),
        }
    }
    if totals.is_empty() {
        return "(empty)".into();
    }
    totals.sort();
    totals
        .iter()
        .map(|(t, q)| format!("{t} ×{q}"))
        .collect::<Vec<_>>()
        .join(" · ")
}

/// Owned containers (any with storage capacity, lodging flagged) sorted by
/// distance to the player then name — the withdraw/deposit picker rows.
pub fn owned_container_candidates(
    placed: &[PlacedContainerView],
    character_id: Option<uuid::Uuid>,
    px: f32,
    py: f32,
) -> Vec<ContainerCandidate> {
    owned_container_candidates_with_occupants(placed, character_id, px, py, &[])
}

/// Like [`owned_container_candidates`], but lodging rows include occupant names in `summary`.
pub fn owned_container_candidates_with_occupants(
    placed: &[PlacedContainerView],
    character_id: Option<uuid::Uuid>,
    px: f32,
    py: f32,
    hired: &[flatland_protocol::HiredWorkerView],
) -> Vec<ContainerCandidate> {
    owned_container_candidates_with_occupants_and_buildings(
        placed,
        &[],
        character_id,
        px,
        py,
        hired,
    )
}

/// Deposit/withdraw picker: owned chests/lodging **plus** town storage halls.
pub fn owned_container_candidates_with_occupants_and_buildings(
    placed: &[PlacedContainerView],
    buildings: &[flatland_protocol::BuildingView],
    character_id: Option<uuid::Uuid>,
    px: f32,
    py: f32,
    hired: &[flatland_protocol::HiredWorkerView],
) -> Vec<ContainerCandidate> {
    let Some(cid) = character_id else {
        return Vec::new();
    };
    let mut out: Vec<ContainerCandidate> = placed
        .iter()
        .filter(|c| c.owner_character_id == Some(cid))
        .filter(|c| {
            c.capacity_volume.unwrap_or(0.0) > 0.0 || c.worker_lodging_capacity.unwrap_or(0) > 0
        })
        .map(|c| {
            let is_lodging = c.worker_lodging_capacity.unwrap_or(0) > 0;
            let mut summary = summarize_contents(&c.contents);
            if is_lodging {
                let who = lodging_occupants_for(hired, &c.id);
                let who = if who.is_empty() {
                    "vacant".into()
                } else {
                    who.join(", ")
                };
                summary = format!("lodged: {who} · {summary}");
            }
            ContainerCandidate {
                id: c.id.clone(),
                name: c.display_name.clone(),
                is_lodging,
                summary,
                dist: dist2d(px, py, c.x, c.y),
            }
        })
        .collect();

    for b in buildings {
        if !b
            .tags
            .iter()
            .any(|t| t.eq_ignore_ascii_case("storage"))
        {
            continue;
        }
        let name = if b.label.is_empty() {
            format!("Town storage ({})", b.id)
        } else {
            b.label.clone()
        };
        out.push(ContainerCandidate {
            id: b.id.clone(),
            name,
            is_lodging: false,
            summary: "(town vault)".into(),
            dist: dist2d(px, py, b.x, b.y),
        });
    }

    out.sort_by(|a, b| {
        a.dist
            .partial_cmp(&b.dist)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.name.cmp(&b.name))
            .then_with(|| a.id.cmp(&b.id))
    });
    out
}

fn lodging_occupants_for(
    hired: &[flatland_protocol::HiredWorkerView],
    container_id: &str,
) -> Vec<String> {
    let mut names: Vec<String> = hired
        .iter()
        .filter(|w| w.lodging_container_id.as_deref() == Some(container_id))
        .map(|w| w.label.clone())
        .collect();
    names.sort();
    names
}

/// One resource-node row for the harvest picker.
#[derive(Debug, Clone, PartialEq)]
pub struct NodeCandidate {
    pub id: String,
    pub label: String,
    pub template: String,
    pub dist: f32,
}

/// Harvestable resource nodes sorted by distance to `anchor_x` / `anchor_y` (rest bed).
pub fn node_candidates(
    nodes: &[ResourceNodeView],
    anchor_x: f32,
    anchor_y: f32,
) -> Vec<NodeCandidate> {
    let mut out: Vec<NodeCandidate> = nodes
        .iter()
        .filter(|n| n.state == flatland_protocol::ResourceNodeState::Available)
        .map(|n| NodeCandidate {
            id: n.id.clone(),
            label: n.label.clone(),
            template: n.item_template.clone(),
            dist: dist2d(anchor_x, anchor_y, n.x, n.y),
        })
        .collect();
    out.sort_by(|a, b| {
        a.dist
            .partial_cmp(&b.dist)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.label.cmp(&b.label))
            .then_with(|| a.id.cmp(&b.id))
    });
    out
}

/// When no rest bed is set, keep a stable order (label, id) so the picker does not jump.
pub fn node_candidates_stable(nodes: &[ResourceNodeView]) -> Vec<NodeCandidate> {
    let mut out: Vec<NodeCandidate> = nodes
        .iter()
        .filter(|n| n.state == flatland_protocol::ResourceNodeState::Available)
        .map(|n| NodeCandidate {
            id: n.id.clone(),
            label: n.label.clone(),
            template: n.item_template.clone(),
            dist: f32::NAN,
        })
        .collect();
    out.sort_by(|a, b| a.label.cmp(&b.label).then_with(|| a.id.cmp(&b.id)));
    out
}

/// Rest-bed world position for the open route editor (if a bed is chosen).
pub fn route_editor_lodging_anchor(
    lodging_container_id: Option<&str>,
    placed: &[PlacedContainerView],
) -> Option<(f32, f32)> {
    let id = lodging_container_id?;
    placed
        .iter()
        .find(|c| c.id == id)
        .map(|c| (c.x, c.y))
}

/// First row in multi-select harvest / sell sheets — always **Done**.
pub const ROUTE_PICKER_DONE_ROW: usize = 0;
/// Sell sheet: row 1 is the sell-all toggle (row 0 = Done).
pub const SELL_ITEM_TOGGLE_ROW: usize = 1;

pub fn harvest_picker_row_count(nodes_len: usize) -> usize {
    nodes_len + 1
}

pub fn sell_item_picker_row_count(templates_len: usize) -> usize {
    templates_len + 2
}

/// Filter helper for harvest picker rows (row 0 = Done, rows 1.. = `nodes[row - 1]`).
pub fn harvest_picker_row_matches(nodes: &[NodeCandidate], row: usize, filter: &str) -> bool {
    if row == ROUTE_PICKER_DONE_ROW {
        return true;
    }
    let slot = row - 1;
    nodes.get(slot).is_some_and(|n| {
        let dist = n.dist.is_finite().then_some(n.dist);
        list_filter_row_matches(filter, dist, &[&n.label, &n.template, &n.id])
    })
}

/// One merchant row for the sell picker.
#[derive(Debug, Clone, PartialEq)]
pub struct TradeNpcCandidate {
    pub id: String,
    pub label: String,
    pub dist: f32,
}

/// Trade-capable NPCs sorted by distance to the player.
pub fn trade_npc_candidates(npcs: &[NpcView], px: f32, py: f32) -> Vec<TradeNpcCandidate> {
    let mut out: Vec<TradeNpcCandidate> = npcs
        .iter()
        .filter(|n| n.can_trade)
        .map(|n| TradeNpcCandidate {
            id: n.id.clone(),
            label: n.label.clone(),
            dist: dist2d(px, py, n.x, n.y),
        })
        .collect();
    out.sort_by(|a, b| {
        a.dist
            .partial_cmp(&b.dist)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.id.cmp(&b.id))
    });
    out
}

// ---- editor state ---------------------------------------------------

/// Draft route for a hired worker. `stops` is the ordered, editable list;
/// `lodging_container_id` is the bed used for `RestIfNeeded`.
#[derive(Debug, Clone)]
pub struct WorkerRouteEditorState {
    pub worker_instance_id: String,
    pub worker_label: String,
    pub lodging_container_id: Option<String>,
    /// Ordered, player-authored stops. May be empty until the player adds some.
    pub stops: Vec<WorkerRouteStop>,
    /// Selected stop index for reorder / delete operations.
    pub selected_stop_index: usize,
    /// Carry threshold passed to each `HarvestNode` stop's compiled `HarvestRoute`.
    pub carry_return_ratio: f32,
    /// Active sheet (sub-screen). `Stops` is the root.
    pub sheet: RouteEditorSheet,
    /// When set, confirming a sheet **replaces** this stop instead of appending
    /// (Enter on a stop = edit it in place).
    pub editing_index: Option<usize>,
    /// When true, only a thin bar is drawn so the map stays visible for clicks.
    pub panel_collapsed: bool,
    /// `/` search string for the active picker sheet.
    pub sheet_filter: String,
    pub sheet_filter_focused: bool,
}

impl WorkerRouteEditorState {
    pub fn new(
        worker_instance_id: String,
        worker_label: String,
        lodging_container_id: Option<String>,
    ) -> Self {
        Self {
            worker_instance_id,
            worker_label,
            lodging_container_id,
            stops: Vec::new(),
            selected_stop_index: 0,
            carry_return_ratio: 0.90,
            sheet: RouteEditorSheet::Stops,
            editing_index: None,
            panel_collapsed: false,
            sheet_filter: String::new(),
            sheet_filter_focused: false,
        }
    }

    pub fn toggle_panel_collapsed(&mut self) {
        self.panel_collapsed = !self.panel_collapsed;
    }

    pub fn from_saved_route(
        worker_instance_id: String,
        worker_label: String,
        route: &WorkerRouteView,
        lodging_fallback: Option<String>,
    ) -> Self {
        let lodging = route
            .lodging_container_id
            .clone()
            .or(lodging_fallback);

        match route.kind {
            WorkerRouteKindView::Ordered => Self {
                worker_instance_id,
                worker_label,
                lodging_container_id: lodging,
                stops: route
                    .stops
                    .iter()
                    .map(stop_view_to_stop)
                    .collect(),
                selected_stop_index: 0,
                carry_return_ratio: route.carry_return_ratio,
                sheet: RouteEditorSheet::Stops,
                editing_index: None,
                panel_collapsed: false,
                sheet_filter: String::new(),
                sheet_filter_focused: false,
            },
            WorkerRouteKindView::HarvestLoop => {
                // Convert legacy harvest_loop shape into an ordered stop list so
                // the editor presents one unified model. Outbound waypoints and
                // harvest nodes are interleaved in declaration order (waypoints
                // first, then harvest, then deposit at lodging, then rest).
                let mut stops = Vec::new();
                for wp in &route.outbound_waypoints {
                    stops.push(WorkerRouteStop::Waypoint {
                        x: wp.x,
                        y: wp.y,
                        z: wp.z,
                    });
                }
                for node in &route.harvest_nodes {
                    stops.push(WorkerRouteStop::HarvestNode {
                        node_id: node.clone(),
                    });
                }
                if let Some(lodging) = &lodging {
                    stops.push(WorkerRouteStop::DepositAt {
                        container_id: lodging.clone(),
                        filter: None,
                    });
                    stops.push(WorkerRouteStop::RestIfNeeded);
                }
                Self {
                    worker_instance_id,
                    worker_label,
                    lodging_container_id: lodging,
                    stops,
                    selected_stop_index: 0,
                    carry_return_ratio: route.carry_return_ratio,
                    sheet: RouteEditorSheet::Stops,
                    editing_index: None,
                    panel_collapsed: false,
                    sheet_filter: String::new(),
                    sheet_filter_focused: false,
                }
            }
        }
    }

    // ---- stop list editing ------------------------------------------

    pub fn stop_count(&self) -> usize {
        self.stops.len()
    }

    pub fn select_stop(&mut self, index: usize) {
        if self.stops.is_empty() {
            self.selected_stop_index = 0;
            return;
        }
        self.selected_stop_index = index.min(self.stops.len() - 1);
    }

    pub fn move_selected_up(&mut self) {
        if self.selected_stop_index == 0 {
            return;
        }
        self.stops
            .swap(self.selected_stop_index, self.selected_stop_index - 1);
        self.selected_stop_index -= 1;
    }

    pub fn move_selected_down(&mut self) {
        if self.selected_stop_index + 1 >= self.stops.len() {
            return;
        }
        self.stops
            .swap(self.selected_stop_index, self.selected_stop_index + 1);
        self.selected_stop_index += 1;
    }

    pub fn remove_selected_stop(&mut self) {
        if self.stops.is_empty() {
            return;
        }
        let idx = self.selected_stop_index.min(self.stops.len() - 1);
        self.stops.remove(idx);
        self.editing_index = None;
        if self.selected_stop_index >= self.stops.len() {
            self.selected_stop_index = self.stops.len().saturating_sub(1);
        }
    }

    /// Index of the first stop matching `pred`, if any.
    fn find_stop(&self, pred: impl Fn(&WorkerRouteStop) -> bool) -> Option<usize> {
        self.stops.iter().position(pred)
    }

    pub fn harvest_node_index(&self, node_id: &str) -> Option<usize> {
        self.find_stop(
            |s| matches!(s, WorkerRouteStop::HarvestNode { node_id: n } if n == node_id),
        )
    }

    pub fn deposit_container_index(&self, container_id: &str) -> Option<usize> {
        self.find_stop(
            |s| matches!(s, WorkerRouteStop::DepositAt { container_id: c, .. } if c == container_id),
        )
    }

    pub fn trade_stop_index(&self, npc_id: Option<&str>, template: &str) -> Option<usize> {
        self.find_stop(|s| {
            matches!(s, WorkerRouteStop::TradeWith { npc_id: n, template: t, .. }
                if n.as_deref() == npc_id && t == template)
        })
    }

    /// Insert a stop, deduping targets that must not repeat (harvest nodes,
    /// deposit containers, identical sell stops): a duplicate selects the
    /// existing stop instead of appending. Returns (appended, index).
    pub fn insert_stop(&mut self, stop: WorkerRouteStop) -> (bool, usize) {
        let existing = match &stop {
            WorkerRouteStop::HarvestNode { node_id } => self.harvest_node_index(node_id),
            WorkerRouteStop::DepositAt { container_id, .. } => {
                self.deposit_container_index(container_id)
            }
            WorkerRouteStop::TradeWith { npc_id, template, .. } => {
                self.trade_stop_index(npc_id.as_deref(), template)
            }
            _ => None,
        };
        if let Some(idx) = existing {
            self.selected_stop_index = idx;
            return (false, idx);
        }
        self.stops.push(stop);
        self.selected_stop_index = self.stops.len() - 1;
        (true, self.stops.len() - 1)
    }

    pub fn append_waypoint(&mut self, x: f32, y: f32, z: f32) {
        self.insert_stop(WorkerRouteStop::Waypoint { x, y, z });
    }

    pub fn append_harvest_node(&mut self, node_id: &str) -> bool {
        self.insert_stop(WorkerRouteStop::HarvestNode {
            node_id: node_id.to_string(),
        })
        .0
    }

    pub fn append_deposit_at(&mut self, container_id: &str) -> bool {
        self.insert_stop(WorkerRouteStop::DepositAt {
            container_id: container_id.to_string(),
            filter: None,
        })
        .0
    }

    /// Append a filtered deposit (deposit only `filter_templates`, keep everything else —
    /// e.g. keep the worker's handsaw while depositing lumber).
    pub fn append_deposit_at_filtered(&mut self, container_id: &str, filter_templates: Vec<String>) {
        self.stops.push(WorkerRouteStop::DepositAt {
            container_id: container_id.to_string(),
            filter: Some(filter_templates),
        });
        self.selected_stop_index = self.stops.len() - 1;
    }

    pub fn append_rest_if_needed(&mut self) {
        self.insert_stop(WorkerRouteStop::RestIfNeeded);
    }

    pub fn append_wait(&mut self, wait_ticks: u64) {
        self.insert_stop(WorkerRouteStop::Wait { wait_ticks });
    }

    /// Append a `TradeWith` stop — sell `template` (whole stack) to `npc_id`
    /// (`None` = auto-pick the nearest NPC that buys it). An identical sell
    /// stop (same merchant + template) is selected instead of duplicated.
    pub fn append_trade_with(&mut self, template: String, npc_id: Option<String>, sell_all: bool) -> bool {
        self.insert_stop(WorkerRouteStop::TradeWith {
            npc_id,
            template,
            sell_all,
        })
        .0
    }

    /// Pin the selected stop's NPC when the player clicks a merchant on the map.
    /// Only affects `TradeWith` stops; returns true if a stop was updated.
    /// If pinning would duplicate another sell stop (same merchant + template),
    /// the selected stop is removed and the existing one is selected instead.
    pub fn set_selected_trade_npc(&mut self, npc_id: String) -> bool {
        let Some(stop) = self.stops.get_mut(self.selected_stop_index) else {
            return false;
        };
        let WorkerRouteStop::TradeWith { npc_id: slot, template, .. } = stop else {
            return false;
        };
        *slot = Some(npc_id.clone());
        let template = template.clone();
        let selected = self.selected_stop_index;
        if let Some(other) = self
            .trade_stop_index(Some(npc_id.as_str()), template.as_str())
            .filter(|&i| i != selected)
        {
            self.stops.remove(selected);
            self.selected_stop_index = if other > selected { other - 1 } else { other };
        }
        true
    }

    /// Retarget the selected stop's source container when the player clicks a
    /// chest on the map. Only affects `WithdrawFrom` stops; returns true if a
    /// stop was updated.
    pub fn set_selected_withdraw_container(&mut self, container_id: String) -> bool {
        let Some(stop) = self.stops.get_mut(self.selected_stop_index) else {
            return false;
        };
        if let WorkerRouteStop::WithdrawFrom { container_id: slot, .. } = stop {
            *slot = container_id;
            return true;
        }
        false
    }

    /// Retarget the stop currently being edited (or selected) to a new withdraw
    /// chest. Prefer `editing_index` when set.
    pub fn retarget_withdraw_container(&mut self, container_id: String) -> bool {
        let idx = self.editing_index.unwrap_or(self.selected_stop_index);
        let Some(stop) = self.stops.get_mut(idx) else {
            return false;
        };
        if let WorkerRouteStop::WithdrawFrom { container_id: slot, .. } = stop {
            *slot = container_id;
            return true;
        }
        false
    }

    /// Retarget the stop currently being edited (or selected) to a new deposit
    /// chest. Prefer `editing_index` when set.
    pub fn retarget_deposit_container(&mut self, container_id: String) -> bool {
        let idx = self.editing_index.unwrap_or(self.selected_stop_index);
        let Some(stop) = self.stops.get_mut(idx) else {
            return false;
        };
        if let WorkerRouteStop::DepositAt { container_id: slot, .. } = stop {
            *slot = container_id;
            return true;
        }
        false
    }

    // ---- sheet navigation --------------------------------------------

    pub fn open_add_menu(&mut self) {
        self.editing_index = None;
        self.sheet = RouteEditorSheet::AddMenu { index: 0 };
    }

    pub fn open_sheet(&mut self, sheet: RouteEditorSheet) {
        self.sheet_filter.clear();
        self.sheet_filter_focused = false;
        self.sheet = sheet;
    }

    /// Append harvest stops for every picked node (edit replaces first, rest append).
    pub fn confirm_harvest_picks(&mut self, node_ids: &[String]) -> usize {
        if node_ids.is_empty() {
            return 0;
        }
        let mut added = 0usize;
        if let Some(idx) = self.editing_index.take() {
            if let Some(first) = node_ids.first() {
                if idx < self.stops.len() {
                    self.stops[idx] = WorkerRouteStop::HarvestNode {
                        node_id: first.clone(),
                    };
                    self.selected_stop_index = idx;
                    added = 1;
                }
                for id in node_ids.iter().skip(1) {
                    if self
                        .insert_stop(WorkerRouteStop::HarvestNode {
                            node_id: id.clone(),
                        })
                        .0
                    {
                        added += 1;
                    }
                }
            }
        } else {
            for id in node_ids {
                if self
                    .insert_stop(WorkerRouteStop::HarvestNode {
                        node_id: id.clone(),
                    })
                    .0
                {
                    added += 1;
                }
            }
        }
        self.sheet = RouteEditorSheet::Stops;
        added
    }

    /// Append sell stops for every picked template (same merchant + sell-all flag).
    pub fn confirm_trade_picks(
        &mut self,
        npc_id: Option<String>,
        templates: &[String],
        sell_all: bool,
    ) -> usize {
        if templates.is_empty() {
            return 0;
        }
        let mut added = 0usize;
        if let Some(idx) = self.editing_index.take() {
            if let Some(first) = templates.first() {
                if idx < self.stops.len() {
                    self.stops[idx] = WorkerRouteStop::TradeWith {
                        npc_id: npc_id.clone(),
                        template: first.clone(),
                        sell_all,
                    };
                    self.selected_stop_index = idx;
                    added = 1;
                }
                for template in templates.iter().skip(1) {
                    if self
                        .insert_stop(WorkerRouteStop::TradeWith {
                            npc_id: npc_id.clone(),
                            template: template.clone(),
                            sell_all,
                        })
                        .0
                    {
                        added += 1;
                    }
                }
            }
        } else {
            for template in templates {
                if self
                    .insert_stop(WorkerRouteStop::TradeWith {
                        npc_id: npc_id.clone(),
                        template: template.clone(),
                        sell_all,
                    })
                    .0
                {
                    added += 1;
                }
            }
        }
        self.sheet = RouteEditorSheet::Stops;
        added
    }

    /// Mark the selected stop as being edited; the next `confirm_stop` replaces
    /// it in place. Caller then opens the matching sheet (prefilled).
    pub fn begin_edit_selected(&mut self) {
        if self.selected_stop_index < self.stops.len() {
            self.editing_index = Some(self.selected_stop_index);
        }
    }

    /// Esc pops one sheet level. When editing, Esc from an items/filter sheet
    /// returns to the container picker (still editing); Esc from the picker
    /// cancels the edit. Root (`Stops`) is a no-op — the caller closes the editor.
    pub fn sheet_back(&mut self) {
        use RouteEditorSheet as S;
        let editing = self.editing_index.is_some();
        let next = match &self.sheet {
            S::Stops => return,
            S::AddMenu { .. } | S::BedPicker { .. } | S::FarmPlotPicker { .. } => S::Stops,
            S::FarmPlantSeed { .. } => S::FarmPlotPicker {
                index: 0,
                action: FarmPlotAction::Plant,
            },
            S::WaypointMapPick => {
                if editing {
                    S::Stops
                } else {
                    S::WaypointMenu { index: 0 }
                }
            }
            // While editing, back out of items/filter to the chest/NPC picker
            // so the player can retarget without canceling the whole edit.
            S::WithdrawItems { .. } => S::WithdrawContainers { index: 0 },
            S::DepositFilter { .. } => S::DepositContainers { index: 0 },
            S::SellItem { .. } => S::SellNpcs { index: 0 },
            S::WithdrawContainers { .. }
            | S::DepositContainers { .. }
            | S::SellNpcs { .. }
                if editing =>
            {
                S::Stops
            }
            // Top-level sheets: back to the Add menu (or Stops when editing).
            _ => {
                if editing {
                    S::Stops
                } else {
                    S::AddMenu { index: 0 }
                }
            }
        };
        if matches!(next, S::Stops) {
            self.editing_index = None;
        }
        self.sheet = next;
    }

    /// Confirm the current sheet's stop: replace the edited stop in place, or
    /// append (deduped). Returns true when a stop was appended/replaced and
    /// false when a duplicate selected the existing stop instead.
    pub fn confirm_stop(&mut self, stop: WorkerRouteStop) -> bool {
        let result = if let Some(idx) = self.editing_index.take() {
            if idx < self.stops.len() {
                self.stops[idx] = stop;
                self.selected_stop_index = idx;
            }
            true
        } else {
            self.insert_stop(stop).0
        };
        self.sheet = RouteEditorSheet::Stops;
        result
    }

    /// Build withdraw line drafts for `container_id` from its contents.
    /// `existing` pre-fills modes (editing an existing stop); templates no
    /// longer present are kept with `available: 0`.
    pub fn withdraw_line_drafts(
        contents: &[ItemStack],
        existing: &[WorkerRouteWithdrawItem],
    ) -> Vec<WithdrawLineDraft> {
        let mut lines: Vec<WithdrawLineDraft> = Vec::new();
        for s in contents {
            if s.template_id.is_empty() {
                continue;
            }
            match lines.iter_mut().find(|l| l.template == s.template_id) {
                Some(l) => l.available += s.quantity,
                None => lines.push(WithdrawLineDraft {
                    template: s.template_id.clone(),
                    available: s.quantity,
                    mode: WithdrawLineMode::Off,
                }),
            }
        }
        for item in existing {
            let mode = match item.qty {
                None => WithdrawLineMode::All,
                Some(q) => WithdrawLineMode::Qty(q),
            };
            match lines.iter_mut().find(|l| l.template == item.template) {
                Some(l) => l.mode = mode,
                None => lines.push(WithdrawLineDraft {
                    template: item.template.clone(),
                    available: 0,
                    mode,
                }),
            }
        }
        lines.sort_by(|a, b| a.template.cmp(&b.template));
        lines
    }

    /// Collect the active withdraw lines into stop items (`None` = all).
    pub fn withdraw_items_from_lines(lines: &[WithdrawLineDraft]) -> Vec<WorkerRouteWithdrawItem> {
        lines
            .iter()
            .filter_map(|l| match l.mode {
                WithdrawLineMode::Off => None,
                WithdrawLineMode::All => Some(WorkerRouteWithdrawItem {
                    template: l.template.clone(),
                    qty: None,
                }),
                WithdrawLineMode::Qty(q) => Some(WorkerRouteWithdrawItem {
                    template: l.template.clone(),
                    qty: Some(q),
                }),
            })
            .collect()
    }

    // ---- YAML emission -----------------------------------------------

    fn job_id(&self) -> String {
        format!(
            "route_{}",
            self.worker_instance_id
                .chars()
                .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
                .collect::<String>()
        )
    }

    /// YAML that parks the worker: `mode: idle` with no steps. Saving an empty
    /// route means "stand down" rather than leaving the worker in a broken
    /// job loop.
    pub fn build_idle_job_yaml(&self) -> String {
        // No `route` block — an empty ordered route is rejected server-side,
        // and `mode: idle` with no steps is the explicit "stand down" signal.
        let job_id = self.job_id();
        [format!("job_id: {job_id}"), "mode: idle".into(), "steps: []".into()].join("\n")
    }

    pub fn build_job_yaml(&self) -> Result<String, String> {
        if self.stops.is_empty() {
            return Err("add at least one stop (waypoint, harvest node, or deposit)".into());
        }
        let job_id = self.job_id();
        let mut lines = vec![
            format!("job_id: {job_id}"),
            "mode: job_loop".into(),
            "route:".into(),
            "  kind: ordered".into(),
        ];
        if let Some(lodging) = &self.lodging_container_id {
            lines.push(format!("  lodging_container_id: {lodging}"));
        }
        lines.push(format!(
            "  carry_return_ratio: {:.2}",
            self.carry_return_ratio
        ));
        lines.push("  stops:".into());
        for stop in &self.stops {
            match stop {
                WorkerRouteStop::Waypoint { x, y, z } => {
                    lines.push(format!(
                        "    - {{ stop: waypoint, x: {:.1}, y: {:.1}, z: {:.1} }}",
                        x, y, z
                    ));
                }
                WorkerRouteStop::HarvestNode { node_id } => {
                    lines.push(format!("    - {{ stop: harvest_node, node_id: {node_id} }}"));
                }
                WorkerRouteStop::DepositAt { container_id, filter } => {
                    let f = filter
                        .as_ref()
                        .filter(|f| !f.is_empty())
                        .map(|f| format!(", filter: [{}]", f.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")))
                        .unwrap_or_default();
                    lines.push(format!(
                        "    - {{ stop: deposit_at, container_id: {container_id}{f} }}"
                    ));
                }
                WorkerRouteStop::RestIfNeeded => {
                    lines.push("    - { stop: rest_if_needed }".into());
                }
                WorkerRouteStop::Wait { wait_ticks } => {
                    lines.push(format!("    - {{ stop: wait, wait_ticks: {wait_ticks} }}"));
                }
                WorkerRouteStop::TradeWith {
                    npc_id,
                    template,
                    sell_all,
                } => {
                    let who = npc_id
                        .as_deref()
                        .map(|n| format!(", npc_id: {n}"))
                        .unwrap_or_default();
                    lines.push(format!(
                        "    - {{ stop: trade_with, template: {template}{who}, sell_all: {sell_all} }}"
                    ));
                }
                WorkerRouteStop::WithdrawFrom { container_id, items } => {
                    let mut block = format!(
                        "    - stop: withdraw_from\n      container_id: {container_id}\n      items:"
                    );
                    for it in items {
                        let line = match it.qty {
                            None => format!("\n        - {{ template: {}, all: true }}", it.template),
                            Some(q) => format!("\n        - {{ template: {}, qty: {} }}", it.template, q),
                        };
                        block.push_str(&line);
                    }
                    lines.push(block);
                }
                WorkerRouteStop::CraftAt {
                    device,
                    blueprint,
                    qty,
                } => {
                    let qty_str = qty
                        .map(|q| format!(", qty: {q}"))
                        .unwrap_or_default();
                    lines.push(format!(
                        "    - {{ stop: craft_at, device: {device}, blueprint: {blueprint}{qty_str} }}"
                    ));
                }
                WorkerRouteStop::CultivatePlot { plot_id } => {
                    lines.push(format!(
                        "    - {{ stop: cultivate_plot, plot_id: \"{plot_id}\" }}"
                    ));
                }
                WorkerRouteStop::PlantPlot {
                    plot_id,
                    seed_template,
                } => {
                    lines.push(format!(
                        "    - {{ stop: plant_plot, plot_id: \"{plot_id}\", seed_template: {seed_template} }}"
                    ));
                }
                WorkerRouteStop::HarvestPlot { plot_id } => {
                    lines.push(format!(
                        "    - {{ stop: harvest_plot, plot_id: \"{plot_id}\" }}"
                    ));
                }
            }
        }
        lines.push("steps: []".into());
        Ok(lines.join("\n"))
    }

    /// Build a protocol route view matching the current draft (for optimistic client UI).
    pub fn to_route_view(&self) -> flatland_protocol::WorkerRouteView {
        use flatland_protocol::{
            WorkerRouteKindView, WorkerRouteStopView, WorkerRouteView, WorkerWithdrawItemView,
        };
        WorkerRouteView {
            kind: WorkerRouteKindView::Ordered,
            lodging_container_id: self.lodging_container_id.clone(),
            outbound_waypoints: Vec::new(),
            harvest_nodes: Vec::new(),
            carry_return_ratio: self.carry_return_ratio,
            stops: self
                .stops
                .iter()
                .map(|stop| match stop {
                    WorkerRouteStop::Waypoint { x, y, z } => WorkerRouteStopView::Waypoint {
                        x: *x,
                        y: *y,
                        z: *z,
                    },
                    WorkerRouteStop::HarvestNode { node_id } => WorkerRouteStopView::HarvestNode {
                        node_id: node_id.clone(),
                    },
                    WorkerRouteStop::DepositAt { container_id, filter } => {
                        WorkerRouteStopView::DepositAt {
                            container_id: container_id.clone(),
                            filter: filter.clone(),
                        }
                    }
                    WorkerRouteStop::TradeWith {
                        npc_id,
                        template,
                        sell_all,
                    } => WorkerRouteStopView::TradeWith {
                        npc_id: npc_id.clone(),
                        template: template.clone(),
                        sell_all: *sell_all,
                    },
                    WorkerRouteStop::WithdrawFrom { container_id, items } => {
                        WorkerRouteStopView::WithdrawFrom {
                            container_id: container_id.clone(),
                            items: items
                                .iter()
                                .map(|i| WorkerWithdrawItemView {
                                    template: i.template.clone(),
                                    qty: i.qty.unwrap_or(0),
                                    all: i.qty.is_none(),
                                })
                                .collect(),
                        }
                    }
                    WorkerRouteStop::CraftAt {
                        device,
                        blueprint,
                        qty,
                    } => WorkerRouteStopView::CraftAt {
                        device: device.clone(),
                        blueprint: blueprint.clone(),
                        qty: *qty,
                    },
                    WorkerRouteStop::CultivatePlot { plot_id } => {
                        WorkerRouteStopView::CultivatePlot {
                            plot_id: *plot_id,
                        }
                    }
                    WorkerRouteStop::PlantPlot {
                        plot_id,
                        seed_template,
                    } => WorkerRouteStopView::PlantPlot {
                        plot_id: *plot_id,
                        seed_template: seed_template.clone(),
                    },
                    WorkerRouteStop::HarvestPlot { plot_id } => WorkerRouteStopView::HarvestPlot {
                        plot_id: *plot_id,
                    },
                    WorkerRouteStop::RestIfNeeded => WorkerRouteStopView::RestIfNeeded,
                    WorkerRouteStop::Wait { wait_ticks } => WorkerRouteStopView::Wait {
                        wait_ticks: *wait_ticks,
                    },
                })
                .collect(),
        }
    }
}

fn stop_view_to_stop(view: &WorkerRouteStopView) -> WorkerRouteStop {
    match view {
        WorkerRouteStopView::Waypoint { x, y, z } => WorkerRouteStop::Waypoint {
            x: *x,
            y: *y,
            z: *z,
        },
        WorkerRouteStopView::HarvestNode { node_id } => WorkerRouteStop::HarvestNode {
            node_id: node_id.clone(),
        },
        WorkerRouteStopView::DepositAt { container_id, filter } => WorkerRouteStop::DepositAt {
            container_id: container_id.clone(),
            filter: filter.clone(),
        },
        WorkerRouteStopView::TradeWith {
            npc_id,
            template,
            sell_all,
        } => WorkerRouteStop::TradeWith {
            npc_id: npc_id.clone(),
            template: template.clone(),
            sell_all: *sell_all,
        },
        WorkerRouteStopView::WithdrawFrom { container_id, items } => WorkerRouteStop::WithdrawFrom {
            container_id: container_id.clone(),
            items: items
                .iter()
                .map(|i| WorkerRouteWithdrawItem {
                    template: i.template.clone(),
                    qty: if i.all { None } else { Some(i.qty) },
                })
                .collect(),
        },
        WorkerRouteStopView::CraftAt {
            device,
            blueprint,
            qty,
        } => WorkerRouteStop::CraftAt {
            device: device.clone(),
            blueprint: blueprint.clone(),
            qty: *qty,
        },
        WorkerRouteStopView::CultivatePlot { plot_id } => WorkerRouteStop::CultivatePlot {
            plot_id: *plot_id,
        },
        WorkerRouteStopView::PlantPlot {
            plot_id,
            seed_template,
        } => WorkerRouteStop::PlantPlot {
            plot_id: *plot_id,
            seed_template: seed_template.clone(),
        },
        WorkerRouteStopView::HarvestPlot { plot_id } => WorkerRouteStop::HarvestPlot {
            plot_id: *plot_id,
        },
        WorkerRouteStopView::RestIfNeeded => WorkerRouteStop::RestIfNeeded,
        WorkerRouteStopView::Wait { wait_ticks } => WorkerRouteStop::Wait {
            wait_ticks: *wait_ticks,
        },
    }
}

// ---- map-click picking ----------------------------------------------

const HARVEST_NODE_PICK_M: f32 = 4.0;
const LODGING_PICK_M: f32 = 5.0;
const STORAGE_PICK_M: f32 = 5.0;

fn dist2d(x0: f32, y0: f32, x1: f32, y1: f32) -> f32 {
    let dx = x0 - x1;
    let dy = y0 - y1;
    (dx * dx + dy * dy).sqrt()
}

/// Nearest harvestable resource node within click range.
pub fn pick_resource_node_at<'a>(
    nodes: &'a [ResourceNodeView],
    x: f32,
    y: f32,
) -> Option<&'a ResourceNodeView> {
    nodes
        .iter()
        .filter(|n| n.state == flatland_protocol::ResourceNodeState::Available)
        .filter_map(|n| {
            let d = dist2d(x, y, n.x, n.y);
            if d <= HARVEST_NODE_PICK_M {
                Some((d, n))
            } else {
                None
            }
        })
        .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
        .map(|(_, n)| n)
}

/// Owned placed lodging containers (camp beds) — used as the rest/bed target.
pub fn owned_lodging_container_ids(
    placed: &[PlacedContainerView],
    character_id: Option<uuid::Uuid>,
) -> Vec<(String, String)> {
    owned_lodging_container_ids_with_occupants(placed, character_id, &[])
}

/// Lodging beds with display names that include occupant labels (`Camp bed — Elda`).
pub fn owned_lodging_container_ids_with_occupants(
    placed: &[PlacedContainerView],
    character_id: Option<uuid::Uuid>,
    hired: &[flatland_protocol::HiredWorkerView],
) -> Vec<(String, String)> {
    let Some(cid) = character_id else {
        return Vec::new();
    };
    let mut out: Vec<(String, String)> = placed
        .iter()
        .filter(|c| c.worker_lodging_capacity.unwrap_or(0) > 0)
        .filter(|c| c.owner_character_id == Some(cid))
        .map(|c| {
            let who = lodging_occupants_for(hired, &c.id);
            let name = if who.is_empty() {
                format!("{} — vacant", c.display_name)
            } else {
                format!("{} — {}", c.display_name, who.join(", "))
            };
            (c.id.clone(), name)
        })
        .collect();
    out.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
    out
}

pub fn pick_lodging_container_at(
    placed: &[PlacedContainerView],
    character_id: Option<uuid::Uuid>,
    x: f32,
    y: f32,
) -> Option<String> {
    let cid = character_id?;
    placed
        .iter()
        .filter(|c| c.worker_lodging_capacity.unwrap_or(0) > 0)
        .filter(|c| c.owner_character_id == Some(cid))
        .filter_map(|c| {
            let d = dist2d(x, y, c.x, c.y);
            if d <= LODGING_PICK_M {
                Some((d, c.id.clone()))
            } else {
                None
            }
        })
        .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
        .map(|(_, id)| id)
}

/// Nearest trade-capable NPC within click range.
pub fn pick_trade_npc_at(
    npcs: &[NpcView],
    x: f32,
    y: f32,
) -> Option<(String, String)> {
    const NPC_PICK_M: f32 = 5.0;
    npcs.iter()
        .filter(|n| n.can_trade)
        .filter_map(|n| {
            let d = dist2d(x, y, n.x, n.y);
            if d <= NPC_PICK_M {
                Some((d, n.id.clone(), n.label.clone()))
            } else {
                None
            }
        })
        .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
        .map(|(_, id, label)| (id, label))
}

/// Distinct item templates present in the employer's owned placed containers —
/// candidate sell templates for `TradeWith` stops.
pub fn owned_storage_template_ids(
    placed: &[PlacedContainerView],
    character_id: Option<uuid::Uuid>,
) -> Vec<String> {
    let Some(cid) = character_id else {
        return Vec::new();
    };
    let mut out: Vec<String> = placed
        .iter()
        .filter(|c| c.owner_character_id == Some(cid))
        .flat_map(|c| c.contents.iter().map(|s| s.template_id.clone()))
        .filter(|t| !t.is_empty())
        .collect();
    out.sort();
    out.dedup();
    out
}

/// Blueprint ids the route editor may assign to a `craft_at hand` stop.
///
/// Order matches `blueprints`. When the worker has a non-empty
/// `known_blueprint_ids` list, only those recipes are included — the picker UI
/// and j/k navigation must use the same list so the cursor cannot land on
/// recipes the worker does not know (and so Enter confirms the highlighted row).
pub fn worker_craft_blueprint_ids(
    blueprints: &[flatland_protocol::BlueprintView],
    known_blueprint_ids: Option<&[String]>,
) -> Vec<String> {
    let mut ids: Vec<String> = blueprints.iter().map(|b| b.id.clone()).collect();
    if let Some(known) = known_blueprint_ids {
        if !known.is_empty() {
            ids.retain(|id| known.iter().any(|k| k == id));
        }
    }
    ids
}

/// Item templates for deposit filters / sell stops — not limited to what is
/// already in a chest. Includes storage, inventory, craft outputs/inputs, harvest
/// node products, and any `extra` seeds (existing filter selections, route craft
/// outputs) so factory lines can be authored before the first batch is made.
pub fn route_item_template_candidates(
    placed: &[PlacedContainerView],
    character_id: Option<uuid::Uuid>,
    inventory: &std::collections::HashMap<String, u32>,
    blueprints: &[flatland_protocol::BlueprintView],
    resource_nodes: &[flatland_protocol::ResourceNodeView],
    extra: &[String],
) -> Vec<String> {
    let mut out = owned_storage_template_ids(placed, character_id);
    for (template, qty) in inventory {
        if *qty > 0 && !template.is_empty() {
            out.push(template.clone());
        }
    }
    for bp in blueprints {
        if !bp.output.is_empty() {
            out.push(bp.output.clone());
        }
        for input in &bp.inputs {
            if !input.template_id.is_empty() {
                out.push(input.template_id.clone());
            }
        }
        for tool in &bp.required_tools {
            if !tool.item.is_empty() {
                out.push(tool.item.clone());
            }
        }
    }
    for node in resource_nodes {
        if !node.item_template.is_empty() {
            out.push(node.item_template.clone());
        }
        for t in &node.harvest_drop_templates {
            if !t.is_empty() {
                out.push(t.clone());
            }
        }
    }
    for t in extra {
        if !t.is_empty() {
            out.push(t.clone());
        }
    }
    out.sort();
    out.dedup();
    out
}

/// Pick any owned storage container at a click position (lodging or regular chest).
pub fn pick_storage_container_at(
    placed: &[PlacedContainerView],
    character_id: Option<uuid::Uuid>,
    x: f32,
    y: f32,
) -> Option<String> {
    let cid = character_id?;
    placed
        .iter()
        .filter(|c| c.owner_character_id == Some(cid))
        .filter(|c| c.capacity_volume.unwrap_or(0.0) > 0.0)
        .filter_map(|c| {
            let d = dist2d(x, y, c.x, c.y);
            if d <= STORAGE_PICK_M {
                Some((d, c.id.clone()))
            } else {
                None
            }
        })
        .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
        .map(|(_, id)| id)
}

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

    #[test]
    fn worker_craft_blueprint_ids_filters_to_known_recipes() {
        use flatland_protocol::{BlueprintIngredientView, BlueprintView};

        fn bp(id: &str) -> BlueprintView {
            BlueprintView {
                id: id.into(),
                label: id.into(),
                output: "x".into(),
                output_qty: 1,
                craft_ticks: 1,
                inputs: vec![BlueprintIngredientView {
                    template_id: "oak_log".into(),
                    quantity: 1,
                    consumed: true,
                }],
                station: Some("hand".into()),
                category: None,
                required_tools: vec![],
                skill: None,
                failure_chance: 0.0,
                worker_train_copper: 0,
            }
        }

        let all = vec![
            bp("oak_to_lumber"),
            bp("vegetable_soup"),
            bp("craft_simple_camp_bed"),
            bp("craft_wooden_chest_small"),
            bp("iron_ingot"),
        ];
        let known = vec![
            "oak_to_lumber".into(),
            "craft_simple_camp_bed".into(),
            "craft_wooden_chest_small".into(),
        ];

        let filtered = worker_craft_blueprint_ids(&all, Some(&known));
        assert_eq!(
            filtered,
            vec![
                "oak_to_lumber",
                "craft_simple_camp_bed",
                "craft_wooden_chest_small"
            ]
        );

        // Empty known list = no filter (legacy / unknown worker).
        assert_eq!(
            worker_craft_blueprint_ids(&all, Some(&[])).len(),
            all.len()
        );
        assert_eq!(worker_craft_blueprint_ids(&all, None).len(), all.len());
    }

    #[test]
    fn route_item_candidates_include_craft_outputs_not_in_storage() {
        use flatland_protocol::{
            BlueprintIngredientView, BlueprintView, PlacedContainerView, ResourceNodeView,
            ResourceNodeState,
        };
        use std::collections::HashMap;
        use uuid::Uuid;

        let cid = Uuid::from_u128(0x1111_2222_3333_4444_5555_6666_7777_8888);
        let placed = vec![PlacedContainerView {
            id: "chest-1".into(),
            template_id: "wooden_chest_small".into(),
            display_name: "Chest".into(),
            x: 0.0,
            y: 0.0,
            z: 0.0,
            locked: false,
            accessible: true,
            owner_character_id: Some(cid),
            contents: vec![],
            lock_id: None,
            capacity_volume: Some(20.0),
            item_instance_id: None,
            tile_id: None,
            worker_lodging_capacity: None,
            blocking: false,
            blocking_radius_m: 0.0,
        }];
        let blueprints = vec![BlueprintView {
            id: "smelt_iron".into(),
            label: "Smelt Iron".into(),
            output: "iron_ingot".into(),
            output_qty: 1,
            craft_ticks: 30,
            inputs: vec![BlueprintIngredientView {
                template_id: "iron_ore".into(),
                quantity: 1,
                consumed: true,
            }],
            station: Some("hand".into()),
            category: None,
            required_tools: vec![],
            skill: None,
            failure_chance: 0.0,
            worker_train_copper: 0,
        }];
        let nodes = vec![ResourceNodeView {
            id: "ore-1".into(),
            label: "Iron Ore".into(),
            x: 1.0,
            y: 1.0,
            z: 0.0,
            item_template: "iron_ore".into(),
            state: ResourceNodeState::Available,
            blocking: true,
            blocking_radius_m: 0.8,
            tile_id: None,
            yaw: 0.0,
            pitch: 0.0,
            roll: 0.0,
            draw_scale: 1.0,
            sprite_mode: None,
            growth_progress: None,
            presentation_state: None,
            channel_start_tick: None,
            channel_end_tick: None,
            harvest_drop_templates: vec![],
        }];
        let ids = route_item_template_candidates(
            &placed,
            Some(cid),
            &HashMap::new(),
            &blueprints,
            &nodes,
            &[],
        );
        assert!(
            ids.contains(&"iron_ingot".to_string()),
            "craft output should be selectable before any exists in storage: {ids:?}"
        );
        assert!(ids.contains(&"iron_ore".to_string()));
    }

    #[test]
    fn route_item_template_includes_harvest_loot_table_drops() {
        use flatland_protocol::{ResourceNodeState, ResourceNodeView};
        use std::collections::HashMap;
        let nodes = vec![ResourceNodeView {
            id: "crop-carrot-1".into(),
            label: "Wild carrots".into(),
            x: 1.0,
            y: 1.0,
            z: 0.0,
            item_template: "carrot_wild".into(),
            state: ResourceNodeState::Available,
            blocking: false,
            blocking_radius_m: 0.8,
            tile_id: None,
            yaw: 0.0,
            pitch: 0.0,
            roll: 0.0,
            draw_scale: 1.0,
            sprite_mode: None,
            growth_progress: None,
            presentation_state: None,
            channel_start_tick: None,
            channel_end_tick: None,
            harvest_drop_templates: vec!["carrot".into(), "carrot_seed".into()],
        }];
        let ids = route_item_template_candidates(
            &[],
            None,
            &HashMap::new(),
            &[],
            &nodes,
            &[],
        );
        assert!(
            ids.contains(&"carrot_seed".to_string()),
            "deposit filter should list seeds from harvest loot tables: {ids:?}"
        );
        assert!(ids.contains(&"carrot_wild".to_string()));
    }

    #[test]
    fn build_ordered_job_yaml_includes_stops() {
        let mut ed = WorkerRouteEditorState::new(
            "worker-worker_laborer-1".into(),
            "Laborer".into(),
            Some("chest-bed".into()),
        );
        ed.append_waypoint(10.0, 20.0, 0.0);
        ed.append_harvest_node("oak-n1");
        ed.append_deposit_at("chest-storage-a");
        ed.append_rest_if_needed();
        let yaml = ed.build_job_yaml().expect("yaml");
        assert!(yaml.contains("kind: ordered"));
        assert!(yaml.contains("lodging_container_id: chest-bed"));
        assert!(yaml.contains("stop: waypoint"));
        assert!(yaml.contains("oak-n1"));
        assert!(yaml.contains("deposit_at"));
        assert!(yaml.contains("chest-storage-a"));
        assert!(yaml.contains("rest_if_needed"));
    }

    #[test]
    fn requires_at_least_one_stop() {
        let ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        assert!(ed.build_job_yaml().is_err());
    }

    #[test]
    fn reorder_stops() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.append_harvest_node("oak-a");
        ed.append_harvest_node("oak-b");
        ed.append_waypoint(5.0, 6.0, 0.0);
        // select index 1 (oak-b), move up → order becomes oak-b, oak-a, waypoint
        ed.select_stop(1);
        ed.move_selected_up();
        assert!(
            matches!(&ed.stops[0], WorkerRouteStop::HarvestNode { node_id } if node_id == "oak-b")
        );
        // move down again restores
        ed.move_selected_down();
        assert!(
            matches!(&ed.stops[1], WorkerRouteStop::HarvestNode { node_id } if node_id == "oak-b")
        );
    }

    #[test]
    fn duplicate_harvest_node_selects_existing_instead() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        assert!(ed.append_harvest_node("oak-a"));
        ed.append_waypoint(1.0, 2.0, 0.0);
        assert!(!ed.append_harvest_node("oak-a"));
        assert_eq!(ed.stops.len(), 2);
        assert_eq!(ed.selected_stop_index, 0);
    }

    #[test]
    fn duplicate_deposit_container_selects_existing_instead() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        assert!(ed.append_deposit_at("chest-1"));
        ed.append_harvest_node("oak-a");
        assert!(!ed.append_deposit_at("chest-1"));
        assert_eq!(ed.stops.len(), 2);
        assert_eq!(ed.selected_stop_index, 0);
    }

    #[test]
    fn duplicate_trade_stop_selects_existing_instead() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        assert!(ed.append_trade_with("oak_log".into(), Some("ada".into()), true));
        assert!(!ed.append_trade_with("oak_log".into(), Some("ada".into()), true));
        // Different template at the same merchant is a distinct stop.
        assert!(ed.append_trade_with("lumber".into(), Some("ada".into()), true));
        assert_eq!(ed.stops.len(), 2);
    }

    #[test]
    fn build_idle_job_yaml_parks_worker() {
        let ed = WorkerRouteEditorState::new("w1".into(), "L".into(), Some("bed-1".into()));
        let yaml = ed.build_idle_job_yaml();
        assert!(yaml.contains("mode: idle"));
        assert!(yaml.contains("steps: []"));
        assert!(!yaml.contains("route:"));
    }

    #[test]
    fn remove_selected_stop_adjusts_index() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.append_waypoint(1.0, 2.0, 0.0);
        ed.append_harvest_node("oak-a");
        ed.append_deposit_at("chest-1");
        ed.select_stop(2);
        ed.remove_selected_stop();
        assert_eq!(ed.stops.len(), 2);
        assert_eq!(ed.selected_stop_index, 1);
    }

    #[test]
    fn build_job_yaml_includes_trade_with_stop() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.append_trade_with("oak_log".into(), None, true);
        ed.append_trade_with("lumber".into(), Some("ada_broker".into()), false);
        let yaml = ed.build_job_yaml().expect("yaml");
        assert!(yaml.contains("stop: trade_with, template: oak_log, sell_all: true"));
        assert!(yaml.contains("npc_id: ada_broker"));
        assert!(yaml.contains("sell_all: false"));
    }

    #[test]
    fn set_selected_trade_npc_updates_stop() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.append_trade_with("oak_log".into(), None, true);
        assert!(ed.set_selected_trade_npc("ada_broker".into()));
        assert!(matches!(&ed.stops[0], WorkerRouteStop::TradeWith { npc_id, .. } if npc_id.as_deref() == Some("ada_broker")));
    }

    #[test]
    fn build_job_yaml_deposit_filter_round_trips() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), Some("bed-1".into()));
        ed.append_deposit_at_filtered("chest-out", vec!["lumber".into()]);
        let yaml = ed.build_job_yaml().expect("yaml");
        assert!(yaml.contains("stop: deposit_at, container_id: chest-out, filter: [lumber]"));
    }

    #[test]
    fn build_job_yaml_includes_withdraw_and_craft_stops() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.stops.push(WorkerRouteStop::WithdrawFrom {
            container_id: "chest-src".into(),
            items: vec![WorkerRouteWithdrawItem { template: "oak_log".into(), qty: None }],
        });
        ed.stops.push(WorkerRouteStop::WithdrawFrom {
            container_id: "chest-src-2".into(),
            items: vec![WorkerRouteWithdrawItem { template: "iron_ore".into(), qty: Some(10) }],
        });
        ed.stops.push(WorkerRouteStop::CraftAt {
            device: "hand".into(),
            blueprint: "oak_to_lumber".into(),
            qty: None,
        });
        ed.append_deposit_at("chest-out");
        let yaml = ed.build_job_yaml().expect("yaml");
        assert!(yaml.contains("stop: withdraw_from"));
        assert!(yaml.contains("container_id: chest-src"));
        assert!(yaml.contains("template: oak_log, all: true"));
        assert!(yaml.contains("template: iron_ore, qty: 10"));
        assert!(yaml.contains("stop: craft_at, device: hand, blueprint: oak_to_lumber"));
        assert!(yaml.contains("stop: deposit_at"));
    }

    #[test]
    fn withdraw_summary_shows_all_vs_qty() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.stops.push(WorkerRouteStop::WithdrawFrom {
            container_id: "chest-src".into(),
            items: vec![WorkerRouteWithdrawItem { template: "oak_log".into(), qty: None }],
        });
        assert!(ed.stops[0].summary().contains("withdraw all oak_log"));
    }

    #[test]
    fn withdraw_view_round_trips_all_flag() {
        let view = WorkerRouteStopView::WithdrawFrom {
            container_id: "chest-1".into(),
            items: vec![
                flatland_protocol::WorkerWithdrawItemView {
                    template: "oak_log".into(),
                    qty: 0,
                    all: true,
                },
                flatland_protocol::WorkerWithdrawItemView {
                    template: "iron_ore".into(),
                    qty: 5,
                    all: false,
                },
            ],
        };
        let stop = stop_view_to_stop(&view);
        let WorkerRouteStop::WithdrawFrom { items, .. } = stop else {
            panic!("expected withdraw stop");
        };
        assert_eq!(items[0].qty, None);
        assert_eq!(items[1].qty, Some(5));
    }

    #[test]
    fn legacy_harvest_loop_route_converts_to_ordered_stops() {
        let route = WorkerRouteView {
            kind: WorkerRouteKindView::HarvestLoop,
            lodging_container_id: Some("bed-1".into()),
            outbound_waypoints: vec![flatland_protocol::WorkerRouteWaypointView {
                x: 1.0,
                y: 2.0,
                z: 0.0,
            }],
            harvest_nodes: vec!["oak-1".into()],
            carry_return_ratio: 0.9,
            stops: Vec::new(),
        };
        let ed = WorkerRouteEditorState::from_saved_route(
            "w1".into(),
            "L".into(),
            &route,
            None,
        );
        // waypoint, harvest, deposit@bed, rest
        assert_eq!(ed.stops.len(), 4);
        assert!(matches!(&ed.stops[2], WorkerRouteStop::DepositAt { container_id, .. } if container_id == "bed-1"));
        assert!(matches!(&ed.stops[3], WorkerRouteStop::RestIfNeeded));
    }

    // ---- sheet state machine ------------------------------------------

    #[test]
    fn retarget_withdraw_container_updates_editing_stop() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.stops.push(WorkerRouteStop::WithdrawFrom {
            container_id: "chest-old".into(),
            items: vec![WorkerRouteWithdrawItem {
                template: "iron_ore".into(),
                qty: None,
            }],
        });
        ed.selected_stop_index = 0;
        ed.editing_index = Some(0);
        assert!(ed.retarget_withdraw_container("chest-new".into()));
        assert!(matches!(
            &ed.stops[0],
            WorkerRouteStop::WithdrawFrom { container_id, .. } if container_id == "chest-new"
        ));
    }

    #[test]
    fn summary_resolved_uses_friendly_labels() {
        let stop = WorkerRouteStop::WithdrawFrom {
            container_id: "uuid-iron".into(),
            items: vec![WorkerRouteWithdrawItem {
                template: "iron_ore".into(),
                qty: None,
            }],
        };
        let summary = stop.summary_resolved(
            |_| "Iron Ore Container".into(),
            |_| "Ada".into(),
            |_| "Oak Tree".into(),
        );
        assert_eq!(summary, "withdraw all iron_ore from Iron Ore Container");
        assert!(!summary.contains("uuid"));
    }

    #[test]
    fn list_filter_row_matches_name_and_distance() {
        assert!(list_filter_row_matches("oak", None, &["Oak Tree", "oak_log"]));
        assert!(!list_filter_row_matches("pine", None, &["Oak Tree", "oak_log"]));
        assert!(list_filter_row_matches("oak 50m", Some(40.0), &["Oak Tree"]));
        assert!(!list_filter_row_matches("oak 50m", Some(60.0), &["Oak Tree"]));
        assert!(list_filter_row_matches("", Some(999.0), &["anything"]));
    }

    #[test]
    fn node_candidates_sort_from_lodging_anchor_not_player() {
        use flatland_protocol::{ResourceNodeState, ResourceNodeView};
        fn node(id: &str, label: &str, x: f32) -> ResourceNodeView {
            ResourceNodeView {
                id: id.into(),
                label: label.into(),
                x,
                y: 0.0,
                z: 0.0,
                item_template: "oak_log".into(),
                state: ResourceNodeState::Available,
                blocking: true,
                blocking_radius_m: 0.8,
                tile_id: None,
                yaw: 0.0,
                pitch: 0.0,
                roll: 0.0,
                draw_scale: 1.0,
                sprite_mode: None,
                presentation_state: None,
                growth_progress: None,
                channel_start_tick: None,
                channel_end_tick: None,
                harvest_drop_templates: vec![],
            }
        }
        let nodes = vec![node("far", "Far Oak", 100.0), node("near", "Near Oak", 5.0)];
        let sorted = node_candidates(&nodes, 0.0, 0.0);
        assert_eq!(sorted[0].id, "near");
        assert_eq!(sorted[1].id, "far");
        assert!((sorted[0].dist - 5.0).abs() < 0.01);

        let stable = node_candidates_stable(&nodes);
        assert_eq!(stable[0].label, "Far Oak");
        assert_eq!(stable[1].label, "Near Oak");
        assert!(stable[0].dist.is_nan());
    }

    #[test]
    fn sheet_back_walks_up_hierarchy() {
        use RouteEditorSheet as S;
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        assert_eq!(ed.sheet, S::Stops);
        ed.open_add_menu();
        assert_eq!(ed.sheet, S::AddMenu { index: 0 });
        ed.open_sheet(S::WithdrawContainers { index: 0 });
        ed.open_sheet(S::WithdrawItems {
            container_id: "c1".into(),
            lines: vec![],
            index: 0,
        });
        ed.sheet_back();
        assert_eq!(ed.sheet, S::WithdrawContainers { index: 0 });
        ed.sheet_back();
        assert_eq!(ed.sheet, S::AddMenu { index: 0 });
        ed.sheet_back();
        assert_eq!(ed.sheet, S::Stops);
        // Root: back is a no-op.
        ed.sheet_back();
        assert_eq!(ed.sheet, S::Stops);
    }

    #[test]
    fn sheet_back_while_editing_returns_to_stops() {
        use RouteEditorSheet as S;
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.append_harvest_node("oak-a");
        ed.begin_edit_selected();
        ed.open_sheet(S::HarvestPicker {
            index: 0,
            picked: BTreeSet::new(),
            nodes: Vec::new(),
        });
        ed.sheet_back();
        assert_eq!(ed.sheet, S::Stops);
        assert_eq!(ed.editing_index, None);
    }

    #[test]
    fn sheet_back_while_editing_withdraw_keeps_edit_on_container_picker() {
        use RouteEditorSheet as S;
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.stops.push(WorkerRouteStop::WithdrawFrom {
            container_id: "chest-a".into(),
            items: vec![WorkerRouteWithdrawItem {
                template: "oak_log".into(),
                qty: None,
            }],
        });
        ed.begin_edit_selected();
        ed.open_sheet(S::WithdrawItems {
            container_id: "chest-a".into(),
            lines: vec![],
            index: 0,
        });
        ed.sheet_back();
        assert!(matches!(ed.sheet, S::WithdrawContainers { .. }));
        assert_eq!(ed.editing_index, Some(0), "still editing after back to picker");
        ed.sheet_back();
        assert_eq!(ed.sheet, S::Stops);
        assert_eq!(ed.editing_index, None);
    }

    #[test]
    fn confirm_stop_replaces_withdraw_container_when_editing() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.stops.push(WorkerRouteStop::WithdrawFrom {
            container_id: "chest-old".into(),
            items: vec![WorkerRouteWithdrawItem {
                template: "oak_log".into(),
                qty: None,
            }],
        });
        ed.stops.push(WorkerRouteStop::RestIfNeeded);
        ed.select_stop(0);
        ed.begin_edit_selected();
        assert!(ed.confirm_stop(WorkerRouteStop::WithdrawFrom {
            container_id: "chest-new".into(),
            items: vec![WorkerRouteWithdrawItem {
                template: "oak_log".into(),
                qty: None,
            }],
        }));
        assert_eq!(ed.stops.len(), 2);
        assert!(matches!(
            &ed.stops[0],
            WorkerRouteStop::WithdrawFrom { container_id, .. } if container_id == "chest-new"
        ));
    }

    #[test]
    fn confirm_stop_replaces_when_editing() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.append_harvest_node("oak-a");
        ed.append_waypoint(1.0, 1.0, 0.0);
        ed.select_stop(0);
        ed.begin_edit_selected();
        assert!(ed.confirm_stop(WorkerRouteStop::HarvestNode {
            node_id: "oak-b".into()
        }));
        assert_eq!(ed.stops.len(), 2, "edit replaces in place, no append");
        assert!(
            matches!(&ed.stops[0], WorkerRouteStop::HarvestNode { node_id } if node_id == "oak-b")
        );
        assert_eq!(ed.sheet, RouteEditorSheet::Stops);
        assert_eq!(ed.editing_index, None);
    }

    #[test]
    fn confirm_stop_dedupes_on_append() {
        let mut ed = WorkerRouteEditorState::new("w1".into(), "L".into(), None);
        ed.append_harvest_node("oak-a");
        assert!(!ed.confirm_stop(WorkerRouteStop::HarvestNode {
            node_id: "oak-a".into()
        }));
        assert_eq!(ed.stops.len(), 1);
        assert_eq!(ed.selected_stop_index, 0);
    }

    #[test]
    fn withdraw_line_cycle_and_collect() {
        let contents = vec![
            ItemStack {
                template_id: "oak_log".into(),
                quantity: 12,
                ..Default::default()
            },
            ItemStack {
                template_id: "lumber".into(),
                quantity: 4,
                ..Default::default()
            },
        ];
        let mut lines =
            WorkerRouteEditorState::withdraw_line_drafts(&contents, &[]);
        assert_eq!(lines.len(), 2);
        // cycle oak_log (sorted first: lumber, oak_log)
        lines[1].cycle();
        assert_eq!(lines[1].mode, WithdrawLineMode::All);
        lines[0].cycle();
        lines[0].cycle();
        assert!(matches!(lines[0].mode, WithdrawLineMode::Qty(_)));
        lines[0].adjust_qty(5);
        let items = WorkerRouteEditorState::withdraw_items_from_lines(&lines);
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].template, "lumber");
        // lumber available = 4: Qty starts at 4, +5 clamps back to 4.
        assert_eq!(items[0].qty, Some(4));
        assert_eq!(items[1].qty, None);
    }

    #[test]
    fn withdraw_drafts_prefill_existing_and_keep_missing() {
        let contents = vec![ItemStack {
            template_id: "oak_log".into(),
            quantity: 3,
            ..Default::default()
        }];
        let existing = vec![
            WorkerRouteWithdrawItem { template: "oak_log".into(), qty: None },
            WorkerRouteWithdrawItem { template: "iron_ore".into(), qty: Some(5) },
        ];
        let lines = WorkerRouteEditorState::withdraw_line_drafts(&contents, &existing);
        assert_eq!(lines.len(), 2);
        let ore = lines.iter().find(|l| l.template == "iron_ore").expect("ore line");
        assert_eq!(ore.available, 0, "missing template kept with 0 available");
        assert_eq!(ore.mode, WithdrawLineMode::Qty(5));
        let oak = lines.iter().find(|l| l.template == "oak_log").expect("oak line");
        assert_eq!(oak.mode, WithdrawLineMode::All);
    }
}