File size: 50,770 Bytes
92abf74
 
 
 
e58357c
92abf74
 
 
 
54d2fa5
29c7547
 
e58357c
 
5389735
 
 
e58357c
 
 
 
92abf74
 
 
 
54d2fa5
 
 
 
 
 
 
 
 
 
 
 
 
 
92abf74
 
 
1d1ce53
 
 
 
 
 
 
 
 
 
 
 
92abf74
44dd6b6
5389735
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26fafd3
 
 
 
1d1ce53
26fafd3
 
92abf74
 
 
 
 
 
1d1ce53
26fafd3
 
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29c7547
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29c7547
 
 
 
 
 
 
e82116f
c759458
 
 
 
 
 
 
e82116f
 
29c7547
 
 
92abf74
29c7547
92abf74
e82116f
92abf74
29c7547
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26fafd3
5389735
92abf74
 
26fafd3
92abf74
 
54d2fa5
 
92abf74
5389735
 
 
 
 
54d2fa5
92abf74
 
 
 
 
 
 
 
54d2fa5
 
 
 
 
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9938f86
92abf74
 
 
2ede057
92abf74
44dd6b6
92abf74
 
 
 
9938f86
 
 
 
 
242bd01
9938f86
 
 
 
 
 
242bd01
9938f86
 
 
 
892826b
210366b
 
 
 
 
 
 
 
 
 
 
 
892826b
9938f86
 
 
 
 
 
 
 
 
 
92abf74
9938f86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92abf74
 
9938f86
 
92abf74
 
b671293
5389735
b671293
5389735
b671293
5389735
 
 
 
 
 
 
 
 
 
 
 
 
d170a1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5389735
 
d170a1b
5389735
a0b3454
e86045f
5389735
 
 
 
 
 
 
 
 
 
 
 
 
 
92abf74
 
 
 
 
 
 
5389735
 
 
 
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5389735
92abf74
 
 
 
 
 
 
 
 
 
5389735
92abf74
54d2fa5
 
 
 
 
 
 
 
 
92abf74
 
 
 
 
54d2fa5
 
 
 
 
 
 
 
 
 
 
92abf74
 
 
 
 
 
 
 
 
 
 
 
54d2fa5
 
 
 
 
 
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5389735
92abf74
 
 
26fafd3
 
 
 
 
ddf71f0
92abf74
 
 
 
 
 
 
 
 
 
54d2fa5
 
92abf74
54d2fa5
92abf74
 
54d2fa5
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54d2fa5
 
92abf74
 
 
 
 
ddf71f0
92abf74
 
 
 
 
ddf71f0
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5144eec
 
e0e1f8b
5144eec
1d1ce53
e0e1f8b
5144eec
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddf71f0
 
 
 
 
 
 
 
92abf74
ddf71f0
92abf74
ddf71f0
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5389735
92abf74
 
 
 
 
 
29c7547
 
 
 
 
 
 
92abf74
 
 
e82116f
92abf74
 
29c7547
92abf74
 
b5e6455
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29c7547
 
5389735
29c7547
 
 
 
 
 
 
 
1d1ce53
 
 
29c7547
ddf71f0
 
29c7547
 
 
5389735
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5389735
 
92abf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5389735
 
92abf74
 
 
 
 
 
 
 
 
29c7547
ddf71f0
29c7547
 
 
ddf71f0
 
 
 
 
 
 
 
 
 
29c7547
 
 
62596f1
29c7547
 
 
 
e82116f
 
 
 
 
 
5389735
 
 
 
 
 
29c7547
 
 
 
92abf74
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
// ============================================================================
//  js/map.js
//  超大戰略沙盤大地圖系統(沙盤名都佈局、動態路網、即時互動面板與世界 Boss 標記)
// ============================================================================
import { BUILDINGS, APP_BUILD_VERSION } from './config.js?v=20261129_v1';
import {
  isUnlocked, buildingProd, getConquerRequirements, canConquer, conquerTown,
  maxAffordable, bulkCost, starCost, nextStarMult, nextMilestone, getTianjiStatus,
  getActiveWorldBossConfig, calcWorldBossStatus, calcWorldBossRewards,
  formatCountdown, formatOpenAt,
  checkConstructionStatus, isEventOpen, derive,
  getEra2Status, getEra2UpgradeInfo, evolveTownToEra2, ERA2_TOWN_NAMES, ERA2_SEQUENCE, ERA2_TALLY_COST
} from './engine.js?v=20261129_v1';
import { resolveWeeklySpotlight, resolveCaravanModeState } from './event-schedule.js?v=20261129_v1';
import {
  MAX_DAILY_LOTTERY_ROUNDS, LOTTERY_DEFAULT_MILESTONES,
  calcLotteryBallStats, calcLotteryMilestonesProgress
} from './lottery-core.js?v=20261129_v1';
import { getMerchantStatus, getCaravanImgSrc } from './merchant.js?v=20261129_v1';
import { computeBazaarSummary } from './bazaar.js?v=20261129_v1';
import { $, $$, bind, esc, fmt, toast, openModal, todayStr } from './util.js?v=20261129_v1';

// 目前在地圖上選中的城池(預設關閉,點擊城池時才彈出)
let selectedTownId = null;
let mapCtx = null;
let bossCountdownTimer = null;
let lastBossUnlockedState = null;

function ensureBossCountdownTimer(shouldRun) {
  if (!shouldRun) {
    if (bossCountdownTimer) { clearInterval(bossCountdownTimer); bossCountdownTimer = null; }
    return;
  }
  if (bossCountdownTimer) return;
  bossCountdownTimer = setInterval(() => {
    if (document.hidden) return;
    updateMapBossHpUI();
  }, 1000);
}

// 10 大特色名都與特殊奇遇在沙盤大地圖上的精確座標定位與微縮手辦尺寸(由校準器校準導出)
export const MAP_POS = {
  b1: { x: 27.8, y: 70.7, size: 166 }, // 景陽瓷都
  b9: { x: 18.1, y: 62.1, size: 174 }, // 柴桑水寨
  b2: { x: 37.7, y: 78.9, size: 167 }, // 平原稻鄉
  b4: { x: 62.1, y: 79.0, size: 174 }, // 百草藥谷
  b7: { x: 71.8, y: 70.6, size: 171 }, // 塞外天馬
  b3: { x: 50.5, y: 48.5, size: 169 }, // 神兵鐵城
  b5: { x: 59.9, y: 42.2, size: 173 }, // 蜀錦絲城
  b6: { x: 81.6, y: 62.2, size: 172 }, // 崑崙玉塞
  b8: { x: 67.5, y: 34.7, size: 172 }, // 軍機策府
  b10: { x: 52.0, y: 20.6, size: 175 }, // 霸業王城(萬里神州天下名都,居於山巔平臺)
  tianji: { x: 34.5, y: 29.7, size: 154 }, // 天機閣
  boss: { x: 81.5, y: 22.0, size: 168 }, // 世界 Boss(懸空禁地)
  merchantCamp: { x: 44.2, y: 46.8, size: 145 }, // 西域商隊(天機閣右下平原)
  bazaarCamp: { x: 44.2, y: 46.8, size: 155 }, // 西域萬國大市集(獨立沙盤座標)
  lottery: { x: 18.0, y: 27.5, size: 158 }, // 錯題樂透(天機閣左方琉璃山谷)
};

