-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1579 lines (1439 loc) · 85.9 KB
/
script.js
File metadata and controls
1579 lines (1439 loc) · 85.9 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
/*!
* HotADex
* @version 0.9.1
* @date 2025-10-09
*/
const APP_VERSION = '0.9.1';
// Expose version for debugging and tooling
window.HotADexVersion = APP_VERSION;
// Mark the document for quick inspection
document.addEventListener('DOMContentLoaded', () => {
document.body.dataset.version = APP_VERSION;
console.info(`[HotADex] v${APP_VERSION} ready`);
});
document.addEventListener('DOMContentLoaded', () => {
// --- Data ---
const heroes = heroesData;
const skills = skillsData;
const skillProbs = skillProbabilities;
const classes = classesData;
const moveData = movementData;
const allCreatures = creaturesData;
const allSpells = spellsData;
const allArtifacts = artifactsData;
const grailInfo = grailData;
const tavernTips = tavernTipsData;
// Normalize Structures data once; reuse everywhere (faster & deterministic)
const structuresAll = validateStructuresData(window.hotadexStructures || []);
// --- DOM Elements (Core UI) ---
const navButtons = document.querySelectorAll('.nav-button');
const views = document.querySelectorAll('.view');
const modal = document.getElementById('modal');
const modalClose = document.getElementById('modal-close');
// Ensure dialog semantics
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-modal', 'true');
const modalBody = document.getElementById('modal-body');
const mobileDropdownContainer = document.getElementById('mobile-dropdown-container');
// Desktop Search Elements
const searchContainerDesktop = document.getElementById('search-container-desktop');
const searchIconDesktop = document.getElementById('search-icon-desktop');
const searchBarDesktop = document.getElementById('search-bar-desktop');
const searchSuggestionsDesktop = document.getElementById('search-suggestions-desktop');
// Mobile Search Elements
const searchButtonMobile = document.getElementById('search-button-mobile');
const searchModalMobile = document.getElementById('search-modal-mobile');
const searchModalClose = document.getElementById('search-modal-close');
const searchBarMobile = document.getElementById('search-bar-mobile');
const searchSuggestionsMobile = document.getElementById('search-suggestions-mobile');
// --- State Variables ---
const isMobile = window.matchMedia("(max-width: 768px)").matches;
let searchIndex = [];
let structuresFilter = (new URL(location.href).hash.match(/structures=([^&]+)/)?.[1])
? decodeURIComponent(new URL(location.href).hash.match(/structures=([^&]+)/)[1])
: (localStorage.getItem('structuresFilter') || 'All');
function persistStructuresFilter(value) {
structuresFilter = value;
localStorage.setItem('structuresFilter', value);
const hash = new URL(location.href).hash;
const newHash = hash.includes('structures=')
? hash.replace(/structures=([^&]+)/, 'structures=' + encodeURIComponent(value))
: (hash ? hash + '&structures=' + encodeURIComponent(value)
: '#structures=' + encodeURIComponent(value));
history.replaceState(null, '', newHash);
}
// --- Initialization ---
function init() {
buildSearchIndex();
setupEventListeners();
if (isMobile) {
renderClassView(Object.keys(classes)[0]);
renderCreatureView('All');
renderSpellView('Air');
renderArtifactsView('All');
renderTavernTipsView('All');
showView('heroes-view');
} else {
populateClassSidebar();
renderClassView(Object.keys(classes)[0]);
populateFactionSidebar();
renderCreatureView('All');
populateSchoolSidebar();
renderSpellView('Air');
populateArtifactsSidebar();
renderArtifactsView('All');
populateTavernTipsSidebar();
renderTavernTipsView('All');
}
}
// --- View Management ---
function showView(viewId) {
views.forEach(view => view.classList.add('view-hidden'));
document.getElementById(viewId)?.classList.remove('view-hidden');
navButtons.forEach(button => {
if (button.dataset.view) {
button.classList.toggle('active', button.dataset.view === viewId);
}
});
if (isMobile) {
mobileDropdownContainer.innerHTML = '';
switch (viewId) {
case 'heroes-view': populateClassDropdown_Mobile(); break;
case 'creatures-view': populateFactionDropdown_Mobile(); break;
case 'spells-view': populateSchoolDropdown_Mobile(); break;
case 'artifacts-view': populateArtifactsDropdown_Mobile(); break;
case 'taverntips-view':populateTavernTipsDropdown_Mobile(); break;
case 'structures-view': populateStructuresDropdown_Mobile(); break;
default: mobileDropdownContainer.innerHTML = ''; break;
}
}
// ✅ Runs on BOTH desktop and mobile
if (viewId === 'structures-view') {
renderStructuresView();
if (!isMobile) {
renderStructuresSidebar();
}
}
}
// --- Custom Mobile Dropdown Logic ---
function setupCustomSelectEventListeners(container, renderCallback) {
const button = container.querySelector('.custom-select-button');
const valueSpan = container.querySelector('.custom-select-value');
const optionsPanel = container.querySelector('.custom-select-options');
const options = container.querySelectorAll('.custom-select-option');
const arrow = container.querySelector('.custom-select-arrow');
button.addEventListener('click', (e) => {
e.stopPropagation();
const currentlyOpen = document.querySelector('.custom-select-options:not(.hidden)');
if (currentlyOpen && currentlyOpen !== optionsPanel) {
currentlyOpen.classList.add('hidden');
const otherArrow = currentlyOpen.parentElement.querySelector('.custom-select-arrow');
if (otherArrow) otherArrow.classList.remove('up');
}
optionsPanel.classList.toggle('hidden');
arrow.classList.toggle('up');
});
options.forEach(option => {
option.addEventListener('click', () => {
const selectedValue = option.dataset.value;
valueSpan.textContent = option.textContent;
optionsPanel.classList.add('hidden');
arrow.classList.remove('up');
if(renderCallback) renderCallback(selectedValue);
});
});
}
function createCustomSelect(optionsConfig, initialValue, initialText, renderCallback) {
mobileDropdownContainer.innerHTML = '';
const container = document.createElement('div');
container.className = 'custom-select-container';
const button = document.createElement('button');
button.className = 'custom-select-button';
button.innerHTML = `<span class="custom-select-value">${initialText}</span><span class="custom-select-arrow">▼</span>`;
const optionsPanel = document.createElement('div');
optionsPanel.className = 'custom-select-options hidden';
if (optionsConfig.groups) {
for (const groupName in optionsConfig.groups) {
const optgroupDiv = document.createElement('div');
optgroupDiv.className = 'custom-select-optgroup';
optgroupDiv.textContent = groupName;
optionsPanel.appendChild(optgroupDiv);
optionsConfig.groups[groupName].forEach(item => {
const optionDiv = document.createElement('div');
optionDiv.className = 'custom-select-option';
optionDiv.dataset.value = item.value;
optionDiv.textContent = item.text;
optionsPanel.appendChild(optionDiv);
});
}
} else {
optionsConfig.items.forEach(item => {
const optionDiv = document.createElement('div');
optionDiv.className = 'custom-select-option';
optionDiv.dataset.value = item.value;
optionDiv.textContent = item.text;
optionsPanel.appendChild(optionDiv);
});
}
container.appendChild(button);
container.appendChild(optionsPanel);
mobileDropdownContainer.appendChild(container);
setupCustomSelectEventListeners(container, renderCallback);
}
function populateClassDropdown_Mobile() {
const factions = {};
for (const className in classes) {
const faction = classes[className].faction;
if (!factions[faction]) factions[faction] = [];
factions[faction].push({ value: className, text: className });
}
const sortedFactions = Object.keys(factions).sort();
const groupedOptions = {};
sortedFactions.forEach(faction => {
groupedOptions[faction] = factions[faction];
});
createCustomSelect({ groups: groupedOptions }, Object.keys(classes)[0], Object.keys(classes)[0], renderClassView);
}
function populateFactionDropdown_Mobile() {
const factions = ["All", ...[...new Set(allCreatures.map(c => c.faction))].sort()];
const options = {
groups: {
"Factions": factions.map(f => ({ value: f, text: f === 'All' ? 'All Creatures' : f })),
"Comparisons": [{ value: 'Compare Creatures', text: 'Compare Creatures' }]
}
};
createCustomSelect(options, 'All', 'All Creatures', renderCreatureView);
}
function populateSchoolDropdown_Mobile() {
const schools = ["Air", "Earth", "Fire", "Water"];
const options = { items: schools.map(s => ({ value: s, text: `${s} Magic` })) };
createCustomSelect(options, 'Air', 'Air Magic', renderSpellView);
}
function populateArtifactsDropdown_Mobile() {
const classes = ["Treasure", "Minor", "Major", "Relic", "Combination"];
const slots = ["Helmet", "Necklace", "Torso", "Weapon", "Shield", "Ring", "Cape", "Feet", "Misc."];
const options = {
groups: {
"General": [{ value: "All", text: "All Artifacts" }],
"By Class": classes.map(c => ({ value: `class-${c}`, text: c })),
"By Slot": slots.map(s => ({ value: `slot-${s}`, text: s })),
"Special": [{ value: "Grail", text: "Grail" }]
}
};
createCustomSelect(options, 'All', 'All Artifacts', renderArtifactsView);
}
function populateTavernTipsDropdown_Mobile() {
const categories = ["All", "Hero Trade Screen", "Hero Management Screen", "Adventure Screen", "Combat Screen", "Town Screen"];
const options = {
groups: {
"Keybinds": categories.map(c => ({ value: c, text: c }))
}
};
createCustomSelect(options, 'All', 'All', renderTavernTipsView);
}
function populateStructuresDropdown_Mobile() {
const container = document.getElementById('mobile-dropdown-container');
if (!container) return;
// Build options from categories
const items = structuresAll;
const cats = getStructuresCategories(items);
const selectItems = cats.map(cat => ({ value: cat, text: cat }));
// Label to show on the button
const label = structuresFilter || 'All';
// Render the shared custom select (same helper used elsewhere)
createCustomSelect(
{ items: selectItems }, // optionsConfig
structuresFilter, // initialValue
label, // initialText
(nextValue) => { // renderCallback
if (nextValue !== structuresFilter) {
persistStructuresFilter(nextValue); // updates hash + localStorage
renderStructuresView(); // re-render cards
}
}
);
}
// --- Helper Functions ---
function formatCost(cost) {
if (typeof cost === 'object' && cost !== null) {
return `${cost.gold} + ${cost.resource_amount}${cost.resource_type}`;
}
return cost;
}
function formatSpecial(special) {
if (!special) return '–';
if (typeof special === 'object' && special.description) {
return `<span class="clickable" data-special-name="${special.name}" data-special-desc="${special.description}">${special.name}</span>`;
}
if (typeof special === 'string') {
return special;
}
return special.name || '–';
}
function generateItemId(type, name) {
return `${type.toLowerCase()}-${name.replace(/\s+/g, '-').replace(/[^a-zA-Z0-9-]/g, '')}`;
}
// --- Search Indexing and Execution ---
function buildSearchIndex() {
const getKeywords = (...args) => args.join(' ').toLowerCase().replace(/<[^>]*>/g, ' ').split(/[\s,()/]+/).filter(k => k && k.length > 1);
searchIndex = []; // Clear index before building
heroes.forEach(h => searchIndex.push({ keywords: getKeywords(h.name, h.specialty, h.faction, 'hero', h.class), displayText: h.name, type: 'Hero', action: 'navigate', view: 'heroes-view', filter: h.class, targetId: generateItemId('hero', h.name) }));
allCreatures.forEach(c => searchIndex.push({ keywords: getKeywords(c.name, c.faction, 'creature', c.special?.name, c.special?.description, c.lore, c.gameplay_analysis), displayText: c.name, type: 'Creature', action: 'navigate', view: 'creatures-view', filter: c.faction, targetId: generateItemId('creature', c.name) }));
Object.values(allSpells).forEach(s => searchIndex.push({ keywords: getKeywords(s.name, s.school, 'spell', s.effect.summary, s.general_info), displayText: s.name, type: 'Spell', action: 'navigate', view: 'spells-view', filter: s.school, targetId: generateItemId('spell', s.name) }));
allArtifacts.forEach(a => searchIndex.push({ keywords: getKeywords(a.name, 'artifact', a.effect, a.class, a.slot), displayText: a.name, type: 'Artifact', action: 'navigate', view: 'artifacts-view', filter: `class-${a.class}`, targetId: generateItemId('artifact', a.name) }));
Object.entries(skills).forEach(([skillName, skillData]) => searchIndex.push({ keywords: getKeywords(skillName, 'skill', skillData.description.Basic, skillData.gameplay_analysis), displayText: skillName, type: 'Skill', action: 'modal', name: skillName }));
const factions = [...new Set(allCreatures.map(c => c.faction))].filter(f => f !== 'Neutral');
factions.forEach(faction => {
searchIndex.push({ keywords: getKeywords(faction, 'creatures'), displayText: `${faction} (Creatures)`, type: 'Faction', action: 'navigate', view: 'creatures-view', filter: faction });
const heroClass = Object.entries(classes).find(([_,d]) => d.faction === faction)?.[0];
if (heroClass) {
searchIndex.push({ keywords: getKeywords(faction, 'heroes'), displayText: `${faction} (Heroes)`, type: 'Faction', action: 'navigate', view: 'heroes-view', filter: heroClass });
}
});
searchIndex.push({ keywords: getKeywords("Primary Skills"), displayText: 'Primary Skills', type: 'UI Section', action: 'navigate', view: 'heroes-view', filter: 'Knight' });
searchIndex.push({ keywords: getKeywords("Movement Points"), displayText: 'Movement Points', type: 'UI Section', action: 'navigate', view: 'heroes-view', filter: 'Knight' });
searchIndex.push({ keywords: getKeywords("Magic & Wisdom"), displayText: 'Magic & Wisdom', type: 'UI Section', action: 'navigate', view: 'heroes-view', filter: 'Knight' });
const primarySkills = ['Attack', 'Defense', 'Spell Power', 'Knowledge'];
primarySkills.forEach(ps => {
searchIndex.push({ keywords: getKeywords(ps, 'primary skill'), displayText: ps, type: 'Primary Skill', action: 'modal', name: ps.toLowerCase().replace(' ', '') });
});
const magicSchools = ['Air Magic', 'Earth Magic', 'Fire Magic', 'Water Magic'];
magicSchools.forEach(ms => {
searchIndex.push({ keywords: getKeywords(ms, 'magic school'), displayText: ms, type: 'Spell School', action: 'navigate', view: 'spells-view', filter: ms.split(' ')[0] });
});
searchIndex.push({ keywords: getKeywords('grail', 'holy grail'), displayText: 'Grail', type: 'Building', action: 'navigate', view: 'artifacts-view', filter: 'Grail' });
const keybindCategories = ["Hero Trade Screen", "Hero Management Screen", "Adventure Screen", "Combat Screen", "Town Screen"];
keybindCategories.forEach(cat => searchIndex.push({ keywords: getKeywords(cat, 'keybinds', 'hotkeys'), displayText: `${cat} (Keybinds)`, type: 'Keybinds', action: 'navigate', view: 'taverntips-view', filter: cat }));
searchIndex.push({ keywords: getKeywords('keybinds', 'hotkeys'), displayText: 'Keybinds (All)', type: 'Keybinds', action: 'navigate', view: 'taverntips-view', filter: 'All' });
// --- Structures (global search) ---
const structures = structuresAll;
structures.forEach(s => {
const cats = Array.isArray(s.categories) ? s.categories : (s.categories ? [s.categories] : []);
const primaryCat = cats[0] || 'All';
searchIndex.push({
keywords: getKeywords(
s.name,
'structure',
cats.join(' '),
s.short,
s.inDepth,
s.notes,
s.trivia
),
displayText: s.name,
type: 'Structure',
action: 'navigate',
view: 'structures-view',
filter: primaryCat, // which category to show
targetId: `structure-${s.id}` // so we can scroll/highlight
});
});
}
function performSearch(query) {
const lowerCaseQuery = query.toLowerCase();
const results = searchIndex.map(item => {
let score = 0;
const lowerCaseDisplayText = item.displayText.toLowerCase();
if (lowerCaseDisplayText === lowerCaseQuery) score = 100;
else if (lowerCaseDisplayText.startsWith(lowerCaseQuery)) score = 50;
else if (item.keywords.some(keyword => keyword.includes(lowerCaseQuery))) score = 10;
return { ...item, score };
}).filter(item => item.score > 0).sort((a, b) => b.score - a.score);
if (isMobile) {
displaySuggestions(results, searchSuggestionsMobile);
} else {
displaySuggestions(results, searchSuggestionsDesktop);
}
}
function displaySuggestions(results, container) {
if (results.length === 0) {
hideSuggestions(false);
return;
}
const suggestionsHTML = results.slice(0, 15).map(result => `
<div class="suggestion-item" data-name="${result.name || result.displayText}" data-type="${result.type}" data-action="${result.action}" data-view="${result.view || ''}" data-filter="${result.filter || ''}" data-target-id="${result.targetId || ''}">
<span class="suggestion-name">${result.displayText}</span>
<span class="suggestion-type">${result.type}</span>
</div>`).join('');
container.innerHTML = suggestionsHTML;
container.classList.remove('search-hidden');
container.querySelectorAll('.suggestion-item').forEach(item => {
item.addEventListener('click', () => {
const { name, type, action, view, filter, targetId } = item.dataset;
if (action === 'navigate') {
showView(view);
switch (view) {
case 'heroes-view': renderClassView(filter); break;
case 'creatures-view': renderCreatureView(filter); break;
case 'spells-view': renderSpellView(filter); break;
case 'artifacts-view': renderArtifactsView(filter); break;
case 'taverntips-view': renderTavernTipsView(filter); break;
case 'structures-view':
// apply sticky filter and render the grid
persistStructuresFilter(filter || 'All');
renderStructuresView();
// on desktop, also refresh the sidebar active state if present
if (!isMobile) {
const aside = document.getElementById('structures-sidebar');
if (aside) renderStructuresSidebar();
}
break;
}
if (targetId) {
setTimeout(() => {
const targetElement = document.getElementById(targetId);
if (targetElement) {
targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
targetElement.classList.add('highlight-flash');
setTimeout(() => targetElement.classList.remove('highlight-flash'), 1500);
}
}, 100);
}
} else {
switch (type) {
case 'Skill': displaySkillDetails(name); break;
case 'Primary Skill': displayPrimarySkillDetails(name); break;
}
}
hideSuggestions(true);
});
});
}
function hideSuggestions(hideAll = true) {
searchSuggestionsDesktop.classList.add('search-hidden');
searchSuggestionsDesktop.innerHTML = '';
if (hideAll) {
searchBarDesktop.value = '';
searchBarDesktop.classList.add('search-bar-collapsed');
}
if (isMobile) {
searchBarMobile.value = '';
searchSuggestionsMobile.innerHTML = '';
searchModalMobile.classList.add('modal-hidden');
}
}
// --- Heroes View Functions ---
function populateClassSidebar() {
const classSidebar = document.getElementById('class-sidebar');
if (!classSidebar) return;
classSidebar.innerHTML = '';
const factions = {};
for (const className in classes) {
const faction = classes[className].faction;
if (!factions[faction]) factions[faction] = [];
factions[faction].push(className);
}
const sortedFactions = Object.keys(factions).sort();
for (const factionName of sortedFactions) {
const factionTab = document.createElement('div');
factionTab.className = 'faction-tab';
const factionButton = document.createElement('button');
factionButton.className = 'faction-tab-button';
factionButton.dataset.faction = factionName;
factionButton.textContent = factionName;
const classSubTabs = document.createElement('div');
classSubTabs.className = 'class-sub-tabs hidden';
const classesInFaction = factions[factionName];
classesInFaction.forEach(className => {
const classButton = document.createElement('button');
classButton.className = 'sidebar-button';
classButton.dataset.className = className;
classButton.textContent = className;
classButton.addEventListener('click', () => renderClassView(className));
classSubTabs.appendChild(classButton);
});
factionButton.addEventListener('click', () => {
if (classesInFaction.length > 0) renderClassView(classesInFaction[0]);
});
factionTab.appendChild(factionButton);
factionTab.appendChild(classSubTabs);
classSidebar.appendChild(factionTab);
}
}
function renderClassView(className) {
const classData = classes[className];
const heroesOfClass = heroes.filter(h => h.class === className);
if (isMobile) {
renderClassView_Mobile(className, classData, heroesOfClass);
} else {
renderClassView_Desktop(className, classData, heroesOfClass);
}
attachMainContentListeners();
}
function renderClassView_Desktop(className, classData, heroesOfClass) {
const mainContent = document.getElementById('main-content');
if (!mainContent) return;
const selectedFactionName = classData.faction;
document.querySelectorAll('#class-sidebar .faction-tab-button').forEach(btn => btn.classList.toggle('active', btn.dataset.faction === selectedFactionName));
document.querySelectorAll('#class-sidebar .class-sub-tabs').forEach(container => container.classList.add('hidden'));
const activeFactionButton = document.querySelector(`.faction-tab-button[data-faction="${selectedFactionName}"]`);
if (activeFactionButton) activeFactionButton.nextElementSibling.classList.remove('hidden');
document.querySelectorAll('#class-sidebar .sidebar-button').forEach(btn => btn.classList.toggle('active', btn.dataset.className === className));
const classSkillProbs = skillProbabilities[className];
const processTerrain = (terrainString) => terrainString.split(', ').map(terrain => moveData.nativeTerrains[terrain] ? `<span class="clickable" data-terrain-name="${terrain}">${terrain}</span>` : terrain).join(', ');
mainContent.innerHTML = `
<div class="page-grid">
<div id="class-primary-skills-panel" class="panel"><h2>${className} Primary Skills (%)</h2><table class="stats-grid-table"><thead><tr><th></th><th class="clickable" data-primary-skill="attack">A</th><th class="clickable" data-primary-skill="defense">D</th><th class="clickable" data-primary-skill="power">SP</th><th class="clickable" data-primary-skill="knowledge">K</th></tr></thead><tbody><tr><td>Lvl 1</td><td>${classData.primary_skills.attack}</td><td>${classData.primary_skills.defense}</td><td>${classData.primary_skills.power}</td><td>${classData.primary_skills.knowledge}</td></tr><tr><td>Lvl 2-9</td><td>${classData.primary_skill_chance.levels_2_9.attack}</td><td>${classData.primary_skill_chance.levels_2_9.defense}</td><td>${classData.primary_skill_chance.levels_2_9.power}</td><td>${classData.primary_skill_chance.levels_2_9.knowledge}</td></tr><tr><td>Lvl 10+</td><td>${classData.primary_skill_chance.levels_10_plus.attack}</td><td>${classData.primary_skill_chance.levels_10_plus.defense}</td><td>${classData.primary_skill_chance.levels_10_plus.power}</td><td>${classData.primary_skill_chance.levels_10_plus.knowledge}</td></tr></tbody></table></div>
<div id="movement-panel" class="panel"><h2>Movement Points</h2><table class="movement-table"><thead><tr><th>Unit Spd</th><th>Mvt Pts</th></tr></thead><tbody>${moveData.speedToBase.map(row => `<tr><td>${row.speed}</td><td>${row.points}</td></tr>`).join('')}</tbody></table><table class="movement-table"><thead><tr><th>Terrain</th><th>Cost (S/D)</th></tr></thead><tbody>${moveData.groundCost.map(row => `<tr><td>${processTerrain(row.terrain)}</td><td>${row.straight} / ${row.diagonal}</td></tr>`).join('')}</tbody></table><div class="movement-links"><span class="clickable" data-modal-type="flying">Flying Movement Points</span><br><span class="clickable" data-modal-type="diagonal">Diagonal Move Exception</span></div></div>
<div id="magic-chance-panel" class="panel"><h2>Magic & Wisdom %</h2><div class="magic-chance-grid"><div class="school-name clickable" data-school-name="Air">Air</div><div class="school-name clickable" data-school-name="Earth">Earth</div><div class="school-name clickable" data-school-name="Fire">Fire</div><div class="school-name clickable" data-school-name="Water">Water</div><div class="school-chance">${classData.magic_roll_chance.air}%</div><div class="school-chance">${classData.magic_roll_chance.earth}%</div><div class="school-chance">${classData.magic_roll_chance.fire}%</div><div class="school-chance">${classData.magic_roll_chance.water}%</div></div><div class="guaranteed-skill-info"><div>Choice of a Magic School guaranteed every ${classData.guaranteed_magic_school} lvl</div><div>Choice of Wisdom guaranteed every ${classData.guaranteed_wisdom} lvl</div></div></div>
<div id="secondary-skills-panel" class="panel"><h2>Sec. Skills %</h2><table class="info-table">${Object.entries(classSkillProbs).sort((a, b) => b[1] - a[1]).map(([skill, chance]) => `<tr class="clickable" data-skill-name="${skill}"><td>${skill}</td><td>${chance}</td></tr>`).join('')}</table></div>
<div id="heroes-panel" class="panel"><h2>Heroes</h2><table class="hero-table"><thead><tr><th>Hero</th><th>Specialty</th><th>Starting skill(s)</th><th>Army</th><th>Spell</th></tr></thead><tbody>${heroesOfClass.map(hero => `<tr id="${generateItemId('hero', hero.name)}"><td><div class="hero-name-cell clickable" data-hero-name="${hero.name}"><img class="hero-portrait" src="https://heroes.thelazy.net/images/thumb/e/e4/Hero_${hero.name.replace(/\s/g, '_')}.png/28px-Hero_${hero.name.replace(/\s/g, '_')}.png" alt="${hero.name}" onerror="this.style.display='none'"><strong>${hero.name}</strong></div></td><td class="clickable" data-specialty-name="${hero.specialty}" data-specialty-desc="${hero.specialty_description}">${hero.specialty}</td><td>${hero.skills.map(skill => `<div class="clickable" data-skill-name="${skill.replace(/^(Basic|Advanced|Expert)\s/, '')}">${skill}</div>`).join('')}</td><td>${hero.army.map(u => `${u.quantity} ${u.creature}`).join('<br>')}</td><td>${hero.spell || '–'}</td></tr>`).join('')}</tbody></table></div>
</div>`;
}
function renderClassView_Mobile(className, classData, heroesOfClass) {
const mainContent = document.getElementById('main-content');
if (!mainContent) return;
const classSkillProbs = skillProbabilities[className];
const processTerrain = (terrainString) => terrainString.split(', ').map(terrain => moveData.nativeTerrains[terrain] ? `<span class="clickable" data-terrain-name="${terrain}">${terrain}</span>` : terrain).join(', ');
const heroesHTML = heroesOfClass.map(hero => `
<div id="${generateItemId('hero', hero.name)}" class="mobile-card hero-card clickable" data-hero-name="${hero.name}">
<div class="card-header">
<div class="hero-info">
<img class="hero-portrait" src="https://heroes.thelazy.net/images/thumb/e/e4/Hero_${hero.name.replace(/\s/g, '_')}.png/32px-Hero_${hero.name.replace(/\s/g, '_')}.png" alt="${hero.name}" onerror="this.style.display='none'">
<div>
<div class="hero-name">${hero.name}</div>
<div class="hero-specialty clickable" data-specialty-name="${hero.specialty}" data-specialty-desc="${hero.specialty_description}">${hero.specialty}</div>
</div>
</div>
</div>
<div class="card-body hero-details">
<p><span class="label">Skills:</span> ${hero.skills.map(skill => `<span class="clickable" data-skill-name="${skill.replace(/^(Basic|Advanced|Expert)\s/, '')}">${skill}</span>`).join(', ')}</p>
<p><span class="label">Army:</span> ${hero.army.map(u => `${u.quantity} ${u.creature}`).join(', ')}</p>
${hero.spell ? `<p><span class="label">Spell:</span> ${hero.spell}</p>` : ''}
</div>
</div>`).join('');
mainContent.innerHTML = `
<div class="mobile-accordion">
<details>
<summary>Primary Skills</summary>
<div class="panel-content"><table class="stats-grid-table"><thead><tr><th></th><th class="clickable" data-primary-skill="attack">A</th><th class="clickable" data-primary-skill="defense">D</th><th class="clickable" data-primary-skill="power">SP</th><th class="clickable" data-primary-skill="knowledge">K</th></tr></thead><tbody><tr><td>Lvl 1</td><td>${classData.primary_skills.attack}</td><td>${classData.primary_skills.defense}</td><td>${classData.primary_skills.power}</td><td>${classData.primary_skills.knowledge}</td></tr><tr><td>Lvl 2-9</td><td>${classData.primary_skill_chance.levels_2_9.attack}</td><td>${classData.primary_skill_chance.levels_2_9.defense}</td><td>${classData.primary_skill_chance.levels_2_9.power}</td><td>${classData.primary_skill_chance.levels_2_9.knowledge}</td></tr><tr><td>Lvl 10+</td><td>${classData.primary_skill_chance.levels_10_plus.attack}</td><td>${classData.primary_skill_chance.levels_10_plus.defense}</td><td>${classData.primary_skill_chance.levels_10_plus.power}</td><td>${classData.primary_skill_chance.levels_10_plus.knowledge}</td></tr></tbody></table></div>
</details>
<details>
<summary>Secondary Skills %</summary>
<div class="panel-content"><table class="info-table">${Object.entries(classSkillProbs).sort((a, b) => b[1] - a[1]).map(([skill, chance]) => `<tr class="clickable" data-skill-name="${skill}"><td>${skill}</td><td>${chance}</td></tr>`).join('')}</table></div>
</details>
<details>
<summary>Magic & Wisdom %</summary>
<div class="panel-content"><div class="magic-chance-grid"><div class="school-name clickable" data-school-name="Air">Air</div><div class="school-name clickable" data-school-name="Earth">Earth</div><div class="school-name clickable" data-school-name="Fire">Fire</div><div class="school-name clickable" data-school-name="Water">Water</div><div class="school-chance">${classData.magic_roll_chance.air}%</div><div class="school-chance">${classData.magic_roll_chance.earth}%</div><div class="school-chance">${classData.magic_roll_chance.fire}%</div><div class="school-chance">${classData.magic_roll_chance.water}%</div></div><div class="guaranteed-skill-info"><div>Magic School guaranteed every ${classData.guaranteed_magic_school} lvl</div><div>Wisdom guaranteed every ${classData.guaranteed_wisdom} lvl</div></div></div>
</details>
<details>
<summary>Movement</summary>
<div class="panel-content"><table class="movement-table"><thead><tr><th>Unit Spd</th><th>Mvt Pts</th></tr></thead><tbody>${moveData.speedToBase.map(row => `<tr><td>${row.speed}</td><td>${row.points}</td></tr>`).join('')}</tbody></table><table class="movement-table"><thead><tr><th>Terrain</th><th>Cost (S/D)</th></tr></thead><tbody>${moveData.groundCost.map(row => `<tr><td>${processTerrain(row.terrain)}</td><td>${row.straight} / ${row.diagonal}</td></tr>`).join('')}</tbody></table><div class="movement-links"><span class="clickable" data-modal-type="flying">Flying Movement</span><br><span class="clickable" data-modal-type="diagonal">Diagonal Exception</span></div></div>
</details>
</div>
<div class="panel" style="margin-top: 0.75rem;"><h2>Heroes</h2><div class="mobile-card-list">${heroesHTML}</div></div>`;
}
// --- Creatures View Functions ---
function populateFactionSidebar() {
const factionSidebar = document.getElementById('faction-sidebar');
if (!factionSidebar) return;
const factions = ["All", ...[...new Set(allCreatures.map(c => c.faction))].sort()];
factionSidebar.innerHTML = `<button class="sidebar-button active" data-faction="All">All Creatures</button>`;
factions.slice(1).forEach(faction => {
const button = document.createElement('button');
button.className = 'sidebar-button';
button.dataset.faction = faction;
button.textContent = faction;
factionSidebar.appendChild(button);
});
factionSidebar.innerHTML += `<div class="sidebar-divider"></div><button class="sidebar-button" data-faction="Compare Creatures">Compare Creatures</button>`;
factionSidebar.querySelectorAll('.sidebar-button').forEach(button => {
button.addEventListener('click', () => renderCreatureView(button.dataset.faction));
});
}
function renderCreatureView(faction) {
if (isMobile) {
renderCreatureView_Mobile(faction);
} else {
renderCreatureView_Desktop(faction);
}
attachCreatureContentListeners();
}
function renderCreatureView_Desktop(faction) {
const creatureContent = document.getElementById('creature-content');
if (!creatureContent) return;
document.querySelectorAll('#faction-sidebar .sidebar-button').forEach(btn => btn.classList.toggle('active', btn.dataset.faction === faction));
if (faction === "Compare Creatures") {
renderCreatureComparisonView();
return;
}
let nativeTerrainInfo = '';
const factionsWithTerrain = ["Castle", "Rampart", "Tower", "Inferno", "Necropolis", "Dungeon", "Stronghold", "Fortress", "Conflux", "Cove", "Factory"];
if (factionsWithTerrain.includes(faction)) {
let terrainName = '', associatedFactions = [];
for (const [terrain, factionList] of Object.entries(moveData.nativeTerrains)) {
if (factionList.includes(faction)) {
terrainName = terrain;
associatedFactions = factionList;
break;
}
}
if (terrainName) {
const combatBonus = "+1 A / D / Spd";
const movementBonus = `No ${terrainName} terrain movement penalty if all units in the hero army are ${associatedFactions.join(' / ')} ones`;
nativeTerrainInfo = `<p class="native-terrain-info"><strong>Native terrain:</strong> ${terrainName} → ${combatBonus} ${terrainName !== 'Grass' ? `- ${movementBonus}` : ''}</p>`;
}
}
const filteredCreatures = faction === 'All' ? allCreatures : allCreatures.filter(c => c.faction === faction);
creatureContent.innerHTML = `<div class="panel"><h2>${faction} Creatures</h2>${nativeTerrainInfo}<table class="creature-table"><thead><tr><th>Lvl</th><th>Creature</th><th>Att</th><th>Def</th><th>Dmg</th><th>HP</th><th>Spd</th><th>Grw</th><th>AI</th><th>Cost</th><th>Special</th></tr></thead><tbody>${filteredCreatures.map(c => `<tr id="${generateItemId('creature', c.name)}" class="${c.upgraded ? 'upgraded-row' : ''}"><td>${c.level}${c.upgraded ? '+' : ''}</td><td class="creature-name clickable" data-creature-name="${c.name}">${c.name}</td><td>${c.att}</td><td>${c.def}</td><td>${c.dmg_min}-${c.dmg_max}</td><td>${c.hp}</td><td>${c.spd}</td><td>${c.grw}</td><td>${c.ai_val}</td><td>${formatCost(c.cost)}</td><td>${formatSpecial(c.special)}</td></tr>`).join('')}</tbody></table></div>`;
}
function renderCreatureView_Mobile(faction) {
const creatureContent = document.getElementById('creature-content');
if (!creatureContent) return;
if (faction === "Compare Creatures") {
renderCreatureComparisonView();
return;
}
const filteredCreatures = faction === 'All' ? allCreatures : allCreatures.filter(c => c.faction === faction);
const cardsHTML = filteredCreatures.map(c => `
<div id="${generateItemId('creature', c.name)}" class="mobile-card creature-card clickable ${c.upgraded ? 'upgraded' : ''}" data-creature-name="${c.name}">
<div class="card-header">
<span class="card-title">${c.name}</span>
<span class="card-subtitle">Lvl ${c.level}${c.upgraded ? '+' : ''}</span>
</div>
<div class="card-body">
<div class="card-stats">
<div class="stat-item"><span class="label">Attack</span><span class="stat-value">${c.att}</span></div>
<div class="stat-item"><span class="label">Defense</span><span class="stat-value">${c.def}</span></div>
<div class="stat-item"><span class="label">Damage</span><span class="stat-value">${c.dmg_min}-${c.dmg_max}</span></div>
<div class="stat-item"><span class="label">Health</span><span class="stat-value">${c.hp}</span></div>
<div class="stat-item"><span class="label">Speed</span><span class="stat-value">${c.spd}</span></div>
<div class="stat-item"><span class="label">Growth</span><span class="stat-value">${c.grw}</span></div>
</div>
${c.special ? `<div class="card-special"><span class="label">Special:</span> ${formatSpecial(c.special)}</div>` : ''}
</div>
</div>
`).join('');
creatureContent.innerHTML = `<div class="mobile-card-list">${cardsHTML}</div>`;
}
// --- Spells View Functions ---
function populateSchoolSidebar() {
const schoolSidebar = document.getElementById('school-sidebar');
if (!schoolSidebar) return;
const schools = ["Air", "Earth", "Fire", "Water"];
schoolSidebar.innerHTML = '';
schools.forEach(school => {
const button = document.createElement('button');
button.className = 'sidebar-button';
button.dataset.school = school;
button.textContent = `${school} Magic`;
schoolSidebar.appendChild(button);
});
schoolSidebar.querySelectorAll('.sidebar-button').forEach(button => {
button.addEventListener('click', () => renderSpellView(button.dataset.school));
});
}
function renderSpellView(school) {
if (isMobile) {
renderSpellView_Mobile(school);
} else {
renderSpellView_Desktop(school);
}
attachSpellContentListeners();
}
function renderSpellView_Desktop(school) {
const spellContent = document.getElementById('spell-content');
if (!spellContent) return;
document.querySelectorAll('#school-sidebar .sidebar-button').forEach(btn => btn.classList.toggle('active', btn.dataset.school === school));
const spellsToDisplay = [...Object.values(allSpells).filter(s => s.school === "All"), ...Object.values(allSpells).filter(s => s.school === school)].sort((a,b) => a.level - b.level);
const spellsByLevel = {};
spellsToDisplay.forEach(spell => {
if (!spellsByLevel[spell.level]) spellsByLevel[spell.level] = [];
spellsByLevel[spell.level].push(spell);
});
let contentHTML = `<div class="panel"><h2>${school} Magic Spells</h2>`;
for (const level in spellsByLevel) {
contentHTML += `<h3>Level ${level}</h3><table class="spell-list-table"><thead><tr><th>Spell</th><th>Cost (w/o / with skill)</th><th>Duration</th><th>Effect</th></tr></thead><tbody>`;
spellsByLevel[level].forEach(spell => {
contentHTML += `<tr id="${generateItemId('spell', spell.name)}"><td class="clickable spell-name" data-spell-name="${spell.name}">${spell.name}</td><td>${spell.cost}</td><td>${spell.duration}</td><td>${spell.effect.summary}</td></tr>`;
});
contentHTML += `</tbody></table>`;
}
contentHTML += `</div>`;
spellContent.innerHTML = contentHTML;
}
function renderSpellView_Mobile(school) {
const spellContent = document.getElementById('spell-content');
if (!spellContent) return;
const spellsToDisplay = [...Object.values(allSpells).filter(s => s.school === "All"), ...Object.values(allSpells).filter(s => s.school === school)].sort((a,b) => a.level - b.level);
const cardsHTML = spellsToDisplay.map(spell => `
<div id="${generateItemId('spell', spell.name)}" class="mobile-card spell-card clickable" data-spell-name="${spell.name}">
<div class="card-header">
<span class="card-title">${spell.name}</span>
<span class="card-subtitle">Lvl ${spell.level} / ${spell.cost} MP</span>
</div>
<div class="card-body">
<p>${spell.effect.summary}</p>
</div>
</div>
`).join('');
spellContent.innerHTML = `<div class="mobile-card-list">${cardsHTML}</div>`;
}
// --- Artifacts View Functions ---
function populateArtifactsSidebar() {
const artifactsSidebar = document.getElementById('artifacts-sidebar');
if (!artifactsSidebar) return;
const classes = ["Treasure", "Minor", "Major", "Relic", "Combination"];
const slots = ["Helmet", "Necklace", "Torso", "Weapon", "Shield", "Ring", "Cape", "Feet", "Misc."];
let sidebarHTML = `<button class="sidebar-button active" data-artifact-filter="All">All Artifacts</button><div class="sidebar-divider"></div>`;
sidebarHTML += `<div class="faction-tab"><button class="faction-tab-button" data-artifact-filter="class">By Class</button><div class="class-sub-tabs hidden">`;
classes.forEach(c => sidebarHTML += `<button class="sidebar-button" data-artifact-filter="class-${c}">${c}</button>`);
sidebarHTML += `</div></div>`;
sidebarHTML += `<div class="faction-tab"><button class="faction-tab-button" data-artifact-filter="slot">By Slot</button><div class="class-sub-tabs hidden">`;
slots.forEach(s => sidebarHTML += `<button class="sidebar-button" data-artifact-filter="slot-${s}">${s}</button>`);
sidebarHTML += `</div></div>`;
sidebarHTML += `<div class="sidebar-divider"></div><button class="sidebar-button" data-artifact-filter="Grail">Grail</button>`;
artifactsSidebar.innerHTML = sidebarHTML;
artifactsSidebar.querySelectorAll('.sidebar-button').forEach(button => button.addEventListener('click', (e) => renderArtifactsView(e.currentTarget.dataset.artifactFilter)));
artifactsSidebar.querySelectorAll('.faction-tab-button').forEach(button => {
button.addEventListener('click', (e) => {
const subTabs = e.currentTarget.nextElementSibling;
const wasOpen = !subTabs.classList.contains('hidden');
artifactsSidebar.querySelectorAll('.class-sub-tabs').forEach(s => s.classList.add('hidden'));
if (!wasOpen) subTabs.classList.remove('hidden');
});
});
}
function renderArtifactsView(filter) {
if (isMobile) {
renderArtifactsView_Mobile(filter);
} else {
renderArtifactsView_Desktop(filter);
}
attachArtifactsContentListeners();
}
function renderArtifactsView_Desktop(filter) {
const artifactsContent = document.getElementById('artifacts-content');
if (!artifactsContent) return;
document.querySelectorAll('#artifacts-sidebar .sidebar-button, #artifacts-sidebar .faction-tab-button').forEach(btn => btn.classList.remove('active'));
const activeButton = document.querySelector(`#artifacts-sidebar [data-artifact-filter="${filter}"]`);
if (activeButton) {
activeButton.classList.add('active');
if (activeButton.parentElement.classList.contains('class-sub-tabs')) {
activeButton.parentElement.previousElementSibling.classList.add('active');
}
}
if (filter === 'Grail') {
renderGrailView();
return;
}
let filteredArtifacts = [...allArtifacts];
let tableHTML = '', title = 'All Artifacts';
if (filter.startsWith('class-')) {
const artifactClass = filter.split('-')[1];
title = `${artifactClass} Artifacts`;
filteredArtifacts = allArtifacts.filter(a => a.class === artifactClass);
tableHTML = `<table class="artifacts-table"><thead><tr><th>Name</th><th>Effect</th><th>Slot</th></tr></thead><tbody>${filteredArtifacts.sort((a, b) => a.name.localeCompare(b.name)).map(a => `<tr id="${generateItemId('artifact', a.name)}" class="clickable" data-artifact-name="${a.name}"><td>${a.name}</td><td>${a.effect || '–'}</td><td>${a.slot || '–'}</td></tr>`).join('')}</tbody></table>`;
} else if (filter.startsWith('slot-')) {
const artifactSlot = filter.split('-')[1];
title = `Artifacts by Slot: ${artifactSlot}`;
filteredArtifacts = allArtifacts.filter(a => a.slot && a.slot.includes(artifactSlot) && a.class !== 'Combination');
tableHTML = `<table class="artifacts-table"><thead><tr><th>Name</th><th>Class</th><th>Effect</th></tr></thead><tbody>${filteredArtifacts.sort((a, b) => a.name.localeCompare(b.name)).map(a => `<tr id="${generateItemId('artifact', a.name)}" class="clickable" data-artifact-name="${a.name}"><td>${a.name}</td><td>${a.class || '–'}</td><td>${a.effect || '–'}</td></tr>`).join('')}</tbody></table>`;
} else {
tableHTML = `<table class="artifacts-table"><thead><tr><th>Name</th><th>Class</th><th>Effect</th><th>Slot</th></tr></thead><tbody>${filteredArtifacts.sort((a, b) => a.name.localeCompare(b.name)).map(a => `<tr id="${generateItemId('artifact', a.name)}" class="clickable" data-artifact-name="${a.name}"><td>${a.name}</td><td>${a.class || '–'}</td><td>${a.effect || '–'}</td><td>${a.slot || '–'}</td></tr>`).join('')}</tbody></table>`;
}
artifactsContent.innerHTML = `<div class="panel"><h2>${title}</h2>${tableHTML}</div>`;
}
function renderArtifactsView_Mobile(filter) {
const artifactsContent = document.getElementById('artifacts-content');
if (!artifactsContent) return;
if (filter === 'Grail') {
renderGrailView();
return;
}
let filteredArtifacts = [...allArtifacts];
if (filter.startsWith('class-')) {
const artifactClass = filter.split('-')[1];
filteredArtifacts = allArtifacts.filter(a => a.class === artifactClass);
} else if (filter.startsWith('slot-')) {
const artifactSlot = filter.split('-')[1];
filteredArtifacts = allArtifacts.filter(a => a.slot && a.slot.includes(artifactSlot) && a.class !== 'Combination');
}
const cardsHTML = filteredArtifacts.sort((a, b) => a.name.localeCompare(b.name)).map(a => `
<div id="${generateItemId('artifact', a.name)}" class="mobile-card artifact-card clickable" data-artifact-name="${a.name}">
<div class="card-header">
<span class="card-title">${a.name}</span>
<span class="card-subtitle">${a.class || ''} / ${a.slot || ''}</span>
</div>
<div class="card-body">
<p>${a.effect || '–'}</p>
</div>
</div>
`).join('');
artifactsContent.innerHTML = `<div class="mobile-card-list">${cardsHTML}</div>`;
}
function renderGrailView() {
const artifactsContent = document.getElementById('artifacts-content');
if (!artifactsContent) return;
if (isMobile) {
let grailHTML = `<div class="panel"><h2>Grail</h2>`;
grailHTML += `<h3>General Effects</h3>`;
grailHTML += `<p><strong>Gold:</strong> ${grailInfo.general.gold}</p>`;
grailHTML += `<p><strong>Creature Growth:</strong> ${grailInfo.general.growth}</p></div>`;
grailHTML += `<h3>Faction-Specific Effects</h3>`;
grailHTML += `<div class="mobile-card-list" style="margin-top: 0.75rem;">`;
grailHTML += grailInfo.factions.map(f => `
<div class="mobile-card artifact-card">
<div class="card-header">
<span class="card-title" style="text-decoration: none;">${f.name}</span>
</div>
<div class="card-body">
<p><span class="label">Building:</span> ${f.building}</p>
<p><span class="label">Effect:</span> ${f.effect}</p>
</div>
</div>
`).join('');
grailHTML += `</div>`;
artifactsContent.innerHTML = grailHTML;
} else {
let grailHTML = `<div class="panel"><h2>Grail</h2>`;
grailHTML += `<h3>General Effects</h3>`;
grailHTML += `<p><strong>Gold:</strong> ${grailInfo.general.gold}</p>`;
grailHTML += `<p><strong>Creature Growth:</strong> ${grailInfo.general.growth}</p>`;
grailHTML += `<h3>Faction-Specific Effects</h3>`;
grailHTML += `<table class="artifacts-table"><thead><tr><th>Faction</th><th>Building</th><th>Effect</th></tr></thead><tbody>`;
grailHTML += grailInfo.factions.map(f => `<tr><td>${f.name}</td><td>${f.building}</td><td>${f.effect}</td></tr>`).join('');
grailHTML += `</tbody></table></div>`;
artifactsContent.innerHTML = grailHTML;
}
}
// Collapse extra whitespace and trim ends
function cleanText(x) {
if (x == null) return '';
return String(x).replace(/\s+/g, ' ').trim();
}
// Remove any HTML tags from data fields (defense-in-depth, we still escape at render)
function stripHtml(x) {
if (x == null) return '';
return String(x).replace(/<[^>]*>/g, '');
}
function validateStructuresData(raw) {
if (!Array.isArray(raw)) return [];
const KNOWN_KEYS = new Set([
'id', 'name', 'short', 'inDepth', 'notes', 'trivia',
'rmgValue', 'mapLimit', 'categories', 'levels'
]);
const out = [];
raw.forEach((s, i) => {
const o = (s && typeof s === 'object') ? { ...s } : {};
// Strip unknown fields early (keeps renders deterministic)
Object.keys(o).forEach(k => { if (!KNOWN_KEYS.has(k)) delete o[k]; });
// id
if (!o.id) {
o.id = `auto-${i}`;
console.warn('[Structures] Missing id → auto-', i, s);
} else {
o.id = cleanText(o.id);
}
// name (required-ish: ensure not empty)
o.name = cleanText(o.name || '');
if (!o.name) {
o.name = '—';
console.warn('[Structures] Missing name at index', i, s);
}
// text fields: remove HTML, normalize whitespace
const cleanLong = (v) => cleanText(stripHtml(v));
o.short = cleanLong(o.short);
o.inDepth = cleanLong(o.inDepth);
o.notes = cleanLong(o.notes);
o.trivia = cleanLong(o.trivia);
// numeric-ish / free text values (keep as text; render escapes anyway)
if (o.rmgValue != null) o.rmgValue = cleanText(o.rmgValue);
if (o.mapLimit != null) o.mapLimit = cleanText(o.mapLimit);
// categories → array<string>, trimmed; discard empties/dashes
const rawCats = Array.isArray(o.categories) ? o.categories
: (o.categories != null ? [o.categories] : []);
o.categories = rawCats
.map(c => cleanText(c))
.filter(c => c && c !== '-' && c !== '—');
// levels (optional table): normalize to safe strings
if (Array.isArray(o.levels)) {
o.levels = o.levels.map((row, j) => {
const r = row && typeof row === 'object' ? row : {};
return {
level: cleanText(r.level ?? ''),
guards: cleanText(stripHtml(r.guards ?? '')),
rewards: cleanText(stripHtml(r.rewards ?? '')),
xp: cleanText(r.xp ?? '')
};
});
// drop empty levels rows
o.levels = o.levels.filter(r =>
r.level || r.guards || r.rewards || r.xp
);
if (!o.levels.length) delete o.levels;
} else {
delete o.levels;
}
out.push(o);
});
return out;
}
function renderStructuresSidebar() {
const aside = document.getElementById('structures-sidebar');
if (!aside) return;
// Mark the sidebar as a navigation region for screen readers
aside.setAttribute('role', 'navigation');
aside.setAttribute('aria-label', 'Structure categories');
aside.setAttribute('aria-orientation', 'vertical');
// Remove any generic "Categories" header injected by shared code
const sib = aside.previousElementSibling;
if (sib && (sib.classList?.contains('faction-tab') ||
sib.querySelector?.('.faction-tab-button'))) {
sib.remove();
}
aside.querySelectorAll('.faction-tab, .faction-tab-button, .sidebar-title')
.forEach(n => n.remove());
// Build buttons
aside.innerHTML = '';
// Just render the buttons directly (no "Categories" header)
const items = structuresAll;
const cats = getStructuresCategories(items);
const frag = document.createDocumentFragment();
cats.forEach(cat => {
const btn = document.createElement('button');
btn.className = 'sidebar-button';
btn.textContent = cat;
// NEW: proper button semantics & state
btn.type = 'button';
const isActive = (cat === structuresFilter);
btn.setAttribute('aria-pressed', String(isActive));
if (isActive) btn.setAttribute('aria-current', 'page');
btn.addEventListener('click', () => {
// Immediate visual + ARIA feedback before re-render
aside.querySelectorAll('button').forEach(b => {
b.setAttribute('aria-pressed', 'false');
b.classList.remove('active');
b.removeAttribute('aria-current');
});
btn.setAttribute('aria-pressed', 'true');
btn.classList.add('active');
btn.setAttribute('aria-current', 'page');
// Persist and re-render (will rebuild sidebar with correct state anyway)
persistStructuresFilter(cat);
renderStructuresView();
renderStructuresSidebar();
});
frag.appendChild(btn);
});
aside.appendChild(frag);
}