BlueGit

blue-star tribegen

Files

tribegen / web / js / app.js

app.js

attempt at relationships tab
timfa Tim Falken · pushed by timfa · 9 months ago
960ca7e4 History
app.js 61.6 KiB Download Raw
1var doneTyping = true;
2// Main Game App
3class TribeGenApp
4{
5 constructor()
6 {
7 this.currentUser = null;
8 this.currentSave = null;
9 this.currentTribe = null;
10 this.availableEvents = [];
11 this.availableEventsByType = {};
12 this.environments = [];
13 this.environmentMap = {};
14 this.environmentPreviewTimer = null;
15 this.selectedEnvironmentId = null;
16 this.pendingSetup = null;
17 this.lastPlacementKey = null;
18 this.init();
19 }
20
21 async init ()
22 {
23 this.setupEventListeners();
24 this.checkAuth();
25 }
26
27 setupEventListeners ()
28 {
29 // Auth Events
30 document.getElementById('loginForm').addEventListener('submit', (e) => this.handleLogin(e));
31 document.getElementById('registerForm').addEventListener('submit', (e) => this.handleRegister(e));
32 document.getElementById('logoutBtn').addEventListener('click', () => this.handleLogout());
33
34 // Tab switching
35 document.querySelectorAll('.tab-btn').forEach(btn =>
36 {
37 btn.addEventListener('click', (e) => this.switchTab(e.target.dataset.tab));
38 });
39
40 // Main Menu
41 document.getElementById('newGameBtn').addEventListener('click', () => this.startGameSetup());
42
43 // Game Setup
44 document.getElementById('startGenerationBtn').addEventListener('click', () => this.generateKobolds());
45 document.getElementById('selectLeaderBtn').addEventListener('click', () => this.selectLeader());
46 document.getElementById('finishTribeBtn').addEventListener('click', () => this.finishTribe());
47 const envSelect = document.getElementById('environmentSelect');
48 if (envSelect)
49 {
50 envSelect.addEventListener('change', () => this.handleEnvironmentSelection());
51 }
52 const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn');
53 if (confirmEnvBtn)
54 {
55 confirmEnvBtn.addEventListener('click', () => this.confirmEnvironment());
56 }
57
58 // Game Screen
59 document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth());
60 const environmentEl = document.getElementById('environment');
61 if (environmentEl)
62 {
63 environmentEl.addEventListener('click', (e) => this.logEnvironmentClick(e));
64 }
65
66 // Modal close buttons
67 document.querySelectorAll('.modal-close').forEach(btn =>
68 {
69 btn.addEventListener('click', (e) =>
70 {
71 const modal = e.target.closest('.modal');
72 if (modal) modal.classList.add('hidden');
73 });
74 });
75
76 document.getElementById('eventContinueBtn').addEventListener('click', () => this.hideEventModal());
77 }
78
79 switchTab (tabName)
80 {
81 document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
82 document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
83 document.getElementById(tabName + 'Tab').classList.add('active');
84 event.target.classList.add('active');
85 }
86
87 async checkAuth ()
88 {
89 // Check if user is logged in
90 const savedUser = localStorage.getItem('currentUser');
91 if (savedUser)
92 {
93 this.currentUser = JSON.parse(savedUser);
94 this.showMainMenu();
95 } else
96 {
97 this.showAuthScreen();
98 }
99 }
100
101 async handleLogin (e)
102 {
103 e.preventDefault();
104 const email = document.querySelector('#loginForm input[name="email"]').value;
105 const password = document.querySelector('#loginForm input[name="password"]').value;
106 let dataText = "Request failed altogether";
107 try
108 {
109 const response = await fetch('api/auth/login', {
110 method: 'POST',
111 headers: { 'Content-Type': 'application/json' },
112 body: JSON.stringify({ email, password })
113 });
114
115 const dataJson = await response;
116 dataText = await dataJson.text();
117 const data = JSON.parse(dataText);
118
119 if (data.success)
120 {
121 this.currentUser = data.user;
122 localStorage.setItem('currentUser', JSON.stringify(data.user));
123 this.showMainMenu();
124 } else
125 {
126 this.showAuthError(data.error);
127 }
128 } catch (error)
129 {
130 this.showAuthError('Login failed');
131 console.error(error);
132 console.error('Response data:', dataText);
133 }
134 }
135
136 async handleRegister (e)
137 {
138 e.preventDefault();
139 const email = document.querySelector('#registerForm input[name="email"]').value;
140 const password = document.querySelector('#registerForm input[name="password"]').value;
141 const passwordConfirm = document.querySelector('#registerForm input[name="passwordConfirm"]').value;
142
143 if (password !== passwordConfirm)
144 {
145 this.showAuthError('Passwords do not match');
146 return;
147 }
148
149 let dataText = "Request failed altogether";
150 try
151 {
152 const response = await fetch('api/auth/register', {
153 method: 'POST',
154 headers: { 'Content-Type': 'application/json' },
155 body: JSON.stringify({ email, password })
156 });
157
158 const dataRaw = await response;
159 dataText = await dataRaw.text();
160 const data = JSON.parse(dataText);
161
162 if (data.success)
163 {
164 this.currentUser = data.user;
165 localStorage.setItem('currentUser', JSON.stringify(data.user));
166 this.showMainMenu();
167 } else
168 {
169 this.showAuthError(data.error);
170 }
171 } catch (error)
172 {
173 this.showAuthError('Registration failed');
174 console.error(error);
175 console.error('Response data:', dataText);
176 }
177 }
178
179 handleLogout ()
180 {
181 this.currentUser = null;
182 localStorage.removeItem('currentUser');
183 this.showAuthScreen();
184 }
185
186 showAuthError (error)
187 {
188 const errorDiv = document.getElementById('authError');
189 errorDiv.textContent = error;
190 errorDiv.classList.add('show');
191 setTimeout(() => errorDiv.classList.remove('show'), 5000);
192 }
193
194 showAuthScreen ()
195 {
196 this.hideAll();
197 document.getElementById('authScreen').classList.remove('hidden');
198 }
199
200 showMainMenu ()
201 {
202 this.hideAll();
203 document.getElementById('mainMenuScreen').classList.remove('hidden');
204 document.getElementById('userEmail').textContent = this.currentUser.email;
205 this.loadSaves();
206 }
207
208 async loadSaves ()
209 {
210 let dataText = "Request failed altogether";
211 try
212 {
213 const response = await fetch(`api/game/list?userId=${this.currentUser.email}`, {
214 method: 'GET',
215 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
216 });
217
218 dataText = await response.text();
219 const data = JSON.parse(dataText);
220
221 if (!data.success && data.error == "Not authenticated")
222 {
223 this.handleLogout();
224 return;
225 }
226
227 const savesList = document.getElementById('savesList');
228 savesList.innerHTML = '';
229
230 if (data.saves && data.saves.length > 0)
231 {
232 data.saves.forEach(save =>
233 {
234 const card = document.createElement('div');
235 card.className = 'save-card';
236 card.innerHTML = `
237 <h3>${save.name}</h3>
238 <p>Month: ${save.current_month}</p>
239 <p>Season: ${save.current_season}</p>
240 `;
241 card.addEventListener('click', () => this.loadGame(save.id));
242 savesList.appendChild(card);
243 });
244 }
245 } catch (error)
246 {
247 console.error('Failed to load saves:', error);
248 console.error('Response data:', dataText);
249 }
250 }
251
252 startGameSetup ()
253 {
254 this.hideAll();
255 document.getElementById('gameSetupScreen').classList.remove('hidden');
256 document.getElementById('setupStep1').classList.remove('hidden');
257 document.getElementById('setupStep2').classList.add('hidden');
258 document.getElementById('setupStep3').classList.add('hidden');
259 document.getElementById('setupStep4').classList.add('hidden');
260 this.selectedEnvironmentId = null;
261 this.pendingSetup = null;
262 }
263
264 async generateKobolds ()
265 {
266 const tribeName = document.getElementById('tribeName').value;
267
268 if (!tribeName)
269 {
270 alert('Please enter a tribe name');
271 return;
272 }
273
274 let dataText = "Request failed altogether";
275 try
276 {
277 const response = await fetch('api/game/generation', {
278 method: 'POST',
279 headers: {
280 'Content-Type': 'application/json',
281 'Authorization': `Bearer ${this.currentUser.token}`
282 },
283 body: JSON.stringify({
284 saveName: tribeName,
285 userId: this.currentUser.email
286 })
287 });
288
289 dataText = await response.text();
290 const data = JSON.parse(dataText);
291
292 if (data.success)
293 {
294 this.currentSave = data.save;
295 this.displayKobolds(data.kobolds, 'leader');
296 this.displayKobolds(data.kobolds, 'member');
297
298 document.getElementById('setupStep1').classList.add('hidden');
299 document.getElementById('setupStep2').classList.remove('hidden');
300 }
301 } catch (error)
302 {
303 alert('Failed to generate kobolds');
304 console.error(error);
305 console.error('Response data:', dataText);
306 }
307 }
308
309 displayKobolds (kobolds, type)
310 {
311 const container = type === 'leader'
312 ? document.getElementById('leaderSelectionGrid')
313 : document.getElementById('memberSelectionGrid');
314
315 container.innerHTML = '';
316
317 kobolds.forEach((kobold, index) =>
318 {
319 const card = document.createElement('div');
320 card.className = 'kobold-card';
321
322 const spriteUrl = `api/game/sprite?userId=${this.currentUser.email}&koboldId=${kobold.id}&age=${kobold.ageCategory}`;
323
324 card.innerHTML = `
325 <img src="${spriteUrl}" alt="Kobold sprite" class="kobold-sprite">
326 <div class="kobold-name">${kobold.age} years</div>
327 <div class="kobold-stats">
328 <div>Vitality: ${kobold.stats.vitality}</div>
329 </div>
330 `;
331
332 if (type === 'member')
333 {
334 card.addEventListener('click', () => this.toggleMemberSelection(card, index));
335 } else
336 {
337 card.addEventListener('click', () => this.selectLeaderCard(card, index));
338 }
339
340 container.appendChild(card);
341 });
342 }
343
344 async selectLeaderCard (card, index)
345 {
346 const leaderName = document.getElementById('leaderName').value;
347
348 if (!leaderName)
349 {
350 alert('Please enter a leader name');
351 return;
352 }
353
354 document.querySelectorAll('#leaderSelectionGrid .kobold-card').forEach(c => c.classList.remove('selected'));
355 card.classList.add('selected');
356 document.getElementById('selectLeaderBtn').dataset.leaderIndex = index;
357
358 this.toggleMemberSelection(card, index, true);
359 await this.selectLeader();
360 }
361
362 toggleMemberSelection (card, index, force)
363 {
364 const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex;
365 if (force || leaderIndex != index)
366 {
367 const selectedCard = document.querySelectorAll('#memberSelectionGrid .kobold-card')[index];
368 selectedCard.classList.toggle('selected');
369
370 if (force)
371 {
372 selectedCard.id = "tribeLeader";
373 }
374
375 const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length;
376 document.getElementById('memberCount').textContent = `${selected} / 5 selected`;
377
378 if (selected === 5)
379 {
380 document.getElementById('finishTribeBtn').disabled = false;
381 } else
382 {
383 document.getElementById('finishTribeBtn').disabled = true;
384 }
385 }
386 }
387
388 async selectLeader ()
389 {
390 const leaderName = document.getElementById('leaderName').value;
391
392 if (!leaderName)
393 {
394 alert('Please enter a leader name');
395 return;
396 }
397
398 // Proceed to member selection
399 document.getElementById('setupStep2').classList.add('hidden');
400 document.getElementById('setupStep3').classList.remove('hidden');
401
402 // For now, just display remaining kobolds (in real implementation, filter out leader)
403 }
404
405 async finishTribe ()
406 {
407 const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex;
408 const selectedMembers = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected');
409
410 const memberIndices = Array.from(selectedMembers).map(card =>
411 {
412 return Array.from(card.parentElement.children).indexOf(card);
413 });
414
415 this.pendingSetup = {
416 leaderIndex: leaderIndex,
417 memberIndices: memberIndices,
418 leaderName: document.getElementById('leaderName').value
419 };
420
421 await this.showEnvironmentStep();
422 }
423
424 async showEnvironmentStep ()
425 {
426 await this.ensureEnvironmentsLoaded();
427 this.renderEnvironmentOptions();
428 const select = document.getElementById('environmentSelect');
429 if (select)
430 {
431 select.value = '';
432 }
433 document.getElementById('setupStep3').classList.add('hidden');
434 document.getElementById('setupStep4').classList.remove('hidden');
435 this.selectedEnvironmentId = null;
436 const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn');
437 if (confirmEnvBtn)
438 {
439 confirmEnvBtn.disabled = true;
440 }
441 this.stopEnvironmentPreview();
442 const preview = document.getElementById('environmentPreview');
443 if (preview)
444 {
445 preview.removeAttribute('src');
446 }
447 const desc = document.getElementById('environmentDescription');
448 if (desc)
449 {
450 desc.textContent = '';
451 }
452 }
453
454 async ensureEnvironmentsLoaded ()
455 {
456 if (this.environments && this.environments.length > 0)
457 {
458 return;
459 }
460
461 await this.loadEnvironments();
462 }
463
464 async loadEnvironments ()
465 {
466 let dataText = "Request failed altogether";
467 try
468 {
469 const response = await fetch('api/game/environments', {
470 method: 'GET'
471 });
472
473 dataText = await response.text();
474 const data = JSON.parse(dataText);
475
476 if (data.success)
477 {
478 this.environments = data.environments || [];
479 this.environmentMap = {};
480 this.environments.forEach(env =>
481 {
482 if (env && env.id)
483 {
484 this.environmentMap[env.id] = env;
485 }
486 });
487 }
488 } catch (error)
489 {
490 console.error('Failed to load environments', error);
491 console.error('Response data:', dataText);
492 }
493 }
494
495 renderEnvironmentOptions ()
496 {
497 const select = document.getElementById('environmentSelect');
498 if (!select)
499 {
500 return;
501 }
502
503 select.innerHTML = '<option value="">Select an environment...</option>';
504 this.environments.forEach(env =>
505 {
506 const option = document.createElement('option');
507 option.value = env.id;
508 option.textContent = env.name || env.id;
509 select.appendChild(option);
510 });
511 }
512
513 handleEnvironmentSelection ()
514 {
515 const select = document.getElementById('environmentSelect');
516 const envId = select ? select.value : '';
517 this.selectedEnvironmentId = envId || null;
518
519 const env = this.environmentMap[envId];
520 const desc = document.getElementById('environmentDescription');
521 if (desc)
522 {
523 desc.textContent = env && env.description ? env.description : '';
524 }
525
526 const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn');
527 if (confirmEnvBtn)
528 {
529 confirmEnvBtn.disabled = !envId;
530 }
531
532 if (env && Array.isArray(env.images))
533 {
534 this.startEnvironmentPreview(env.images);
535 } else
536 {
537 this.stopEnvironmentPreview();
538 }
539 }
540
541 startEnvironmentPreview (images)
542 {
543 this.stopEnvironmentPreview();
544 const preview = document.getElementById('environmentPreview');
545 if (!preview || !images || images.length === 0)
546 {
547 return;
548 }
549
550 let index = 0;
551 preview.src = images[index];
552 this.environmentPreviewTimer = setInterval(() =>
553 {
554 index = (index + 1) % images.length;
555 preview.src = images[index];
556 }, 2000);
557 }
558
559 stopEnvironmentPreview ()
560 {
561 if (this.environmentPreviewTimer)
562 {
563 clearInterval(this.environmentPreviewTimer);
564 this.environmentPreviewTimer = null;
565 }
566 }
567
568 async confirmEnvironment ()
569 {
570 if (!this.pendingSetup)
571 {
572 alert('Missing tribe setup data. Please start again.');
573 return;
574 }
575
576 if (!this.selectedEnvironmentId)
577 {
578 alert('Please select an environment');
579 return;
580 }
581
582 let dataText = "Request failed altogether";
583 try
584 {
585 const response = await fetch('api/game/save', {
586 method: 'POST',
587 headers: {
588 'Content-Type': 'application/json',
589 'Authorization': `Bearer ${this.currentUser.token}`
590 },
591 body: JSON.stringify({
592 userId: this.currentUser.email,
593 saveId: this.currentSave.id,
594 leaderName: this.pendingSetup.leaderName,
595 memberIndices: this.pendingSetup.memberIndices,
596 leaderId: this.pendingSetup.leaderIndex,
597 environmentId: this.selectedEnvironmentId
598 })
599 });
600
601 dataText = await response.text();
602 const data = JSON.parse(dataText);
603
604 if (data.success)
605 {
606 this.stopEnvironmentPreview();
607 this.loadGame(this.currentSave.id);
608 }
609 } catch (error)
610 {
611 alert('Failed to finish tribe setup');
612 console.error(error);
613 console.error('Response data:', dataText);
614 }
615 }
616
617 async loadGame (saveId)
618 {
619 let dataText = "Request failed altogether";
620 try
621 {
622 const response = await fetch(`api/game/load?saveId=${saveId}&userId=${this.currentUser.email}`, {
623 method: 'GET',
624 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
625 });
626
627 dataText = await response.text();
628 const data = JSON.parse(dataText);
629
630 if (data.success)
631 {
632 this.currentSave = data.save;
633 this.currentTribe = data.tribe;
634 await this.ensureEnvironmentsLoaded();
635 await this.fetchAvailableEvents();
636 this.showGameScreen();
637 }
638 } catch (error)
639 {
640 alert('Failed to load game');
641 console.error(error);
642 console.error('Response data:', dataText);
643 }
644 }
645
646 showGameScreen ()
647 {
648 this.hideAll();
649 document.getElementById('gameScreen').classList.remove('hidden');
650 this.renderGame();
651 }
652
653 renderGame ()
654 {
655 document.getElementById('tribeName').textContent = this.currentSave.name;
656 document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`;
657 document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season);
658
659 this.renderEnvironment();
660 this.renderStorage();
661 this.renderTribeList();
662 this.renderEvents();
663 }
664
665 renderEnvironment ()
666 {
667 const envElement = document.getElementById('environment');
668 if (!envElement)
669 {
670 return;
671 }
672
673 const envId = this.getActiveEnvironmentId();
674 if (!envId)
675 {
676 envElement.style.backgroundImage = '';
677 const placements = document.getElementById('koboldPlacements');
678 if (placements)
679 {
680 placements.innerHTML = '';
681 }
682 return;
683 }
684
685 const season = (this.currentSave.current_season || 'spring').toLowerCase();
686 let imageUrl = `assets/environments/${envId}/${season}.png`;
687 const env = this.environmentMap[envId];
688 if (env && Array.isArray(env.images) && env.images.length > 0)
689 {
690 const seasonMatch = env.images.find(img => img.includes(`/${season}.png`));
691 if (seasonMatch)
692 {
693 imageUrl = seasonMatch;
694 } else
695 {
696 imageUrl = env.images[0];
697 }
698 }
699
700 envElement.style.backgroundImage = `url('${imageUrl}')`;
701 this.renderEnvironmentPlacements(envId);
702 }
703
704 renderEnvironmentPlacements (envId)
705 {
706 const placements = document.getElementById('koboldPlacements');
707 if (!placements)
708 {
709 return;
710 }
711
712 const placementKey = `${this.currentSave?.id ?? 'save'}-${envId}-${this.currentSave?.current_month ?? 0}`;
713 if (this.lastPlacementKey === placementKey && placements.children.length > 0)
714 {
715 return;
716 }
717
718 this.lastPlacementKey = placementKey;
719 placements.innerHTML = '';
720 const env = this.environmentMap[envId];
721 if (!env || !Array.isArray(env.koboldLocations))
722 {
723 return;
724 }
725
726 const spots = env.koboldLocations
727 .map(loc => ({
728 x: loc ? Number(loc.x) : NaN,
729 y: loc ? Number(loc.y) : NaN
730 }))
731 .filter(loc => Number.isFinite(loc.x) && Number.isFinite(loc.y));
732
733 if (spots.length === 0 || !this.currentTribe || !Array.isArray(this.currentTribe.kobolds))
734 {
735 return;
736 }
737
738 let availableSpots = this.shuffleArray(spots.slice());
739 if (availableSpots.length > 30)
740 {
741 availableSpots = availableSpots.slice(0, 30);
742 }
743
744 let leader = this.currentTribe.kobolds.find(k => k.is_leader);
745 if (!leader)
746 {
747 leader = this.currentTribe.kobolds[0];
748 }
749
750 if (!leader)
751 {
752 return;
753 }
754
755 const leaderSpotIndex = Math.floor(Math.random() * availableSpots.length);
756 const leaderSpot = availableSpots.splice(leaderSpotIndex, 1)[0];
757 const placementList = [{ kobold: leader, spot: leaderSpot }];
758
759 const others = this.currentTribe.kobolds.filter(k => k.id !== leader.id);
760 const shuffledOthers = this.shuffleArray(others.slice());
761 const maxOthers = Math.min(availableSpots.length, 29, shuffledOthers.length);
762
763 for (let i = 0; i < maxOthers; i++)
764 {
765 placementList.push({ kobold: shuffledOthers[i], spot: availableSpots[i] });
766 }
767
768 placementList.sort((a, b) => a.spot.y - b.spot.y);
769
770 placementList.forEach(entry =>
771 {
772 const spriteUrl = `api/game/sprite?userId=${this.currentUser.email}&koboldId=${entry.kobold.id}&age=${entry.kobold.ageCategory}`;
773 const img = document.createElement('img');
774 img.src = spriteUrl;
775 img.alt = entry.kobold.name;
776 img.className = 'kobold-placement';
777 if (Math.random() < 0.5)
778 {
779 img.classList.add('flipped');
780 }
781 img.style.left = `${entry.spot.x * 100}%`;
782 img.style.top = `${entry.spot.y * 100}%`;
783 img.style.zIndex = Math.round(entry.spot.y * 1000).toString();
784 img.addEventListener('click', (event) =>
785 {
786 event.stopPropagation();
787 this.showKoboldModal(entry.kobold);
788 });
789 placements.appendChild(img);
790 });
791 }
792
793 getActiveEnvironmentId ()
794 {
795 if (this.currentSave && this.currentSave.environment_id)
796 {
797 return this.currentSave.environment_id;
798 }
799 if (this.selectedEnvironmentId)
800 {
801 return this.selectedEnvironmentId;
802 }
803 if (this.environments && this.environments.length > 0)
804 {
805 return this.environments[0].id;
806 }
807 return null;
808 }
809
810 logEnvironmentClick (event)
811 {
812 const envElement = document.getElementById('environment');
813 if (!envElement)
814 {
815 return;
816 }
817
818 if (event.target && event.target.closest && event.target.closest('.kobold-placement'))
819 {
820 return;
821 }
822
823 const rect = envElement.getBoundingClientRect();
824 const x = (event.clientX - rect.left) / rect.width;
825 const y = (event.clientY - rect.top) / rect.height;
826 const normalizedX = Math.max(0, Math.min(1, x));
827 const normalizedY = Math.max(0, Math.min(1, y));
828 console.log('Environment click:', {
829 x: Number(normalizedX.toFixed(3)),
830 y: Number(normalizedY.toFixed(3))
831 });
832 }
833
834 shuffleArray (array)
835 {
836 for (let i = array.length - 1; i > 0; i--)
837 {
838 const j = Math.floor(Math.random() * (i + 1));
839 [array[i], array[j]] = [array[j], array[i]];
840 }
841 return array;
842 }
843
844 renderTribeList ()
845 {
846 const list = document.getElementById('tribeList');
847 list.innerHTML = '';
848
849 this.currentTribe.kobolds.forEach(kobold =>
850 {
851 const spriteUrl = `api/game/sprite?userId=${this.currentUser.email}&koboldId=${kobold.id}&age=${kobold.ageCategory}`;
852 const item = document.createElement('div');
853 const isInjured = kobold.injuries && kobold.injuries.length > 0;
854 item.className = `tribe-item ${isInjured ? 'injured' : ''}`;
855 item.innerHTML = `
856 <table style="width:100%">
857 <td>
858 <img class="kobold-list-sprite" src="${spriteUrl}"/>
859 </td>
860 <td>
861 <div>
862 <div class="tribe-item-name">${kobold.name}</div>
863 <div class="tribe-item-age">${(kobold.age > 0 ? kobold.age : 0)} years</div>
864 </div>
865 </td>
866 </table>
867 `;
868 item.addEventListener('click', () => this.showKoboldModal(kobold));
869 list.appendChild(item);
870 });
871 }
872
873 renderEvents ()
874 {
875 const list = document.getElementById('eventsList');
876 list.innerHTML = '';
877
878 this.availableEvents = this.availableEvents || [];
879 this.availableEvents = this.availableEvents.filter(evt => !!evt.available);
880
881 if (!this.availableEvents || this.availableEvents.length === 0)
882 {
883 const empty = document.createElement('div');
884 empty.className = 'event-item disabled';
885 empty.textContent = 'No events available';
886 list.appendChild(empty);
887 return;
888 }
889
890 this.availableEvents.forEach(evt =>
891 {
892 function costToText (cost)
893 {
894 if (cost >= 95) return "impossible";
895 if (cost >= 80) return "near impossible";
896 if (cost >= 70) return "extreme";
897 if (cost >= 60) return "brutal";
898 if (cost >= 50) return "very hard";
899 if (cost >= 40) return "hard";
900 if (cost >= 30) return "difficult";
901 if (cost >= 20) return "moderate";
902 if (cost >= 10) return "easy";
903 return "trivial";
904 }
905
906 const item = document.createElement('div');
907 const isAvailable = !!evt.available;
908 item.className = `event-item ${isAvailable ? '' : 'disabled'}`.trim();
909 const costText = Number.isFinite(Number(evt.cost)) ? ` (${costToText(Number(evt.cost))})` : '';
910 item.textContent = `${evt.name || evt.type}${costText}${isAvailable ? '' : ' (Unavailable)'}`;
911 if (isAvailable)
912 {
913 item.addEventListener('click', () => this.showParticipantModal(evt.type));
914 }
915 list.appendChild(item);
916 });
917 }
918
919 async fetchAvailableEvents ()
920 {
921 this.availableEvents = [];
922 this.availableEventsByType = {};
923
924 if (!this.currentUser || !this.currentSave)
925 return;
926
927 let dataText = "Request failed altogether";
928 try
929 {
930 const response = await fetch(`api/game/events?saveId=${this.currentSave.id}&userId=${this.currentUser.email}`, {
931 method: 'GET',
932 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
933 });
934
935 dataText = await response.text();
936 const data = JSON.parse(dataText);
937
938 if (data.success && Array.isArray(data.events))
939 {
940 this.availableEvents = data.events;
941 data.events.forEach(evt =>
942 {
943 if (evt && evt.type)
944 this.availableEventsByType[evt.type] = evt;
945 });
946 }
947 } catch (error)
948 {
949 console.error('Failed to load events:', error);
950 console.error('Response data:', dataText);
951 }
952 }
953
954 async executeEvent (eventType)
955 {
956 // Deprecated direct execution; use participant modal instead
957 this.showParticipantModal(eventType);
958 }
959
960 showParticipantModal (eventType)
961 {
962 this.currentEventType = eventType;
963 const modal = document.getElementById('participantModal');
964 const eventData = this.availableEventsByType[eventType] || {};
965 const eventLabel = eventData.name || eventType;
966 document.getElementById('participantModalTitle').textContent = `Select participants for ${eventLabel}`;
967
968 const list = document.getElementById('participantsList');
969 list.innerHTML = '';
970
971 this.participantMin = eventData.min_participants ?? 1;
972 this.participantMax = eventData.max_participants ?? 3;
973 this.participantMinAge = eventData.min_age ?? 0;
974 this.participantCost = eventData.cost || 0;
975
976 // Helper: check if kobold is eligible
977 const isEligible = (kobold) =>
978 {
979 const ageCategory = (kobold.ageCategory || '').toLowerCase();
980 if (ageCategory === 'egg') return false; // eggs cannot participate
981 if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend)
982 if (kobold.age < this.participantMinAge) return false; // too young
983 const fatigue = Number(kobold.fatigue || 0);
984 const vitality = Number(kobold.stats?.vitality || 0);
985 if ((fatigue + this.participantCost) > vitality) return false;
986 return true;
987 };
988
989 // Render kobolds with eligibility status
990 this.currentTribe.kobolds.forEach(kobold =>
991 {
992 const ageCategory = (kobold.ageCategory || '').toLowerCase();
993 const eligible = isEligible(kobold);
994 let reason = '';
995
996 if (ageCategory === 'egg')
997 reason = '(eggs cannot participate)';
998 else if (kobold.age < this.participantMinAge)
999 reason = `(too young, needs age ${this.participantMinAge}+)`;
1000 else if (this.participantCost > Number(kobold.stats?.vitality || 0))
1001 reason = '(too weak)';
1002 else if ((Number(kobold.fatigue || 0) + this.participantCost) > Number(kobold.stats?.vitality || 0))
1003 reason = '(too tired)';
1004
1005 const row = document.createElement('div');
1006 row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`;
1007
1008 const fatigueValue = Number(kobold.fatigue || 0);
1009 const vitalityValue = Number(kobold.stats?.vitality || 0);
1010 const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue);
1011
1012 if (eligible)
1013 {
1014 row.innerHTML = `
1015 <label>
1016 <input type="checkbox" class="participant-checkbox" data-id="${kobold.id}">
1017 <strong>${kobold.name}</strong> (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'})
1018 </label>
1019 `;
1020 const cb = row.querySelector('.participant-checkbox');
1021 cb.addEventListener('change', () => this._updateParticipantButtons());
1022 } else
1023 {
1024 row.innerHTML = `
1025 <div class="participant-disabled">
1026 <span>${kobold.name} (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'})</span>
1027 <span class="disabled-reason">${reason}</span>
1028 </div>
1029 `;
1030 }
1031
1032 list.appendChild(row);
1033 });
1034
1035 document.getElementById('participantCount').textContent = `0 selected`;
1036
1037 // cancel/start handlers
1038 const cancelBtn = document.getElementById('cancelParticipantsBtn');
1039 const startBtn = document.getElementById('startEventBtn');
1040
1041 cancelBtn.onclick = () => { modal.classList.add('hidden'); };
1042 startBtn.onclick = async () => { await this.startEventWithParticipants(); };
1043
1044 // initial state
1045 this._updateParticipantButtons();
1046
1047 modal.classList.remove('hidden');
1048 }
1049
1050 _updateParticipantButtons ()
1051 {
1052 const list = document.getElementById('participantsList');
1053 const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id);
1054 const count = selected.length;
1055 const participantCount = document.getElementById('participantCount');
1056 const minRequired = this.participantMin || 1;
1057 const maxAllowed = this.participantMax || 3;
1058 let warning = '';
1059 if (count < minRequired)
1060 {
1061 warning = `need at least ${minRequired}`;
1062 } else if (count > maxAllowed)
1063 {
1064 warning = `${count - maxAllowed} too many`;
1065 }
1066
1067 const warningHtml = warning ? `<br><span style="color:#d9534f;">${warning.trim()}</span>` : '';
1068 participantCount.innerHTML = `${count} selected${warningHtml}`;
1069
1070 const startBtn = document.getElementById('startEventBtn');
1071 if (count >= (this.participantMin || 1) && count <= (this.participantMax || 3))
1072 {
1073 startBtn.disabled = false;
1074 } else
1075 {
1076 startBtn.disabled = true;
1077 }
1078 }
1079
1080 async startEventWithParticipants ()
1081 {
1082 const modal = document.getElementById('participantModal');
1083 const list = document.getElementById('participantsList');
1084 const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id);
1085
1086 if (!selected || selected.length === 0) return;
1087
1088 let dataText = "Request failed altogether";
1089 try
1090 {
1091 const resp = await fetch('api/game/event', {
1092 method: 'POST',
1093 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` },
1094 body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected })
1095 });
1096
1097 dataText = await resp.text();
1098 const data = JSON.parse(dataText);
1099
1100 if (data.success)
1101 {
1102 typeText(document.getElementById('eventStory'), data.story);
1103 this.showEventModal();
1104 modal.classList.add('hidden');
1105 await this.loadGame(this.currentSave.id);
1106 } else
1107 {
1108 alert(data.error || 'Failed to start event');
1109 console.error('Event error:', data);
1110 }
1111 } catch (err)
1112 {
1113 console.error(err);
1114 console.error('Response data:', dataText);
1115 }
1116 }
1117
1118 async endMonth ()
1119 {
1120 let dataT = "Request failed altogether";
1121 try
1122 {
1123 const response = await fetch('api/game/endMonth', {
1124 method: 'POST',
1125 headers: {
1126 'Content-Type': 'application/json',
1127 'Authorization': `Bearer ${this.currentUser.token}`
1128 },
1129 body: JSON.stringify({
1130 userId: this.currentUser.email, saveId: this.currentSave.id
1131 })
1132 });
1133
1134 dataT = await response.text();
1135 const data = JSON.parse(dataT);
1136
1137 if (data.success)
1138 {
1139 this.currentSave = data.save;
1140 typeText(document.getElementById('eventStory'), data.monthStory);
1141 this.showEventModal();
1142 await this.loadGame(this.currentSave.id);
1143 }
1144 } catch (error)
1145 {
1146 alert('Failed to end month');
1147 console.error(error);
1148 console.error('Response data:', dataT);
1149 }
1150 }
1151
1152 showEventModal ()
1153 {
1154 document.getElementById('eventModal').classList.remove('hidden');
1155 }
1156
1157 hideEventModal ()
1158 {
1159 if (!doneTyping) return;
1160 document.getElementById('eventModal').classList.add('hidden');
1161 this.renderGame();
1162 }
1163
1164 renderStorage ()
1165 {
1166 const foodDisplay = document.getElementById('foodDisplay');
1167 const timeLeft = this.currentSave.food_time_remaining;
1168 if (timeLeft !== undefined && timeLeft !== null)
1169 {
1170 const label = timeLeft;
1171 foodDisplay.textContent = `Food: ${label}`;
1172 } else
1173 {
1174 foodDisplay.textContent = `Food: ${this.currentSave.food_count}`;
1175 }
1176
1177 const storageItems = document.getElementById('storageItems');
1178 storageItems.innerHTML = '';
1179
1180 if (!this.currentTribe.storage || this.currentTribe.storage.length === 0)
1181 {
1182 storageItems.innerHTML = '<div style="text-align: center; color: #999; padding: 10px;">No items in storage</div>';
1183 return;
1184 }
1185
1186 this.currentTribe.storage.forEach(item =>
1187 {
1188 const itemEl = document.createElement('div');
1189 itemEl.className = 'storage-item';
1190 itemEl.innerHTML = `<div class="storage-item-name">${item.name}</div>`;
1191 itemEl.addEventListener('click', () => this.showItemModal(item));
1192 storageItems.appendChild(itemEl);
1193 });
1194 }
1195
1196 showItemModal (item)
1197 {
1198 const modal = document.getElementById('itemModal');
1199 document.getElementById('itemModalName').textContent = item.name;
1200 document.getElementById('itemModalDescription').textContent = item.description || 'No description';
1201
1202 // Show stat modifications (handle both camelCase and snake_case)
1203 const statMods = document.getElementById('itemModalStatMods');
1204 statMods.innerHTML = '';
1205
1206 const modifications = item.stat_modifications || item.statModifications || {};
1207 if (Object.keys(modifications).length > 0)
1208 {
1209 Object.entries(modifications).forEach(([stat, value]) =>
1210 {
1211 if (value !== 0)
1212 {
1213 const modEl = document.createElement('div');
1214 modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`;
1215 modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`;
1216 statMods.appendChild(modEl);
1217 }
1218 });
1219 } else
1220 {
1221 statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>';
1222 }
1223
1224 // Restore item modal actions to storage version
1225 const actions = document.querySelector('.item-modal-actions');
1226 actions.innerHTML = '';
1227
1228 const select = document.createElement('select');
1229 select.id = 'itemKoboldSelect';
1230 select.className = 'kobold-select';
1231 select.innerHTML = '<option value="">Select a Kobold...</option>';
1232 this.currentTribe.kobolds.forEach(kobold =>
1233 {
1234 const option = document.createElement('option');
1235 option.value = kobold.id;
1236 option.textContent = kobold.name;
1237 select.appendChild(option);
1238 });
1239
1240 const giveBtn = document.createElement('button');
1241 giveBtn.id = 'giveItemBtn';
1242 giveBtn.className = 'primary';
1243 giveBtn.textContent = 'Give Item';
1244 giveBtn.disabled = true;
1245
1246 select.addEventListener('change', (e) =>
1247 {
1248 giveBtn.disabled = !e.target.value;
1249 });
1250
1251 giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value));
1252
1253 actions.appendChild(select);
1254 actions.appendChild(giveBtn);
1255
1256 modal.classList.remove('hidden');
1257 }
1258
1259 async giveItemToKobold (item, koboldId)
1260 {
1261 let dataText = "Request failed altogether";
1262 try
1263 {
1264 const resp = await fetch('api/game/giveItem', {
1265 method: 'POST',
1266 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
1267 body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id })
1268 });
1269
1270 dataText = await resp.text();
1271 const data = JSON.parse(dataText);
1272 if (data.success)
1273 {
1274 typeText(document.getElementById('eventStory'), data.story);
1275 this.showEventModal();
1276 // Refresh game state
1277 await this.loadGame(this.currentSave.id);
1278 const kob = this.currentTribe.kobolds.find(k => k.id === koboldId);
1279 } else
1280 {
1281 alert(data.error || 'Failed to give item');
1282 console.error('Give item error:', data);
1283 }
1284 } catch (err)
1285 {
1286 console.error(err);
1287 alert('Failed to give item');
1288 console.error('Response data:', dataText);
1289 } finally
1290 {
1291 this.hideItemModal();
1292 }
1293 }
1294
1295 hideItemModal ()
1296 {
1297 document.getElementById('itemModal').classList.add('hidden');
1298 }
1299
1300 hideKoboldModal ()
1301 {
1302 const modal = document.getElementById('koboldModal');
1303 modal.classList.add('hidden');
1304 }
1305
1306 showKoboldModal (kobold)
1307 {
1308 const modal = document.getElementById('koboldModal');
1309 document.getElementById('koboldModalName').textContent = kobold.name;
1310
1311 const a = (kobold.ageCategory == "old" || kobold.ageCategory == "adult") ? "An" : "A";
1312
1313 if (kobold.ageCategory == "egg")
1314 {
1315 document.getElementById('koboldModalAge').textContent = `Not yet hatched`;
1316 document.getElementById('koboldModalDescription').textContent = `An egg.`;
1317 }
1318 else
1319 {
1320 document.getElementById('koboldModalAge').textContent = `${kobold.age} years old`;
1321 document.getElementById('koboldModalDescription').textContent = `${a} ${kobold.ageCategory} ${(kobold.male ? "male" : "female")} Kobold.`;
1322 }
1323
1324 this.renderKoboldStats(kobold);
1325 this.renderKoboldInventory(kobold);
1326 this.renderKoboldInjuries(kobold);
1327 this.renderKoboldRelationships(kobold);
1328
1329 // Setup tab buttons
1330 document.querySelectorAll('.kobold-tab-btn').forEach(btn =>
1331 {
1332 btn.classList.remove('active');
1333 btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab));
1334 });
1335 document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active');
1336
1337 // Hide all tabs
1338 document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active'));
1339 document.getElementById('koboldStatsTab').classList.add('active');
1340
1341 // Store current kobold for inventory actions
1342 this.selectedKobold = kobold;
1343
1344 modal.classList.remove('hidden');
1345 }
1346
1347 renderKoboldStats (kobold)
1348 {
1349 const statsGrid = document.getElementById('koboldStats');
1350 statsGrid.innerHTML = '';
1351
1352 const stats = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
1353 stats.forEach(stat =>
1354 {
1355 const value = kobold.stats[stat];
1356 const label = this.getStatLabel(value);
1357 const statEl = document.createElement('div');
1358 statEl.className = 'stat-item';
1359 statEl.innerHTML = `
1360 <div class="stat-name">${stat}</div>
1361 <div class="stat-value">${label}</div>
1362 `;
1363 statsGrid.appendChild(statEl);
1364 });
1365
1366 const fatigueValue = Number(kobold.fatigue || 0);
1367 const vitalityValue = Number(kobold.stats?.vitality || 0);
1368 const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue);
1369 const fatigueEl = document.createElement('div');
1370 fatigueEl.className = 'stat-item';
1371 fatigueEl.innerHTML = `
1372 <div class="stat-name">energy</div>
1373 <div class="stat-value">${fatigueLabel}</div>
1374 `;
1375 statsGrid.appendChild(fatigueEl);
1376 }
1377
1378 renderKoboldInventory (kobold)
1379 {
1380 const inventory = document.getElementById('koboldInventory');
1381 inventory.innerHTML = '';
1382
1383 if (!kobold.items || kobold.items.length === 0)
1384 {
1385 inventory.innerHTML = '<div class="kobold-inventory-empty">No items in inventory</div>';
1386 return;
1387 }
1388
1389 kobold.items.forEach(item =>
1390 {
1391 const itemEl = document.createElement('div');
1392 itemEl.className = 'kobold-inventory-item';
1393 itemEl.innerHTML = `<div class="kobold-item-name">${item.name}</div>`;
1394 itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold));
1395 inventory.appendChild(itemEl);
1396 });
1397 }
1398
1399 renderKoboldInjuries (kobold)
1400 {
1401 const container = document.getElementById('koboldInjuries');
1402 container.innerHTML = '';
1403
1404 if (!kobold.injuries || kobold.injuries.length === 0)
1405 {
1406 container.innerHTML = '<div class="kobold-inventory-empty">No injuries</div>';
1407 return;
1408 }
1409
1410 // Mapping of injury category to required cure item (matches PHP Injury::$cureMap)
1411 const cureMap = {
1412 'wound': 'basic_medicine',
1413 'fracture': 'bone-setting',
1414 'infection': 'healing_herbs',
1415 'poison': 'antidote',
1416 'burn': 'burn_salve',
1417 'malnourished': 'food',
1418 'old-age': null
1419 };
1420
1421 kobold.injuries.forEach(injury =>
1422 {
1423 const el = document.createElement('div');
1424 el.className = 'injury-item';
1425 const name = injury.injury_type || injury.injuryType || 'Injury';
1426 const desc = injury.description || '';
1427 const severity = injury.severity ?? injury.severity ?? 1;
1428
1429 el.innerHTML = `
1430 <div class="injury-name">${name}</div>
1431 <div class="injury-desc">${desc}</div>
1432 `;
1433
1434 const actions = document.createElement('div');
1435 actions.className = 'injury-actions';
1436
1437 // malnourished has no cure button here
1438 if (injury.category !== 'malnourished' && injury.category !== 'old-age')
1439 {
1440 // Get required medicine from server or calculate from cureMap
1441 let required = injury.required_medicine || injury.requiredMedicine || null;
1442 if (!required && injury.category)
1443 {
1444 required = cureMap[injury.category] || null;
1445 }
1446
1447 if (required)
1448 {
1449 // check if kobold has item with this id
1450 const hasItem = (kobold.items || []).some(it => it.id === required);
1451 if (hasItem)
1452 {
1453 const btn = document.createElement('button');
1454 btn.className = 'primary';
1455 btn.textContent = `Cure using ${required}`;
1456 btn.addEventListener('click', async () =>
1457 {
1458 let dataText = "Request failed altogether";
1459 try
1460 {
1461 const resp = await fetch('api/game/cureInjury', {
1462 method: 'POST',
1463 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
1464 body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required })
1465 });
1466 dataText = await resp.text();
1467 const data = JSON.parse(dataText);
1468 if (data.success)
1469 {
1470 this.hideKoboldModal();
1471 typeText(document.getElementById('eventStory'), data.story);
1472 this.showEventModal();
1473 // Refresh game state
1474 await this.loadGame(this.currentSave.id);
1475 // reopen kobold modal after refresh
1476 const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id);
1477
1478 } else
1479 {
1480 alert(data.error || 'Failed to cure injury');
1481 console.error('Cure injury error:', data);
1482 }
1483 } catch (err)
1484 {
1485 console.error(err);
1486 alert('Failed to cure injury');
1487 console.error('Response data:', dataText);
1488 }
1489 });
1490 actions.appendChild(btn);
1491 } else
1492 {
1493 const note = document.createElement('div');
1494 note.style.color = '#999';
1495 note.textContent = `Needs: ${required}`;
1496 actions.appendChild(note);
1497 }
1498 }
1499 }
1500
1501 el.appendChild(actions);
1502 container.appendChild(el);
1503 });
1504 }
1505
1506 showKoboldItemModal (item, kobold)
1507 {
1508 const modal = document.getElementById('itemModal');
1509 document.getElementById('itemModalName').textContent = item.name;
1510 document.getElementById('itemModalDescription').textContent = item.description || 'No description';
1511
1512 this.hideKoboldModal();
1513 // Show stat modifications (handle both camelCase and snake_case)
1514 const statMods = document.getElementById('itemModalStatMods');
1515 statMods.innerHTML = '';
1516
1517 const modifications = item.stat_modifications || item.statModifications || {};
1518 if (Object.keys(modifications).length > 0)
1519 {
1520 Object.entries(modifications).forEach(([stat, value]) =>
1521 {
1522 if (value !== 0)
1523 {
1524 const modEl = document.createElement('div');
1525 modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`;
1526 modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`;
1527 statMods.appendChild(modEl);
1528 }
1529 });
1530 } else
1531 {
1532 statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>';
1533 }
1534
1535 // Change button to return item
1536 const actions = document.querySelector('.item-modal-actions');
1537 actions.innerHTML = '';
1538
1539 const returnBtn = document.createElement('button');
1540 returnBtn.className = 'secondary';
1541 returnBtn.textContent = 'Return to Storage';
1542 returnBtn.addEventListener('click', () =>
1543 {
1544 this.hideKoboldModal();
1545 this.returnItemToStorage(item, kobold);
1546 });
1547
1548 actions.appendChild(returnBtn);
1549
1550 modal.classList.remove('hidden');
1551 this.selectedKobold = kobold;
1552 }
1553
1554 async returnItemToStorage (item, kobold)
1555 {
1556 let dataText = "Request failed altogether";
1557 try
1558 {
1559 const resp = await fetch('api/game/returnItem', {
1560 method: 'POST',
1561 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
1562 body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id })
1563 });
1564
1565 dataText = await resp.text();
1566 const data = JSON.parse(dataText);
1567 if (data.success)
1568 {
1569 typeText(document.getElementById('eventStory'), data.story);
1570 this.showEventModal();
1571 // Refresh game state
1572 await this.loadGame(this.currentSave.id);
1573 const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id);
1574 } else
1575 {
1576 alert(data.error || 'Failed to return item');
1577 console.error('Return item error:', data);
1578 }
1579 } catch (err)
1580 {
1581 console.error(err);
1582 alert('Failed to return item');
1583 console.error('Response data:', dataText);
1584 } finally
1585 {
1586 this.hideItemModal();
1587 }
1588 }
1589
1590 switchKoboldTab (tabName)
1591 {
1592 // Hide all tabs
1593 document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active'));
1594 document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active'));
1595
1596 // Show selected tab
1597 const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab';
1598 document.getElementById(tabId).classList.add('active');
1599 document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
1600 }
1601
1602 getLikeDescriptor (likeValue)
1603 {
1604 const val = Number(likeValue || 0);
1605
1606 if (val <= -40) return { text: 'terrible', color: '#d9534f' };
1607 if (val <= -30) return { text: 'awful', color: '#e74c3c' };
1608 if (val <= -20) return { text: 'poor', color: '#e8765d' };
1609 if (val <= -10) return { text: 'bad', color: '#ec8a6a' };
1610 if (val < 0) return { text: 'cold', color: '#f0a080' };
1611 if (val === 0) return { text: 'neutral', color: '#999' };
1612 if (val < 10) return { text: 'okay', color: '#95b9a5' };
1613 if (val < 20) return { text: 'good', color: '#7cb87b' };
1614 if (val < 30) return { text: 'nice', color: '#63b76f' };
1615 if (val < 40) return { text: 'great', color: '#51a859' };
1616 return { text: 'wonderful', color: '#27ae60' };
1617 }
1618
1619 renderKoboldRelationships (kobold)
1620 {
1621 const container = document.getElementById('koboldRelationships');
1622 container.innerHTML = '';
1623
1624 const likes = kobold.likes || {};
1625
1626 // Separate tribe members and rivals
1627 const tribeMembers = [];
1628 const rivals = [];
1629
1630 for (const [targetId, likeValue] of Object.entries(likes))
1631 {
1632 if (likeValue === 0) continue; // Skip neutral relationships
1633
1634 // Check if it's a tribe member
1635 const tribeMember = this.currentTribe.kobolds.find(k => k.id === targetId);
1636 if (tribeMember)
1637 {
1638 tribeMembers.push({ id: targetId, name: tribeMember.name, likeValue });
1639 } else
1640 {
1641 // Check if it's a rival
1642 const rivalData = this.currentSave?.rivals || [];
1643 const rival = rivalData.find(r => r.id === targetId);
1644 if (rival)
1645 {
1646 rivals.push({ id: targetId, name: rival.name, likeValue });
1647 }
1648 }
1649 }
1650
1651 // Sort by like value (descending)
1652 const sort = (a, b) => b.likeValue - a.likeValue;
1653 tribeMembers.sort(sort);
1654 rivals.sort(sort);
1655
1656 // Render tribe members
1657 if (tribeMembers.length > 0)
1658 {
1659 const tribeSection = document.createElement('div');
1660 tribeSection.className = 'relationships-section';
1661
1662 const tribeTitle = document.createElement('h4');
1663 tribeTitle.textContent = 'Tribe Members';
1664 tribeSection.appendChild(tribeTitle);
1665
1666 tribeMembers.forEach(member =>
1667 {
1668 const descriptor = this.getLikeDescriptor(member.likeValue);
1669 const item = document.createElement('div');
1670 item.className = 'relationship-item';
1671 item.innerHTML = `
1672 <span class="relationship-name">${member.name}</span>
1673 <span class="relationship-descriptor" style="color: ${descriptor.color}">${descriptor.text}</span>
1674 `;
1675 tribeSection.appendChild(item);
1676 });
1677
1678 container.appendChild(tribeSection);
1679 }
1680
1681 // Render rivals
1682 if (rivals.length > 0)
1683 {
1684 const rivalsSection = document.createElement('div');
1685 rivalsSection.className = 'relationships-section';
1686
1687 const rivalsTitle = document.createElement('h4');
1688 rivalsTitle.textContent = 'Rivals';
1689 rivalsSection.appendChild(rivalsTitle);
1690
1691 rivals.forEach(rival =>
1692 {
1693 const descriptor = this.getLikeDescriptor(rival.likeValue);
1694 const item = document.createElement('div');
1695 item.className = 'relationship-item';
1696 item.innerHTML = `
1697 <span class="relationship-name">${rival.name}</span>
1698 <span class="relationship-descriptor" style="color: ${descriptor.color}">${descriptor.text}</span>
1699 `;
1700 rivalsSection.appendChild(item);
1701 });
1702
1703 container.appendChild(rivalsSection);
1704 }
1705
1706 // Show message if no relationships
1707 if (tribeMembers.length === 0 && rivals.length === 0)
1708 {
1709 const noRels = document.createElement('p');
1710 noRels.style.color = '#999';
1711 noRels.textContent = 'No relationships to display.';
1712 container.appendChild(noRels);
1713 }
1714 }
1715
1716 getStatLabel (statValue)
1717 {
1718 if (statValue >= 90) return 'godlike';
1719 if (statValue >= 80) return 'divine';
1720 if (statValue >= 70) return 'master';
1721 if (statValue >= 60) return 'fantastic';
1722 if (statValue >= 50) return 'excellent';
1723 if (statValue >= 40) return 'good';
1724 if (statValue >= 30) return 'decent';
1725 if (statValue >= 20) return 'unskilled';
1726 if (statValue >= 10) return 'bad';
1727 return 'terrible';
1728 }
1729
1730 getFatigueLabel (fatigue, vitality)
1731 {
1732 const vit = Number(vitality || 0);
1733 const fat = Number(fatigue || 0);
1734 if (vit <= 0) return 'exhausted';
1735 if (fat <= 0) return 'energetic';
1736 const ratio = fat / Math.max(1, vit);
1737 if (ratio < 0.3) return 'fresh';
1738 if (ratio < 0.6) return 'tired';
1739 if (ratio < 0.85) return 'weary';
1740 return 'exhausted';
1741 }
1742
1743 hideAll ()
1744 {
1745 document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden'));
1746 }
1747
1748 capitalizeFirst (str)
1749 {
1750 return str.charAt(0).toUpperCase() + str.slice(1);
1751 }
1752}
1753
1754// Initialize app when DOM is ready
1755document.addEventListener('DOMContentLoaded', () =>
1756{
1757 window.app = new TribeGenApp();
1758});
1759
1760function typeText (element, text, minDelay = 3, maxDelay = 65)
1761{
1762 doneTyping = false;
1763 element.textContent = "";
1764 let index = 0;
1765 let timerId = null;
1766
1767 const randDelay = () =>
1768 Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;
1769
1770 const shouldStop = () =>
1771 {
1772 if (!element.isConnected) return true;
1773 if (getComputedStyle(element).display === "none") return true;
1774 return false;
1775 };
1776
1777 return new Promise((resolve) =>
1778 {
1779 function tick ()
1780 {
1781 if (shouldStop())
1782 {
1783 if (timerId) clearTimeout(timerId);
1784 doneTyping = true;
1785 resolve(false); // stopped early
1786 return;
1787 }
1788
1789 if (index >= text.length)
1790 {
1791 doneTyping = true;
1792 resolve(true); // finished normally
1793 return;
1794 }
1795
1796 element.textContent += text[index++];
1797 timerId = setTimeout(tick, randDelay());
1798 }
1799
1800 tick();
1801 });
1802}
1803