// 戰略行軍補給網絡連線(由四周外圍向內層層遞進,直通山巔)
export const STRATEGIC_ROUTES = [
  ['b1', 'b9'], // 瓷都 -> 水寨 (外圍左翼)
  ['b1', 'b2'], // 瓷都 -> 稻鄉 (外圍正南)
  ['b2', 'b4'], // 稻鄉 -> 藥谷 (外圍東南)
  ['b4', 'b7'], // 藥谷 -> 天馬 (外圍東南邊陲)
  ['b1', 'b3'], // 瓷都 -> 神兵 (挺進中央腹地)
  ['b2', 'b3'], // 稻鄉 -> 神兵 (挺進中央腹地)
  ['b3', 'b5'], // 神兵 -> 蜀錦 (中層推進)
  ['b7', 'b5'], // 天馬 -> 蜀錦 (中層會師)
  ['b5', 'b6'], // 蜀錦 -> 崑崙 (開拓極東要塞)
  ['b7', 'b6'], // 天馬 -> 崑崙 (側翼合圍)
  ['b5', 'b8'], // 蜀錦 -> 軍機策府 (進逼王畿門戶)
  ['b6', 'b8'], // 崑崙 -> 軍機策府 (進逼王畿門戶)
  ['b8', 'b10'], // 軍機策府 -> 霸業王城 (直搗天下皇城)
];

/**
 * 初始化地圖模組,注入外部相依上下文
 */
export function setupMap(context) {
  mapCtx = context;
  initMapDrag();
}

export function getSelectedTownId() {
  return selectedTownId;
}

export function setSelectedTownId(bid) {
  selectedTownId = bid;
}

/**
 * 初始化大地圖:支援觸控自然上下滾動與點擊城池就近互動
 */
export function initMapDrag() {
  const wrap = $('#territoryMapWrap');
  if (!wrap || wrap.dataset.dragInited) return;
  wrap.dataset.dragInited = 'true';

  // 點擊地圖空白處自動收起城池戰略面板
  wrap.addEventListener('click', (e) => {
    if (!e.target.closest('.map-spot') && !e.target.closest('.inmap-town-panel')) {
      if (selectedTownId) {
        selectedTownId = null;
        renderMapSpots();
        renderInMapTownPanel();
      }
    }
  });

  // 全覽清單開關
  $('#btnToggleList')?.addEventListener('click', () => {
    const listWrap = $('#buildingListWrap');
    if (listWrap) {
      const isHidden = listWrap.classList.toggle('hidden');
      $('#btnToggleList').textContent = isHidden ? '📜 展開十都名錄全覽' : '▲ 收起十都名錄全覽';
    }
  });
}

/**
 * 選中城池並就近彈出城池面板
 */
export function focusTownOnMap(bid, smooth = true) {
  selectedTownId = bid;
  renderMapSpots();
  renderInMapTownPanel();
}

/**
 * 取得城池在地圖上的座標與尺寸(支援由校準編輯器產生的自訂佈局)
 */
export function getTownLayout(bid) {
  // 1. 優先採用班級雲端最新發布之佈局(教師後台儲存發布後,全班學生即時同動)
  try {
    const classLayout = mapCtx?.getClassInfo()?.mapLayout;
    if (classLayout && classLayout[bid]) return classLayout[bid];
  } catch (e) { }

  // 2. 次之採用本機自訂快取(教師本地預覽或校準)
  try {
    const saved = localStorage.getItem('idle_custom_map_layout');
    if (saved) {
      const parsed = JSON.parse(saved);
      if (parsed[bid]) return parsed[bid];
    }
  } catch (e) { }

  // 3. 官方標準預設座標
  const def = MAP_POS[bid] || { x: 50, y: 50, size: 120 };
  return { x: def.x, y: def.y, size: def.size || 120 };
}

export function renderMapRoutes() {
  const svg = $('#mapRoutesSvg');
  if (svg) svg.innerHTML = ''; // 依使用者需求隱藏連線,呈現純淨沙盤山水
}

/**
 * 渲染地圖全點位(10大名都、天機閣、世界Boss、西域商隊)
 */
