File size: 27,676 Bytes
a4e7318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
888d0b6
 
 
 
 
a4e7318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26fafd3
 
 
 
 
 
 
 
 
 
 
 
 
a4e7318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26fafd3
 
 
 
 
 
 
 
 
 
 
 
a4e7318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26fafd3
a4e7318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26fafd3
a4e7318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="zh-Hant">
<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=Inter:wght@400;600;700;800&family=Noto+Sans+TC:wght@400;600;700;900&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #0f172a;
      --card-bg: rgba(30, 41, 59, 0.92);
      --border: rgba(255, 255, 255, 0.12);
      --gold: #f59e0b;
      --gold-glow: rgba(245, 158, 11, 0.4);
      --accent: #3b82f6;
      --text: #f8fafc;
      --text-dim: #94a3b8;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0; padding: 0; background: var(--bg); color: var(--text);
      font-family: 'Noto Sans TC', 'Inter', system-ui, sans-serif;
      display: flex; height: 100vh; overflow: hidden; user-select: none;
    }

    /* 主地圖畫布區 */
    .editor-stage {
      flex: 1; height: 100vh; overflow: auto; position: relative;
      background: radial-gradient(circle at center, #1e293b, #090d16);
      display: flex; align-items: flex-start; justify-content: flex-start;
      padding: 30px; cursor: default;
    }
    .map-canvas-container {
      position: relative; width: 1400px; height: 787.5px; /* 16:9 比例 */
      background: #000; border-radius: 20px; overflow: hidden;
      box-shadow: 0 25px 60px rgba(0,0,0,0.7), 0 0 0 2px rgba(245, 158, 11, 0.4);
      flex-shrink: 0;
    }
    .map-bg-img {
      width: 100%; height: 100%; object-fit: cover; display: block;
      pointer-events: none; filter: saturate(1.05);
    }

    /* 城池節點元素 */
    .town-node {
      position: absolute; transform: translate(-50%, -50%);
      cursor: grab; z-index: 10; display: flex; flex-direction: column;
      align-items: center; justify-content: center;
      transition: filter 0.2s;
    }
    .town-node:active, .town-node.dragging { cursor: grabbing; z-index: 99 !important; }
    .town-node.selected { z-index: 50; }

    .town-thumb-box {
      position: relative; display: flex; align-items: center; justify-content: center;
      border: 2px dashed transparent; border-radius: 16px;
      transition: all 0.15s ease;
    }
    .town-node:hover .town-thumb-box {
      border-color: rgba(59, 130, 246, 0.8);
      background: rgba(59, 130, 246, 0.1);
    }
    .town-node.selected .town-thumb-box {
      border: 2.5px solid var(--gold);
      background: rgba(245, 158, 11, 0.15);
      box-shadow: 0 0 25px var(--gold-glow);
    }

    .town-img {
      width: 100%; height: 100%; object-fit: contain; display: block;
      pointer-events: none;
      filter: drop-shadow(0 10px 16px rgba(0,0,0,0.6));
    }
    .capital-box {
      width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;
      font-size: 36px; border-radius: 20px;
    }

    /* 縮放把手 (Resize Handle) */
    .resize-handle {
      position: absolute; right: -8px; bottom: -8px; width: 16px; height: 16px;
      background: var(--gold); border: 2px solid #fff; border-radius: 50%;
      cursor: nwse-resize; display: none; z-index: 100;
      box-shadow: 0 2px 6px rgba(0,0,0,0.5);
    }
    .town-node.selected .resize-handle { display: block; }

    /* 節點標籤 */
    .town-tag {
      margin-top: 4px; padding: 2px 10px; border-radius: 99px;
      background: rgba(15, 23, 42, 0.9); border: 1px solid rgba(255,255,255,0.25);
      font-size: 11px; font-weight: 700; color: #fff; white-space: nowrap;
      pointer-events: none; box-shadow: 0 4px 10px rgba(0,0,0,0.4);
      display: flex; gap: 6px; align-items: center;
    }
    .town-node.selected .town-tag {
      background: var(--gold); color: #000; border-color: #fff; font-weight: 900;
    }

    /* 側邊控制台 */
    .editor-sidebar {
      width: 420px; height: 100vh; background: var(--card-bg);
      backdrop-filter: blur(20px); border-left: 1px solid var(--border);
      display: flex; flex-direction: column; flex-shrink: 0; z-index: 100;
      box-shadow: -10px 0 35px rgba(0,0,0,0.5);
    }
    .sidebar-header {
      padding: 20px; border-bottom: 1px solid var(--border);
      display: flex; flex-direction: column; gap: 4px;
    }
    .sidebar-title { margin: 0; font-size: 18px; font-weight: 900; color: var(--gold); display: flex; align-items: center; gap: 8px; }
    .sidebar-sub { font-size: 12px; color: var(--text-dim); }

    .sidebar-body {
      flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 18px;
    }

    /* 控制面板小節 */
    .ctrl-card {
      background: rgba(15, 23, 42, 0.6); border: 1px solid var(--border);
      border-radius: 14px; padding: 14px; display: flex; flex-direction: column; gap: 10px;
    }
    .ctrl-title { font-size: 13px; font-weight: 800; color: #e2e8f0; display: flex; justify-content: space-between; align-items: center; }

    .slider-row {
      display: flex; align-items: center; gap: 12px; font-size: 12px;
    }
    .slider-row label { width: 80px; color: var(--text-dim); }
    .slider-row input[type="range"] { flex: 1; accent-color: var(--gold); cursor: pointer; }
    .slider-row .val-badge {
      width: 55px; text-align: right; font-weight: 800; color: var(--gold);
      font-family: monospace; font-size: 13px;
    }

    /* 座標微調按鈕群 */
    .nudge-grid {
      display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; width: 140px; margin: 0 auto;
    }
    .btn-nudge {
      background: rgba(255,255,255,0.08); border: 1px solid var(--border);
      color: #fff; border-radius: 8px; height: 32px; cursor: pointer;
      font-size: 14px; display: flex; align-items: center; justify-content: center;
      transition: all 0.15s;
    }
    .btn-nudge:hover { background: var(--accent); color: #fff; }

    /* 城鎮快速選取清單 */
    .town-quick-list {
      display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px;
    }
    .btn-town-pick {
      background: rgba(255,255,255,0.05); border: 1px solid var(--border);
      color: var(--text); padding: 8px 10px; border-radius: 10px;
      font-size: 12px; font-weight: 700; cursor: pointer; text-align: left;
      display: flex; align-items: center; justify-content: space-between;
      transition: all 0.2s;
    }
    .btn-town-pick:hover { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.3); }
    .btn-town-pick.active { background: var(--gold); color: #000; border-color: #fff; font-weight: 900; }

    /* JSON 輸出框 */
    .json-box {
      width: 100%; height: 160px; background: #090d16; color: #38bdf8;
      border: 1px solid rgba(255,255,255,0.15); border-radius: 10px;
      padding: 10px; font-family: monospace; font-size: 11px;
      resize: none; outline: none; line-height: 1.4;
    }

    /* 操作按鈕群 */
    .sidebar-footer {
      padding: 16px 20px; border-top: 1px solid var(--border);
      display: flex; flex-direction: column; gap: 10px; background: rgba(15, 23, 42, 0.95);
    }
    .btn-group-row { display: flex; gap: 8px; }
    .btn {
      flex: 1; padding: 12px; border-radius: 12px; font-weight: 800; font-size: 13px;
      cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 6px;
      transition: all 0.2s cubic-bezier(.34,1.56,.64,1); border: 0;
    }
    .btn-primary { background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff; box-shadow: 0 4px 15px rgba(245,158,11,0.4); }
    .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(245,158,11,0.6); }
    .btn-secondary { background: rgba(255,255,255,0.1); color: #fff; border: 1px solid var(--border); }
    .btn-secondary:hover { background: rgba(255,255,255,0.18); transform: translateY(-1px); }
    .btn-success { background: linear-gradient(135deg, #10b981, #059669); color: #fff; }
    .btn-success:hover { transform: translateY(-2px); }

    /* 提示彈窗 Toast */
    .toast-box {
      position: fixed; top: 20px; left: 50%; transform: translateX(-50%) translateY(-20px);
      background: #10b981; color: #fff; padding: 10px 24px; border-radius: 99px;
      font-weight: 800; font-size: 13px; box-shadow: 0 10px 30px rgba(0,0,0,0.5);
      pointer-events: none; opacity: 0; transition: all 0.3s cubic-bezier(.34,1.56,.64,1);
      z-index: 9999;
    }
    .toast-box.show { opacity: 1; transform: translateX(-50%) translateY(0); }
  </style>
</head>
<body>
  <!-- 安全引導橫幅:提醒此工具已正式移入教師後台 -->
  <div style="position:fixed; top:12px; left:50%; transform:translateX(-50%); z-index:9999; background:rgba(217,119,6,0.95); color:#fff; padding:10px 24px; border-radius:99px; box-shadow:0 8px 24px rgba(0,0,0,0.5); font-size:13px; font-weight:700; display:flex; align-items:center; gap:12px; backdrop-filter:blur(8px);">
    <span>🔒 此沙盤校準器已正式整合並保護於【教師管理後台】</span>
    <a href="../teacher.html" style="background:#fff; color:#92400e; padding:4px 14px; border-radius:99px; text-decoration:none; font-weight:800;">前往教師後台 ➡️</a>
  </div>

  <!-- 畫布區 -->
  <main class="editor-stage" id="stage">
    <div class="map-canvas-container" id="mapCanvas">
      <img src="../assets/map_chibi.jpg" class="map-bg-img" alt="大陸沙盤">
      <!-- 城鎮動態節點 -->
      <div id="nodesContainer"></div>
    </div>
  </main>

  <!-- 側邊控制台 -->
  <aside class="editor-sidebar">
    <div class="sidebar-header">
      <h2 class="sidebar-title">🗺️ 沙盤城鎮校準器</h2>
      <span class="sidebar-sub">滑鼠直接拖放城鎮・拖動右下把手縮放・輸出 JSON</span>
    </div>

    <div class="sidebar-body">
      <!-- 選中城池控制 -->
      <div class="ctrl-card">
        <div class="ctrl-title">
          <span>🎯 當前選中城池</span>
          <span id="txtSelectedName" style="color:var(--gold);">尚未選取</span>
        </div>

        <div class="slider-row">
          <label>X 水平位置</label>
          <input type="range" id="slX" min="5" max="95" step="0.1" value="50">
          <span class="val-badge" id="valX">50.0%</span>
        </div>

        <div class="slider-row">
          <label>Y 垂直位置</label>
          <input type="range" id="slY" min="5" max="95" step="0.1" value="50">
          <span class="val-badge" id="valY">50.0%</span>
        </div>

        <div class="slider-row">
          <label>城鎮尺寸</label>
          <input type="range" id="slSize" min="60" max="240" step="2" value="120">
          <span class="val-badge" id="valSize">120px</span>
        </div>

        <div style="display:flex; justify-content:space-between; align-items:center; margin-top:4px;">
          <span style="font-size:12px; color:var(--text-dim);">鍵盤精確微調:</span>
          <div class="nudge-grid">
            <div></div>
            <button class="btn-nudge" id="btnNudgeUp" title="往上移 (0.2%)">↑</button>
            <div></div>
            <button class="btn-nudge" id="btnNudgeLeft" title="往左移 (0.2%)">←</button>
            <button class="btn-nudge" id="btnNudgeDown" title="往下移 (0.2%)">↓</button>
            <button class="btn-nudge" id="btnNudgeRight" title="往右移 (0.2%)">→</button>
          </div>
        </div>
      </div>

      <!-- 全域控制 -->
      <div class="ctrl-card">
        <div class="ctrl-title">
          <span>⚙️ 全域城鎮統一縮放</span>
          <span style="font-size:11px; color:var(--text-dim);">批次調整</span>
        </div>
        <div class="slider-row">
          <label>全體尺寸</label>
          <input type="range" id="slGlobalSize" min="70" max="220" step="2" value="120">
          <button class="btn btn-secondary" id="btnApplyGlobalSize" style="padding:4px 8px; font-size:11px;">套用全體</button>
        </div>
      </div>

      <!-- 城鎮快速選取清單 -->
      <div class="ctrl-card">
        <div class="ctrl-title">
          <span>🏰 十大名都清單</span>
          <span style="font-size:11px; color:var(--text-dim);">點擊切換選取</span>
        </div>
        <div class="town-quick-list" id="quickList"></div>
      </div>

      <!-- JSON 即時程式碼 -->
      <div class="ctrl-card">
        <div class="ctrl-title">
          <span>📄 佈局 JSON 代碼</span>
          <span style="font-size:11px; color:var(--text-dim);">即時同步</span>
        </div>
        <textarea class="json-box" id="jsonOutput" readonly></textarea>
      </div>
    </div>

    <!-- 底部動作按鈕 -->
    <div class="sidebar-footer">
      <div class="btn-group-row">
        <button class="btn btn-primary" id="btnCopyJson">📋 複製 JSON 代碼</button>
        <button class="btn btn-secondary" id="btnDownloadJson">💾 下載 JSON</button>
      </div>
      <div class="btn-group-row">
        <button class="btn btn-success" id="btnApplyToGame">⚡ 即時套用至遊戲</button>
        <button class="btn btn-secondary" id="btnResetDefault" title="恢復預設位置">🔄 恢復預設</button>
      </div>
    </div>
  </aside>

  <div class="toast-box" id="toastBox">已複製 JSON!</div>

  <script>
    // 預設 10 大城鎮初始資料
    const TOWNS_DEF = [
      { id: 'b1',           name: '景陽瓷都', icon: '🏺', defX: 27.8, defY: 70.7, defSize: 166 },
      { id: 'b9',           name: '柴桑水寨', icon: '⚓', defX: 18.1, defY: 62.1, defSize: 174 },
      { id: 'b2',           name: '平原稻鄉', icon: '🌾', defX: 37.7, defY: 78.9, defSize: 167 },
      { id: 'b4',           name: '百草藥谷', icon: '🌿', defX: 62.1, defY: 79.0, defSize: 174 },
      { id: 'b7',           name: '塞外天馬', icon: '🐎', defX: 71.8, defY: 70.6, defSize: 171 },
      { id: 'b3',           name: '神兵鐵城', icon: '⚔️', defX: 50.5, defY: 48.5, defSize: 169 },
      { id: 'b5',           name: '蜀錦絲城', icon: '👘', defX: 59.9, defY: 42.2, defSize: 173 },
      { id: 'b6',           name: '崑崙玉塞', icon: '⛏️', defX: 81.6, defY: 62.2, defSize: 172 },
      { id: 'b8',           name: '軍機策府', icon: '🏫', defX: 67.5, defY: 34.7, defSize: 172 },
      { id: 'b10',          name: '霸業王城', icon: '🏰', defX: 52.0, defY: 22.0, defSize: 140 },
      { id: 'tianji',       name: '天機閣',   icon: '🏯', defX: 34.5, defY: 29.7, defSize: 154 },
      { id: 'merchantCamp', name: '西域商隊', icon: '🎪', defX: 44.2, defY: 46.8, defSize: 145 },
      { id: 'boss',         name: '世界Boss', icon: '🐲', defX: 81.5, defY: 22.0, defSize: 168 },
    ];

    // 當前工作狀態
    let layoutData = {};
    let selectedId = 'b1';

    // 初始化資料(優先讀取 localStorage 快取)
    function initData() {
      const saved = localStorage.getItem('idle_custom_map_layout');
      if (saved) {
        try {
          layoutData = JSON.parse(saved);
        } catch(e) {}
      }
      TOWNS_DEF.forEach(t => {
        if (!layoutData[t.id]) {
          layoutData[t.id] = { x: t.defX, y: t.defY, size: t.defSize, name: t.name };
        }
      });
    }

    // 渲染節點
    function renderNodes() {
      const container = document.getElementById('nodesContainer');
      container.innerHTML = '';

      TOWNS_DEF.forEach(t => {
        const item = layoutData[t.id];
        const node = document.createElement('div');
        node.className = 'town-node' + (t.id === selectedId ? ' selected' : '');
        node.id = 'node_' + t.id;
        node.style.left = item.x + '%';
        node.style.top = item.y + '%';

        let innerContent = '';
        if (t.id === 'b10') {
          innerContent = `
            <div class="capital-box" style="width:${item.size + 20}px; height:${item.size}px;">
              <span style="font-size:24px; filter:drop-shadow(0 2px 6px rgba(0,0,0,0.7));">👑</span>
            </div>`;
        } else if (t.id === 'boss') {
          innerContent = `
            <div class="town-thumb-box" style="width:${item.size}px; height:${item.size}px; background:radial-gradient(circle, rgba(239,68,68,0.25) 0%, transparent 70%);">
              <img src="../assets/boss_taotie.png" class="town-img" alt="${t.name}" onerror="this.src='../assets/boss_qiongqi.png'">
              <div class="resize-handle" data-bid="${t.id}" title="拖動調整大小"></div>
            </div>`;
        } else if (t.id === 'merchantCamp') {
          innerContent = `
            <div class="town-thumb-box" style="width:${item.size}px; height:${Math.round(item.size * 0.75)}px; background:radial-gradient(circle, rgba(245,158,11,0.2) 0%, transparent 70%);">
              <img src="../assets/merchant_tent.png" class="town-img" alt="${t.name}" style="object-fit:contain;">
              <div class="resize-handle" data-bid="${t.id}" title="拖動調整大小"></div>
            </div>`;
        } else {
          innerContent = `
            <div class="town-thumb-box" style="width:${item.size}px; height:${item.size}px;">
              <img src="../assets/building_${t.id}.png" class="town-img" alt="${t.name}">
              <div class="resize-handle" data-bid="${t.id}" title="拖動調整大小"></div>
            </div>`;
        }

        node.innerHTML = `
          ${innerContent}
          <div class="town-tag">
            <span>${t.icon} ${t.name}</span>
            <small style="opacity:0.7;">(${item.size}px)</small>
          </div>
        `;

        // 綁定節點拖動
        bindDrag(node, t.id);
        container.appendChild(node);
      });

      renderQuickList();
      updateSidebarInputs();
      updateJsonOutput();
    }

    // 拖動與縮放事件處理
    function bindDrag(el, bid) {
      const canvas = document.getElementById('mapCanvas');

      el.addEventListener('mousedown', (e) => {
        if (e.target.classList.contains('resize-handle')) {
          // 縮放操作
          startResize(e, bid);
          return;
        }

        e.preventDefault();
        selectTown(bid);

        const rect = canvas.getBoundingClientRect();
        const startMouseX = e.clientX;
        const startMouseY = e.clientY;
        const startPctX = layoutData[bid].x;
        const startPctY = layoutData[bid].y;

        el.classList.add('dragging');

        const onMouseMove = (ev) => {
          const dx = ev.clientX - startMouseX;
          const dy = ev.clientY - startMouseY;
          const newX = Math.max(2, Math.min(98, startPctX + (dx / rect.width) * 100));
          const newY = Math.max(2, Math.min(98, startPctY + (dy / rect.height) * 100));

          layoutData[bid].x = Math.round(newX * 10) / 10;
          layoutData[bid].y = Math.round(newY * 10) / 10;

          el.style.left = layoutData[bid].x + '%';
          el.style.top = layoutData[bid].y + '%';

          updateSidebarInputs();
          updateJsonOutput();
        };

        const onMouseUp = () => {
          el.classList.remove('dragging');
          window.removeEventListener('mousemove', onMouseMove);
          window.removeEventListener('mouseup', onMouseUp);
        };

        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mouseup', onMouseUp);
      });
    }

    // 縮放把手處理
    function startResize(e, bid) {
      e.preventDefault();
      e.stopPropagation();

      const startX = e.clientX;
      const startSize = layoutData[bid].size || 120;

      const onMouseMove = (ev) => {
        const delta = ev.clientX - startX;
        const newSize = Math.max(60, Math.min(260, Math.round(startSize + delta)));
        layoutData[bid].size = newSize;

        const thumb = document.querySelector(`#node_${bid} .town-thumb-box`);
        if (thumb) {
          thumb.style.width = newSize + 'px';
          thumb.style.height = (bid === 'merchantCamp' ? Math.round(newSize * 0.75) : newSize) + 'px';
        }
        updateSidebarInputs();
        updateJsonOutput();
      };

      const onMouseUp = () => {
        window.removeEventListener('mousemove', onMouseMove);
        window.removeEventListener('mouseup', onMouseUp);
        renderNodes();
      };

      window.addEventListener('mousemove', onMouseMove);
      window.addEventListener('mouseup', onMouseUp);
    }

    // 選取城池
    function selectTown(bid) {
      selectedId = bid;
      document.querySelectorAll('.town-node').forEach(n => {
        n.classList.toggle('selected', n.id === 'node_' + bid);
      });
      document.querySelectorAll('.btn-town-pick').forEach(b => {
        b.classList.toggle('active', b.dataset.bid === bid);
      });
      updateSidebarInputs();
    }

    // 更新側邊控制欄數值
    function updateSidebarInputs() {
      const cur = layoutData[selectedId];
      const townDef = TOWNS_DEF.find(t => t.id === selectedId);
      if (!cur || !townDef) return;

      document.getElementById('txtSelectedName').textContent = `${townDef.icon} ${townDef.name} (${selectedId})`;
      document.getElementById('slX').value = cur.x;
      document.getElementById('valX').textContent = cur.x.toFixed(1) + '%';

      document.getElementById('slY').value = cur.y;
      document.getElementById('valY').textContent = cur.y.toFixed(1) + '%';

      document.getElementById('slSize').value = cur.size;
      document.getElementById('valSize').textContent = cur.size + 'px';
    }

    // 渲染城鎮快速清單
    function renderQuickList() {
      const listEl = document.getElementById('quickList');
      listEl.innerHTML = TOWNS_DEF.map(t => `
        <button class="btn-town-pick ${t.id === selectedId ? 'active' : ''}" data-bid="${t.id}">
          <span>${t.icon} ${t.name}</span>
          <small style="opacity:0.7;">${layoutData[t.id].size}px</small>
        </button>
      `).join('');

      listEl.querySelectorAll('.btn-town-pick').forEach(btn => {
        btn.addEventListener('click', () => selectTown(btn.dataset.bid));
      });
    }

    // 更新 JSON 輸出
    function updateJsonOutput() {
      const out = {};
      TOWNS_DEF.forEach(t => {
        const item = layoutData[t.id];
        out[t.id] = {
          x: item.x,
          y: item.y,
          size: item.size,
          name: t.name
        };
      });
      document.getElementById('jsonOutput').value = JSON.stringify(out, null, 2);
    }

    // 鍵盤上下左右微調
    function nudge(dx, dy) {
      if (!layoutData[selectedId]) return;
      layoutData[selectedId].x = Math.round((layoutData[selectedId].x + dx) * 10) / 10;
      layoutData[selectedId].y = Math.round((layoutData[selectedId].y + dy) * 10) / 10;
      const el = document.getElementById('node_' + selectedId);
      if (el) {
        el.style.left = layoutData[selectedId].x + '%';
        el.style.top = layoutData[selectedId].y + '%';
      }
      updateSidebarInputs();
      updateJsonOutput();
    }

    // Toast 提示
    function showToast(msg) {
      const tb = document.getElementById('toastBox');
      tb.textContent = msg;
      tb.classList.add('show');
      setTimeout(() => tb.classList.remove('show'), 2000);
    }

    // 綁定事件
    document.addEventListener('DOMContentLoaded', () => {
      initData();
      renderNodes();

      // 滑桿事件
      document.getElementById('slX').addEventListener('input', (e) => {
        layoutData[selectedId].x = parseFloat(e.target.value);
        document.getElementById('node_' + selectedId).style.left = layoutData[selectedId].x + '%';
        document.getElementById('valX').textContent = layoutData[selectedId].x.toFixed(1) + '%';
        updateJsonOutput();
      });

      document.getElementById('slY').addEventListener('input', (e) => {
        layoutData[selectedId].y = parseFloat(e.target.value);
        document.getElementById('node_' + selectedId).style.top = layoutData[selectedId].y + '%';
        document.getElementById('valY').textContent = layoutData[selectedId].y.toFixed(1) + '%';
        updateJsonOutput();
      });

      document.getElementById('slSize').addEventListener('input', (e) => {
        layoutData[selectedId].size = parseInt(e.target.value);
        document.getElementById('valSize').textContent = layoutData[selectedId].size + 'px';
        const thumb = document.querySelector(`#node_${selectedId} .town-thumb-box`);
        if (thumb) {
          thumb.style.width = layoutData[selectedId].size + 'px';
          thumb.style.height = (selectedId === 'merchantCamp' ? Math.round(layoutData[selectedId].size * 0.75) : layoutData[selectedId].size) + 'px';
        }
        updateJsonOutput();
      });

      // 全體縮放
      document.getElementById('btnApplyGlobalSize').addEventListener('click', () => {
        const sz = parseInt(document.getElementById('slGlobalSize').value);
        TOWNS_DEF.forEach(t => layoutData[t.id].size = sz);
        renderNodes();
        showToast(`已將全體城鎮尺寸設定為 ${sz}px!`);
      });

      // 微調按鈕
      document.getElementById('btnNudgeUp').addEventListener('click', () => nudge(0, -0.2));
      document.getElementById('btnNudgeDown').addEventListener('click', () => nudge(0, 0.2));
      document.getElementById('btnNudgeLeft').addEventListener('click', () => nudge(-0.2, 0));
      document.getElementById('btnNudgeRight').addEventListener('click', () => nudge(0.2, 0));

      // 鍵盤方向鍵支援
      window.addEventListener('keydown', (e) => {
        if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
          e.preventDefault();
          const step = e.shiftKey ? 1.0 : 0.2;
          if (e.key === 'ArrowUp') nudge(0, -step);
          if (e.key === 'ArrowDown') nudge(0, step);
          if (e.key === 'ArrowLeft') nudge(-step, 0);
          if (e.key === 'ArrowRight') nudge(step, 0);
        }
      });

      // 複製 JSON
      document.getElementById('btnCopyJson').addEventListener('click', () => {
        const text = document.getElementById('jsonOutput').value;
        navigator.clipboard.writeText(text).then(() => {
          showToast('📋 已複製 JSON 到剪貼簿!可直接提供給 AI 或存檔!');
        });
      });

      // 下載 JSON 檔案
      document.getElementById('btnDownloadJson').addEventListener('click', () => {
        const text = document.getElementById('jsonOutput').value;
        const blob = new Blob([text], { type: 'application/json' });
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = 'map_pos.json';
        a.click();
        showToast('💾 已下載 map_pos.json 檔案!');
      });

      // 即時套用至本機遊戲
      document.getElementById('btnApplyToGame').addEventListener('click', () => {
        const text = document.getElementById('jsonOutput').value;
        localStorage.setItem('idle_custom_map_layout', text);
        showToast('⚡ 已將新佈局套用至遊戲!回到遊戲頁面重整即可見效!');
      });

      // 恢復預設
      document.getElementById('btnResetDefault').addEventListener('click', () => {
        if (confirm('確定要將所有城鎮重設回預設座標與大小嗎?')) {
          localStorage.removeItem('idle_custom_map_layout');
          TOWNS_DEF.forEach(t => {
            layoutData[t.id] = { x: t.defX, y: t.defY, size: t.defSize, name: t.name };
          });
          renderNodes();
          showToast('🔄 已恢復為預設佈局!');
        }
      });
    });
  </script>
</body>
</html>