-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2509 lines (2322 loc) · 93.4 KB
/
Copy pathscript.js
File metadata and controls
2509 lines (2322 loc) · 93.4 KB
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
let chartInstance = null;
let radarChartInstance = null;
let subscoreMiniChartInstance = null;
let towerImpactMiniChartInstance = null;
let ACTIVE_API_BASE = window.__CR_API_BASE__ || "http://127.0.0.1:7295";
const ASSET_VARIANT_BASE = "https://raw.githubusercontent.com/RoyaleAPI/cr-api-assets/master/cards/";
const REV_KEY = "cr_deck_revisions_v1";
const SELECT_GUARD_MS = 140;
function fmtPct(value, digits = 1) {
const n = Number(value || 0);
if (!Number.isFinite(n)) return "0.0";
return n.toFixed(digits);
}
function normalizeBase(base) {
return String(base || "").trim().replace(/\/+$/, "");
}
function apiUrl(base, endpoint) {
const cleanBase = normalizeBase(base);
const cleanEndpoint = `/${String(endpoint || "").replace(/^\/+/, "")}`;
if (cleanBase.endsWith("/api")) return `${cleanBase}${cleanEndpoint}`;
return `${cleanBase}/api${cleanEndpoint}`;
}
function getApiBaseCandidates() {
const out = [];
const push = (v) => {
const value = normalizeBase(v);
if (!value) return;
if (!out.includes(value)) out.push(value);
};
push(ACTIVE_API_BASE);
push("/api");
push(location.origin === "null" ? "" : location.origin);
push("https://clashroyaleanalyticswebapp.vercel.app/api");
return out;
}
const EVO_CARD_SLUGS = new Set([
"archers", "baby-dragon", "barbarians", "bats", "battle-ram",
"bomber", "cannon", "dart-goblin", "electro-dragon", "executioner",
"firecracker", "furnace", "giant-snowball", "goblin-barrel", "goblin-cage",
"goblin-drill", "goblin-giant", "hunter", "ice-spirit",
"inferno-dragon", "knight", "lumberjack", "mega-knight",
"minion-horde", "musketeer", "princess",
"mortar", "pekka", "royal-ghost", "royal-giant",
"royal-hogs", "royal-recruits", "skeleton-army", "skeleton-barrel", "skeletons",
"tesla", "valkyrie", "wall-breakers", "witch", "wizard", "zap"
]);
const HERO_CARD_SLUGS = new Set([
"barbarian-barrel", "giant", "goblins", "ice-golem", "knight",
"magic-archer", "mega-minion", "mini-pekka", "musketeer", "wizard", "balloon",
"dark-prince", "bowler", "tombstone"
]);
const CHAMPION_CARD_SLUGS = new Set([
"archer-queen", "boss-bandit", "goblinstein", "golden-knight",
"little-prince", "mighty-miner", "monk", "skeleton-king"
]);
const EVO_FORCE_OFF_SLUGS = new Set(["the-log"]);
const HERO_ART_OVERRIDES = {
"Balloon": [
"/assets/hero/balloon-hero-cover.png",
"assets/hero/balloon-hero-cover.png"
],
"Dark Prince": [
"/assets/hero/dark-prince-hero-cover.png?v=20260517e",
"assets/hero/dark-prince-hero-cover.png?v=20260517e"
],
"Bowler": [
"/assets/hero/bowler-hero-cover.png?v=20260517e",
"assets/hero/bowler-hero-cover.png?v=20260517e"
],
"Tombstone": [
"/assets/hero/tombstone-hero-cover.png?v=20260603d",
"assets/hero/tombstone-hero-cover.png?v=20260603d"
]
};
const EVO_ART_OVERRIDES = {
"Minion Horde": [
"https://cdn.royaleapi.com/static/img/cards-150/minion-horde-ev1.png"
],
"Princess": [
"/assets/evo-princess-cover.png?v=20260603d",
"assets/evo-princess-cover.png?v=20260603d"
]
};
const EVO_ABILITY_INFO = {
"barbarians": {
cycles: 1,
effects: ["Gain Rage-like boosts after attacking.", "Increased attack speed.", "Increased movement speed."]
},
"electro-dragon": {
cycles: 1,
effects: ["Lightning chains continuously between nearby enemies.", "Longer chain potential than normal Electro Dragon."]
},
"executioner": {
cycles: 1,
effects: ["Deals bonus damage at close range.", "Close-range attacks apply knockback."]
},
"goblin-cage": {
cycles: 1,
effects: ["Pulls a nearby ground troop toward the cage.", "Trapped troop is attacked by the Brawler."]
},
"goblin-giant": {
cycles: 1,
effects: ["Spawns Goblins after dropping below a health threshold."]
},
"mega-knight": {
cycles: 1,
effects: ["Punches launch enemies forward.", "Can throw troops toward enemy tower."]
},
"minion-horde": {
cycles: 1,
effects: ["First hit grants temporary invisibility/protection effect."]
},
"pekka": {
cycles: 1,
effects: ["Heals after getting kills.", "Can temporarily overheal."]
},
"royal-giant": {
cycles: 1,
effects: ["Cannon shots create damaging shockwaves.", "Shockwaves apply knockback."]
},
"royal-recruits": {
cycles: 1,
effects: ["Gain charge attacks after shields break."]
},
"witch": {
cycles: 1,
effects: ["Heals when nearby Skeletons die."]
},
"wizard": {
cycles: 1,
effects: ["Shield explodes when broken.", "Explosion deals splash damage and applies knockback."]
},
"archers": {
cycles: 2,
effects: ["Periodically fire charged long-range arrows.", "Charged arrows have increased range, higher damage, and pierce enemies."]
},
"baby-dragon": {
cycles: 2,
effects: ["Creates a wind field while attacking.", "Wind field speeds up allies and slows enemies."]
},
"bats": {
cycles: 2,
effects: ["Heal themselves when attacking.", "Can temporarily overheal beyond base HP."]
},
"battle-ram": {
cycles: 2,
effects: ["Ram repeatedly hits and knocks back enemies while alive.", "Chains charge hits and spawns evolved Barbarians after destruction."]
},
"bomber": {
cycles: 2,
effects: ["Bomb bounces after the first explosion.", "Can damage secondary targets/groups."]
},
"dart-goblin": {
cycles: 2,
effects: ["Attacks apply poison damage over time.", "Poison effect stacks with repeated hits."]
},
"firecracker": {
cycles: 2,
effects: ["Rockets leave sparks on impact.", "Sparks deal damage over time and slow enemies."]
},
"hunter": {
cycles: 2,
effects: ["Nets the closest enemy.", "Grounded effect temporarily removes flying from air troops."]
},
"ice-spirit": {
cycles: 2,
effects: ["Applies an initial freeze.", "Applies a delayed secondary freeze."]
},
"knight": {
cycles: 2,
effects: ["Takes reduced damage while moving."]
},
"lumberjack": {
cycles: 2,
effects: ["After death, Rage remains active.", "A spirit version continues fighting temporarily."]
},
"musketeer": {
cycles: 2,
effects: ["Periodically fires powerful long-range sniper shots."]
},
"princess": {
cycles: 2,
effects: ["First attack and every third attack fire icy arrows that slow enemies in range.", "Upon defeat, Princess leaves arrows behind that slow and damage nearby enemies."]
},
"royal-ghost": {
cycles: 2,
effects: ["Spawns ghost soldiers while invisible."]
},
"royal-hogs": {
cycles: 2,
effects: ["Hogs temporarily fly.", "They crash down with landing damage."]
},
"skeleton-army": {
cycles: 2,
effects: ["Skeleton General protects the Skeleton Army.", "Skeletons stay protected while the General is alive."]
},
"skeleton-barrel": {
cycles: 2,
effects: ["Drops two barrels instead of one.", "Both barrels spawn Skeletons."]
},
"skeletons": {
cycles: 2,
effects: ["Each successful hit spawns another Skeleton.", "Maximum of 8 cloned Skeletons can exist at once."]
},
"valkyrie": {
cycles: 2,
effects: ["Spin attacks pull enemies inward."]
},
"wall-breakers": {
cycles: 2,
effects: ["Continue moving after first explosion.", "Can explode multiple times."]
},
"cannon": {
cycles: 2,
effects: ["Drops bombs around itself when deployed.", "Deals area damage on spawn."]
},
"furnace": {
cycles: 2,
effects: ["Spawns Fire Spirits faster than normal Furnace."]
},
"giant-snowball": {
cycles: 2,
effects: ["Snowball rolls forward instead of normal knockback.", "Pulls enemies inward while moving."]
},
"goblin-barrel": {
cycles: 2,
effects: ["Throws one real barrel and one fake barrel."]
},
"goblin-drill": {
cycles: 2,
effects: ["Reburrows after the initial attack.", "Reappears for another attack cycle."]
},
"mortar": {
cycles: 2,
effects: ["Mortar shells spawn Goblins on impact."]
},
"tesla": {
cycles: 2,
effects: ["Emits electric stun pulses when surfacing/deploying."]
},
"zap": {
cycles: 2,
effects: ["Hits once initially, then adds one extra electric pulse.", "Total of 2 hits with multiple stun/reset activations."]
}
};
const HERO_ABILITY_INFO = {
"mini-pekka": {
cost: 1,
ability: "Breakfast Boost",
effects: ["Cooks pancakes while on the field (charges with every hit).", "Activating consumes pancakes to instantly level up mid-fight with major stat boosts (one-time use)."]
},
"wizard": {
cost: 1,
ability: "Fiery Flight",
effects: ["Launches into the air to avoid ground melee attacks.", "Summons fire tornadoes that deal continuous area damage below."]
},
"barbarian-barrel": {
cost: 1,
ability: "Rowdy Reroll",
effects: ["After barrel break, deploys a second barrel down the lane.", "Heals the Barbarian and deals new trample damage (one-time use)."]
},
"goblins": {
cost: 1,
ability: "Banner Brigade",
effects: ["When only one Goblin remains, activates a battle banner.", "Immediately calls a fresh wave of Goblin reinforcements."]
},
"magic-archer": {
cost: 2,
ability: "Triple Threat",
effects: ["Dashes backward out of danger while projecting a decoy clone.", "Next attack fires a heavy triple-arrow spread."]
},
"knight": {
cost: 2,
ability: "Triumphant Taunt",
effects: ["Gains a defensive shield.", "Forces nearby enemies to retarget and focus him."]
},
"giant": {
cost: 2,
ability: "Heroic Hurl",
effects: ["Grabs the highest-HP nearby enemy unit.", "Throws it backward and deals heavy impact damage."]
},
"ice-golem": {
cost: 2,
ability: "Snowstorm",
effects: ["Creates a blizzard centered on himself.", "Continuously slows and damages enemies before freezing them."]
},
"mega-minion": {
cost: 2,
ability: "Wounding Warp",
effects: ["Teleports to the lowest-HP nearby enemy unit.", "Deals heavy AoE burst damage on arrival."]
},
"balloon": {
cost: 2,
ability: "Coffin Cadet",
effects: ["Spawns a flying Skeletrooper from the basket.", "Skeletrooper dives into nearest defender for heavy crash damage."]
},
"bowler": {
cost: 2,
ability: "Stone Swish",
effects: ["Roots in place and launches high-powered boulders.", "Boulders travel with amplified long range."]
},
"musketeer": {
cost: 3,
ability: "Trusty Turret",
effects: ["Drops a fast-firing automated defense turret.", "Turret tanks and attacks both air and ground targets."]
},
"dark-prince": {
cost: 3,
ability: "Destructive Dismount",
effects: ["Leaps off mount with heavy AoE smash and keeps fighting on foot.", "Rhino mount continues as a separate building-targeting charger."]
},
"tombstone": {
cost: 6,
ability: "Regal Revival",
effects: ["Destroys the Tombstone and raises the Tomb Queen from the earth.", "Tomb Queen spawns Skeletons, becomes a massive high-HP tank, and targets buildings."]
}
};
const CHAMPION_ABILITY_INFO = {
"mighty-miner": {
cost: 1,
ability: "Bomb Rush",
effects: ["Burrows and tunnels horizontally to the mirrored position in the opposite lane.", "Leaves a ticking area bomb at his original spot to clear swarms and support resets."]
},
"skeleton-king": {
cost: 2,
ability: "Soul Summon",
effects: ["Collects up to 14 souls from dying units on the field.", "Spends souls to summon a large ring of Skeletons around him."]
},
"archer-queen": {
cost: 1,
ability: "Cloaking Cape",
effects: ["Becomes invisible and untargetable for 3.5 seconds.", "Massively increases attack speed while cloaked for high safe DPS."]
},
"golden-knight": {
cost: 1,
ability: "Dashing Dash",
effects: ["Chain-dashes through up to 10 enemy targets ahead.", "Dash is invulnerable and stops early on Crown Tower hit or when no target is in range."]
},
"monk": {
cost: 1,
ability: "Pensive Protection",
effects: ["Channels a 4-second defensive stance with 80% incoming damage reduction.", "Reflects enemy ranged projectiles, including heavy spells, back toward the opponent."]
},
"little-prince": {
cost: 2,
ability: "Guardian Assist",
effects: ["Calls in Guardienne directly in front of him.", "Entry causes a wide horizontal knockback that damages and shoves ground troops away."]
},
"goblinstein": {
cost: 2,
ability: "High-Voltage Link",
effects: ["Activates an electrical beam between the Doctor and the Monster.", "Enemies caught near or crossing the link take continuous shock damage for 4 seconds."]
},
"boss-bandit": {
cost: 1,
ability: "Getaway Grenade",
effects: ["Drops a smoke grenade, turns invisible briefly, and teleports 6 tiles backward to break lock-on.", "Sets up another heavy invulnerable dash; max 2 ability uses per deployment."]
}
};
const SLOT_RULES = [
{ id: 0, type: "evo", label: "Slot 1 - Evo Only" },
{ id: 1, type: "wild", label: "Slot 2 - Wild (Evo/Hero/Champion)" },
{ id: 2, type: "hero", label: "Slot 3 - Hero/Champion" },
{ id: 3, type: "normal", label: "Slot 4 - Normal" },
{ id: 4, type: "normal", label: "Slot 5 - Normal" },
{ id: 5, type: "normal", label: "Slot 6 - Normal" },
{ id: 6, type: "normal", label: "Slot 7 - Normal" },
{ id: 7, type: "normal", label: "Slot 8 - Normal" }
];
const TOWER_TROOPS = [
{ id: "tower_princess", label: "Tower Princess" },
{ id: "royal_chef", label: "Royal Chef" },
{ id: "cannoneer", label: "Cannoneer" },
{ id: "dagger_duchess", label: "Dagger Duchess" }
];
const TOWER_TROOP_ICONS = {
tower_princess: "/assets/towers/tower-princess.png",
royal_chef: "/assets/towers/royal-chef.png",
cannoneer: "/assets/towers/cannoneer.png",
dagger_duchess: "/assets/towers/dagger-duchess.png"
};
const META_PRESETS = [
{ name: "Hog EQ Cycle", cards: [26000021, 26000014, 26000012, 26000010, 26000031, 28000014, 28000000, 27000000], towerTroop: "tower_princess" },
{ name: "Giant Beatdown", cards: [26000003, 26000007, 26000015, 26000024, 26000019, 28000000, 28000017, 26000010], towerTroop: "royal_chef" },
{ name: "X-Bow Siege", cards: [27000008, 26000002, 26000010, 26000001, 28000004, 28000017, 26000031, 28000010], towerTroop: "cannoneer" },
{ name: "Lava Loon", cards: [26000029, 26000004, 26000022, 26000015, 26000011, 28000000, 28000008, 26000010], towerTroop: "tower_princess" },
{ name: "Hyper Bait", cardNames: ["Goblin Barrel", "Princess", "Dart Goblin", "Goblin Gang", "Rocket", "The Log", "Knight", "Inferno Tower"], towerTroop: "dagger_duchess" },
{ name: "Classic Golem Beatdown", cardNames: ["Golem", "Night Witch", "Baby Dragon", "Lumberjack", "Tornado", "Lightning", "Barbarian Barrel", "Mega Minion"], towerTroop: "royal_chef" },
{ name: "Royal Hogs EQ Cycle", cardNames: ["Royal Hogs", "Earthquake", "Archer Queen", "Cannon", "Fire Spirit", "The Log", "Skeletons", "Musketeer"], towerTroop: "tower_princess" },
{ name: "PEKKA Bridge Spam", cardNames: ["P.E.K.K.A", "Bandit", "Royal Ghost", "Battle Ram", "Electro Wizard", "Poison", "Zap", "Magic Archer"], towerTroop: "cannoneer" }
];
const state = {
cards: [],
filteredCards: [],
poolTypeFilter: "all",
poolSortFilter: "az",
deck: Array(8).fill(null),
drag: null,
selectedTowerTroop: "tower_princess",
latestAnalysis: null,
revisions: [],
wildSlotModes: {},
lastPoolSelect: { cardId: null, at: 0 },
analysisRunId: 0,
feedbackQueueBusy: false
};
let analysisLayoutFrame = null;
const FEEDBACK_QUEUE_KEY = "royalepro_ml_feedback_queue_v1";
const OPP_ARCHETYPE_NORMALIZE = new Map([
["cycle", "fast_cycle"],
["fast cycle", "fast_cycle"],
["hog cycle", "fast_cycle"],
["hog 26", "fast_cycle"],
["hog 2.6", "fast_cycle"],
["hog eq", "fast_cycle"],
["hog earthquake", "fast_cycle"],
["miner wb", "fast_cycle"],
["miner wall breakers", "fast_cycle"],
["drill cycle", "fast_cycle"],
["xbow cycle", "fast_cycle"],
["x-bow cycle", "fast_cycle"],
["beatdown", "beatdown"],
["air beatdown", "air_beatdown"],
["air_beatdown", "air_beatdown"],
["lava", "air_beatdown"],
["lava loon", "air_beatdown"],
["lavaloon", "air_beatdown"],
["log bait", "log_bait"],
["log_bait", "log_bait"],
["classic log bait", "log_bait"],
["hyper bait", "hyper_bait"],
["hyper_bait", "hyper_bait"],
["spam bait", "hyper_bait"],
["bait", "log_bait"],
["spell bait", "log_bait"],
["control", "control_counterpush"],
["control/counter-push", "control_counterpush"],
["counterpush", "control_counterpush"],
["counter push", "control_counterpush"],
["splashyard", "control_counterpush"],
["miner poison", "control_counterpush"],
["giant graveyard", "control_counterpush"],
["graveyard control", "control_counterpush"],
["siege", "siege"],
["bridge spam", "bridge_spam"],
["pekka bridge spam", "bridge_spam"],
["pekka bridgespam", "bridge_spam"],
["bridge_spam", "bridge_spam"],
["bridgespam", "bridge_spam"],
["split lane", "split_lane_pressure"],
["split-lane", "split_lane_pressure"],
["split_lane_pressure", "split_lane_pressure"],
["recruits hogs", "split_lane_pressure"],
["3m", "split_lane_pressure"],
["three musketeers", "split_lane_pressure"],
["no wincon", "midladder_no_wincon"],
["no win condition", "midladder_no_wincon"],
["quad tank", "midladder_overcommit"],
["overcommit", "midladder_overcommit"],
["spell turtle", "midladder_spell_turtle"],
["pocket rocket", "midladder_spell_turtle"],
["freeze trap", "midladder_freeze_trap"],
["lumberloon freeze", "midladder_freeze_trap"],
["balloon freeze", "midladder_freeze_trap"],
["e golem healer", "midladder_overcommit"],
["egolem healer", "midladder_overcommit"],
["mega knight witch wizard", "midladder_overcommit"],
["mk witch wizard", "midladder_overcommit"],
["ebarbs rage", "midladder_overcommit"],
["mega knight bait", "midladder_meta_hodgepodge"],
["mk bait", "midladder_meta_hodgepodge"],
["meta hodgepodge", "midladder_meta_hodgepodge"],
["top deck copier", "midladder_meta_hodgepodge"],
["offmeta", "custom_offmeta"],
["custom", "custom_offmeta"],
["custom_offmeta", "custom_offmeta"]
]);
const deckSlotsEl = document.getElementById("deckSlots");
const towerTroopsEl = document.getElementById("towerTroops");
const cardPoolEl = document.getElementById("cardPool");
const statusEl = document.getElementById("status");
const searchEl = document.getElementById("searchInput");
const cardTypeFilterEl = document.getElementById("cardTypeFilter");
const cardSortFilterEl = document.getElementById("cardSortFilter");
const simDeckSelect = document.getElementById("simDeckSelect");
const weaknessPanelEl = document.getElementById("weaknessPanel");
document.getElementById("analyzeBtn").addEventListener("click", analyzeDeck);
document.getElementById("optimizeTowerBtn").addEventListener("click", optimizeTowerTroop);
document.getElementById("clearBtn").addEventListener("click", clearDeck);
document.getElementById("simRunBtn").addEventListener("click", runMatchupSim);
document.getElementById("saveRevisionBtn").addEventListener("click", saveRevision);
document.getElementById("exportRevisionBtn").addEventListener("click", exportSnapshot);
document.getElementById("mlWonBtn")?.addEventListener("click", () => submitMlFeedback(true));
document.getElementById("mlLostBtn")?.addEventListener("click", () => submitMlFeedback(false));
searchEl.addEventListener("input", onSearch);
cardTypeFilterEl?.addEventListener("change", onCardTypeFilterChange);
cardSortFilterEl?.addEventListener("change", onCardSortFilterChange);
document.querySelectorAll(".weakness-btn").forEach((btn) => btn.addEventListener("click", () => runWeaknessProfile(btn.dataset.profile)));
window.addEventListener("resize", () => scheduleAnalysisLayout());
boot();
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function loadFeedbackQueue() {
try {
const raw = localStorage.getItem(FEEDBACK_QUEUE_KEY);
const list = raw ? JSON.parse(raw) : [];
return Array.isArray(list) ? list : [];
} catch {
return [];
}
}
function saveFeedbackQueue(queue) {
try {
localStorage.setItem(FEEDBACK_QUEUE_KEY, JSON.stringify(Array.isArray(queue) ? queue : []));
} catch {
// Ignore storage failures.
}
}
function enqueueFeedback(payload) {
const queue = loadFeedbackQueue();
queue.push({ payload, at: Date.now(), tries: 0 });
saveFeedbackQueue(queue);
}
async function postMlFeedbackPayload(payload) {
const res = await fetch(apiUrl(ACTIVE_API_BASE, "ml/feedback"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload)
});
const data = await res.json();
if (!res.ok || !data?.ok) {
const err = new Error(data?.error || data?.message || `HTTP ${res.status}`);
err.retryable = data?.retryable !== false;
throw err;
}
}
async function flushFeedbackQueue() {
if (state.feedbackQueueBusy) return;
state.feedbackQueueBusy = true;
try {
const queue = loadFeedbackQueue();
if (!queue.length) return;
const nextQueue = [];
for (const item of queue) {
try {
await postMlFeedbackPayload(item.payload);
} catch (err) {
const tries = Number(item.tries || 0) + 1;
if (tries < 5 && err?.retryable !== false) nextQueue.push({ ...item, tries });
}
}
saveFeedbackQueue(nextQueue);
if (nextQueue.length === 0) await renderLearningStatus();
} finally {
state.feedbackQueueBusy = false;
}
}
async function upgradeAnalysisWithPythonMl(payload, runId) {
const attempts = [900, 2200, 4200];
for (const waitMs of attempts) {
if (runId !== state.analysisRunId) return false;
await delay(waitMs);
if (runId !== state.analysisRunId) return false;
try {
const refreshed = await analyzePayload(payload, { mlMode: "prefer_python" });
if (runId !== state.analysisRunId) return false;
if (String(refreshed?.mlMeta?.source || "") === "python-ml-service") {
state.latestAnalysis = refreshed;
renderAllAnalysis(refreshed);
await renderLearningStatus();
statusEl.textContent = "Analysis complete (Python ML synced).";
return true;
}
} catch {
// Keep retrying quietly while user keeps working.
}
}
return false;
}
async function boot() {
statusEl.textContent = "Loading card pool...";
loadRevisions();
try {
const { cards, base } = await loadCardsWithFallback();
ACTIVE_API_BASE = base;
state.cards = normalizeCardFlags(cards).sort((a, b) => a.name.localeCompare(b.name));
applyCardPoolFilters();
renderTowerTroops();
renderSlots();
renderCardPool();
renderMetaPresets();
renderRevisionList();
renderQuickRead(null);
renderBattleSnapshot(null);
renderSubscoreMiniChart(null);
renderTowerImpactMiniChart(null);
setText("towerOptimizerBest", "Run Optimize Tower Troop to compare all tower troop outcomes for this deck.");
setText("deltaSummary", "Analyze runs the swap planner automatically. Meaningful one-card upgrades will show here.");
setText("patchDriftLine", "Analyze deck to estimate patch drift risk and adaptation guidance.");
updateAnalysisPanelState();
statusEl.textContent = "Drag cards, choose tower troop, then analyze.";
flushFeedbackQueue();
} catch (err) {
console.error(err);
statusEl.textContent = "Could not load cards from API. Please refresh once.";
}
}
async function loadCardsWithFallback() {
let lastError = null;
for (const base of getApiBaseCandidates()) {
try {
const res = await fetch(apiUrl(base, "clashroyale/cards"), { cache: "no-store" });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (!Array.isArray(data) || data.length === 0) throw new Error("Empty card response");
return { cards: data, base };
} catch (err) {
lastError = err;
}
}
throw lastError || new Error("No API endpoint available");
}
function normalizeCardFlags(cards) {
return (cards || []).map((c) => {
const slug = toCardSlug(c.name);
const rarity = String(c?.rarity || "").toLowerCase();
const isChampion = !!c.isChampion || rarity === "champion" || CHAMPION_CARD_SLUGS.has(slug);
const isHero = HERO_CARD_SLUGS.has(slug);
const isEvolution = EVO_CARD_SLUGS.has(slug) && !EVO_FORCE_OFF_SLUGS.has(slug);
const allowedSlots = ["normal"];
if (isChampion) {
// Champions are restricted to Hero/Champion or Wild slots.
allowedSlots.length = 0;
}
if (isEvolution) allowedSlots.push("evo");
if (isHero || isChampion) allowedSlots.push("hero");
if (isEvolution || isHero || isChampion) allowedSlots.push("wild");
return {
...c,
isHero,
isChampion,
isEvolution,
allowedSlots
};
});
}
function renderMetaPresets() {
if (!simDeckSelect) return;
simDeckSelect.innerHTML = "";
META_PRESETS.forEach((p, i) => {
const isReady = !!resolvePresetCardIds(p);
const opt = document.createElement("option");
opt.value = String(i);
opt.textContent = isReady ? p.name : `${p.name} (updating...)`;
simDeckSelect.appendChild(opt);
});
}
function onSearch() {
applyCardPoolFilters();
renderCardPool();
}
function onCardTypeFilterChange() {
state.poolTypeFilter = String(cardTypeFilterEl?.value || "all");
applyCardPoolFilters();
renderCardPool();
}
function onCardSortFilterChange() {
state.poolSortFilter = String(cardSortFilterEl?.value || "az");
applyCardPoolFilters();
renderCardPool();
}
function cardMatchesTypeFilter(card, typeFilter) {
if (typeFilter === "evo") return !!card?.isEvolution;
if (typeFilter === "heroes_champions") return !!card?.isHero || !!card?.isChampion;
if (typeFilter === "champions") return !!card?.isChampion;
if (typeFilter === "heroes") return !!card?.isHero;
return true;
}
function applyCardPoolFilters() {
const q = String(searchEl?.value || "").trim().toLowerCase();
const typeFilter = String(cardTypeFilterEl?.value || state.poolTypeFilter || "all");
const sortFilter = String(cardSortFilterEl?.value || state.poolSortFilter || "az");
state.poolTypeFilter = typeFilter;
state.poolSortFilter = sortFilter;
const filtered = state.cards
.filter((c) => cardMatchesTypeFilter(c, typeFilter))
.filter((c) => c.name.toLowerCase().includes(q))
.sort((a, b) => a.name.localeCompare(b.name));
if (sortFilter === "za") filtered.reverse();
state.filteredCards = filtered;
}
function hasText(id) {
const el = document.getElementById(id);
return !!(el && String(el.textContent || "").trim().length);
}
function setPanelCompact(panelId, compact) {
const panel = document.getElementById(panelId);
if (!panel) return;
panel.classList.toggle("panel-compact", !!compact);
}
function applyAnalysisMasonry() {
const grid = document.querySelector(".analysis-mosaic");
if (!grid) return;
const style = window.getComputedStyle(grid);
const rowSize = Number.parseFloat(style.getPropertyValue("grid-auto-rows"));
const rowGap = Number.parseFloat(style.getPropertyValue("row-gap") || style.getPropertyValue("gap") || "0");
if (!Number.isFinite(rowSize) || rowSize <= 0) return;
[...grid.children].forEach((item) => {
if (!(item instanceof HTMLElement)) return;
item.style.gridRowEnd = "span 1";
});
[...grid.children].forEach((item) => {
if (!(item instanceof HTMLElement)) return;
const h = item.getBoundingClientRect().height;
const span = Math.max(1, Math.ceil((h + rowGap) / (rowSize + rowGap)));
item.style.gridRowEnd = `span ${span}`;
});
}
function scheduleAnalysisLayout() {
if (analysisLayoutFrame) cancelAnimationFrame(analysisLayoutFrame);
analysisLayoutFrame = requestAnimationFrame(() => {
analysisLayoutFrame = null;
applyAnalysisMasonry();
window.setTimeout(applyAnalysisMasonry, 120);
});
}
function updateAnalysisPanelState() {
const towerCards = document.querySelectorAll("#towerOptimizerVisual .insight-card").length;
const swapCards = document.querySelectorAll("#swapBoard .swap-card").length;
const driftCards = document.querySelectorAll("#patchDriftVisual .insight-card").length;
const deltaChips = document.querySelectorAll("#deltaVisualStats .chip").length;
setPanelCompact("cardSwapPanel", towerCards === 0 && !hasText("towerOptimizerBest"));
setPanelCompact("metaStabilityPanel", swapCards === 0 && deltaChips === 0 && !hasText("deltaSummary"));
setPanelCompact("patchDriftPanel", driftCards === 0 && !hasText("patchDriftLine"));
scheduleAnalysisLayout();
}
function clearDeck() {
state.deck = Array(8).fill(null);
state.wildSlotModes = {};
state.latestAnalysis = null;
renderSlots();
renderCardPool();
["towerOptimizerList", "deltaBreakdown", "weaknessProfileList", "patchDriftList", "simDetails", "mlDriversList", "mlSuggestionsList"].forEach((id) => renderList(id, []));
setText("towerOptimizerBest", "Run Optimize Tower Troop to compare all tower troop outcomes for this deck.");
setText("deltaSummary", "Analyze runs the swap planner automatically. Meaningful one-card upgrades will show here.");
setText("patchDriftLine", "Analyze deck to estimate patch drift risk and adaptation guidance.");
["simSummary", "mlForecastLine"].forEach((id) => setText(id, ""));
setText("learningStatusLine", "");
setText("mlFeedbackLine", "");
["mlOppArchetypeInput", "mlTrophiesInput", "mlCrownsForInput", "mlCrownsAgainstInput"].forEach((id) => {
const el = document.getElementById(id);
if (el) el.value = "";
});
renderMetricTiles("subscoreTiles", []);
renderMetricTiles("towerImpactTiles", []);
renderSubscoreMiniChart(null);
renderTowerImpactMiniChart(null);
renderMlForecastVisual(null);
renderTowerOptimizerVisual([]);
renderSwapBoard([]);
setRisk("riskAir", "riskAirLabel", 0);
setRisk("riskSwarm", "riskSwarmLabel", 0);
setRisk("riskBeatdown", "riskBeatdownLabel", 0);
setPatchDriftMeter(0);
renderQuickRead(null);
renderBattleSnapshot(null);
weaknessPanelEl?.classList.add("hidden");
updateAnalysisPanelState();
renderBuilderMetrics();
statusEl.textContent = "Deck cleared.";
}
function renderTowerTroops() {
towerTroopsEl.innerHTML = "";
TOWER_TROOPS.forEach((tower) => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = `tower-btn ${state.selectedTowerTroop === tower.id ? "active" : ""}`;
const img = document.createElement("img");
img.className = "tower-icon";
img.alt = tower.label;
img.src = TOWER_TROOP_ICONS[tower.id];
const label = document.createElement("span");
label.className = "tower-label";
label.textContent = tower.label;
btn.appendChild(img);
btn.appendChild(label);
btn.addEventListener("click", () => {
state.selectedTowerTroop = tower.id;
renderTowerTroops();
statusEl.textContent = `Tower troop selected: ${tower.label}.`;
});
towerTroopsEl.appendChild(btn);
});
}
function renderSlots() {
deckSlotsEl.innerHTML = "";
SLOT_RULES.forEach((rule, index) => {
const slot = document.createElement("div");
slot.className = `slot ${rule.type}`;
slot.addEventListener("dragover", (e) => { e.preventDefault(); slot.classList.add("drag-over"); });
slot.addEventListener("dragleave", () => slot.classList.remove("drag-over"));
slot.addEventListener("drop", (e) => { e.preventDefault(); slot.classList.remove("drag-over"); handleDropOnSlot(index); });
const title = document.createElement("div");
title.className = "slot-title";
title.textContent = rule.label;
slot.appendChild(title);
const card = state.deck[index];
if (card) {
slot.appendChild(buildCardChip(card, {
showRemove: true,
onRemove: () => removeCardFromSlot(index),
slotType: getVisualMode(card, rule.type, index),
slotRuleType: rule.type,
slotIndex: index,
draggable: true,
onDragStart: () => { state.drag = { source: "slot", slotIndex: index, cardId: card.id }; },
onDragEnd: () => { state.drag = null; }
}));
}
deckSlotsEl.appendChild(slot);
});
renderBuilderMetrics();
}
function renderCardPool() {
cardPoolEl.innerHTML = "";
state.filteredCards.forEach((card) => {
const inDeck = state.deck.some((d) => d?.id === card.id);
const chip = buildCardChip(card, {
showRemove: false,
slotType: null,
slotRuleType: null,
draggable: !inDeck,
onDragStart: () => { state.drag = { source: "pool", cardId: card.id }; },
onDragEnd: () => { state.drag = null; }
});
if (inDeck) chip.classList.add("in-deck");
else {
const onSelect = (e) => {
e.preventDefault();
e.stopPropagation();
selectPoolCard(card.id);
};
chip.addEventListener("pointerup", onSelect);
chip.addEventListener("click", onSelect);
}
cardPoolEl.appendChild(chip);
});
}
function selectPoolCard(cardId) {
const now = Date.now();
if (state.lastPoolSelect.cardId === cardId && (now - state.lastPoolSelect.at) < SELECT_GUARD_MS) return;
state.lastPoolSelect = { cardId, at: now };
addCardToFirstValidSlot(cardId);
}
function buildCardChip(card, options) {
const { showRemove, onRemove, slotType, slotRuleType, slotIndex, draggable, onDragStart, onDragEnd } = options;
const isPoolCard = !showRemove && !slotType;
const slotLabel = slotType ? slotType.toUpperCase() : (slotRuleType ? slotRuleType.toUpperCase() : "CARD");
const chip = document.createElement("div");
chip.className = "card-chip";
if (slotType) chip.classList.add(`slot-${slotType}`);
if (draggable) {
chip.draggable = true;
chip.addEventListener("dragstart", onDragStart);
chip.addEventListener("dragend", onDragEnd);
}
const image = getDisplayImage(card, slotType);
const fallbackChain = getDisplayImageFallbacks(card, slotType, slotIndex);
const fallbackData = escapeHtml(fallbackChain.join("|"));
const hasEvoMode = isEvolutionCard(card);
const hasHeroMode = isHeroOrChampion(card);
const canToggleWildMode = slotRuleType === "wild" && showRemove && (hasEvoMode || hasHeroMode);
const currentWildMode = canToggleWildMode ? getWildModeForCard(slotIndex, card) : "";
const visualMode = slotType ? getVisualMode(card, slotType, slotIndex) : null;
const modeLabel = slotType ? getModeLabel(slotType, slotRuleType, card) : "";
const modeInfo = slotType ? getCardModeInfo(card, visualMode) : null;
const infoTitle = modeInfo?.kind === "evo"
? "Show Evolution ability details"
: modeInfo?.kind === "hero"
? "Show Hero ability details"
: "Show Champion ability details";
chip.innerHTML = `
${isPoolCard ? "" : `<span class="variant-pill">${slotLabel}</span>`}
${slotType ? getSlotBadge(slotType) : ""}
<div class="card-img-wrap">
<img class="card-img" src="${image || card.iconUrls?.medium || ""}" data-fallbacks="${fallbackData}" data-fallback-index="0" alt="${escapeHtml(card.name)}" loading="lazy" />
</div>
<div class="name">${card.name}${isPoolCard ? getPoolSpecialSuffix(card) : ""}</div>
<div class="meta">${card.elixirCost} Elixir</div>
${slotType ? `<div class="mode-row"><div class="mode-line ${slotType}">${modeLabel}</div>${modeInfo ? `<button type="button" class="mode-info-btn" title="${escapeHtml(infoTitle)}">INFO</button>` : ""}</div>` : ""}
${canToggleWildMode ? `<div class="mode-switch"><button type="button" class="mode-opt ${currentWildMode === "evo" ? "active" : ""}" data-mode="evo" ${hasEvoMode ? "" : "disabled"}>EVO</button><button type="button" class="mode-opt ${currentWildMode === "hero" ? "active" : ""}" data-mode="hero" ${hasHeroMode ? "" : "disabled"}>HERO</button></div>` : ""}
`;
if (showRemove && onRemove) {
chip.addEventListener("dblclick", onRemove);
chip.title = "Double-click to remove";
}
const imgEl = chip.querySelector(".card-img");
if (imgEl) {
imgEl.addEventListener("error", () => {
if (window.__crNextImageFallback) window.__crNextImageFallback(imgEl);
});
}
if (canToggleWildMode) {
chip.querySelectorAll(".mode-opt").forEach((btn) => {
btn.addEventListener("click", (e) => {
e.stopPropagation();
const nextMode = btn.dataset.mode;
if (nextMode !== "evo" && nextMode !== "hero") return;
if ((nextMode === "evo" && !hasEvoMode) || (nextMode === "hero" && !hasHeroMode)) return;
state.wildSlotModes[slotIndex] = nextMode;
const check = validateDeckComposition(state.deck);
if (!check.ok) {
// Revert if mode switch breaks composition rules.
state.wildSlotModes[slotIndex] = nextMode === "evo" ? "hero" : "evo";
statusEl.textContent = check.message;
return;
}
renderSlots();
});
});
}
if (modeInfo) {
chip.querySelector(".mode-info-btn")?.addEventListener("click", (e) => {
e.stopPropagation();
openCardModeInfoModal(card, modeInfo);
});
}
return chip;
}
function getDisplayImage(card, slotType) {
const chain = getDisplayImageFallbacks(card, slotType, 1);
if (chain.length > 0) return chain[0];
return card.iconUrls?.medium || "";