export function renderMapSpots() {
  renderMapRoutes();
  initMapDrag();
  const el = $('#mapSpots');
  if (!el || !mapCtx) return;

  const game = mapCtx.getGame();
  const dState = mapCtx.getDState();
  const classInfo = mapCtx.getClassInfo();
  const progress = mapCtx.getProgress();
  if (!game || !dState) return;

  const spotsHtml = BUILDINGS.map(b => {
    const layout = getTownLayout(b.id);
    const pos = { x: layout.x, y: layout.y };
    const size = layout.size || 160;
    const st = game.buildings[b.id] || { lv: 0, star: 0 };
    const un = isUnlocked(b, dState);
    const ev = dState.evolved.has(b.id);
    const reqs = getConquerRequirements(b, game, dState);
    const isSelected = selectedTownId === b.id;
    let stateCls = 'locked';
    let statusText = '🔒 待開拓';
    let iconBadge = '';
    let costBadge = '';
    let prodText = '';

    if (!un || !reqs.prereqMet) {
      stateCls = 'locked';
      statusText = '🔒 待開拓';
      prodText = `需通過 ${b.unlockUnits} 單元`;
    } else if (st.lv === 0) {
      stateCls = reqs.ready ? 'ready' : 'ready prep';
      statusText = reqs.ready ? '⚔️ 可出征' : '🚩 籌備中';
      iconBadge = '<span class="spot-flag">🚩</span>';
      costBadge = `<span class="spot-tally-cost" title="出征需消耗 ${b.tallyCost} 兵符"><img src="assets/icon_tally.jpg" class="res-mini-icon" alt="兵符">${b.tallyCost}</span>`;
      prodText = `收復可得 +${b.baseProd}/秒`;
    } else {
      stateCls = 'active' + (ev ? ' evolved' : '');
      statusText = `Lv.${st.lv}` + (st.star > 0 ? ` ★${st.star}` : '');
      iconBadge = '';
      const curProd = buildingProd(b, st, dState);
      prodText = `<img src="assets/icon_grain.jpg" class="res-mini-icon" alt="糧草">+${fmt(curProd)}/秒`;
    }

    if (isSelected) stateCls += ' selected';

    // 針對所有名都(包含 B10 霸業王城):統一以 3D 微縮手辦渲染,平地基座自然襯托
    const isEra2 = !!st.era2;
    const imgSrc = isEra2 ? `assets/building_${b.id}_era2.png` : `assets/building_${b.id}.png`;
    const displayName = isEra2 ? (ERA2_TOWN_NAMES[b.id] || b.name) : b.name;

    const visualBody = `
      <div class="spot-building-wrap ${isEra2 ? 'era2-wrap' : ''}" style="width:clamp(48px, calc(${size} * 100cqw / 1400), ${size}px); height:clamp(48px, calc(${size} * 100cqw / 1400), ${size}px);">
        ${isEra2 ? `
          <div class="era2-sparks-wrap">
            <span class="era2-spark"></span>
            <span class="era2-spark"></span>
            <span class="era2-spark"></span>
            <span class="era2-spark"></span>
            <span class="era2-spark"></span>
          </div>
        ` : ''}
        <img class="spot-building-img ${isEra2 ? 'era2-img' : ''}" src="${imgSrc}" alt="${displayName}">
        ${costBadge}
        ${iconBadge}
      </div>`;

    return `<div class="map-spot ${stateCls} ${isEra2 ? 'era2-spot' : ''}" style="left:${pos.x}%; top:${pos.y}%;" data-bid="${b.id}" title="${displayName}(${b.specialty})">
      ${visualBody}
      <div class="spot-label ${isEra2 ? 'era2-label' : ''}">
        <div class="spot-label-top">
          <span>${b.icon} ${displayName}</span>
          <small>${statusText}</small>
        </div>
        <div class="spot-label-prod">${prodText}</div>
      </div>
    </div>`;
  }).join('');

  // 注入每日特殊奇遇入口:【天機閣】(懸浮於沙盤仙境,座標與尺寸依循校準器配置)
  const ts = getTianjiStatus(game);
  const tianjiDone = !ts.canPlay;
  const tianjiLayout = getTownLayout('tianji');
  const tianjiHtml = `
    <div class="map-spot spot-tianji ${tianjiDone ? 'tianji-done' : ''}" style="left:${tianjiLayout.x}%; top:${tianjiLayout.y}%;" data-tianji="true" title="天機閣・每日60秒急速快答演武">
      <span class="spot-badge-daily">${tianjiDone ? '今日遊玩次數 (1/1)' : '今日遊玩次數 (0/1)'}</span>
      <div class="spot-tianji-wrap" style="width:clamp(48px, calc(${tianjiLayout.size} * 100cqw / 1400), ${tianjiLayout.size}px); height:clamp(48px, calc(${tianjiLayout.size} * 100cqw / 1400), ${tianjiLayout.size}px);">
        <img class="spot-tianji-img" src="assets/building_tianji.png" alt="天機閣">
      </div>
      <div class="spot-label">
        <div class="spot-label-top">
          <span>🏯 天機閣</span>
          <small style="${tianjiDone ? 'color:var(--text-mute); font-weight:700;' : 'color:#059669; font-weight:800;'}">${tianjiDone ? '今日遊玩次數 (1/1)' : '今日遊玩次數 (0/1)'}</small>
        </div>
        <div class="spot-label-prod" style="${tianjiDone ? 'color:var(--text-mute); background:rgba(0,0,0,0.06);' : 'color:#b45309;'}">${tianjiDone ? '今日已結算・明日 00:00 重設' : '開軍備箱・奪金兵符'}</div>
      </div>
    </div>
  `;

  // 注入世界 Boss 入口(若活動過期、已圓滿結束收起或非開放模式之饕餮,則大地圖收起不呈現圖案)
  const bossStatus = calcWorldBossStatus(classInfo, progress, game, todayStr(), null, mapCtx?.getUid?.());
  const bossCfg = getActiveWorldBossConfig(classInfo);
  let bossHtml = '';
  if (!bossStatus.isExpired && !bossStatus.isClosedMode && !bossStatus.isTaotieConcluded) {
    const bossLayout = getTownLayout('boss');
    const isBossUnlocked = bossStatus.unlocked;
    lastBossUnlockedState = isBossUnlocked;
    ensureBossCountdownTimer(bossStatus.isCountdown);
    const bossCls = isBossUnlocked ? 'boss-open' : 'boss-sealed';
    const badgeText = bossStatus.claimOnlyAfterEnd
      ? '🎁 領取上期獎勵'
      : (isBossUnlocked
        ? `🔥 討伐 (${bossStatus.ordersLeft}/${bossStatus.maxOrders || 3})`
        : (bossStatus.isCountdown ? `⏳ 倒數 ${formatCountdown(bossStatus.countdownMs)}` : '🔒 破印倒數'));
    const bossBadge = `<span class="spot-badge-boss" id="badgeMapBoss">${badgeText}</span>`;

    const curHp = bossStatus.curHp;
    const maxHp = bossStatus.maxHp;
    const hpPct = bossStatus.pct;
    const isCritical = curHp > 0 && curHp <= Math.round(maxHp * 0.25);
    const isDefeated = bossStatus.defeated;

    let bossSubText = `需通關${bossCfg.unlockUnitName || '指定單元'}・封印倒數中`;
    if (bossStatus.isCountdown) {
      bossSubText = `⏳ ${formatOpenAt(bossStatus.openAt)} 準時破印(剩 ${formatCountdown(bossStatus.countdownMs)})`;
    } else if (!isBossUnlocked && bossStatus.isUnlockedDate) {
      bossSubText = `🔒 已破印開放・需先通關${bossCfg.unlockUnitName || '指定單元'}`;
    } else if (isBossUnlocked) {
      if (isDefeated) {
        bossSubText = '🏆 首討告捷・全服已平定';
      } else if (curHp <= 100) {
        bossSubText = `⚡ ${bossCfg.shortName}殘血剩 ${curHp} HP・搶首破!`;
      } else {
        bossSubText = `⚔️ 圍攻中・剩餘 ${curHp} HP`;
      }
    }

    // 大地圖世界 Boss 直接可見之血條模組
    const hpSectionHtml = `
      <div class="spot-boss-map-hp" id="mapBossHpSection">
        <div class="spot-boss-map-hp-info">
          <span class="spot-boss-map-hp-title">🩸 生命值</span>
          <b class="spot-boss-map-hp-num num" id="lblMapBossHpVal">${isDefeated ? `已平定 0/${maxHp}` : `${curHp} / ${maxHp}`}</b>
          <span class="spot-boss-map-hp-pct num" id="lblMapBossHpPct">${hpPct}%</span>
        </div>
        <div class="spot-boss-map-hp-track">
          <div class="spot-boss-map-hp-fill ${isCritical ? 'is-critical' : ''} ${isDefeated ? 'is-defeated' : ''}" id="barMapBossHp" style="width: ${hpPct}%;"></div>
        </div>
      </div>
    `;

    bossHtml = `
      <div class="map-spot spot-boss ${bossCls}" style="left:${bossLayout.x}%; top:${bossLayout.y}%;" data-boss="true" title="世界Boss【${bossCfg.name}】${isBossUnlocked ? '・全軍熱血討伐中!' : '・封印倒數中'}">
        ${bossBadge}
        <div class="spot-boss-wrap" style="width:clamp(56px, calc(${bossLayout.size} * 100cqw / 1400), ${bossLayout.size}px); height:clamp(56px, calc(${bossLayout.size} * 100cqw / 1400), ${bossLayout.size}px);">
          <div class="spot-boss-aura"></div>
          ${!isBossUnlocked ? '<div class="spot-boss-seal-ring"></div>' : ''}
          <img class="spot-boss-img" src="${bossCfg.sprite}" alt="${bossCfg.name}">
        </div>
        <div class="spot-label spot-boss-label">
          <div class="spot-label-top">
            <span>${bossCfg.icon} ${bossCfg.name}</span>
            <small style="${isBossUnlocked ? 'color:#ef4444; font-weight:800;' : 'color:#cbd5e1; font-weight:700;'}">${isBossUnlocked ? '世界 Boss' : '封印禁域'}</small>
          </div>
          ${hpSectionHtml}
          <div class="spot-label-prod" id="lblMapBossSubText">${bossSubText}</div>
        </div>
      </div>
    `;
  }

  // 注入西域商隊/西域萬國大市集大活動入口:【西域商隊大營】(座落於天機閣右下角、霸業王城階梯下方平原,僅於開放時顯示)
  let merchantCampHtml = '';
  const isCaravanOpen = isEventOpen('caravan', classInfo);
  if (isCaravanOpen) {
    const modeState = resolveCaravanModeState(classInfo);
    const merchantStatus = getMerchantStatus(game);
    const merchantLayout = getTownLayout(modeState.activeType === 'bazaar' ? 'bazaarCamp' : 'merchantCamp');
    const dayInfo = merchantStatus.dayInfo;
    const merchantProgressLabel = dayInfo.displayProgress;
    const mData = game.merchant || {};
    const discountText = mData.todayDiscountLabel || (merchantStatus.todayMult ? (merchantStatus.todayMult <= 1.0 ? '2折' : `${merchantStatus.todayMult}x`) : null);

    if (modeState.activeType === 'bazaar') {
      const uid = mapCtx?.getUid?.() || 'guest';
      const summary = computeBazaarSummary(game, uid, modeState.cycleId);
      const isCountdown = Boolean(modeState.isCountdown && !modeState.isForcedOpen);
      const hasQuotaDot = !isCountdown && summary.remDailyQuota > 0 && summary.litCount < 240;
      const bazaarBadgeText = isCountdown
        ? '⏳ 週一 07:00 萬國開市'
        : `🎪 西域大市集・${summary.totalLines}/120 線`;
      const bazaarDotHtml = hasQuotaDot ? '<span class="spot-bazaar-dot" title="今日尚可點亮賓果格"></span>' : '';
      const bazaarSub = isCountdown
        ? `已點亮 ${summary.litCount}/240 字・07:00 準時開市`
        : `今日 ${summary.dailyLitCount}/${summary.dailyQuotaCap}・總 ${summary.litCount}/240`;

      merchantCampHtml = `
        <div class="map-spot spot-merchant-camp spot-bazaar-camp ${isCountdown ? 'bazaar-countdown' : ''}" style="left:${merchantLayout.x}%; top:${merchantLayout.y}%;" data-merchant-camp="true" title="西域萬國大市集(十卷賓果總複習・四大名師奇遇)">
          <span class="spot-badge-daily">${bazaarDotHtml}${bazaarBadgeText}</span>
          <div class="spot-bazaar-fireworks" aria-hidden="true">
            <span class="bz-fw bz-fw-1">
              <span class="bz-fw-rocket"></span>
              <span class="bz-fw-burst"><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i></span>
            </span>
            <span class="bz-fw bz-fw-2">
              <span class="bz-fw-rocket"></span>
              <span class="bz-fw-burst"><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i></span>
            </span>
            <span class="bz-fw bz-fw-3">
              <span class="bz-fw-rocket"></span>
              <span class="bz-fw-burst"><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i><i><b></b></i></span>
            </span>
          </div>
          <div class="spot-merchant-wrap" style="width:clamp(56px, calc(${merchantLayout.size} * 100cqw / 1400), ${merchantLayout.size}px); height:clamp(42px, calc(${merchantLayout.size} * 0.75 * 100cqw / 1400), ${Math.round(merchantLayout.size * 0.75)}px);">
            <img class="spot-merchant-img" src="assets/bazaar_camp.png?v=${APP_BUILD_VERSION}" alt="西域萬國大市集">
          </div>
          <div class="spot-label">
            <div class="spot-label-top">
              <span>🎪 西域大市集</span>
              <small style="color:#d97706; font-weight:800;">${discountText ? `今日${discountText}` : `Lv.${merchantStatus.currentLv.lv}`}</small>
            </div>
            <div class="spot-label-prod" style="color:#b45309;">${bazaarSub}</div>
          </div>
        </div>
      `;
    } else {
      const merchantSub = discountText
        ? `今日享【${discountText}】特惠・集市熱銷`
        : `今日金幣: ${merchantStatus.dayCoins}/16・40s快答`;

      merchantCampHtml = `
        <div class="map-spot spot-merchant-camp" style="left:${merchantLayout.x}%; top:${merchantLayout.y}%;" data-merchant-camp="true" title="西域商隊(限時 40 秒快答挑戰)">
          <span class="spot-badge-daily">🎪 ${merchantProgressLabel}</span>
          <div class="spot-merchant-wrap" style="width:clamp(56px, calc(${merchantLayout.size} * 100cqw / 1400), ${merchantLayout.size}px); height:clamp(42px, calc(${merchantLayout.size} * 0.75 * 100cqw / 1400), ${Math.round(merchantLayout.size * 0.75)}px);">
            <img class="spot-merchant-img" src="${getCaravanImgSrc(merchantStatus)}" alt="西域商隊">
          </div>
          <div class="spot-label">
            <div class="spot-label-top">
              <span>🎪 西域商隊</span>
              <small style="color:#d97706; font-weight:800;">${merchantStatus.currentLv.name}</small>
            </div>
            <div class="spot-label-prod" style="color:#b45309;">${merchantSub}</div>
          </div>
        </div>
      `;
    }
  }

  // 注入當期錯題樂透入口(依教師指示暫時收起錯題樂透箱,日後需重開將 showLotterySpot 改回 true)
  let lotteryHtml = '';
  const showLotterySpot = false;
  const spotlightState = resolveWeeklySpotlight(classInfo);
  if (showLotterySpot && (spotlightState.active || spotlightState.isBeforeOpen) && spotlightState.eventId === 'lottery' && spotlightState.cycleId) {
    const cycleId = spotlightState.cycleId;
    const lotteryLayout = getTownLayout('lottery');
    const clsCycle = classInfo?.lotteryCycles?.[cycleId] || {};
    const stuCycle = game?.lottery?.cycles?.[cycleId] || {};
    const uid = mapCtx?.getUid?.();
    const myEntry = (uid && clsCycle?.entries?.[uid]) ? clsCycle.entries[uid] : stuCycle;
    const myStats = calcLotteryBallStats(myEntry);
    const prog = calcLotteryMilestonesProgress(clsCycle?.entries || {}, clsCycle?.milestones || spotlightState.milestones || LOTTERY_DEFAULT_MILESTONES);
    const maxDaily = Math.max(1, Number(clsCycle?.maxDailyRounds) || MAX_DAILY_LOTTERY_ROUNDS);
    const usedToday = Math.max(0, Number(stuCycle?.dailyUsed?.[todayStr()]) || Number(myEntry?.dailyUsed?.[todayStr()]) || 0);
    const roundsLeft = Math.max(0, maxDaily - usedToday);
    const isLocked = clsCycle?.status === 'locked';
    const isSettled = clsCycle?.status === 'settled';
    const isBeforeOpen = Boolean(spotlightState.isBeforeOpen);
    const openFmt = (() => {
      const t = Number(spotlightState.openAt);
      if (!Number.isFinite(t)) return '即將開放';
      const d = new Date(t + 8 * 3600 * 1000);
      const hh = String(d.getUTCHours()).padStart(2, '0');
      const mm = String(d.getUTCMinutes()).padStart(2, '0');
      return `${d.getUTCMonth() + 1}/${d.getUTCDate()} ${hh}:${mm}`;
    })();
    const lotBadge = isBeforeOpen
      ? `⏳ ${openFmt} 開放`
      : (isSettled
        ? '🎉 已開獎・查收信箱'
        : (isLocked ? '🔒 封箱待開獎' : `🎰 投球 (${roundsLeft}/${maxDaily})`));
    const lotSub = isBeforeOpen
      ? '搶先看本期獎項與稱號'
      : (myStats.weight > 0
        ? `個人 ${myStats.weight} 籤・班級共 ${prog.totalWeight} 籤`
        : `班級集氣 ${prog.totalWeight} 籤・週五開獎`);

    lotteryHtml = `
      <div class="map-spot spot-lottery ${isLocked ? 'lottery-locked' : ''} ${(!isBeforeOpen && roundsLeft <= 0) ? 'lottery-done' : ''}" id="spot-lottery" style="left:${lotteryLayout.x}%; top:${lotteryLayout.y}%;" data-lottery="true" title="錯題樂透開獎箱(答對投入彩球・週五公開抽獎)">
        <span class="spot-badge-daily spot-badge-lottery">${lotBadge}</span>
        <div class="spot-lottery-wrap" style="width:clamp(54px, calc(${lotteryLayout.size} * 100cqw / 1400), ${lotteryLayout.size}px); height:clamp(42px, calc(${lotteryLayout.size} * 0.75 * 100cqw / 1400), ${Math.round(lotteryLayout.size * 0.75)}px);">
          <div class="spot-lottery-aura"></div>
          <img class="spot-lottery-img" src="assets/lottery_box.png" onerror="this.onerror=null;this.src='assets/chest_gold.png';" alt="錯題樂透箱">
        </div>
        <div class="spot-label">
          <div class="spot-label-top">
            <span>🎰 錯題樂透</span>
            <small style="color:#f59e0b; font-weight:800;">${clsCycle?.prizeMode === 'pilot' ? '快閃場' : '彩球箱'}</small>
          </div>
          <div class="spot-label-prod" style="color:#b45309;">${lotSub}</div>
        </div>
      </div>
    `;
  }

  el.innerHTML = spotsHtml + tianjiHtml + bossHtml + merchantCampHtml + lotteryHtml;

  // 綁定地圖點位點擊事件
  $$('.map-spot', el).forEach(spot => {
    bind(spot, 'mousedown', (e) => e.stopPropagation());
    bind(spot, 'touchstart', (e) => e.stopPropagation());
    bind(spot, 'click', (e) => {
      e.stopPropagation();
      if (spot.dataset.lottery) {
        mapCtx.onOpenLottery?.();
        return;
      }
      if (spot.dataset.merchantCamp) {
        if (!isEventOpen('caravan', classInfo)) return;
        mapCtx.onOpenMerchant?.();
        return;
      }
      if (spot.dataset.boss) {
        openWorldBossModal();
        return;
      }
      if (spot.dataset.tianji) {
        mapCtx.onOpenTianji?.();
        return;
      }
      const bid = spot.dataset.bid;
      if (bid) focusTownOnMap(bid, true);
    });
  });

  renderInMapTownPanel();
}

