File size: 58,234 Bytes
4bba76c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>駱駝商人・碎石步道路徑與鏡像角度編輯工具</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@600;700;800&family=Noto+Sans+TC:wght@400;500;700;800&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #0b0f19;
      --card-bg: rgba(22, 27, 42, 0.92);
      --card-border: rgba(212, 163, 89, 0.32);
      --gold-primary: #d4a359;
      --gold-bright: #f6c574;
      --gold-glow: rgba(246, 197, 116, 0.45);
      --accent-cyan: #38bdf8;
      --accent-purple: #c084fc;
      --accent-red: #ef4444;
      --accent-green: #22c55e;
      --text-main: #f1f5f9;
      --text-sub: #94a3b8;
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }

    body {
      background: radial-gradient(circle at 50% 15%, #182035 0%, var(--bg) 80%);
      color: var(--text-main);
      font-family: 'Noto Sans TC', -apple-system, BlinkMacSystemFont, sans-serif;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      padding: 16px 20px;
    }

    header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 14px;
      padding-bottom: 12px;
      border-bottom: 1px solid rgba(212, 163, 89, 0.25);
      flex-wrap: wrap;
      gap: 12px;
    }

    .title-group {
      display: flex;
      align-items: center;
      gap: 12px;
      flex-wrap: wrap;
    }

    .title-group h1 {
      font-size: 20px;
      font-weight: 800;
      color: var(--gold-bright);
      background: linear-gradient(135deg, #ffffff 15%, var(--gold-bright) 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      letter-spacing: 0.5px;
    }

    .title-group .badge {
      font-size: 11px;
      padding: 3px 8px;
      border-radius: 999px;
      background: rgba(212, 163, 89, 0.18);
      border: 1px solid var(--card-border);
      color: var(--gold-bright);
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      gap: 10px;
      align-items: center;
      flex-wrap: wrap;
    }

    .main-layout {
      display: grid;
      grid-template-columns: 1fr 410px;
      gap: 18px;
      flex: 1;
    }

    @media (max-width: 1080px) {
      .main-layout {
        grid-template-columns: 1fr;
      }
    }

    /* 地圖畫布區域 */
    .map-container {
      position: relative;
      background: #000;
      border-radius: 14px;
      overflow: hidden;
      box-shadow: 0 12px 36px rgba(0,0,0,0.7), 0 0 0 1px var(--card-border);
      user-select: none;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .map-aspect-box {
      position: relative;
      width: 100%;
      aspect-ratio: 16 / 9;
      background: #0b0f19;
      background-image: url('assets/map_chibi.jpg');
      background-size: 100% 100%;
      background-position: center;
      background-repeat: no-repeat;
      cursor: crosshair;
      overflow: hidden;
    }

    .map-bg-img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: fill;
      display: block;
      pointer-events: none;
      filter: saturate(1.06) contrast(1.02);
      transition: filter 0.25s ease;
      z-index: 1;
    }

    .map-bg-img.filter-contrast {
      filter: contrast(1.28) brightness(1.08) saturate(1.25);
    }

    .map-bg-img.filter-dim {
      filter: brightness(0.6) contrast(1.15) saturate(0.9);
    }

    /* 城池建築參考層 */
    .buildings-layer {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      z-index: 5;
      transition: opacity 0.25s ease;
    }

    .building-marker {
      position: absolute;
      transform: translate(-50%, -50%);
      display: flex;
      flex-direction: column;
      align-items: center;
      pointer-events: none;
    }

    .building-marker img {
      width: 48px;
      height: 48px;
      object-fit: contain;
      filter: drop-shadow(0 4px 8px rgba(0,0,0,0.6));
    }

    .building-marker .b-tag {
      font-size: 10px;
      font-weight: 700;
      color: #fff;
      background: rgba(15, 23, 42, 0.85);
      border: 1px solid rgba(212, 163, 89, 0.5);
      padding: 1px 6px;
      border-radius: 4px;
      white-space: nowrap;
      margin-top: -4px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.5);
    }

    #pathCanvas {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      z-index: 15;
    }

    .nodes-layer {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 25;
    }

    .node-marker {
      position: absolute;
      width: 26px;
      height: 26px;
      border-radius: 50%;
      background: radial-gradient(circle, #f6c574 0%, #b8860b 100%);
      border: 2px solid #ffffff;
      box-shadow: 0 0 10px rgba(246, 197, 116, 0.7);
      transform: translate(-50%, -50%);
      cursor: grab;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 11px;
      font-weight: 800;
      color: #1a1e2e;
      transition: box-shadow 0.15s, border-color 0.15s, transform 0.15s;
    }

    .node-marker:active {
      cursor: grabbing;
    }

    .node-marker.selected {
      border-color: #38bdf8;
      box-shadow: 0 0 18px rgba(56, 189, 248, 1);
      background: radial-gradient(circle, #7dd3fc 0%, #0284c7 100%);
      color: #ffffff;
      transform: translate(-50%, -50%) scale(1.22);
      z-index: 35;
    }

    .node-marker.node-start {
      border-color: #4ade80;
      box-shadow: 0 0 14px rgba(74, 222, 128, 0.9);
    }

    .node-marker.node-end {
      border-color: #f87171;
      box-shadow: 0 0 14px rgba(248, 113, 113, 0.9);
    }

    .node-marker .marker-tag {
      position: absolute;
      bottom: -18px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 9px;
      background: rgba(0, 0, 0, 0.88);
      padding: 1px 5px;
      border-radius: 4px;
      color: #f1f5f9;
      white-space: nowrap;
      pointer-events: none;
      border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .node-marker .marker-flip-tag {
      position: absolute;
      top: -13px;
      right: -12px;
      font-size: 9px;
      padding: 1px 4px;
      border-radius: 3px;
      background: rgba(15, 23, 42, 0.92);
      color: #94a3b8;
      border: 1px solid rgba(255, 255, 255, 0.25);
      pointer-events: none;
      font-weight: 700;
    }

    .node-marker.flip-right .marker-flip-tag {
      background: rgba(147, 51, 234, 0.95);
      color: #fdf4ff;
      border-color: #c084fc;
    }

    /* 精簡標籤模式:避免標籤密集重疊擋住碎石路,懸停或選取時才顯示 */
    .nodes-layer.compact-tags .marker-tag,
    .nodes-layer.compact-tags .marker-flip-tag {
      display: none;
    }
    .nodes-layer.compact-tags .node-marker.selected .marker-tag,
    .nodes-layer.compact-tags .node-marker.selected .marker-flip-tag,
    .nodes-layer.compact-tags .node-marker:hover .marker-tag,
    .nodes-layer.compact-tags .node-marker:hover .marker-flip-tag {
      display: block;
    }

    /* 預覽行走中的駱駝實體 */
    #previewCamel {
      position: absolute;
      width: 78px;
      height: 78px;
      pointer-events: none;
      z-index: 45;
      transform-origin: 50% 68%;
      display: none;
      filter: drop-shadow(0 8px 16px rgba(0,0,0,0.75));
    }

    #previewCamel img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      display: block;
    }

    /* 側邊欄控制面板 */
    .sidebar {
      display: flex;
      flex-direction: column;
      gap: 12px;
      max-height: calc(100vh - 90px);
      overflow-y: auto;
      padding-right: 4px;
    }

    .sidebar::-webkit-scrollbar {
      width: 6px;
    }
    .sidebar::-webkit-scrollbar-thumb {
      background: rgba(212, 163, 89, 0.35);
      border-radius: 3px;
    }

    .card {
      background: var(--card-bg);
      border: 1px solid var(--card-border);
      border-radius: 10px;
      padding: 13px;
      box-shadow: 0 4px 18px rgba(0,0,0,0.35);
      backdrop-filter: blur(8px);
    }

    .card-title {
      font-size: 13px;
      font-weight: 700;
      color: var(--gold-bright);
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .card-title span.hint {
      font-size: 11px;
      color: var(--text-sub);
      font-weight: 400;
    }

    .btn {
      background: rgba(212, 163, 89, 0.12);
      border: 1px solid var(--card-border);
      color: var(--gold-bright);
      padding: 7px 11px;
      border-radius: 6px;
      font-size: 12px;
      font-weight: 600;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      justify-content: center;
      transition: all 0.15s ease;
      user-select: none;
    }

    .btn:hover {
      background: rgba(212, 163, 89, 0.25);
      border-color: var(--gold-bright);
      color: #ffffff;
      box-shadow: 0 0 10px rgba(246, 197, 116, 0.25);
    }

    .btn.active {
      background: linear-gradient(135deg, #f6c574 0%, #b8860b 100%);
      color: #1a1e2e;
      border-color: #ffffff;
      font-weight: 800;
      box-shadow: 0 0 12px var(--gold-glow);
    }

    .btn-primary {
      background: linear-gradient(135deg, #d4a359 0%, #b8860b 100%);
      color: #1a1e2e;
      border-color: #f6c574;
      font-weight: 700;
    }
    .btn-primary:hover {
      background: linear-gradient(135deg, #f6c574 0%, #d4a359 100%);
      box-shadow: 0 0 14px var(--gold-glow);
    }

    .btn-success {
      background: rgba(34, 197, 94, 0.18);
      border-color: rgba(34, 197, 94, 0.45);
      color: #86efac;
    }
    .btn-success:hover {
      background: rgba(34, 197, 94, 0.35);
      border-color: var(--accent-green);
      color: #ffffff;
    }

    .btn-danger {
      background: rgba(239, 68, 68, 0.15);
      border-color: rgba(239, 68, 68, 0.4);
      color: #fca5a5;
    }
    .btn-danger:hover {
      background: rgba(239, 68, 68, 0.32);
      border-color: var(--accent-red);
      color: #ffffff;
    }

    .btn-cyan {
      background: rgba(56, 189, 248, 0.15);
      border-color: rgba(56, 189, 248, 0.4);
      color: #7dd3fc;
    }
    .btn-cyan:hover {
      background: rgba(56, 189, 248, 0.3);
      border-color: var(--accent-cyan);
      color: #ffffff;
    }

    .btn-purple {
      background: rgba(192, 132, 252, 0.15);
      border-color: rgba(192, 132, 252, 0.4);
      color: #e9d5ff;
    }
    .btn-purple:hover {
      background: rgba(192, 132, 252, 0.3);
      border-color: var(--accent-purple);
      color: #ffffff;
    }

    .btn-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
    }

    .btn-grid-3 {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      gap: 6px;
    }

    /* 節點屬性微調區 */
    .prop-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 8px;
      font-size: 12px;
    }

    .prop-label {
      color: var(--text-sub);
    }

    .prop-val {
      font-family: monospace;
      color: var(--accent-cyan);
      font-size: 13px;
      font-weight: 700;
    }

    .slider-row {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
    }

    .slider-row input[type="range"] {
      flex: 1;
      accent-color: var(--gold-bright);
      height: 6px;
      background: rgba(255,255,255,0.12);
      border-radius: 3px;
    }

    .slider-row input[type="number"] {
      width: 58px;
      background: rgba(0,0,0,0.4);
      border: 1px solid var(--card-border);
      border-radius: 4px;
      color: var(--gold-bright);
      padding: 4px 6px;
      font-size: 12px;
      font-family: monospace;
      text-align: center;
    }

    .quick-angles {
      display: flex;
      gap: 4px;
      margin-bottom: 10px;
    }
    .quick-angles .btn {
      flex: 1;
      padding: 4px 0;
      font-size: 10px;
    }

    /* 鏡像控制區域 */
    .flip-status-box {
      padding: 8px 10px;
      border-radius: 6px;
      background: rgba(0, 0, 0, 0.35);
      border: 1px solid rgba(255, 255, 255, 0.08);
      margin-bottom: 8px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .flip-badge {
      font-size: 11px;
      padding: 2px 8px;
      border-radius: 4px;
      font-weight: 700;
    }

    .flip-badge.left {
      background: rgba(56, 189, 248, 0.2);
      border: 1px solid rgba(56, 189, 248, 0.5);
      color: #7dd3fc;
    }

    .flip-badge.right {
      background: rgba(192, 132, 252, 0.2);
      border: 1px solid rgba(192, 132, 252, 0.5);
      color: #f0abfc;
    }

    /* 時間軸進度條控制 */
    .timeline-wrap {
      background: rgba(0, 0, 0, 0.35);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 8px;
      padding: 10px;
      margin-bottom: 10px;
    }

    .timeline-slider {
      width: 100%;
      accent-color: #38bdf8;
      height: 7px;
      background: rgba(255,255,255,0.15);
      border-radius: 4px;
      cursor: pointer;
    }

    /* JSON 代碼區 */
    .json-textarea {
      width: 100%;
      height: 120px;
      background: rgba(0,0,0,0.55);
      border: 1px solid rgba(255,255,255,0.15);
      border-radius: 6px;
      color: #a7f3d0;
      font-family: monospace;
      font-size: 11px;
      padding: 8px;
      resize: vertical;
      line-height: 1.4;
      margin-bottom: 8px;
    }
    .json-textarea:focus {
      outline: none;
      border-color: var(--gold-bright);
    }

    /* 操作秘笈指南 */
    .guide-list {
      list-style: none;
      font-size: 11px;
      color: var(--text-sub);
      line-height: 1.7;
    }
    .guide-list li {
      position: relative;
      padding-left: 14px;
    }
    .guide-list li::before {
      content: '•';
      position: absolute;
      left: 2px;
      color: var(--gold-bright);
    }

    .kbd-chip {
      background: rgba(255, 255, 255, 0.12);
      border: 1px solid rgba(255, 255, 255, 0.25);
      border-radius: 4px;
      padding: 1px 4px;
      font-family: monospace;
      color: var(--gold-bright);
      font-size: 10px;
    }

    /* Toast 通知 */
    .toast {
      position: fixed;
      bottom: 24px;
      left: 50%;
      transform: translateX(-50%) translateY(40px);
      background: linear-gradient(135deg, #1e293b, #0f172a);
      border: 1px solid var(--gold-bright);
      color: var(--gold-bright);
      padding: 10px 24px;
      border-radius: 999px;
      font-size: 13px;
      font-weight: 700;
      box-shadow: 0 10px 25px rgba(0,0,0,0.7), 0 0 15px rgba(246, 197, 116, 0.3);
      opacity: 0;
      pointer-events: none;
      transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1);
      z-index: 1000;
    }
    .toast.show {
      transform: translateX(-50%) translateY(0);
      opacity: 1;
    }
  </style>
</head>
<body>
  <header>
    <div class="title-group">
      <h1>🐫 駱駝商人・碎石步道路徑 & 鏡像角度編輯工具</h1>
      <span class="badge">含 鏡像 flip + 旋轉角度 rot 即時對位</span>
    </div>
    <div class="header-actions">
      <button class="btn btn-primary" id="btnPlayPreview">
        <span id="playIcon">▶</span> 播放行走預覽
      </button>
      <button class="btn btn-success" id="btnSaveToGame" title="儲存並同步至本地遊戲,切換到 index.html 即可立即看到!">
        <span>💾</span> 儲存同步至遊戲
      </button>
      <button class="btn btn-danger" id="btnClearAll">
        <span>🗑</span> 清空重來
      </button>
    </div>
  </header>

  <div class="main-layout">
    <!-- 地圖操作區 -->
    <div class="map-container" id="mapContainer">
      <div class="map-aspect-box" id="mapAspectBox">
        <!-- 真實遊戲大地圖背景圖片 -->
        <img class="map-bg-img" id="mapBgImg" src="assets/map_chibi.jpg" alt="沙盤大地圖" draggable="false">

        <!-- 城池地標參考圖層 -->
        <div class="buildings-layer" id="buildingsLayer"></div>

        <!-- 路徑繪製 Canvas -->
        <canvas id="pathCanvas"></canvas>

        <!-- 節點標記層 -->
        <div class="nodes-layer" id="nodesLayer"></div>

        <!-- 預覽駱駝商人行走實體 -->
        <div id="previewCamel">
          <div id="previewCamelInner" style="width: 100%; height: 100%;">
            <img src="assets/camel_caravan.png" alt="駱駝商人">
          </div>
        </div>
      </div>
    </div>

    <!-- 右側屬性與導出面板 -->
    <div class="sidebar">

      <!-- 視覺輔助控制卡片 -->
      <div class="card">
        <div class="card-title">
          <span>🗺️ 地圖視覺輔助</span>
          <span class="hint">幫助精準對齊碎石步道</span>
        </div>
        
        <!-- 城池參考標記開關 -->
        <div class="prop-row">
          <span class="prop-label">🏰 城池建築參考 (MAP_POS)</span>
          <div style="display: flex; gap: 6px; align-items: center;">
            <button class="btn" id="btnToggleTowns" style="padding: 3px 8px; font-size: 11px;">顯示 (50%)</button>
          </div>
        </div>
        <div class="slider-row" style="margin-bottom: 10px;">
          <span style="font-size: 11px; color: var(--text-sub);">城池透明度:</span>
          <input type="range" id="sliderTownOpacity" min="0" max="100" value="50">
          <span id="valTownOpacity" style="font-family: monospace; font-size: 11px; width: 34px;">50%</span>
        </div>

        <!-- 地圖對比濾鏡切換 -->
        <div class="prop-row" style="margin-bottom: 4px;">
          <span class="prop-label">🔍 步道紋理濾鏡</span>
        </div>
        <div class="btn-grid-3">
          <button class="btn active" id="btnFilterNormal">原色標準</button>
          <button class="btn" id="btnFilterContrast">碎石高對比</button>
          <button class="btn" id="btnFilterDim">暗色突顯</button>
        </div>

        <!-- 節點標籤模式 -->
        <div class="prop-row" style="margin-top: 10px; margin-bottom: 0;">
          <span class="prop-label">🏷️ 節點標籤顯示</span>
          <button class="btn active" id="btnToggleTags" style="padding: 3px 8px; font-size: 11px;">精簡 (防遮擋)</button>
        </div>
      </div>

      <!-- 行走預覽與互動時間軸卡片 -->
      <div class="card">
        <div class="card-title">
          <span>🎬 行走預覽與進度檢驗</span>
          <span class="hint" id="valAnimProgress">0% (第 1 點)</span>
        </div>

        <div class="timeline-wrap">
          <div style="display: flex; justify-content: space-between; font-size: 11px; color: var(--text-sub); margin-bottom: 4px;">
            <span>🟢 起點淡入</span>
            <span id="timelineCurText">拖動滑桿快速檢視轉彎</span>
            <span>🔴 終點淡出</span>
          </div>
          <input type="range" class="timeline-slider" id="timelineSlider" min="0" max="1000" value="0">
        </div>

        <div class="prop-row" style="margin-bottom: 6px;">
          <span class="prop-label">預覽速度:</span>
          <div style="display: flex; gap: 4px;">
            <button class="btn" data-speed="0.5" id="btnSpeed05">0.5x 慢速</button>
            <button class="btn active" data-speed="1" id="btnSpeed10">1.0x 正常</button>
            <button class="btn" data-speed="1.8" id="btnSpeed18">1.8x 快速</button>
          </div>
        </div>
      </div>

      <!-- 選取節點微調卡片 -->
      <div class="card" id="cardNodeProps">
        <div class="card-title">
          <span>🎯 選取節點微調</span>
          <span class="hint" id="selectedNodeIndex">尚未選取</span>
        </div>

        <div id="nodePropsBody" style="opacity: 0.4; pointer-events: none;">
          <div class="prop-row">
            <span class="prop-label">座標 (X %, Y %)</span>
            <span class="prop-val" id="valPos">-- , --</span>
          </div>
          <div style="font-size: 10px; color: var(--text-sub); margin-top: -4px; margin-bottom: 8px;">
            💡 鍵盤 <span class="kbd-chip">↑</span><span class="kbd-chip">↓</span><span class="kbd-chip">←</span><span class="kbd-chip">→</span> 可 0.1% 像素微調位置(加 Shift 移動 1%)
          </div>

          <!-- 鏡像朝向控制 -->
          <div style="margin-top: 10px; margin-bottom: 6px;">
            <div class="prop-row" style="margin-bottom: 4px;">
              <span class="prop-label" style="font-weight: 700; color: #fff;">🚶 鏡像朝向 (flip)</span>
              <span class="hint">複製時一併導出</span>
            </div>
            <div class="flip-status-box">
              <span style="font-size: 11px; color: var(--text-sub);">當前朝向:</span>
              <span class="flip-badge left" id="valFlipBadge">👈 面向左 (false)</span>
            </div>
            <div class="btn-grid" style="margin-bottom: 6px;">
              <button class="btn btn-cyan" id="btnFlipLeft">👈 面向左 (false)</button>
              <button class="btn btn-purple" id="btnFlipRight">👉 鏡像右 (true)</button>
            </div>
            <div class="btn-grid">
              <button class="btn" id="btnFlipAuto">⚡ 依走勢自動算</button>
              <button class="btn" id="btnApplyFlipToRest" title="將目前點的朝向同步到之後的所有點">⏩ 套用至後續點</button>
            </div>
          </div>

          <!-- 旋轉角度控制 -->
          <div style="margin-top: 12px; margin-bottom: 6px;">
            <div class="prop-row" style="margin-bottom: 4px;">
              <span class="prop-label" style="font-weight: 700; color: #fff;">📐 傾斜旋轉 (rot 度)</span>
              <span class="prop-val" id="valRot">0°</span>
            </div>
            <div class="slider-row">
              <input type="range" id="sliderRot" min="-180" max="180" step="1" value="0">
              <input type="number" id="inputRot" min="-180" max="180" step="1" value="0">
            </div>
            <div class="quick-angles">
              <button class="btn" data-angle="0">平 0°</button>
              <button class="btn" data-angle="-15">緩下 -15°</button>
              <button class="btn" data-angle="15">緩上 +15°</button>
              <button class="btn" data-angle="-30">陡下 -30°</button>
              <button class="btn" data-angle="30">陡上 +30°</button>
            </div>
            <button class="btn" id="btnAutoRot" style="width: 100%;">⚡ 依下一段切線自動計算角度</button>
          </div>

          <!-- 節點插入與刪除 -->
          <div class="btn-grid" style="margin-top: 12px; margin-bottom: 6px;">
            <button class="btn btn-cyan" id="btnInsertAfter">➕ 在此點後插入新點</button>
            <button class="btn btn-danger" id="btnDeleteSelected">🗑 刪除此節點</button>
          </div>
          <button class="btn" id="btnDeselect" style="width: 100%;">取消選取</button>
        </div>
      </div>

      <!-- JSON 導出與匯入卡片 -->
      <div class="card">
        <div class="card-title">
          <span>📋 路徑 JSON 代碼</span>
          <span class="hint" id="nodeCount">0 個節點</span>
        </div>
        <textarea class="json-textarea" id="jsonOutput" placeholder="路徑節點將即時以包含 flip 與 rot 的 JSON 格式顯示在此..."></textarea>
        <div class="btn-grid">
          <button class="btn btn-primary" id="btnCopyJson">📋 複製路徑 JSON</button>
          <button class="btn" id="btnApplyJson">📥 匯入/更新 JSON</button>
        </div>
        <button class="btn" id="btnResetDefault" style="width: 100%; margin-top: 8px;">
          🔄 載入預設 15 步道節點(含分段鏡像)
        </button>
      </div>

      <!-- 操作秘笈 -->
      <div class="card">
        <div class="card-title">
          <span>💡 操作打點秘笈</span>
        </div>
        <ul class="guide-list">
          <li><strong>新增節點</strong>:直接在步道地圖上點擊滑鼠左鍵。</li>
          <li><strong>精準微調</strong>:按住金黃色圓圈拖曳,或選中後按鍵盤 <span class="kbd-chip">↑</span><span class="kbd-chip">↓</span><span class="kbd-chip">←</span><span class="kbd-chip">→</span> 微調。</li>
          <li><strong>切換節點</strong>:鍵盤 <span class="kbd-chip">[</span> 或 <span class="kbd-chip">]</span> 可依序跳選上一個/下一個節點。</li>
          <li><strong>插入新點</strong>:選中任一點後點擊「➕ 在此點後插入新點」,不用刪除重排!</li>
          <li><strong>鏡像控制</strong>:選中節點後點擊「👈 面向左」或「👉 鏡像右」,標籤即時更新。</li>
          <li><strong>即時測試</strong>:點「💾 儲存同步至遊戲」後,打開主遊戲即可看到最新走法!</li>
        </ul>
      </div>
    </div>
  </div>

  <div class="toast" id="toastMsg">已複製到剪貼簿!</div>

  <script>
    // 預設 16 個節點(附帶精細配置的 flip、rot 與碎石步道折返)
    const DEFAULT_ROUTE = [
      { "x": 68.8, "y": 46.5, "rot": 0,   "flip": false },
      { "x": 67.7, "y": 54.1, "rot": 0,   "flip": false },
      { "x": 68.4, "y": 61.9, "rot": 0,   "flip": false },
      { "x": 63.1, "y": 65.7, "rot": 0,   "flip": false },
      { "x": 55.1, "y": 70.4, "rot": 36,  "flip": false },
      { "x": 47.6, "y": 65.6, "rot": 30,  "flip": false },
      { "x": 37.4, "y": 58.2, "rot": 33,  "flip": false },
      { "x": 30.3, "y": 54.0, "rot": 0,   "flip": true },
      { "x": 46.5, "y": 64.3, "rot": 0,   "flip": true },
      { "x": 53.6, "y": 70.4, "rot": -18, "flip": true },
      { "x": 67.2, "y": 62.8, "rot": -17, "flip": true },
      { "x": 69.1, "y": 62.0, "rot": 0,   "flip": false },
      { "x": 53.1, "y": 71.3, "rot": 31,  "flip": false },
      { "x": 44.5, "y": 65.5, "rot": 31,  "flip": false },
      { "x": 35.2, "y": 56.2, "rot": 30,  "flip": false },
      { "x": 31.5, "y": 47.1, "rot": 31,  "flip": false }
    ];

    // 停頓站點設定:改為在筆直大道與平緩直道上停歇(轉角處流暢轉向不滯留)
    const PAUSES = {
      5:  { sec: 3.2, desc: '🌾 隴畝豐登,麥浪飄香~ (直道路段停歇 3.2秒)' },
      8:  { sec: 4.0, desc: '🐫 駝鈴悠揚,大道平坦,正好清點貨物~ (平坦直道大歇 4.0秒)' },
      13: { sec: 3.0, desc: '📜 行商四海,貨殖八方,不急不躁~ (林蔭直道小歇 3.0秒)' }
    };

    // 城池參考地標位置定義 (MAP_POS)
    const MAP_BUILDINGS = [
      { id: 'b1', name: '涿縣', x: 27.8, y: 70.7, img: 'assets/building_b1.png' },
      { id: 'b9', name: '常山', x: 18.1, y: 62.1, img: 'assets/building_b9.png' },
      { id: 'b2', name: '鉅鹿', x: 37.7, y: 78.9, img: 'assets/building_b2.png' },
      { id: 'b4', name: '平原', x: 62.1, y: 79.0, img: 'assets/building_b4.png' },
      { id: 'b7', name: '南皮', x: 71.8, y: 70.6, img: 'assets/building_b7.png' },
      { id: 'b3', name: '鄴城', x: 50.5, y: 48.5, img: 'assets/building_b3.png' },
      { id: 'b5', name: '北海', x: 59.9, y: 42.2, img: 'assets/building_b5.png' },
      { id: 'b6', name: '徐州', x: 81.6, y: 62.2, img: 'assets/building_b6.png' },
      { id: 'b8', name: '許昌', x: 67.5, y: 34.7, img: 'assets/building_b8.png' },
      { id: 'b10', name: '洛陽', x: 52.0, y: 22.0, img: 'assets/building_b10.png' },
      { id: 'tianji', name: '天機閣', x: 34.5, y: 29.7, img: 'assets/building_tianji.png' },
      { id: 'boss', name: '饕餮巢穴', x: 81.5, y: 22.0, img: 'assets/boss_taotie.png' }
    ];

    // 優先讀取先前在瀏覽器中暫存的路徑,若無或節點數不符合則載入最新 DEFAULT_ROUTE
    let nodes = [];
    try {
      const saved = localStorage.getItem('idle_custom_merchant_route');
      if (saved) {
        const parsed = JSON.parse(saved);
        if (Array.isArray(parsed) && parsed.length === DEFAULT_ROUTE.length) {
          nodes = parsed;
        }
      }
    } catch (e) {}
    if (nodes.length === 0) {
      nodes = JSON.parse(JSON.stringify(DEFAULT_ROUTE));
      try {
        localStorage.setItem('idle_custom_merchant_route', JSON.stringify(DEFAULT_ROUTE));
      } catch (e) {}
    }

    let selectedIdx = -1;
    let isDragging = false;
    let justDragged = false;
    let dragIdx = -1;

    // 行走預覽
    let isPlaying = false;
    let previewAnimFrame = null;
    let loopTimeout = null;
    let previewSpeed = 1.0;
    const baseDuration = 45000; // 基礎時間 45 秒 (完整模擬真實行商悠然巡遊)
    let animProgress = 0; // 0 ~ 1

    // DOM 元素
    const mapAspectBox = document.getElementById('mapAspectBox');
    const mapBgImg = document.getElementById('mapBgImg');
    const buildingsLayer = document.getElementById('buildingsLayer');
    const pathCanvas = document.getElementById('pathCanvas');
    const ctx = pathCanvas.getContext('2d');
    const nodesLayer = document.getElementById('nodesLayer');
    const jsonOutput = document.getElementById('jsonOutput');
    const nodeCount = document.getElementById('nodeCount');
    const cardNodeProps = document.getElementById('cardNodeProps');
    const selectedNodeIndex = document.getElementById('selectedNodeIndex');
    const nodePropsBody = document.getElementById('nodePropsBody');
    const valPos = document.getElementById('valPos');
    const valRot = document.getElementById('valRot');
    const sliderRot = document.getElementById('sliderRot');
    const inputRot = document.getElementById('inputRot');
    const valFlipBadge = document.getElementById('valFlipBadge');
    const btnFlipLeft = document.getElementById('btnFlipLeft');
    const btnFlipRight = document.getElementById('btnFlipRight');
    const btnFlipAuto = document.getElementById('btnFlipAuto');
    const btnApplyFlipToRest = document.getElementById('btnApplyFlipToRest');
    const btnAutoRot = document.getElementById('btnAutoRot');
    const btnInsertAfter = document.getElementById('btnInsertAfter');
    const btnDeleteSelected = document.getElementById('btnDeleteSelected');
    const btnDeselect = document.getElementById('btnDeselect');
    const btnCopyJson = document.getElementById('btnCopyJson');
    const btnApplyJson = document.getElementById('btnApplyJson');
    const btnResetDefault = document.getElementById('btnResetDefault');
    const btnClearAll = document.getElementById('btnClearAll');
    const btnPlayPreview = document.getElementById('btnPlayPreview');
    const playIcon = document.getElementById('playIcon');
    const btnSaveToGame = document.getElementById('btnSaveToGame');
    const previewCamel = document.getElementById('previewCamel');
    const previewCamelInner = document.getElementById('previewCamelInner');
    const toastMsg = document.getElementById('toastMsg');
    const timelineSlider = document.getElementById('timelineSlider');
    const valAnimProgress = document.getElementById('valAnimProgress');
    const timelineCurText = document.getElementById('timelineCurText');

    // 輔助視覺 DOM
    const btnToggleTowns = document.getElementById('btnToggleTowns');
    const sliderTownOpacity = document.getElementById('sliderTownOpacity');
    const valTownOpacity = document.getElementById('valTownOpacity');
    const btnFilterNormal = document.getElementById('btnFilterNormal');
    const btnFilterContrast = document.getElementById('btnFilterContrast');
    const btnFilterDim = document.getElementById('btnFilterDim');

    // 速度按鈕
    const btnSpeed05 = document.getElementById('btnSpeed05');
    const btnSpeed10 = document.getElementById('btnSpeed10');
    const btnSpeed18 = document.getElementById('btnSpeed18');

    // 初始化城池建築參考層
    function initBuildingsLayer() {
      buildingsLayer.innerHTML = '';
      MAP_BUILDINGS.forEach(b => {
        const el = document.createElement('div');
        el.className = 'building-marker';
        el.style.left = `${b.x}%`;
        el.style.top = `${b.y}%`;
        el.innerHTML = `
          <img src="${b.img}" alt="${b.name}">
          <span class="b-tag">${b.name}</span>
        `;
        buildingsLayer.appendChild(el);
      });
      updateTownOpacity(50);
    }

    function updateTownOpacity(val) {
      buildingsLayer.style.opacity = (val / 100).toFixed(2);
      valTownOpacity.textContent = `${val}%`;
      sliderTownOpacity.value = val;
      btnToggleTowns.textContent = val > 0 ? `顯示 (${val}%)` : '已隱藏';
      if (val > 0) btnToggleTowns.classList.add('active');
      else btnToggleTowns.classList.remove('active');
    }

    sliderTownOpacity.addEventListener('input', (e) => {
      updateTownOpacity(parseInt(e.target.value, 10));
    });

    btnToggleTowns.addEventListener('click', () => {
      const cur = parseInt(sliderTownOpacity.value, 10);
      if (cur > 0) updateTownOpacity(0);
      else updateTownOpacity(50);
    });

    // 地圖濾鏡控制
    btnFilterNormal.addEventListener('click', () => {
      mapBgImg.className = 'map-bg-img';
      btnFilterNormal.classList.add('active');
      btnFilterContrast.classList.remove('active');
      btnFilterDim.classList.remove('active');
    });

    btnFilterContrast.addEventListener('click', () => {
      mapBgImg.className = 'map-bg-img filter-contrast';
      btnFilterContrast.classList.add('active');
      btnFilterNormal.classList.remove('active');
      btnFilterDim.classList.remove('active');
    });

    btnFilterDim.addEventListener('click', () => {
      mapBgImg.className = 'map-bg-img filter-dim';
      btnFilterDim.classList.add('active');
      btnFilterNormal.classList.remove('active');
      btnFilterContrast.classList.remove('active');
    });

    // 節點標籤精簡/全開切換
    const btnToggleTags = document.getElementById('btnToggleTags');
    let isCompactTags = true;
    nodesLayer.classList.add('compact-tags');

    btnToggleTags.addEventListener('click', () => {
      isCompactTags = !isCompactTags;
      if (isCompactTags) {
        nodesLayer.classList.add('compact-tags');
        btnToggleTags.textContent = '精簡 (防遮擋)';
        btnToggleTags.classList.add('active');
      } else {
        nodesLayer.classList.remove('compact-tags');
        btnToggleTags.textContent = '全部顯示';
        btnToggleTags.classList.remove('active');
      }
    });

    // 速度切換
    function setSpeed(spd, activeBtn) {
      previewSpeed = spd;
      [btnSpeed05, btnSpeed10, btnSpeed18].forEach(b => b.classList.remove('active'));
      activeBtn.classList.add('active');
    }
    btnSpeed05.addEventListener('click', () => setSpeed(0.5, btnSpeed05));
    btnSpeed10.addEventListener('click', () => setSpeed(1.0, btnSpeed10));
    btnSpeed18.addEventListener('click', () => setSpeed(1.8, btnSpeed18));

    function resizeCanvas() {
      const rect = mapAspectBox.getBoundingClientRect();
      pathCanvas.width = rect.width;
      pathCanvas.height = rect.height;
      drawPath();
    }
    window.addEventListener('resize', resizeCanvas);

    // 格式化輸出包含 flip 與 rot 的乾淨 JSON
    function updateJson() {
      const cleanNodes = nodes.map(n => ({
        x: Number(Number(n.x).toFixed(1)),
        y: Number(Number(n.y).toFixed(1)),
        rot: Math.round(n.rot || 0),
        flip: Boolean(n.flip)
      }));
      jsonOutput.value = JSON.stringify(cleanNodes, null, 2);
      nodeCount.textContent = `${nodes.length} 個節點`;

      // 同時自動暫存至本地 localStorage,防止刷新遺失
      try {
        localStorage.setItem('idle_custom_merchant_route', JSON.stringify(cleanNodes));
      } catch (e) {}
    }

    // 選取節點
    function selectNode(idx) {
      selectedIdx = idx;
      render();
    }

    // 重新渲染畫布與節點標記
    function render() {
      nodesLayer.innerHTML = '';
      nodes.forEach((n, idx) => {
        if (typeof n.rot !== 'number') n.rot = 0;
        if (typeof n.flip !== 'boolean') n.flip = false;

        const el = document.createElement('div');
        const isSelected = idx === selectedIdx;
        const isStart = idx === 0;
        const isEnd = idx === nodes.length - 1;

        el.className = 'node-marker'
          + (isSelected ? ' selected' : '')
          + (isStart ? ' node-start' : '')
          + (isEnd ? ' node-end' : '')
          + (n.flip ? ' flip-right' : '');

        el.style.left = `${n.x}%`;
        el.style.top = `${n.y}%`;

        let typeText = '';
        if (isStart) typeText = '🟢 起點 ';
        else if (isEnd) typeText = '🔴 終點 ';
        else if (typeof PAUSES !== 'undefined' && PAUSES[idx]) typeText = `☕ 歇息 ${PAUSES[idx].sec}s `;
        else if (idx === 7 || idx === 11) typeText = '↩ 轉角順行 ';

        el.innerHTML = `
          ${idx + 1}
          <div class="marker-tag">#${idx + 1} ${typeText}(${n.rot}°)</div>
          <div class="marker-flip-tag">${n.flip ? '▶ 鏡像' : '◀ 原圖'}</div>
        `;

        el.addEventListener('mousedown', (e) => {
          e.stopPropagation();
          selectNode(idx);
          isDragging = true;
          dragIdx = idx;
        });

        nodesLayer.appendChild(el);
      });

      drawPath();
      updateJson();
      updatePropsPanel();
    }

    // 繪製路徑線條與行進方向箭頭
    function drawPath() {
      ctx.clearRect(0, 0, pathCanvas.width, pathCanvas.height);
      if (nodes.length < 2) return;

      const w = pathCanvas.width;
      const h = pathCanvas.height;

      // 1. 步道外層金黃色柔和光暈
      ctx.beginPath();
      ctx.moveTo((nodes[0].x / 100) * w, (nodes[0].y / 100) * h);
      for (let i = 1; i < nodes.length; i++) {
        ctx.lineTo((nodes[i].x / 100) * w, (nodes[i].y / 100) * h);
      }
      ctx.strokeStyle = 'rgba(246, 197, 116, 0.28)';
      ctx.lineWidth = 10;
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
      ctx.stroke();

      // 2. 步道核心實線
      ctx.beginPath();
      ctx.moveTo((nodes[0].x / 100) * w, (nodes[0].y / 100) * h);
      for (let i = 1; i < nodes.length; i++) {
        ctx.lineTo((nodes[i].x / 100) * w, (nodes[i].y / 100) * h);
      }
      ctx.strokeStyle = '#f6c574';
      ctx.lineWidth = 3.5;
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
      ctx.stroke();

      // 3. 節點間繪製方向箭頭
      for (let i = 0; i < nodes.length - 1; i++) {
        const x1 = (nodes[i].x / 100) * w;
        const y1 = (nodes[i].y / 100) * h;
        const x2 = (nodes[i+1].x / 100) * w;
        const y2 = (nodes[i+1].y / 100) * h;
        const midX = (x1 + x2) / 2;
        const midY = (y1 + y2) / 2;
        const angle = Math.atan2(y2 - y1, x2 - x1);

        drawArrowHead(ctx, midX, midY, angle, 9, '#ffffff');
      }
    }

    function drawArrowHead(context, x, y, angle, size, color) {
      context.save();
      context.translate(x, y);
      context.rotate(angle);
      context.fillStyle = color;
      context.beginPath();
      context.moveTo(size * 0.8, 0);
      context.lineTo(-size, -size * 0.6);
      context.lineTo(-size * 0.4, 0);
      context.lineTo(-size, size * 0.6);
      context.closePath();
      context.fill();
      context.restore();
    }

    function updatePropsPanel() {
      if (selectedIdx >= 0 && selectedIdx < nodes.length) {
        const n = nodes[selectedIdx];
        nodePropsBody.style.opacity = '1';
        nodePropsBody.style.pointerEvents = 'auto';
        selectedNodeIndex.textContent = `節點 #${selectedIdx + 1} / ${nodes.length}`;
        valPos.textContent = `${Number(n.x).toFixed(1)}% , ${Number(n.y).toFixed(1)}%`;
        
        const rot = Math.round(n.rot || 0);
        valRot.textContent = `${rot}°`;
        sliderRot.value = rot;
        inputRot.value = rot;

        // 鏡像狀態更新
        const isFlip = Boolean(n.flip);
        if (isFlip) {
          valFlipBadge.textContent = '👉 鏡像右 (flip: true)';
          valFlipBadge.className = 'flip-badge right';
          btnFlipRight.classList.add('active');
          btnFlipLeft.classList.remove('active');
        } else {
          valFlipBadge.textContent = '👈 面向左 (flip: false)';
          valFlipBadge.className = 'flip-badge left';
          btnFlipLeft.classList.add('active');
          btnFlipRight.classList.remove('active');
        }
      } else {
        nodePropsBody.style.opacity = '0.4';
        nodePropsBody.style.pointerEvents = 'none';
        selectedNodeIndex.textContent = '尚未選取';
        valPos.textContent = '-- , --';
        valRot.textContent = '0°';
        sliderRot.value = 0;
        inputRot.value = 0;
        btnFlipLeft.classList.remove('active');
        btnFlipRight.classList.remove('active');
      }
    }

    // 旋轉角度控制
    function setRot(val) {
      if (selectedIdx < 0 || selectedIdx >= nodes.length) return;
      let rot = parseInt(val, 10);
      if (isNaN(rot)) rot = 0;
      if (rot < -180) rot = -180;
      if (rot > 180) rot = 180;
      nodes[selectedIdx].rot = rot;
      render();
    }

    sliderRot.addEventListener('input', (e) => setRot(e.target.value));
    inputRot.addEventListener('change', (e) => setRot(e.target.value));

    document.querySelectorAll('.quick-angles .btn').forEach(b => {
      b.addEventListener('click', () => {
        setRot(b.getAttribute('data-angle'));
      });
    });

    // 鏡像朝向控制
    function setFlip(boolVal) {
      if (selectedIdx < 0 || selectedIdx >= nodes.length) return;
      nodes[selectedIdx].flip = boolVal;
      render();
      showToast(`已將節點 #${selectedIdx + 1} 設為 ${boolVal ? '👉 鏡像右 (true)' : '👈 面向左 (false)'}`);
    }

    btnFlipLeft.addEventListener('click', () => setFlip(false));
    btnFlipRight.addEventListener('click', () => setFlip(true));

    btnFlipAuto.addEventListener('click', () => {
      if (selectedIdx < 0 || selectedIdx >= nodes.length) return;
      let dx = 0;
      if (selectedIdx < nodes.length - 1) {
        dx = nodes[selectedIdx + 1].x - nodes[selectedIdx].x;
      } else if (selectedIdx > 0) {
        dx = nodes[selectedIdx].x - nodes[selectedIdx - 1].x;
      }
      const autoFlip = dx > 0;
      setFlip(autoFlip);
    });

    btnApplyFlipToRest.addEventListener('click', () => {
      if (selectedIdx < 0 || selectedIdx >= nodes.length) return;
      const targetFlip = Boolean(nodes[selectedIdx].flip);
      for (let i = selectedIdx; i < nodes.length; i++) {
        nodes[i].flip = targetFlip;
      }
      render();
      showToast(`已將 #${selectedIdx + 1} 之後的所有節點朝向設為 ${targetFlip ? '👉 鏡像右 (true)' : '👈 面向左 (false)'}`);
    });

    btnAutoRot.addEventListener('click', () => {
      if (selectedIdx < 0 || selectedIdx >= nodes.length) return;
      let dx = 0, dy = 0;
      if (selectedIdx < nodes.length - 1) {
        dx = nodes[selectedIdx + 1].x - nodes[selectedIdx].x;
        dy = nodes[selectedIdx + 1].y - nodes[selectedIdx].y;
      } else if (selectedIdx > 0) {
        dx = nodes[selectedIdx].x - nodes[selectedIdx - 1].x;
        dy = nodes[selectedIdx].y - nodes[selectedIdx - 1].y;
      }
      let deg = Math.round(Math.atan2(dy, dx) * 180 / Math.PI);
      if (deg > 90) deg -= 180;
      if (deg < -90) deg += 180;
      setRot(deg);
      showToast(`自動計算傾斜角度:${deg}°`);
    });

    // 在選取點之後插入新點
    btnInsertAfter.addEventListener('click', () => {
      if (selectedIdx < 0 || selectedIdx >= nodes.length) return;
      const cur = nodes[selectedIdx];
      let newX = cur.x;
      let newY = cur.y;
      let newRot = cur.rot || 0;
      let newFlip = cur.flip;

      if (selectedIdx < nodes.length - 1) {
        const next = nodes[selectedIdx + 1];
        newX = Number(((cur.x + next.x) / 2).toFixed(1));
        newY = Number(((cur.y + next.y) / 2).toFixed(1));
        newRot = Math.round(((cur.rot || 0) + (next.rot || 0)) / 2);
      } else {
        newX = Math.min(98, Number((cur.x + 3).toFixed(1)));
        newY = Math.min(98, Number((cur.y + 3).toFixed(1)));
      }

      nodes.splice(selectedIdx + 1, 0, {
        x: newX,
        y: newY,
        rot: newRot,
        flip: newFlip
      });
      selectedIdx = selectedIdx + 1;
      render();
      showToast(`已在 #${selectedIdx} 之後插入新節點!`);
    });

    btnDeleteSelected.addEventListener('click', () => {
      if (selectedIdx < 0 || selectedIdx >= nodes.length) return;
      nodes.splice(selectedIdx, 1);
      selectedIdx = -1;
      render();
      showToast('已刪除節點');
    });

    btnDeselect.addEventListener('click', () => {
      selectedIdx = -1;
      render();
    });

    // 地圖點擊新增節點
    mapAspectBox.addEventListener('click', (e) => {
      if (isDragging || justDragged) return;
      const rect = mapAspectBox.getBoundingClientRect();
      const x = Number(((e.clientX - rect.left) / rect.width * 100).toFixed(1));
      const y = Number(((e.clientY - rect.top) / rect.height * 100).toFixed(1));

      // 繼承前一個點的鏡像或走勢
      let prevFlip = false;
      if (nodes.length > 0) {
        const last = nodes[nodes.length - 1];
        prevFlip = (x > last.x) ? true : last.flip;
      }

      nodes.push({ x, y, rot: 0, flip: prevFlip });
      selectedIdx = nodes.length - 1;
      render();
      showToast(`新增節點 #${nodes.length}`);
    });

    // 拖曳節點
    window.addEventListener('mousemove', (e) => {
      if (!isDragging || dragIdx < 0 || dragIdx >= nodes.length) return;
      const rect = mapAspectBox.getBoundingClientRect();
      let x = (e.clientX - rect.left) / rect.width * 100;
      let y = (e.clientY - rect.top) / rect.height * 100;
      x = Math.max(0, Math.min(100, x));
      y = Math.max(0, Math.min(100, y));

      nodes[dragIdx].x = Number(x.toFixed(1));
      nodes[dragIdx].y = Number(y.toFixed(1));
      render();
    });

    window.addEventListener('mouseup', () => {
      if (isDragging) {
        isDragging = false;
        dragIdx = -1;
        justDragged = true;
        setTimeout(() => { justDragged = false; }, 80);
      }
    });

    // 鍵盤精準微調
    window.addEventListener('keydown', (e) => {
      // 若在輸入框或 textarea 中打字則不攔截
      if (['INPUT', 'TEXTAREA'].includes(document.activeElement.tagName)) return;

      if (e.key === ' ' || e.code === 'Space') {
        e.preventDefault();
        if (isPlaying) stopPreview();
        else startPreview();
        return;
      }

      if (selectedIdx >= 0 && selectedIdx < nodes.length) {
        const step = e.shiftKey ? 1.0 : 0.1;
        let changed = false;

        if (e.key === 'ArrowLeft') {
          nodes[selectedIdx].x = Number(Math.max(0, nodes[selectedIdx].x - step).toFixed(1));
          changed = true;
        } else if (e.key === 'ArrowRight') {
          nodes[selectedIdx].x = Number(Math.min(100, nodes[selectedIdx].x + step).toFixed(1));
          changed = true;
        } else if (e.key === 'ArrowUp') {
          nodes[selectedIdx].y = Number(Math.max(0, nodes[selectedIdx].y - step).toFixed(1));
          changed = true;
        } else if (e.key === 'ArrowDown') {
          nodes[selectedIdx].y = Number(Math.min(100, nodes[selectedIdx].y + step).toFixed(1));
          changed = true;
        } else if (e.key === 'Delete' || e.key === 'Backspace') {
          nodes.splice(selectedIdx, 1);
          selectedIdx = -1;
          changed = true;
          showToast('已刪除節點');
        } else if (e.key === '[') {
          selectedIdx = (selectedIdx - 1 + nodes.length) % nodes.length;
          changed = true;
        } else if (e.key === ']') {
          selectedIdx = (selectedIdx + 1) % nodes.length;
          changed = true;
        }

        if (changed) {
          e.preventDefault();
          render();
        }
      }
    });

    // 複製包含 flip 的 JSON
    btnCopyJson.addEventListener('click', () => {
      updateJson();
      navigator.clipboard.writeText(jsonOutput.value).then(() => {
        showToast('✅ 已複製完整路徑 JSON(含 flip 與 rot)!');
      }).catch(() => {
        jsonOutput.select();
        document.execCommand('copy');
        showToast('✅ 已複製路徑 JSON!');
      });
    });

    // 儲存並同步至本地遊戲
    btnSaveToGame.addEventListener('click', () => {
      updateJson();
      try {
        localStorage.setItem('idle_custom_merchant_route', jsonOutput.value);
        showToast('🚀 已同步至本地遊戲!切換到 index.html 即可看效果!');
      } catch (err) {
        alert('儲存失敗:' + err.message);
      }
    });

    // 匯入 JSON
    btnApplyJson.addEventListener('click', () => {
      try {
        const parsed = JSON.parse(jsonOutput.value);
        if (!Array.isArray(parsed) || parsed.length === 0) {
          throw new Error('請輸入包含節點物件的陣列');
        }
        nodes = parsed.map((p, i) => {
          let flipVal = (typeof p.flip === 'boolean') ? p.flip : false;
          if (typeof p.flip !== 'boolean' && i > 0 && parsed[i-1].x !== undefined) {
            flipVal = p.x > parsed[i-1].x;
          }
          return {
            x: Number(Number(p.x || 0).toFixed(1)),
            y: Number(Number(p.y || 0).toFixed(1)),
            rot: typeof p.rot === 'number' ? Math.round(p.rot) : 0,
            flip: flipVal
          };
        });
        selectedIdx = -1;
        render();
        showToast(`✅ 成功匯入 ${nodes.length} 個節點!`);
      } catch (err) {
        alert('JSON 格式錯誤:' + err.message);
      }
    });

    btnResetDefault.addEventListener('click', () => {
      if (confirm('確定要載入最新 16 步道節點嗎?')) {
        nodes = JSON.parse(JSON.stringify(DEFAULT_ROUTE));
        selectedIdx = -1;
        render();
        showToast('已載入最新 16 步道節點');
      }
    });

    btnClearAll.addEventListener('click', () => {
      if (confirm('確定要清空所有節點重新打點嗎?')) {
        nodes = [];
        selectedIdx = -1;
        render();
        showToast('已清空所有節點');
      }
    });

    function buildTimeline() {
      const segDists = [];
      let totalDist = 0;
      for (let i = 0; i < nodes.length - 1; i++) {
        const dx = nodes[i+1].x - nodes[i].x;
        const dy = nodes[i+1].y - nodes[i].y;
        const dist = Math.sqrt(dx * dx + dy * dy);
        segDists.push(dist);
        totalDist += dist;
      }

      let totalPauseSec = 0;
      for (const k in PAUSES) {
        if (Number(k) < nodes.length) totalPauseSec += PAUSES[k].sec;
      }
      const totalSec = baseDuration / 1000; // 45 秒
      const totalWalkSec = Math.max(10, totalSec - totalPauseSec);

      const timeline = [];
      let curTimelineSec = 0;
      for (let i = 0; i < nodes.length; i++) {
        const pauseInfo = PAUSES[i] || null;
        const pauseSec = pauseInfo ? pauseInfo.sec : 0;
        const arrSec = curTimelineSec;
        const depSec = arrSec + pauseSec;
        timeline.push({
          nodeIdx: i,
          arrSec,
          depSec,
          pauseSec,
          desc: pauseInfo ? pauseInfo.desc : null
        });
        if (i < nodes.length - 1) {
          const segWalkSec = totalDist > 0 ? (segDists[i] / totalDist) * totalWalkSec : 0;
          curTimelineSec = depSec + segWalkSec;
        }
      }
      return { timeline, totalSec };
    }

    // 依據 progress (0 ~ 1) 更新預覽實體(精準 45 秒節奏 + 走走停停 + 搖晃步態)
    function applyPreviewProgress(progress) {
      if (nodes.length < 2) return;
      const { timeline, totalSec } = buildTimeline();
      const curSec = Math.min(totalSec, progress * totalSec);

      let curX = nodes[0].x;
      let curY = nodes[0].y;
      let fromRot = nodes[0].rot || 0;
      let toRot = nodes[0].rot || 0;
      let segProgress = 0;
      let isFlipped = Boolean(nodes[0].flip);
      let isResting = false;
      let statusDesc = '';

      for (let i = 0; i < timeline.length; i++) {
        const t = timeline[i];
        if (curSec >= t.arrSec && curSec <= t.depSec && t.pauseSec > 0) {
          curX = nodes[i].x;
          curY = nodes[i].y;
          fromRot = nodes[i].rot || 0;
          toRot = fromRot;
          segProgress = 0;
          isFlipped = Boolean(nodes[i].flip);
          isResting = true;
          statusDesc = `⏸ 【歇息賞景】#${i+1} ${t.desc}`;
          break;
        } else if (i < timeline.length - 1 && curSec >= t.depSec && curSec <= timeline[i + 1].arrSec) {
          const segTotalSec = timeline[i + 1].arrSec - t.depSec;
          segProgress = segTotalSec > 0 ? (curSec - t.depSec) / segTotalSec : 1;
          curX = nodes[i].x + (nodes[i + 1].x - nodes[i].x) * segProgress;
          curY = nodes[i].y + (nodes[i + 1].y - nodes[i].y) * segProgress;
          fromRot = nodes[i].rot || 0;
          toRot = nodes[i + 1].rot || 0;
          isFlipped = Boolean(nodes[i].flip);
          isResting = false;
          statusDesc = `🚶 【行商漫步中】節點 #${i+1} ➔ #${i+2}`;
          break;
        } else if (i === timeline.length - 1 && curSec >= t.arrSec) {
          curX = nodes[i].x;
          curY = nodes[i].y;
          fromRot = nodes[i].rot || 0;
          toRot = fromRot;
          segProgress = 1;
          isFlipped = Boolean(nodes[i].flip);
          isResting = true;
          statusDesc = `🏁 到達終點 #${nodes.length}`;
          break;
        }
      }

      previewCamel.style.display = 'block';
      previewCamel.style.left = `${curX}%`;
      previewCamel.style.top = `${curY}%`;
      previewCamel.style.transform = 'translate(-50%, -70%)';

      const scaleX = isFlipped ? -1 : 1;

      let diff = (toRot - fromRot) % 360;
      if (diff < -180) diff += 360;
      if (diff > 180) diff -= 360;
      const baseRot = fromRot + diff * segProgress;

      // 擬真駱駝漫步之「搖搖晃晃」與步態顛簸 (Gait Sway & Bobbing)
      const stepFreq = 10.0;
      const stepCycle = curSec * stepFreq;

      let bobY = 0;
      let swayTilt = 0;
      let swayX = 0;

      if (!isResting) {
        bobY = Math.abs(Math.sin(stepCycle)) * 3.4;
        swayTilt = Math.sin(stepCycle) * 2.8;
        swayX = Math.cos(stepCycle) * 1.0;
      } else {
        bobY = Math.sin(curSec * 2.4) * 0.8;
        swayTilt = Math.sin(curSec * 1.6) * 0.5;
      }

      const finalRot = baseRot + swayTilt;
      previewCamelInner.style.transform = `scaleX(${scaleX}) rotate(${isFlipped ? -finalRot : finalRot}deg) translateY(${-bobY.toFixed(1)}px) translateX(${swayX.toFixed(1)}px)`;

      // 淡入與直接淡出
      let opacity = 1;
      const fadeInSec = 3.5;
      const fadeOutSec = 4.5;
      if (curSec < fadeInSec) opacity = curSec / fadeInSec;
      else if (curSec > (totalSec - fadeOutSec)) opacity = Math.max(0, (totalSec - curSec) / fadeOutSec);
      previewCamel.style.opacity = opacity.toFixed(3);

      // 更新進度條 UI
      timelineSlider.value = Math.round(progress * 1000);
      valAnimProgress.textContent = `${curSec.toFixed(1)}s / 45s (${Math.round(progress * 100)}%)`;
      timelineCurText.textContent = `${statusDesc} | X: ${curX.toFixed(1)}% | Y: ${curY.toFixed(1)}% | ${isFlipped ? '👉鏡像' : '👈原圖'} | ${Math.round(finalRot)}°`;
    }

    // 行走預覽動畫
    function startPreview() {
      if (nodes.length < 2) {
        alert('請至少建立 2 個步道節點才能進行預覽!');
        return;
      }

      isPlaying = true;
      btnPlayPreview.innerHTML = '<span>⏸</span> 暫停預覽';
      btnPlayPreview.classList.add('btn-danger');

      const duration = baseDuration / previewSpeed;
      const startTime = performance.now() - (animProgress * duration);

      function step(now) {
        if (!isPlaying) return;
        const elapsed = now - startTime;
        animProgress = Math.min(1, elapsed / duration);
        applyPreviewProgress(animProgress);

        if (animProgress < 1) {
          previewAnimFrame = requestAnimationFrame(step);
        } else {
          animProgress = 0;
          loopTimeout = setTimeout(() => {
            if (isPlaying) startPreview();
          }, 800);
        }
      }

      previewAnimFrame = requestAnimationFrame(step);
    }

    function stopPreview() {
      isPlaying = false;
      if (previewAnimFrame) cancelAnimationFrame(previewAnimFrame);
      if (loopTimeout) clearTimeout(loopTimeout);
      btnPlayPreview.innerHTML = '<span>▶</span> 播放行走預覽';
      btnPlayPreview.classList.remove('btn-danger');
    }

    btnPlayPreview.addEventListener('click', () => {
      if (isPlaying) stopPreview();
      else startPreview();
    });

    // 拖曳時間軸進度條
    timelineSlider.addEventListener('input', (e) => {
      if (isPlaying) stopPreview();
      animProgress = parseInt(e.target.value, 10) / 1000;
      applyPreviewProgress(animProgress);
    });

    function showToast(msg) {
      toastMsg.textContent = msg;
      toastMsg.classList.add('show');
      setTimeout(() => toastMsg.classList.remove('show'), 2300);
    }

    // 初始化載入
    window.addEventListener('DOMContentLoaded', () => {
      initBuildingsLayer();
      setTimeout(() => {
        resizeCanvas();
        render();
        // 預先在時間軸顯示第 1 點狀態
        applyPreviewProgress(0);
      }, 50);
    });
  </script>
</body>
</html>