forked from KenjiEtsu/SkyblockCodexAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1641 lines (1528 loc) · 56.6 KB
/
app.js
File metadata and controls
1641 lines (1528 loc) · 56.6 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
const modeGrid = document.getElementById("modeGrid");
const queryInput = document.getElementById("queryInput");
const searchBtn = document.getElementById("searchBtn");
const results = document.getElementById("results");
const hint = document.getElementById("hint");
const status = document.getElementById("status");
const suggestions = document.getElementById("suggestions");
const mayorCard = document.getElementById("mayorCard");
const bingoCard = document.getElementById("bingoCard");
const currentMayorLink = document.getElementById("currentMayor");
const currentBingoLink = document.getElementById("currentBingo");
const mayorPage = document.getElementById("mayorPage");
const bingoPage = document.getElementById("bingoPage");
const museumPage = document.getElementById("museumPage");
const NIGHT_BACKGROUNDS = [
"https://64.media.tumblr.com/723304f7e96ba769092aa5c3d942cbef/18a032f9a221d0b4-32/s640x960/929448d5d111c42c7ad7f5affb78db023c564874.gifv",
"https://64.media.tumblr.com/6fc3b85fe0e1bafc9dbd06e995a5ad7f/18a032f9a221d0b4-29/s640x960/da8f386d2de45441dbd78847eb79c8a91ca05a01.gifv",
"https://64.media.tumblr.com/ec2b4268bcd420f4cf20c0e94c891150/18a032f9a221d0b4-57/s640x960/5d802ac931c2c6183bbd087fe60bed1d683b9256.gifv",
"https://64.media.tumblr.com/4406b580fb4d10b49a2980a241608f4b/18a032f9a221d0b4-2c/s640x960/a620686b2eef1850beaea53ddaf490fa673f7e39.gifv",
];
let mode = "item";
let suggestTimer = null;
const API_BASE = "https://api.hypixel.net/v2";
const cache = new Map();
const itemTierByName = new Map();
const itemDisplayByName = new Map();
const demoQueries = {
item: [
{ q: "Ender Helmet", tier: "EPIC", fields: [{ label: "Tier", value: "EPIC" }, { label: "Categoría", value: "Armor" }] },
{ q: "Aspect of the End", tier: "RARE", fields: [{ label: "Tier", value: "RARE" }, { label: "Categoría", value: "Weapon" }] },
],
collection: [
{ q: "Cobblestone", fields: [{ label: "Categoría", value: "MINING" }, { label: "Tiers", value: "7" }] },
{ q: "Carrot", fields: [{ label: "Categoría", value: "FARMING" }, { label: "Tiers", value: "9" }] },
],
skill: [
{ q: "Mining", fields: [{ label: "Max Level", value: "60" }, { label: "Tipo", value: "Skill" }] },
{ q: "Taming", fields: [{ label: "Max Level", value: "60" }, { label: "Tipo", value: "Skill" }] },
],
};
let demoIndex = 0;
let demoChar = 0;
let demoTimer = null;
let demoPaused = false;
let demoResetting = false;
const demoArea = document.getElementById("demoArea");
const demoText = document.getElementById("demoText");
const demoResults = document.getElementById("demoResults");
let demoActive = true;
function setRandomHomeBackground() {
if (!document.body?.classList.contains("home-page")) return;
if (!NIGHT_BACKGROUNDS.length) return;
const pick = NIGHT_BACKGROUNDS[Math.floor(Math.random() * NIGHT_BACKGROUNDS.length)];
document.body.style.setProperty("--home-bg", `url("${pick}")`);
}
function now() {
return Date.now();
}
function getCache(key) {
const entry = cache.get(key);
if (!entry) return null;
if (entry.expiresAt <= now()) {
cache.delete(key);
return null;
}
return entry.value;
}
function setCache(key, value, ttlMs) {
cache.set(key, { value, expiresAt: now() + ttlMs });
}
const hints = {
item: "Ejemplo: Wise Dragon Boots",
collection: "Ejemplo: Cobblestone",
skill: "Ejemplo: Mining",
};
function setMode(newMode) {
mode = newMode;
if (modeGrid) {
[...modeGrid.querySelectorAll(".mode")].forEach((btn) => {
btn.classList.toggle("active", btn.dataset.mode === newMode);
});
}
if (hint) hint.textContent = hints[newMode] || "";
if (queryInput) {
queryInput.disabled = false;
queryInput.placeholder = queryInput.disabled ? "No hace falta" : "Escribe el nombre o ID";
}
if (suggestions) suggestions.innerHTML = "";
startDemoTyping();
}
if (modeGrid) {
modeGrid.addEventListener("click", (event) => {
const btn = event.target.closest(".mode");
if (!btn) return;
setMode(btn.dataset.mode);
});
}
async function fetchJson(url) {
status.textContent = "Consultando...";
const res = await fetch(url, { cache: "no-store" });
const data = await res.json();
status.textContent = "Listo";
return { ok: res.ok, data };
}
function renderEmpty(message, isError = false) {
const cls = isError ? "empty error" : "empty";
if (results) {
results.innerHTML = `<div class="${cls}">${message}</div>`;
}
}
function renderCard(title, fields) {
const fieldHtml = fields
.map((f) => `<div><span class="badge">${f.label}</span> ${f.value}</div>`)
.join("");
return `
<div class="result-card">
<div class="result-title">${title}</div>
${fieldHtml}
</div>
`;
}
function rarityClass(tier) {
if (!tier) return "";
const t = String(tier).toLowerCase();
if (t === "very special") return "rarity-very-special";
return `rarity-${t.replace(/\s+/g, "-")}`;
}
function hasMinecraftFormatting(text) {
return typeof text === "string" && (text.includes("§") || /%%[a-z_]+%%/i.test(text));
}
function percentFormatToHtml(text) {
if (typeof text !== "string") return text || "";
const map = {
black: "#000000",
dark_blue: "#0000AA",
dark_green: "#00AA00",
dark_aqua: "#00AAAA",
dark_red: "#AA0000",
dark_purple: "#AA00AA",
gold: "#FFAA00",
gray: "#AAAAAA",
dark_gray: "#555555",
blue: "#5555FF",
green: "#55FF55",
aqua: "#55FFFF",
red: "#FF5555",
light_purple: "#FF55FF",
yellow: "#FFFF55",
white: "#FFFFFF",
};
let result = "";
let currentColor = "";
let lastIndex = 0;
const regex = /%%([a-z_]+)%%/gi;
let match;
while ((match = regex.exec(text)) !== null) {
const chunk = text.slice(lastIndex, match.index);
if (chunk) {
result += currentColor ? `<span style="color:${currentColor}">${chunk}</span>` : chunk;
}
currentColor = map[match[1].toLowerCase()] || currentColor;
lastIndex = regex.lastIndex;
}
const tail = text.slice(lastIndex);
if (tail) {
result += currentColor ? `<span style="color:${currentColor}">${tail}</span>` : tail;
}
return result;
}
function renderItemName(name, tier) {
if (typeof name === "string" && name.includes("§")) {
return minecraftToHtml(name);
}
if (typeof name === "string" && /%%[a-z_]+%%/i.test(name)) {
return percentFormatToHtml(name);
}
const cls = rarityClass(tier);
return cls ? `<span class="${cls}">${name}</span>` : name;
}
function renderItemCard(name, tier, fields, material, skin, color, museumSection = "") {
const title = renderItemName(name, tier);
const icon = material ? materialIconImg(material, skin, color) : "";
const meta = fields
.filter((f) => f.label !== "Tier" && f.label !== "ID")
.filter((f) => f.label === "Categoría" || f.label === "Precio NPC")
.map((f) => {
if (f.label === "Precio NPC") {
return `<div class="item-meta"><span class="badge">NPC</span> <span class="coin-num">${f.value}</span></div>`;
}
return `<div class="item-meta"><span class="badge">${f.label}</span> ${f.value}</div>`;
})
.join("");
const stats = fields
.filter((f) => !["Tier", "ID", "Categoría", "Precio NPC"].includes(f.label))
.map((f) => `<div class="stat-chip"><span class="stat-label">${f.label}</span> <span class="stat-value"${f.style ? ` style="${f.style}"` : ""}>${f.value}</span></div>`)
.join("");
return `
<div class="result-card">
<div class="item-title-row">
${icon}
<div class="result-title">${title}</div>
</div>
${stats ? `<div class="stat-grid">${stats}</div>` : ""}
${museumSection}
${meta}
</div>
`;
}
function renderMuseumSection(match, setItems = null) {
const museum = extractMuseumInfo(match, setItems);
if (!museum) return "";
return `
<div class="museum-card">
<div class="museum-title">Museum</div>
<div class="museum-grid">
<div class="museum-field">XP<span class="museum-value">${museum.xp}</span></div>
<div class="museum-field">Categoría<span class="museum-value">${museum.category}</span></div>
</div>
</div>
`;
}
function extractMuseumInfo(match, setItems = null) {
if (Array.isArray(setItems) && setItems.length) {
const setKey = getArmorSetMuseumKey(setItems);
const setXpMap =
match?.armor_set_donation_xp ??
match?.museum_data?.armor_set_donation_xp ??
match?.museum?.armor_set_donation_xp ??
null;
if (setKey && setXpMap && typeof setXpMap === "object" && setXpMap[setKey] != null) {
const category =
match?.museum_data?.category ??
match?.museumData?.category ??
match?.museum?.category ??
match?.category ??
setItems.find((item) => item?.category)?.category ??
"N/A";
return {
xp: setXpMap[setKey],
category,
};
}
}
const museum =
match?.museum_data ??
match?.museumData ??
match?.museum ??
null;
if (!museum || typeof museum !== "object") return null;
const xp =
museum.donation_xp ??
museum.donationXp ??
museum.xp ??
museum.museum_xp ??
museum.experience_value ??
museum.value_xp ??
museum.experience ??
museum.value ??
null;
const category =
museum.category ??
museum.type ??
museum.item_type ??
museum.donation_type ??
match?.category ??
null;
if (xp == null && category == null) return null;
return {
xp: xp ?? "N/A",
category: category ?? "N/A",
};
}
function renderRelatedItems(match, items) {
const setItems = findRelatedItems(match, items);
if (!setItems.length) return "";
const setSummary = renderSetSummary(setItems);
const museumSection = renderMuseumSection(match, setItems);
const cards = setItems
.map((item) => {
const icon = item.material ? materialIconImg(item.material, item.skin, item.color) : "";
const title = renderItemName(item.name, item.tier);
const active = item.name === match.name ? " data-active=\"1\"" : "";
return `
<button class="related-card"${active} data-related-item="${item.name}">
${icon}
<div>
<div class="related-card-name">${title}</div>
<div class="related-card-meta">${item.category || "Item relacionado"}</div>
</div>
</button>
`;
})
.join("");
return `
<div class="related-items">
<div class="related-title">Relacionados</div>
<div class="related-grid">${cards}</div>
${setSummary}
${museumSection}
</div>
`;
}
function findRelatedItems(match, items) {
if (!match || !Array.isArray(items)) return [];
const armorPieces = ["Helmet", "Chestplate", "Leggings", "Boots"];
const setKeyFromId = getArmorSetGroupingKey(match);
if (setKeyFromId) {
const related = items
.filter((item) => getArmorSetGroupingKey(item) === setKeyFromId)
.sort((a, b) => getArmorPieceOrder(a) - getArmorPieceOrder(b));
if (related.length >= 2) return related;
}
if (!match?.name) return [];
const pattern = parseArmorNamePattern(match.name, armorPieces);
if (!pattern) return [];
return armorPieces
.map((piece) => pattern.template(piece))
.map((name) => items.find((item) => item?.name === name))
.filter(Boolean);
}
function getArmorSetGroupingKey(item) {
const rawId = String(item?.id || "").toUpperCase();
if (!rawId) return "";
const cleaned = rawId
.replace(/(?:^|_)(HELMET|CHESTPLATE|LEGGINGS|BOOTS)(?:_|$)/, "_")
.replace(/^_+|_+$/g, "")
.replace(/_+/g, "_");
return cleaned !== rawId ? cleaned : "";
}
function getArmorPieceOrder(item) {
const rawId = String(item?.id || "").toUpperCase();
if (/(?:^|_)HELMET(?:_|$)/.test(rawId)) return 0;
if (/(?:^|_)CHESTPLATE(?:_|$)/.test(rawId)) return 1;
if (/(?:^|_)LEGGINGS(?:_|$)/.test(rawId)) return 2;
if (/(?:^|_)BOOTS(?:_|$)/.test(rawId)) return 3;
const rawName = String(item?.name || "");
if (/(^|\s)Helmet(\s|$)/i.test(rawName)) return 0;
if (/(^|\s)Chestplate(\s|$)/i.test(rawName)) return 1;
if (/(^|\s)Leggings(\s|$)/i.test(rawName)) return 2;
if (/(^|\s)Boots(\s|$)/i.test(rawName)) return 3;
return 99;
}
function parseArmorNamePattern(name, armorPieces) {
const safePieces = armorPieces.join("|");
const prefixMatch = name.match(new RegExp(`^(${safePieces})\\s+(.+)$`, "i"));
if (prefixMatch) {
const suffix = prefixMatch[2];
return {
displayBase: suffix,
template: (targetPiece) => `${targetPiece} ${suffix}`,
};
}
const infixMatch = name.match(new RegExp(`^(.+?)\\s+(${safePieces})(.*)$`, "i"));
if (infixMatch) {
const prefix = infixMatch[1];
const tail = infixMatch[3] || "";
return {
displayBase: `${prefix}${tail}`.trim(),
template: (targetPiece) => `${prefix} ${targetPiece}${tail}`.trim(),
};
}
return null;
}
function getArmorSetDisplayName(item, relatedItems = []) {
const namePattern = parseArmorNamePattern(item?.name || "", ["Helmet", "Chestplate", "Leggings", "Boots"]);
if (namePattern?.displayBase) {
return namePattern.displayBase.replace(/^of\s+/i, "").trim();
}
const setKey = getArmorSetGroupingKey(item);
if (setKey) {
return setKey
.split("_")
.map((part) => part.charAt(0) + part.slice(1).toLowerCase())
.join(" ");
}
const fallback = relatedItems.find((entry) => entry?.name)?.name || item?.name || "Armor";
return fallback;
}
function renderSetSummary(items) {
const totals = sumItemStats(items);
const statEntries = extractStatFields(totals)
.map((s) => `<div class="stat-chip"><span class="stat-label">${s.label}</span> <span class="stat-value"${s.style ? ` style="${s.style}"` : ""}>${s.value}</span></div>`)
.join("");
if (!statEntries) return "";
return `
<div class="set-summary">
<div class="set-summary-title">Stats totales del set</div>
<div class="stat-grid">${statEntries}</div>
</div>
`;
}
function sumItemStats(items) {
const totals = {};
for (const item of items) {
const stats = item?.stats;
if (!stats || typeof stats !== "object") continue;
for (const [key, value] of Object.entries(stats)) {
const num = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(num)) continue;
totals[key] = (totals[key] || 0) + num;
}
}
return totals;
}
function getArmorSetMuseumKey(items) {
const armorSuffixes = ["_HELMET", "_CHESTPLATE", "_LEGGINGS", "_BOOTS"];
for (const item of items) {
const id = String(item?.id || "").toUpperCase();
for (const suffix of armorSuffixes) {
if (id.endsWith(suffix)) {
return id.slice(0, -suffix.length);
}
}
}
return "";
}
function getArmorSetMuseumKeyFromItem(item) {
return getArmorSetMuseumKey([item]);
}
function formatMuseumLabel(value) {
return String(value || "N/A")
.replace(/_/g, " ")
.replace(/\b\w/g, (m) => m.toUpperCase());
}
function getMuseumEntries(items) {
const setSeen = new Set();
const entries = [];
for (const item of items) {
const museum = extractMuseumInfo(item);
const setKey = getArmorSetMuseumKeyFromItem(item);
const setXpMap =
item?.armor_set_donation_xp ??
item?.museum_data?.armor_set_donation_xp ??
item?.museum?.armor_set_donation_xp ??
null;
if (setKey && setXpMap && typeof setXpMap === "object" && setXpMap[setKey] != null) {
if (setSeen.has(setKey)) continue;
setSeen.add(setKey);
const relatedItems = items.filter((entry) => getArmorSetGroupingKey(entry) === setKey);
const displayBase = getArmorSetDisplayName(item, relatedItems);
const iconItem = relatedItems.find((entry) => getArmorPieceOrder(entry) === 0) || item;
entries.push({
type: "set",
name: `${displayBase} Set`,
museumCategory: formatMuseumLabel(item?.museum_data?.category ?? item?.category ?? "Armor Set"),
museumXp: setXpMap[setKey],
tier: item.tier,
material: iconItem.material,
color: iconItem.color,
skin: iconItem.skin,
note: "Donacion del set completo",
matchItemName: item.name,
});
continue;
}
if (!museum) continue;
entries.push({
type: "item",
name: item.name,
museumCategory: formatMuseumLabel(museum.category),
museumXp: museum.xp,
tier: item.tier,
material: item.material,
color: item.color,
skin: item.skin,
note: formatMuseumLabel(item.category),
matchItemName: item.name,
});
}
return entries.sort((a, b) => {
if (a.museumCategory !== b.museumCategory) return a.museumCategory.localeCompare(b.museumCategory);
return a.name.localeCompare(b.name);
});
}
function renderMuseumBrowser(items) {
const entries = getMuseumEntries(items);
if (!entries.length) {
return `<div class="empty error">No se encontraron entradas de Museum.</div>`;
}
const categories = ["Todas", ...new Set(entries.map((entry) => entry.museumCategory))];
const chips = categories
.map((category, index) => `<button class="museum-filter${index === 0 ? " active" : ""}" data-museum-filter="${category}">${category}</button>`)
.join("");
const cards = entries
.map((entry) => renderMuseumCard(entry))
.join("");
return `
<div class="museum-browser">
<div class="museum-header">
<div class="result-title">Museum</div>
<div class="museum-subtitle">Explora los items aceptados en el Museum por categoria y localiza rapido su XP y categoria.</div>
</div>
<div class="museum-filters">${chips}</div>
<div class="museum-items-grid" id="museumGrid">${cards}</div>
</div>
`;
}
function renderMuseumCard(entry) {
const title = renderItemName(entry.name, entry.tier);
const icon = entry.material ? materialIconImg(entry.material, entry.skin, entry.color) : "";
return `
<button class="museum-item-card" data-museum-category="${entry.museumCategory}" data-related-item="${entry.matchItemName}">
<div class="museum-item-top">
${icon}
<div class="museum-item-name">${title}</div>
</div>
<div class="museum-item-note">${entry.note}</div>
<div class="museum-grid">
<div class="museum-field">XP<span class="museum-value">${entry.museumXp}</span></div>
<div class="museum-field">Categoría<span class="museum-value">${entry.museumCategory}</span></div>
</div>
</button>
`;
}
function materialIconUrl(material) {
const id = normalizeMaterialId(material);
return `https://assets.mcasset.cloud/1.20.4/assets/minecraft/textures/item/${id}.png`;
}
function materialIconImg(material, skin, color) {
const id = normalizeMaterialId(material);
if ((id === "skull_item" || id === "skull") && skin) {
const textureId = skinToTextureId(skin);
if (textureId) {
return `<img class="item-icon" src="https://mc-heads.net/head/${textureId}/32" onerror="this.onerror=null;this.removeAttribute('src');this.style.display='none';" />`;
}
return "";
}
const leatherColor = parseLeatherColor(id, color);
if (leatherColor) {
const primary = materialIconUrl(id);
const fallback = `https://assets.mcasset.cloud/1.16.2/assets/minecraft/textures/items/${id}.png`;
const overlayPrimary = materialIconUrl(`${id}_overlay`);
const overlayFallback = `https://assets.mcasset.cloud/1.16.2/assets/minecraft/textures/items/${id}_overlay.png`;
return `
<span class="item-icon item-icon-leather" style="--leather-color:${leatherColor};">
<span class="item-icon-tint"
style="mask-image:url('${primary}');-webkit-mask-image:url('${primary}');"
onerror="void(0)"></span>
<img class="item-icon-overlay"
src="${overlayPrimary}"
onerror="if(this.dataset.fallback==='1'){this.onerror=null;this.removeAttribute('src');this.style.display='none';}else{this.dataset.fallback='1';this.src='${overlayFallback}';}" />
</span>
`;
}
const primary = materialIconUrl(id);
const fallback = `https://assets.mcasset.cloud/1.16.2/assets/minecraft/textures/items/${id}.png`;
return `<img class="item-icon" src="${primary}" onerror="if(this.dataset.fallback==='1'){this.onerror=null;this.removeAttribute('src');this.style.display='none';}else{this.dataset.fallback='1';this.src='${fallback}';}" />`;
}
function normalizeMaterialId(material) {
const raw = String(material).toLowerCase();
if (raw.startsWith("gold_")) {
return raw.replace(/^gold_/, "golden_");
}
return raw;
}
function parseLeatherColor(materialId, color) {
if (!/^leather_(helmet|chestplate|leggings|boots)$/.test(String(materialId || ""))) {
return "";
}
if (!color) return "";
if (Array.isArray(color) && color.length >= 3) {
return `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
}
if (typeof color === "string") {
const parts = color.split(",").map((part) => Number(part.trim()));
if (parts.length >= 3 && parts.slice(0, 3).every((value) => Number.isFinite(value))) {
return `rgb(${parts[0]}, ${parts[1]}, ${parts[2]})`;
}
}
if (typeof color === "object") {
const values = [color.r, color.g, color.b].map((value) => Number(value));
if (values.every((value) => Number.isFinite(value))) {
return `rgb(${values[0]}, ${values[1]}, ${values[2]})`;
}
}
return "";
}
function skinToTextureId(skin) {
try {
if (!skin) return "";
const value = typeof skin === "string" ? skin : (skin.value || "");
if (!value) return "";
if (value.includes("textures.minecraft.net/texture/")) {
return value.split("textures.minecraft.net/texture/")[1].split(/[?#]/)[0];
}
const decoded = JSON.parse(atob(value));
const url = decoded?.textures?.SKIN?.url || "";
if (!url) return "";
return url.split("textures.minecraft.net/texture/")[1]?.split(/[?#]/)[0] || "";
} catch {
return "";
}
}
function renderSkillCard(name, description, levels) {
const levelCards = levels.length
? `<div class="levels-grid">${levels
.map(
(lvl) => `
<div class="level-card" data-unlocks="${encodeURIComponent((lvl.unlocks || []).join("\n"))}" data-title="${encodeURIComponent(`Nivel ${lvl.level}`)}">
<div class="level-title">Nivel ${lvl.level}</div>
<div class="level-xp">XP nivel: ${lvl.xpRequired ?? "N/A"}</div>
<div class="level-xp">XP total: ${lvl.totalXp ?? "N/A"}</div>
</div>
`
)
.join("")}</div>`
: "";
return `
<div class="result-card">
<div class="result-title">${name}</div>
${description ? `<div class="perk-desc">${description}</div>` : ""}
${levelCards || "<div class='empty'>Sin niveles disponibles.</div>"}
</div>
`;
}
function renderItemDetails(match) {
if (!match) return "Item no encontrado.";
const title = renderItemName(match.name || "Item", match.tier);
const icon = match.material ? materialIconImg(match.material, match.skin, match.color) : "";
const meta = [];
if (match.category) meta.push(`<div class="item-meta"><span class="badge">Categoría</span> ${match.category}</div>`);
if (match.npc_sell_price) meta.push(`<div class="item-meta"><span class="badge">NPC</span> <span class="coin-num">${match.npc_sell_price}</span></div>`);
const stats = extractStatFields(match.stats)
.map((s) => `<div class="stat-chip"><span class="stat-label">${s.label}</span> <span class="stat-value"${s.style ? ` style="${s.style}"` : ""}>${s.value}</span></div>`)
.join("");
return `
<div class="result-card">
<div class="item-title-row">
${icon}
<div class="result-title">${title}</div>
</div>
${stats ? `<div class="stat-grid">${stats}</div>` : ""}
${renderMuseumSection(match)}
${meta.join("")}
</div>
`;
}
function extractStatFields(stats) {
if (!stats || typeof stats !== "object") return [];
const order = ["damage", "strength", "crit_damage", "crit_chance", "attack_speed", "intelligence", "ferocity"];
const entries = Object.entries(stats);
const sorted = [
...order.map((k) => entries.find(([key]) => key === k)).filter(Boolean),
...entries.filter(([key]) => !order.includes(key)),
];
return sorted.map(([key, value]) => {
const label = statLabel(key);
const val = formatStatValue(key, value);
return { label, value: val.text, style: val.style };
});
}
function statLabel(key) {
const map = {
damage: "Damage",
strength: "Strength",
crit_damage: "Crit Damage",
crit_chance: "Crit Chance",
attack_speed: "Attack Speed",
intelligence: "Intelligence",
ferocity: "Ferocity",
};
return map[key] || key.replace(/_/g, " ").replace(/\b\w/g, (m) => m.toUpperCase());
}
function formatStatValue(key, value) {
const num = typeof value === "number" ? value : Number(value);
const sign = num > 0 ? "+" : "";
const text = Number.isFinite(num) ? `${sign}${num}` : String(value);
if (key === "damage") return { text, style: "color:#ff5555;font-weight:600;" };
if (key === "intelligence" || key === "ferocity") return { text, style: "color:#55ff55;font-weight:600;" };
return { text, style: "" };
}
function categoryImage(category) {
const map = {
FARMING: "#22d3ee",
MINING: "#f97316",
COMBAT: "#ef4444",
FORAGING: "#22c55e",
FISHING: "#38bdf8",
RIFT: "#a855f7",
};
const color = map[category] || "#64748b";
const label = category ? category[0] : "?";
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72">
<rect width="72" height="72" rx="12" fill="${color}"/>
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle"
font-family="Space Grotesk, sans-serif" font-size="28" fill="#0b0f14">${label}</text>
</svg>
`;
return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
}
function renderCollectionCard(name, category, tiers, tierLabel) {
const iconSrc = categoryImage(category);
const title = tierLabel ? `<span class="${rarityClass(tierLabel)}">${name}</span>` : name;
const tierHtml = tiers.length
? `<div class="tiers-row">${tiers
.map(
(t) =>
`<div class="tier-chip">
<div class="tier-label">Tier ${t.tier}</div>
<div class="tier-amount">${t.amountRequired}</div>
${renderUnlocks(t.unlocks || [])}
</div>`
)
.join("")}</div>`
: `<div class="empty">Sin tiers disponibles.</div>`;
return `
<div class="result-card">
<div class="result-title">${title}</div>
<div class="collection-meta">
<div class="category-icon"><img src="${iconSrc}" alt="${category || "Categoria"}" /></div>
<div>${category || "N/A"}</div>
</div>
${tierHtml}
</div>
`;
}
function renderUnlocks(unlocks) {
if (!unlocks.length) return "";
const items = unlocks
.map((u) => {
const isXp = typeof u === "string" && u.toLowerCase().includes("skyblock xp");
const text = String(u);
const itemName = guessItemFromUnlock(text);
if (isXp) {
return `<div class="tier-unlock"><span class="xp">${text}</span></div>`;
}
if (itemName) {
const tier = itemTierByName.get(itemName.toLowerCase());
const cls = rarityClass(tier);
const classes = ["tier-unlock", "unlock-item", cls].filter(Boolean).join(" ");
return `<button class="${classes}" data-item="${itemName}">${text}</button>`;
}
return `<div class="tier-unlock">${text}</div>`;
})
.join("");
return `<div class="tier-unlocks">${items}</div>`;
}
function renderUnlockLines(raw) {
const lines = raw.split("\n").map((l) => l.trim()).filter(Boolean);
return lines
.map((line) => {
const normalized = normalizeUnlockItemName(line);
const key = normalized.toLowerCase();
const itemName = itemDisplayByName.get(key);
if (itemName) {
const tier = itemTierByName.get(key);
const cls = rarityClass(tier);
const classes = ["unlock-item", cls].filter(Boolean).join(" ");
return `<button class="${classes}" data-item="${itemName}">${line}</button>`;
}
return `<div>${minecraftToHtml(line)}</div>`;
})
.join("<br>");
}
function normalizeUnlockItemName(text) {
let value = text.trim();
const suffixes = [" Reforge", " Reforge Stone", " Reforge Stone Recipe"];
for (const suf of suffixes) {
if (value.toLowerCase().endsWith(suf.toLowerCase())) {
value = value.slice(0, -suf.length).trim();
break;
}
}
return value;
}
function guessItemFromUnlock(text) {
if (!text) return null;
const lower = text.toLowerCase().trim();
if (lower.endsWith(" recipes") && lower.includes(" minion recipes")) {
const base = text.slice(0, -8).trim();
const name = base.endsWith(" Minion") || base.endsWith(" minion") ? base : `${base} Minion`;
return `${name} I`;
}
if (!lower.endsWith(" recipe")) return null;
const name = text.slice(0, -7).trim();
return name || null;
}
function renderSuggestions(items) {
if (!items.length) {
suggestions.innerHTML = "";
return;
}
suggestions.innerHTML = items
.map(
(item) =>
`<div class="suggestion" data-value="${item.value}">${item.label || item.value}<small>${item.type}</small></div>`
)
.join("");
}
async function loadSuggestions() {
if (queryInput.disabled) return;
const q = queryInput.value.trim();
if (q.length < 2) {
suggestions.innerHTML = "";
return;
}
try {
if (mode === "item") {
const items = await loadItems();
renderSuggestions(makeSuggestions(items, q, "Item"));
return;
}
if (mode === "collection") {
const collections = await loadCollections();
renderSuggestions(makeSuggestions(collections, q, "Colección"));
return;
}
if (mode === "skill") {
const skills = await loadSkills();
renderSuggestions(makeSuggestions(skills, q, "Skill"));
return;
}
suggestions.innerHTML = "";
} catch (err) {
suggestions.innerHTML = "";
}
}
function rankMatches(values, query, limit = 8) {
const q = query.toLowerCase();
const prefix = values.filter((v) => v.toLowerCase().startsWith(q));
const contains = values.filter((v) => v.toLowerCase().includes(q) && !prefix.includes(v));
return [...prefix, ...contains].slice(0, limit);
}
function makeSuggestions(list, query, type) {
const entries = list
.filter((i) => i?.name)
.map((i) => ({
value: i.name,
tier: i.tier,
}));
const ranked = rankMatches(entries.map((entry) => entry.value), query);
return ranked.map((name) => {
const match = entries.find((entry) => entry.value === name);
return {
value: name,
type,
label: match ? renderItemName(match.value, match.tier) : name,
};
});
}
function formatUnix(value) {
if (!value && value !== 0) return "N/A";
const num = Number(value);
if (!Number.isFinite(num)) return "N/A";
const date = new Date(num);
if (Number.isNaN(date.getTime())) return "N/A";
return date.toLocaleString("es-ES");
}
function normalizePerk(perk, fallbackName = "Perk") {
if (!perk) return null;
if (typeof perk === "string") {
return { name: fallbackName, description: perk, minister: false };
}
return {
name: perk.name || fallbackName,
description: perk.description || perk.desc || perk.lore || "Sin descripción",
minister: perk.minister === true || perk.isMinister === true,
};
}
function normalizePerkList(value) {
if (!Array.isArray(value)) return [];
return value.map((perk, index) => normalizePerk(perk, `Perk ${index + 1}`)).filter(Boolean);
}
function collectElectionNodes(value, acc = []) {
if (!value || typeof value !== "object") return acc;
if (Array.isArray(value)) {
value.forEach((entry) => collectElectionNodes(entry, acc));
return acc;
}
if (Array.isArray(value.candidates) || value.year != null) {
acc.push(value);
}
Object.values(value).forEach((entry) => {
if (entry && typeof entry === "object") collectElectionNodes(entry, acc);
});
return acc;
}
function resolveMayorData(data) {
const mayorCandidates = [
data?.mayor,
data?.current?.mayor,
data?.current,
].filter((entry) => entry && typeof entry === "object");
const mayor =
mayorCandidates.find((entry) => entry.name || Array.isArray(entry.perks) || entry.minister) || {};
const electionCandidates = collectElectionNodes(data).filter(
(entry, index, arr) => arr.indexOf(entry) === index
);
const election = electionCandidates.sort((a, b) => {
const aHasCandidates = Array.isArray(a?.candidates) ? 1 : 0;
const bHasCandidates = Array.isArray(b?.candidates) ? 1 : 0;
if (aHasCandidates !== bHasCandidates) return bHasCandidates - aHasCandidates;
const aYear = Number(a?.year ?? -1);
const bYear = Number(b?.year ?? -1);
return bYear - aYear;
})[0] || {};
const minister =
mayor?.minister ||
data?.minister ||
data?.current?.minister ||
{};
return { mayor, election, minister };
}
function minecraftToHtml(text) {
if (!text) return "";
const map = {
"0": "#000000",
"1": "#0000AA",
"2": "#00AA00",
"3": "#00AAAA",
"4": "#AA0000",
"5": "#AA00AA",
"6": "#FFAA00",
"7": "#AAAAAA",