/**
 * 取得當前世界 Boss 狀態(向下相容代理)
 */
export function getWorldBossStatus() {
  if (!mapCtx) return calcWorldBossStatus({}, {}, {});
  return calcWorldBossStatus(mapCtx.getClassInfo(), mapCtx.getProgress(), mapCtx.getGame(), todayStr(), null, mapCtx?.getUid?.());
}

/**
 * 動態平滑更新大地圖上的 Boss 血量條與數值
 */
export function updateMapBossHpUI() {
  if (!mapCtx) return;
  const game = mapCtx.getGame();
  const classInfo = mapCtx.getClassInfo();
  const progress = mapCtx.getProgress();
  const status = calcWorldBossStatus(classInfo, progress, game, todayStr(), null, mapCtx?.getUid?.());
  const bossCfg = getActiveWorldBossConfig(classInfo);
  // 若倒數剛歸零、解鎖狀態翻轉,立即重繪整個地圖點位(解開鎖頭與封印環)
  if (lastBossUnlockedState !== null && lastBossUnlockedState !== status.unlocked) {
    renderMapSpots();
    return;
  }
  ensureBossCountdownTimer(status.isCountdown);

  const badgeEl = $('#badgeMapBoss');
  const modalCdEl = $('#lblModalBossCountdown');
  const barEl = $('#barMapBossHp');
  const valEl = $('#lblMapBossHpVal');
  const pctEl = $('#lblMapBossHpPct');
  const subEl = $('#lblMapBossSubText');

  if (badgeEl) {
    badgeEl.textContent = status.unlocked
      ? `🔥 討伐 (${status.ordersLeft}/${status.maxOrders || 3})`
      : (status.isCountdown ? `⏳ 倒數 ${formatCountdown(status.countdownMs)}` : '🔒 破印倒數');
  }
  if (modalCdEl) {
    modalCdEl.textContent = status.isCountdown
      ? `⏳ ${formatOpenAt(status.openAt)} 準時開打(剩 ${formatCountdown(status.countdownMs)})`
      : '🔥 封印已破!請點擊重新開啟戰場';
  }

  if (barEl) {
    barEl.style.width = `${status.pct}%`;
    barEl.classList.toggle('is-critical', status.curHp > 0 && status.curHp <= Math.round(status.maxHp * 0.25));
    barEl.classList.toggle('is-defeated', status.defeated);
  }
  if (valEl) {
    valEl.textContent = status.defeated ? `已平定 0/${status.maxHp}` : `${status.curHp} / ${status.maxHp}`;
  }
  if (pctEl) {
    pctEl.textContent = `${status.pct}%`;
  }
  if (subEl) {
    if (status.isCountdown) {
      subEl.textContent = `⏳ ${formatOpenAt(status.openAt)} 準時破印(剩 ${formatCountdown(status.countdownMs)})`;
    } else if (!status.unlocked) {
      subEl.textContent = status.isUnlockedDate
        ? `🔒 已破印開放・需先通關${bossCfg.unlockUnitName || '指定單元'}`
        : `需通關${bossCfg.unlockUnitName || '指定單元'}・封印倒數中`;
    } else if (status.defeated) {
      subEl.textContent = '🏆 首討告捷・全服已平定';
    } else if (status.curHp <= 100) {
      subEl.textContent = `⚡ ${bossCfg.shortName}殘血剩 ${status.curHp} HP・搶首破!`;
    } else {
      subEl.textContent = `⚔️ 圍攻中・剩餘 ${status.curHp} HP`;
    }
  }
}

/**
 * 開啟世界 Boss 前置彈窗或直接前往戰鬥頁
 */
export function openWorldBossModal() {
  if (!mapCtx) return;
  const game = mapCtx.getGame();
  const classInfo = mapCtx.getClassInfo();
  const progress = mapCtx.getProgress();
  const status = calcWorldBossStatus(classInfo, progress, game, todayStr(), null, mapCtx?.getUid?.());
  const bossCfg = getActiveWorldBossConfig(classInfo);
  const rew = calcWorldBossRewards(progress, game, classInfo, false);

  if (status.isExpired || status.isClosedMode || status.isTaotieConcluded) {
    toast('🏛️ 當前世界 Boss 活動已圓滿平定封印!下一期神獸即將現身,敬請期待。', 'info');
    return;
  }

  if (status.isPreviewMode) {
    // 尚未破印(或處於預告剪影模式):展示神秘剪影情報與戰備預告(比照饕餮預告方式)
    const annId = bossCfg.id === 'qiongqi' ? 'update_20261105_qiongqi' : 'update_20261027_worldboss';
    const contentHtml = `
      <div style="font-size:14px; line-height:1.6;">
        <div style="position:relative; border-radius:14px; overflow:hidden; margin-bottom:14px; border:1px solid rgba(245,196,81,0.35); box-shadow:0 10px 25px rgba(0,0,0,0.4);">
          <img src="${bossCfg.bg}" style="width:100%; height:180px; object-fit:cover; display:block; filter:brightness(0.7);" alt="戰鬥背景">
          <div style="position:absolute; inset:0; background:linear-gradient(to top, rgba(10,10,16,0.95) 0%, rgba(10,10,16,0.4) 60%, transparent 100%);"></div>
          
          <div style="position:absolute; bottom:12px; left:16px; right:16px; display:flex; align-items:flex-end; gap:14px;">
            <div style="width:90px; height:90px; flex-shrink:0; position:relative;">
              <img src="${bossCfg.sprite}" style="width:100%; height:100%; object-fit:contain; filter:${status.isPreviewMode ? 'brightness(0.06) contrast(1.8) drop-shadow(0 0 12px rgba(245,196,81,0.65))' : 'drop-shadow(0 0 14px rgba(245,196,81,0.75))'};" alt="${bossCfg.name}">
              ${status.isPreviewMode ? `
              <span style="position:absolute; top:28px; left:22px; width:7px; height:7px; border-radius:50%; background:#ef4444; box-shadow:0 0 8px #ef4444; animation:eyeGlow 2s infinite alternate;"></span>
              <span style="position:absolute; top:28px; left:36px; width:7px; height:7px; border-radius:50%; background:#ef4444; box-shadow:0 0 8px #ef4444; animation:eyeGlow 2s infinite alternate;"></span>` : ''}
            </div>
            <div>
              <span class="badge" style="background:#dc2626; color:#fff; font-size:11px; font-weight:800; margin-bottom:4px; display:inline-block;">${status.isCountdown ? `⏳ 破印倒數・${formatOpenAt(status.openAt)} 開打` : '🔒 上古神秘封印預告'}</span>
              <div style="font-size:20px; font-weight:900; color:var(--gold); text-shadow:0 2px 8px rgba(0,0,0,0.9);">
                ${bossCfg.name}
              </div>
              <div style="font-size:12px; color:#cbd5e1;">${bossCfg.subtitle}</div>
            </div>
          </div>
        </div>

        <div style="background:var(--bg-2); border:1px solid var(--line); border-radius:12px; padding:12px 14px; margin-bottom:12px;">
          <div style="font-weight:800; color:var(--gold); margin-bottom:6px; font-size:13px;">📜 破印開放條件:</div>
          <div style="display:flex; flex-direction:column; gap:6px; font-size:13px;">
            <div style="display:flex; justify-content:space-between; align-items:center;">
              <span>1. 完成${bossCfg.unlockUnitName || '第三單元(51-75)'}軍機策驗</span>
              <span class="badge ${status.isU3Passed ? 'badge-mint' : 'badge-rose'}">${status.isU3Passed ? '✅ 已達標' : '⏳ 尚未達標'}</span>
            </div>
            <div style="display:flex; justify-content:space-between; align-items:center;">
              <span>2. 全服破印時間</span>
              <b style="color:var(--gold);" id="lblModalBossCountdown">${status.isCountdown ? `⏳ ${formatOpenAt(status.openAt)} 準時開打(剩 ${formatCountdown(status.countdownMs)})` : (status.isUnlockedDate ? '🔥 活動開放中(請先完成上述單元)' : '⏳ 神秘封印倒數預告中')}</b>
            </div>
          </div>
        </div>

        <div style="background:var(--bg-2); border:1px solid var(--line); border-radius:12px; padding:12px 14px; margin-bottom:14px;">
          <div style="font-weight:800; color:#38bdf8; margin-bottom:6px; font-size:13px;">🎁 討伐成功全服獎勵:</div>
          <div style="display:grid; grid-template-columns:1fr 1fr; gap:8px; font-size:12px;">
            <div style="padding:6px 10px; background:var(--bg-1); border-radius:8px; border:1px solid var(--line);">
              🌾 <b>全軍糧草產量 ${rew.grainHours} 小時包</b>
            </div>
            <div style="padding:6px 10px; background:var(--bg-1); border-radius:8px; border:1px solid var(--line);">
              🧧 <b>兵符 ×${rew.baseBp}(MVP/尾刀 +${rew.killerBonusBp} 共 ${rew.baseBp + rew.killerBonusBp} 枚)</b>
            </div>
            <div style="padding:6px 10px; background:var(--bg-1); border-radius:8px; border:1px solid var(--line);">
              📜 <b>錦囊包(偷看卷×${rew.peekCount}、刪去卷×${rew.eliminateCount})</b>
            </div>
            <div style="padding:6px 10px; background:var(--bg-1); border-radius:8px; border:1px solid var(--line);">
              👑 <b>專屬稱號【${bossCfg.titles.participant}】</b>
            </div>
          </div>
        </div>

        <div style="display:flex; gap:10px; justify-content:flex-end;">
          <button type="button" class="btn btn-gold" onclick="window.showAnnouncementModal && window.showAnnouncementModal('${annId}', true)">
            📜 查看破印預告卷宗
          </button>
        </div>
      </div>
    `;
    openModal(contentHtml, { wide: true });
    return;
  }

  // 若已破印解鎖:優先透過無縫對戰容器進入戰場(免重讀);若無法開啟則向下相容跳轉 boss.html
  if (typeof mapCtx?.onLaunchBossBattle === 'function') {
    mapCtx.onLaunchBossBattle(status.bossId || 'taotie');
  } else {
    try { sessionStorage.setItem('idle_fast_return', '1'); } catch (e) { }
    window.location.href = `boss.html?v=${APP_BUILD_VERSION}&boss=${status.bossId || 'taotie'}`;
  }
}

/**
 * 渲染地圖內置戰略指令面板(城池資訊與升級/出征按鈕直接在點選城池旁就近彈出)
 */
export function renderInMapTownPanel() {
  const panel = $('#inMapTownPanel');
  if (!panel || !mapCtx) return;
  if (!selectedTownId) {
    panel.classList.add('hidden');
    return;
  }
  const b = BUILDINGS.find(x => x.id === selectedTownId);
  if (!b) return;

  const game = mapCtx.getGame();
  const dState = mapCtx.getDState();
  const classInfo = mapCtx.getClassInfo();
  const progress = mapCtx.getProgress();
  const buyMode = mapCtx.getBuyMode();
  if (!game || !dState) return;

  const st = game.buildings[b.id] || { lv: 0, star: 0 };
  const un = isUnlocked(b, dState);
  const ev = dState.evolved.has(b.id);
  const isCaptured = st.lv > 0;
  const reqs = getConquerRequirements(b, game, dState);
  const curProd = isCaptured ? buildingProd(b, st, dState) : 0;

  panel.classList.remove('hidden');

  // 計算城池旁就近定位座標(Popover 智慧貼合於城池左或右側)
  const layout = getTownLayout(b.id);
  const px = layout.x;
  const py = layout.y;
  const isLeftHalf = px < 52;
  const isBottomHalf = py > 55;

  panel.classList.toggle('panel-on-right', isLeftHalf);
  panel.classList.toggle('panel-on-left', !isLeftHalf);
  panel.classList.toggle('arrow-bottom', isBottomHalf);
  panel.classList.toggle('arrow-top', !isBottomHalf);

  if (isLeftHalf) {
    panel.style.left = `calc(${px}% + clamp(28px, 4cqw, 65px))`;
    panel.style.right = 'auto';
  } else {
    panel.style.right = `calc(${100 - px}% + clamp(28px, 4cqw, 65px))`;
    panel.style.left = 'auto';
  }

  const era2StatusForPos = getEra2Status(game, progress);
  const hasEra2Banner = isCaptured && (era2StatusForPos.b10Built || (st.star || 0) >= 5 || !!st.era2);
  if (hasEra2Banner) {
    // 當顯示第二紀元飛升橫幅時,面板高度較高,強制靠上或貼齊安全區,避免平板螢幕底部裁切或遮擋按鈕
    panel.style.top = isBottomHalf
      ? `clamp(8px, calc(${py}% - 260px), 12%)`
      : `clamp(8px, calc(${py}% - 40px), 16%)`;
  } else if (isBottomHalf) {
    // 偏下方城池(如柴桑水寨、百草藥谷、平原稻鄉):面板往上提,確保按鈕與所有內容不被地圖底緣遮擋
    panel.style.top = `clamp(8px, calc(${py}% - 150px), 36%)`;
  } else {
    panel.style.top = `clamp(8px, calc(${py}% - 30px), 44%)`;
  }
  panel.style.bottom = 'auto';

  let bodyHtml = '';
  const pauseStatus = checkConstructionStatus(classInfo);

  if (!un) {
    // 尚未開放情報
    bodyHtml = `
      <div class="panel-head">
        <div class="panel-town-info">
          <img class="panel-town-thumb" src="assets/building_${b.id}.png" alt="${b.name}">
          <div>
            <h3 class="panel-town-title">${b.icon} ${b.name} <span class="badge">敵境未開</span></h3>
            <span class="panel-specialty">${b.specialty}・${b.tierName}</span>
          </div>
        </div>
        <button class="panel-close-btn" id="btnCloseTownPanel" title="關閉面板">✕</button>
      </div>
      <p class="dim" style="font-size:12px; margin:0;">${b.desc}</p>
      <div class="panel-prod-stat">
        <span>情報解鎖條件</span>
        <b style="color:var(--text);">通過 ${b.unlockUnits} 個策驗單元</b>
      </div>
      <button class="btn btn-ghost" style="width:100%; min-height:42px;" onclick="document.querySelector('[data-tab=quiz]').click()">
        📜 前往軍機策驗考核
      </button>`;
  } else if (!isCaptured) {
    // 待出征收復
    let blockerReason = '';
    if (!reqs.prereqMet) {
      blockerReason = `前置連通未足:需先收復 ${reqs.missingPrereqs.join('、')}`;
    } else if (!reqs.tallyMet) {
      blockerReason = `尚缺 ${reqs.tallyNeed - reqs.tallyHave} 兵符(每日複習測驗可得)`;
    } else if (!reqs.grainMet) {
      blockerReason = `糧草輜重不足,尚差 ${fmt(reqs.grainNeed - reqs.grainHave)}`;
    }

    const canConquerNow = reqs.ready && pauseStatus.allowed;

    bodyHtml = `
      <div class="panel-head">
        <div class="panel-town-info">
          <img class="panel-town-thumb" src="assets/building_${b.id}.png" alt="${b.name}">
          <div>
            <h3 class="panel-town-title">
              ${b.icon} ${b.name}
              <span class="badge ${canConquerNow ? 'badge-accent' : ''}">${!pauseStatus.allowed ? '🌙 課後休整' : (reqs.ready ? '⚔️ 兵臨城下' : '🔒 待開拓')}</span>
            </h3>
            <span class="panel-specialty">${b.specialty}・${b.tierName}</span>
          </div>
        </div>
        <button class="panel-close-btn" id="btnCloseTownPanel" title="關閉面板">✕</button>
      </div>
      <p class="dim" style="font-size:12px; margin:0;">${b.desc}</p>
      <div class="panel-prod-stat">
        <span>收復後基準產能</span>
        <b class="panel-prod-val">+${fmt(b.baseProd)} 糧草/秒</b>
      </div>
      <div class="conquest-req-list" style="margin:2px 0;">
        ${b.requires && b.requires.length > 0 ? `
          <div class="req-item ${reqs.prereqMet ? 'met' : 'unmet'}">
            <span>前置商道:<b>${b.requires.map(rid => BUILDINGS.find(x => x.id === rid)?.name).filter(Boolean).join(' 或 ')}</b></span>
            <span class="req-tag">${reqs.prereqMet ? '✔ 已連通' : '❌ 未連通'}</span>
          </div>` : ''}
        <div class="req-item ${reqs.tallyMet ? 'met' : 'unmet'}">
          <span><img src="assets/icon_tally.jpg" class="res-mini-icon" alt="兵符">調兵兵符:<b>${reqs.tallyNeed} 枚</b>(持有:${reqs.tallyHave})</span>
          <span class="req-tag">${reqs.tallyMet ? '✔ 齊備' : `❌ 缺 ${reqs.tallyNeed - reqs.tallyHave}`}</span>
        </div>
        <div class="req-item ${reqs.grainMet ? 'met' : 'unmet'}">
          <span><img src="assets/icon_grain.jpg" class="res-mini-icon" alt="糧草">出兵糧草:<b>${fmt(reqs.grainNeed)}</b>(持有:${fmt(reqs.grainHave)})</span>
          <span class="req-tag">${reqs.grainMet ? '✔ 充足' : `❌ 缺 ${fmt(reqs.grainNeed - reqs.grainHave)}`}</span>
        </div>
      </div>
      <button class="btn-conquer ${canConquerNow ? 'btn-conquer-active' : ''} ${!pauseStatus.allowed ? 'btn-paused' : ''}" id="btnInMapConquer" ${canConquerNow ? '' : 'disabled'} title="${!pauseStatus.allowed ? esc(pauseStatus.reason) : ''}">
        <span>${!pauseStatus.allowed ? '🌙 課後休整中・暫停出征' : (reqs.ready ? '⚔️ 頒布兵符・立即出兵收復!' : '⚠️ 戰備未足・尚不可出兵')}</span>
        <span class="conquer-sub">${!pauseStatus.allowed ? esc(pauseStatus.reason) : (reqs.ready ? `收復後立刻獲取【${b.specialty}】專屬生產力` : blockerReason)}</span>
      </button>`;
  } else {
    // 已收復,可連續升級與升星
    let amt = buyMode;
    if (buyMode === 'max') amt = Math.max(1, maxAffordable(b, st.lv, game.coins, dState?.costDiscount));
    const cost = bulkCost(b, st.lv, amt, dState?.costDiscount);
    const sCost = starCost(st.star);
    const sNext = nextStarMult(st.star);
    const nextProd = buildingProd(b, { ...st, lv: st.lv + amt }, dState);
    const mNext = nextMilestone(st.lv);
    const mPct = mNext ? (st.lv / mNext) * 100 : 100;

    const canLvup = pauseStatus.allowed && game.coins >= cost;
    const canStar = pauseStatus.allowed && game.blueprints >= sCost;

    const isEra2 = !!st.era2;
    const imgSrc = isEra2 ? `assets/building_${b.id}_era2.png` : `assets/building_${b.id}.png`;
    const displayName = isEra2 ? (ERA2_TOWN_NAMES[b.id] || b.name) : b.name;
    const era2Status = getEra2Status(game, progress);
    const era2Info = getEra2UpgradeInfo(b.id, game, progress);
    const b10Built = era2Status.b10Built;

    bodyHtml = `
      <div class="panel-head">
        <div class="panel-town-info">
          <img class="panel-town-thumb ${isEra2 ? 'era2-thumb' : ''}" src="${imgSrc}" alt="${displayName}">
          <div>
            <h3 class="panel-town-title">
              ${b.icon} ${displayName}
              <span class="badge">Lv.${st.lv}</span>
              ${st.star > 0 ? `<span class="badge badge-accent">★${st.star}</span>` : ''}
              ${isEra2 ? '<span class="badge" style="background:linear-gradient(135deg, #f59e0b, #d97706); color:#fff; font-weight:800; box-shadow:0 1px 4px rgba(245,158,11,0.25);">第二紀元・重鑄</span>' : (ev ? '<span class="badge" style="background:#8b5cf6; color:#fff;">進化 x5</span>' : '')}
            </h3>
            <span class="panel-specialty">${b.specialty}・${b.tierName}</span>
          </div>
        </div>
        <button class="panel-close-btn" id="btnCloseTownPanel" title="關閉面板">✕</button>
      </div>

      <div class="panel-prod-stat">
        <div>
          <div style="font-size:11px; color:var(--text-dim);">當前每秒產出</div>
          <b class="panel-prod-val"><img src="assets/icon_grain.jpg" class="res-mini-icon" alt="糧草">${fmt(curProd)}/秒</b>
        </div>
        <div style="text-align:right;">
          <div style="font-size:11px; color:var(--text-dim);">擴軍 +${amt} 預估</div>
          <b style="color:#10b981; font-size:14px;">+${fmt(nextProd - curProd)}/秒</b>
        </div>
      </div>

      <div class="b-ms" style="margin:0;">
        <div class="progress" style="height:6px;"><i style="width:${mPct}%"></i></div>
        <span style="font-size:11px;">${mNext ? `距下個軍階(產量x2)還差 ${mNext - st.lv} 級` : '已達最高軍階'}</span>
      </div>

      <div class="panel-actions">
        <button class="btn btn-inmap-lvup ${!pauseStatus.allowed ? 'btn-paused' : ''}" id="btnInMapLvup" data-bid="${b.id}" ${canLvup ? '' : 'disabled'} title="${!pauseStatus.allowed ? esc(pauseStatus.reason) : ''}">
          <span>${!pauseStatus.allowed ? '駐防擴軍 (🌙休整中)' : `駐防擴軍 +${amt}`}</span>
          <small class="num"><img src="assets/icon_grain.jpg" class="res-mini-icon" alt="糧草">${fmt(cost)}</small>
        </button>
        <button class="btn btn-inmap-star ${!pauseStatus.allowed ? 'btn-paused' : ''}" id="btnInMapStar" data-bid="${b.id}" ${canStar ? '' : 'disabled'} title="${!pauseStatus.allowed ? esc(pauseStatus.reason) : `下一星級產量 x${sNext}`}">
          <span>${!pauseStatus.allowed ? '加官升星 (🌙休整中)' : `加官升星 x${sNext}`}</span>
          <small class="num"><img src="assets/icon_tally.jpg" class="res-mini-icon" alt="兵符">${sCost}</small>
        </button>
      </div>

      ${!isEra2 && (b10Built || st.star >= 5) ? `
        <div class="era2-panel-banner ${era2Info.canUpgrade ? 'ready' : ''}" style="margin-top:8px; padding:8px 10px; background:rgba(245,158,11,0.06); border:1px solid rgba(245,158,11,0.25); border-radius:8px;">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
            <div style="font-weight:800; font-size:12px; color:var(--text); display:flex; align-items:center; gap:6px;">
              <span>🌟 第二紀元飛升:<b>【${era2Info.era2Name}】</b></span>
            </div>
            <span class="badge ${era2Info.canUpgrade ? 'badge-accent' : ''}" style="font-size:10px;">${era2Info.isUnlocked ? (era2Info.canUpgrade ? '✔ 可昇華' : '前置受阻') : '四大誓約未成'}</span>
          </div>
          <div style="font-size:11px; color:var(--text-mute, #64748b); margin-bottom:6px; line-height:1.4;">
            ${era2Info.canUpgrade
          ? '★5 滿星已達標!消耗 25 兵符即可完成昇華,基底時代重鑄並更換第二紀元傳世手辦!'
          : `飛升前置:${era2Info.lockReason}`}
          </div>
          <button type="button" class="btn btn-inmap-era2 ${!pauseStatus.allowed ? 'btn-paused' : ''} ${era2Info.canUpgrade ? 'pulse' : 'locked-action'}" id="btnInMapEra2" data-bid="${b.id}" title="${!pauseStatus.allowed ? esc(pauseStatus.reason) : esc(era2Info.lockReason)}" style="width:100%; margin:0;">
            <span>${!pauseStatus.allowed ? `🌙 課後休整中・暫停飛升` : (era2Info.canUpgrade ? `✨ 消耗 25 兵符・昇華為【${era2Info.era2Name}】!` : `${era2Info.lockReason || '尚未滿足飛升條件'}(點擊查看誓約)`)}</span>
            <small class="num"><img src="assets/icon_tally.jpg" class="res-mini-icon" alt="兵符">${ERA2_TALLY_COST}</small>
          </button>
        </div>
      ` : ''}`;
  }

  panel.innerHTML = bodyHtml;

  // 綁定面板內出征與連續升級按鈕
  bind($('#btnCloseTownPanel'), 'click', (e) => {
    e.stopPropagation();
    panel.classList.add('hidden');
    selectedTownId = null;
    renderMapSpots();
  });

  bind($('#btnInMapConquer'), 'click', (e) => {
    e.stopPropagation();
    const ps = checkConstructionStatus(classInfo);
    if (!ps.allowed) return toast(ps.reason, 'warn', 4500);

    if (canConquer(b, game, dState)) {
      conquerTown(b, game, dState);
      toast(`⚔️ 旗開得勝!三軍成功收復【${b.name}】!專屬特產【${b.specialty}】納入版圖!`, 'success');
      mapCtx.onBuildChange?.();
      if (['b3', 'b8', 'b10'].includes(b.id)) {
        mapCtx.onBroadcastConquer?.(b);
      }
    } else {
      toast('戰備尚未齊全,無法頒布出兵!', 'error');
    }
  });

  // 專屬連續升級事件(直接就地刷新面板,無限連點升級)
  bind($('#btnInMapLvup'), 'click', (e) => {
    e.stopPropagation();
    const ps = checkConstructionStatus(classInfo);
    if (!ps.allowed) return toast(ps.reason, 'warn', 4500);

    let amt = buyMode;
    if (buyMode === 'max') amt = Math.max(1, maxAffordable(b, st.lv, game.coins, dState?.costDiscount));
    const cost = bulkCost(b, st.lv, amt, dState?.costDiscount);
    if (game.coins >= cost) {
      game.coins -= cost;
      st.lv += amt;
      const townName = st.era2 ? (ERA2_TOWN_NAMES[b.id] || b.name) : b.name;
      toast(`【${townName}】駐防擴軍 +${amt} 級!`, 'success');
      // 即時重新計算派生狀態與畫面
      const newD = derive(progress, classInfo, game);
      mapCtx.setDState(newD);
      renderInMapTownPanel();
      renderMapSpots();
      mapCtx.onStateChange?.();
    } else {
      toast('糧草不足,請巡營催糧或稍候輜重!', 'error');
    }
  });

  // 專屬連續升星事件
  bind($('#btnInMapStar'), 'click', (e) => {
    e.stopPropagation();
    const ps = checkConstructionStatus(classInfo);
    if (!ps.allowed) return toast(ps.reason, 'warn', 4500);

    const sCost = starCost(st.star);
    const mult = nextStarMult(st.star);
    if (game.blueprints >= sCost) {
      game.blueprints -= sCost;
      st.star += 1;
      const townName = st.era2 ? (ERA2_TOWN_NAMES[b.id] || b.name) : b.name;
      toast(`👑【${townName}】加官進爵升星成功!產量 x${mult}`, 'success');
      const newD = derive(progress, classInfo, game);
      mapCtx.setDState(newD);
      renderInMapTownPanel();
      renderMapSpots();
      mapCtx.onStateChange?.();
    } else {
      toast(`兵符不足,加官進爵需 ${sCost} 枚!前往軍機策驗考核累積!`, 'error');
    }
  });

  // 專屬第二紀元昇華事件(支援平板觸控點選:若尚未達標則彈出說明或提示,不阻斷點擊回饋)
  bind($('#btnInMapEra2'), 'click', (e) => {
    e.stopPropagation();
    const ps = checkConstructionStatus(classInfo);
    if (!ps.allowed) return toast(`🌙 課後休整管制中:${ps.reason}`, 'warn', 4500);

    const info = getEra2UpgradeInfo(b.id, game, progress);
    if (!info.canUpgrade) {
      toast(`🔒 尚未達成飛升條件:${info.lockReason}`, 'info', 4000);
      if (!info.isUnlocked && typeof window.showEra2IntroModal === 'function') {
        window.showEra2IntroModal();
      }
      return;
    }

    const res = evolveTownToEra2(b.id, game, progress);
    if (res.ok) {
      toast(`✨ 九州同慶!【${b.name}】基底重鑄昇華為第二紀元【${res.townName}】!星級重鑄歸零,全新天朝長征啟航!`, 'success', 6000);
      const newD = derive(progress, classInfo, game);
      mapCtx.setDState(newD);
      renderInMapTownPanel();
      renderMapSpots();
      // 🌟 觸發破空神光(Evolution Burst)震撼光柱特效
      const spotEl = document.querySelector(`.map-spot[data-bid="${b.id}"]`);
      if (spotEl) {
        spotEl.classList.add('era2-burst');
        setTimeout(() => spotEl.classList.remove('era2-burst'), 1800);
      }
      if (mapCtx.onEra2Upgrade) {
        mapCtx.onEra2Upgrade();
      } else {
        mapCtx.onStateChange?.();
        mapCtx.onBuildChange?.();
      }
    } else {
      toast(res.reason || '尚未達成第二紀元昇華條件', 'error');
    }
  });
}