BlueGit

blue-star tribegen

Files

tribegen / web / js / app.js

app.js

app.js 44.0 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.init();
13 }
14
15 async init ()
16 {
17 this.setupEventListeners();
18 this.checkAuth();
19 }
20
21 setupEventListeners ()
22 {
23 // Auth Events
24 document.getElementById('loginForm').addEventListener('submit', (e) => this.handleLogin(e));
25 document.getElementById('registerForm').addEventListener('submit', (e) => this.handleRegister(e));
26 document.getElementById('logoutBtn').addEventListener('click', () => this.handleLogout());
27
28 // Tab switching
29 document.querySelectorAll('.tab-btn').forEach(btn =>
30 {
31 btn.addEventListener('click', (e) => this.switchTab(e.target.dataset.tab));
32 });
33
34 // Main Menu
35 document.getElementById('newGameBtn').addEventListener('click', () => this.startGameSetup());
36
37 // Game Setup
38 document.getElementById('startGenerationBtn').addEventListener('click', () => this.generateKobolds());
39 document.getElementById('selectLeaderBtn').addEventListener('click', () => this.selectLeader());
40 document.getElementById('finishTribeBtn').addEventListener('click', () => this.finishTribe());
41
42 // Game Screen
43 document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth());
44
45 // Modal close buttons
46 document.querySelectorAll('.modal-close').forEach(btn =>
47 {
48 btn.addEventListener('click', (e) =>
49 {
50 const modal = e.target.closest('.modal');
51 if (modal) modal.classList.add('hidden');
52 });
53 });
54
55 document.getElementById('eventContinueBtn').addEventListener('click', () => this.hideEventModal());
56 }
57
58 switchTab (tabName)
59 {
60 document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
61 document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
62 document.getElementById(tabName + 'Tab').classList.add('active');
63 event.target.classList.add('active');
64 }
65
66 async checkAuth ()
67 {
68 // Check if user is logged in
69 const savedUser = localStorage.getItem('currentUser');
70 if (savedUser)
71 {
72 this.currentUser = JSON.parse(savedUser);
73 this.showMainMenu();
74 } else
75 {
76 this.showAuthScreen();
77 }
78 }
79
80 async handleLogin (e)
81 {
82 e.preventDefault();
83 const email = document.querySelector('#loginForm input[name="email"]').value;
84 const password = document.querySelector('#loginForm input[name="password"]').value;
85
86 try
87 {
88 const response = await fetch('api/auth/login', {
89 method: 'POST',
90 headers: { 'Content-Type': 'application/json' },
91 body: JSON.stringify({ email, password })
92 });
93
94 const dataJson = await response;
95 const dataText = await dataJson.text();
96 const data = JSON.parse(dataText);
97
98 if (data.success)
99 {
100 this.currentUser = data.user;
101 localStorage.setItem('currentUser', JSON.stringify(data.user));
102 this.showMainMenu();
103 } else
104 {
105 this.showAuthError(data.error);
106 }
107 } catch (error)
108 {
109 this.showAuthError('Login failed');
110 console.error(error);
111 }
112 }
113
114 async handleRegister (e)
115 {
116 e.preventDefault();
117 const email = document.querySelector('#registerForm input[name="email"]').value;
118 const password = document.querySelector('#registerForm input[name="password"]').value;
119 const passwordConfirm = document.querySelector('#registerForm input[name="passwordConfirm"]').value;
120
121 if (password !== passwordConfirm)
122 {
123 this.showAuthError('Passwords do not match');
124 return;
125 }
126
127 try
128 {
129 const response = await fetch('api/auth/register', {
130 method: 'POST',
131 headers: { 'Content-Type': 'application/json' },
132 body: JSON.stringify({ email, password })
133 });
134
135 const dataRaw = await response;
136 const dataText = await dataRaw.text();
137 const data = JSON.parse(dataText);
138
139 if (data.success)
140 {
141 this.currentUser = data.user;
142 localStorage.setItem('currentUser', JSON.stringify(data.user));
143 this.showMainMenu();
144 } else
145 {
146 this.showAuthError(data.error);
147 }
148 } catch (error)
149 {
150 this.showAuthError('Registration failed');
151 console.error(error);
152 }
153 }
154
155 handleLogout ()
156 {
157 this.currentUser = null;
158 localStorage.removeItem('currentUser');
159 this.showAuthScreen();
160 }
161
162 showAuthError (error)
163 {
164 const errorDiv = document.getElementById('authError');
165 errorDiv.textContent = error;
166 errorDiv.classList.add('show');
167 setTimeout(() => errorDiv.classList.remove('show'), 5000);
168 }
169
170 showAuthScreen ()
171 {
172 this.hideAll();
173 document.getElementById('authScreen').classList.remove('hidden');
174 }
175
176 showMainMenu ()
177 {
178 this.hideAll();
179 document.getElementById('mainMenuScreen').classList.remove('hidden');
180 document.getElementById('userEmail').textContent = this.currentUser.email;
181 this.loadSaves();
182 }
183
184 async loadSaves ()
185 {
186 try
187 {
188 const response = await fetch('api/game/list', {
189 method: 'GET',
190 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
191 });
192
193 const dataText = await response.text();
194 const data = JSON.parse(dataText);
195
196 if (!data.success && data.error == "Not authenticated")
197 {
198 this.handleLogout();
199 return;
200 }
201
202 const savesList = document.getElementById('savesList');
203 savesList.innerHTML = '';
204
205 if (data.saves && data.saves.length > 0)
206 {
207 data.saves.forEach(save =>
208 {
209 const card = document.createElement('div');
210 card.className = 'save-card';
211 card.innerHTML = `
212 <h3>${save.name}</h3>
213 <p>Month: ${save.current_month}</p>
214 <p>Season: ${save.current_season}</p>
215 `;
216 card.addEventListener('click', () => this.loadGame(save.id));
217 savesList.appendChild(card);
218 });
219 }
220 } catch (error)
221 {
222 console.error('Failed to load saves:', error);
223 }
224 }
225
226 startGameSetup ()
227 {
228 this.hideAll();
229 document.getElementById('gameSetupScreen').classList.remove('hidden');
230 document.getElementById('setupStep1').classList.remove('hidden');
231 document.getElementById('setupStep2').classList.add('hidden');
232 document.getElementById('setupStep3').classList.add('hidden');
233 }
234
235 async generateKobolds ()
236 {
237 const tribeName = document.getElementById('tribeName').value;
238
239 if (!tribeName)
240 {
241 alert('Please enter a tribe name');
242 return;
243 }
244
245 try
246 {
247 const response = await fetch('api/game/generation', {
248 method: 'POST',
249 headers: {
250 'Content-Type': 'application/json',
251 'Authorization': `Bearer ${this.currentUser.token}`
252 },
253 body: JSON.stringify({
254 saveName: tribeName,
255 userId: this.currentUser.id
256 })
257 });
258
259 const dataText = await response.text();
260 const data = JSON.parse(dataText);
261
262 if (data.success)
263 {
264 this.currentSave = data.save;
265 this.displayKobolds(data.kobolds, 'leader');
266 this.displayKobolds(data.kobolds, 'member');
267
268 document.getElementById('setupStep1').classList.add('hidden');
269 document.getElementById('setupStep2').classList.remove('hidden');
270 }
271 } catch (error)
272 {
273 alert('Failed to generate kobolds');
274 console.error(error);
275 }
276 }
277
278 displayKobolds (kobolds, type)
279 {
280 const container = type === 'leader'
281 ? document.getElementById('leaderSelectionGrid')
282 : document.getElementById('memberSelectionGrid');
283
284 container.innerHTML = '';
285
286 kobolds.forEach((kobold, index) =>
287 {
288 const card = document.createElement('div');
289 card.className = 'kobold-card';
290
291 const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${kobold.id}&age=${kobold.ageCategory}`;
292
293 card.innerHTML = `
294 <img src="${spriteUrl}" alt="Kobold sprite" class="kobold-sprite">
295 <div class="kobold-name">${kobold.age} years</div>
296 <div class="kobold-stats">
297 <div>Vitality: ${kobold.stats.vitality}</div>
298 </div>
299 `;
300
301 if (type === 'member')
302 {
303 card.addEventListener('click', () => this.toggleMemberSelection(card, index));
304 } else
305 {
306 card.addEventListener('click', () => this.selectLeaderCard(card, index));
307 }
308
309 container.appendChild(card);
310 });
311 }
312
313 async selectLeaderCard (card, index)
314 {
315 const leaderName = document.getElementById('leaderName').value;
316
317 if (!leaderName)
318 {
319 alert('Please enter a leader name');
320 return;
321 }
322
323 document.querySelectorAll('#leaderSelectionGrid .kobold-card').forEach(c => c.classList.remove('selected'));
324 card.classList.add('selected');
325 document.getElementById('selectLeaderBtn').dataset.leaderIndex = index;
326
327 this.toggleMemberSelection(card, index, true);
328 await this.selectLeader();
329 }
330
331 toggleMemberSelection (card, index, force)
332 {
333 const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex;
334 if (force || leaderIndex != index)
335 {
336 const selectedCard = document.querySelectorAll('#memberSelectionGrid .kobold-card')[index];
337 selectedCard.classList.toggle('selected');
338
339 if (force)
340 {
341 selectedCard.id = "tribeLeader";
342 }
343
344 const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length;
345 document.getElementById('memberCount').textContent = `${selected} / 5 selected`;
346
347 if (selected === 5)
348 {
349 document.getElementById('finishTribeBtn').disabled = false;
350 } else
351 {
352 document.getElementById('finishTribeBtn').disabled = true;
353 }
354 }
355 }
356
357 async selectLeader ()
358 {
359 const leaderName = document.getElementById('leaderName').value;
360
361 if (!leaderName)
362 {
363 alert('Please enter a leader name');
364 return;
365 }
366
367 // Proceed to member selection
368 document.getElementById('setupStep2').classList.add('hidden');
369 document.getElementById('setupStep3').classList.remove('hidden');
370
371 // For now, just display remaining kobolds (in real implementation, filter out leader)
372 }
373
374 async finishTribe ()
375 {
376 const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex;
377 const selectedMembers = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected');
378
379 const memberIndices = Array.from(selectedMembers).map(card =>
380 {
381 return Array.from(card.parentElement.children).indexOf(card);
382 });
383
384 // Load the game
385 try
386 {
387 const response = await fetch('api/game/save', {
388 method: 'POST',
389 headers: {
390 'Content-Type': 'application/json',
391 'Authorization': `Bearer ${this.currentUser.token}`
392 },
393 body: JSON.stringify({
394 userId: this.currentUser.id,
395 saveId: this.currentSave.id,
396 leaderName: document.getElementById('leaderName').value,
397 memberIndices: memberIndices,
398 leaderId: leaderIndex
399 })
400 });
401
402 const dataText = await response.text();
403 const data = JSON.parse(dataText);
404
405 if (data.success)
406 {
407 this.loadGame(this.currentSave.id);
408 }
409 } catch (error)
410 {
411 alert('Failed to finish tribe setup');
412 console.error(error);
413 }
414 }
415
416 async loadGame (saveId)
417 {
418 try
419 {
420 const response = await fetch(`api/game/load?saveId=${saveId}&userId=${this.currentUser.id}`, {
421 method: 'GET',
422 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
423 });
424
425 const dataText = await response.text();
426 const data = JSON.parse(dataText);
427
428 if (data.success)
429 {
430 this.currentSave = data.save;
431 this.currentTribe = data.tribe;
432 await this.fetchAvailableEvents();
433 this.showGameScreen();
434 }
435 } catch (error)
436 {
437 alert('Failed to load game');
438 console.error(error);
439 }
440 }
441
442 showGameScreen ()
443 {
444 this.hideAll();
445 document.getElementById('gameScreen').classList.remove('hidden');
446 this.renderGame();
447 }
448
449 renderGame ()
450 {
451 document.getElementById('tribeName').textContent = this.currentSave.name;
452 document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`;
453 document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season);
454
455 this.renderStorage();
456 this.renderTribeList();
457 this.renderEvents();
458 }
459
460 renderTribeList ()
461 {
462 const list = document.getElementById('tribeList');
463 list.innerHTML = '';
464
465 this.currentTribe.kobolds.forEach(kobold =>
466 {
467 const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${kobold.id}&age=${kobold.ageCategory}`;
468 const item = document.createElement('div');
469 const isInjured = kobold.injuries && kobold.injuries.length > 0;
470 item.className = `tribe-item ${isInjured ? 'injured' : ''}`;
471 item.innerHTML = `
472 <table style="width:100%">
473 <td>
474 <img src="${spriteUrl}"/>
475 </td>
476 <td>
477 <div>
478 <div class="tribe-item-name">${kobold.name}</div>
479 <div class="tribe-item-age">${(kobold.age > 0 ? kobold.age : 0)} years</div>
480 </div>
481 </td>
482 </table>
483 `;
484 item.addEventListener('click', () => this.showKoboldModal(kobold));
485 list.appendChild(item);
486 });
487 }
488
489 renderEvents ()
490 {
491 const list = document.getElementById('eventsList');
492 list.innerHTML = '';
493
494 if (!this.availableEvents || this.availableEvents.length === 0)
495 {
496 const empty = document.createElement('div');
497 empty.className = 'event-item disabled';
498 empty.textContent = 'No events available';
499 list.appendChild(empty);
500 return;
501 }
502
503 this.availableEvents.forEach(evt =>
504 {
505 const item = document.createElement('div');
506 const isAvailable = !!evt.available;
507 item.className = `event-item ${isAvailable ? '' : 'disabled'}`.trim();
508 const costText = Number.isFinite(Number(evt.cost)) ? ` (Cost: ${evt.cost})` : '';
509 item.textContent = `${evt.name || evt.type}${costText}${isAvailable ? '' : ' (Unavailable)'}`;
510 if (isAvailable)
511 {
512 item.addEventListener('click', () => this.showParticipantModal(evt.type));
513 }
514 list.appendChild(item);
515 });
516 }
517
518 async fetchAvailableEvents ()
519 {
520 this.availableEvents = [];
521 this.availableEventsByType = {};
522
523 if (!this.currentUser || !this.currentSave)
524 return;
525
526 try
527 {
528 const response = await fetch(`api/game/events?saveId=${this.currentSave.id}&userId=${this.currentUser.id}`, {
529 method: 'GET',
530 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
531 });
532
533 const dataText = await response.text();
534 const data = JSON.parse(dataText);
535
536 if (data.success && Array.isArray(data.events))
537 {
538 this.availableEvents = data.events;
539 data.events.forEach(evt =>
540 {
541 if (evt && evt.type)
542 this.availableEventsByType[evt.type] = evt;
543 });
544 }
545 } catch (error)
546 {
547 console.error('Failed to load events:', error);
548 }
549 }
550
551 async executeEvent (eventType)
552 {
553 // Deprecated direct execution; use participant modal instead
554 this.showParticipantModal(eventType);
555 }
556
557 showParticipantModal (eventType)
558 {
559 this.currentEventType = eventType;
560 const modal = document.getElementById('participantModal');
561 const eventData = this.availableEventsByType[eventType] || {};
562 const eventLabel = eventData.name || eventType;
563 document.getElementById('participantModalTitle').textContent = `Select participants for ${eventLabel}`;
564
565 const list = document.getElementById('participantsList');
566 list.innerHTML = '';
567
568 this.participantMin = eventData.min_participants ?? 1;
569 this.participantMax = eventData.max_participants ?? 3;
570 this.participantMinAge = eventData.min_age ?? 0;
571 this.participantCost = eventData.cost || 0;
572
573 // Helper: check if kobold is eligible
574 const isEligible = (kobold) =>
575 {
576 const ageCategory = (kobold.ageCategory || '').toLowerCase();
577 if (ageCategory === 'egg') return false; // eggs cannot participate
578 if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend)
579 if (kobold.age < this.participantMinAge) return false; // too young
580 const fatigue = Number(kobold.fatigue || 0);
581 const vitality = Number(kobold.stats?.vitality || 0);
582 if ((fatigue + this.participantCost) > vitality) return false;
583 return true;
584 };
585
586 // Render kobolds with eligibility status
587 this.currentTribe.kobolds.forEach(kobold =>
588 {
589 const ageCategory = (kobold.ageCategory || '').toLowerCase();
590 const eligible = isEligible(kobold);
591 let reason = '';
592
593 if (ageCategory === 'egg')
594 reason = '(eggs cannot participate)';
595 else if (kobold.age < this.participantMinAge)
596 reason = `(too young, needs age ${this.participantMinAge}+)`;
597 else if (this.participantCost > Number(kobold.stats?.vitality || 0))
598 reason = '(too weak)';
599 else if ((Number(kobold.fatigue || 0) + this.participantCost) > Number(kobold.stats?.vitality || 0))
600 reason = '(too tired)';
601
602 const row = document.createElement('div');
603 row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`;
604
605 const fatigueValue = Number(kobold.fatigue || 0);
606 const vitalityValue = Number(kobold.stats?.vitality || 0);
607 const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue);
608
609 if (eligible)
610 {
611 row.innerHTML = `
612 <label>
613 <input type="checkbox" class="participant-checkbox" data-id="${kobold.id}">
614 <strong>${kobold.name}</strong> (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'})
615 </label>
616 `;
617 const cb = row.querySelector('.participant-checkbox');
618 cb.addEventListener('change', () => this._updateParticipantButtons());
619 } else
620 {
621 row.innerHTML = `
622 <div class="participant-disabled">
623 <span>${kobold.name} (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'})</span>
624 <span class="disabled-reason">${reason}</span>
625 </div>
626 `;
627 }
628
629 list.appendChild(row);
630 });
631
632 document.getElementById('participantCount').textContent = `0 selected`;
633
634 // cancel/start handlers
635 const cancelBtn = document.getElementById('cancelParticipantsBtn');
636 const startBtn = document.getElementById('startEventBtn');
637
638 cancelBtn.onclick = () => { modal.classList.add('hidden'); };
639 startBtn.onclick = async () => { await this.startEventWithParticipants(); };
640
641 // initial state
642 this._updateParticipantButtons();
643
644 modal.classList.remove('hidden');
645 }
646
647 _updateParticipantButtons ()
648 {
649 const list = document.getElementById('participantsList');
650 const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id);
651 const count = selected.length;
652 const participantCount = document.getElementById('participantCount');
653 const minRequired = this.participantMin || 1;
654 const maxAllowed = this.participantMax || 3;
655 let warning = '';
656 if (count < minRequired)
657 {
658 warning = `need at least ${minRequired}`;
659 } else if (count > maxAllowed)
660 {
661 warning = `${count - maxAllowed} too many`;
662 }
663
664 const warningHtml = warning ? `<br><span style="color:#d9534f;">${warning.trim()}</span>` : '';
665 participantCount.innerHTML = `${count} selected${warningHtml}`;
666
667 const startBtn = document.getElementById('startEventBtn');
668 if (count >= (this.participantMin || 1) && count <= (this.participantMax || 3))
669 {
670 startBtn.disabled = false;
671 } else
672 {
673 startBtn.disabled = true;
674 }
675 }
676
677 async startEventWithParticipants ()
678 {
679 const modal = document.getElementById('participantModal');
680 const list = document.getElementById('participantsList');
681 const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id);
682
683 if (!selected || selected.length === 0) return;
684
685 try
686 {
687 const resp = await fetch('api/game/event', {
688 method: 'POST',
689 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` },
690 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected })
691 });
692
693 const dataText = await resp.text();
694 const data = JSON.parse(dataText);
695
696 if (data.success)
697 {
698 typeText(document.getElementById('eventStory'), data.story);
699 this.showEventModal();
700 modal.classList.add('hidden');
701 await this.loadGame(this.currentSave.id);
702 } else
703 {
704 alert(data.error || 'Failed to start event');
705 }
706 } catch (err)
707 {
708 console.error(err);
709 alert('Failed to start event');
710 }
711 }
712
713 async endMonth ()
714 {
715 try
716 {
717 const response = await fetch('api/game/endMonth', {
718 method: 'POST',
719 headers: {
720 'Content-Type': 'application/json',
721 'Authorization': `Bearer ${this.currentUser.token}`
722 },
723 body: JSON.stringify({
724 userId: this.currentUser.id, saveId: this.currentSave.id
725 })
726 });
727
728 const dataT = await response.text();
729 const data = JSON.parse(dataT);
730
731 if (data.success)
732 {
733 this.currentSave = data.save;
734 typeText(document.getElementById('eventStory'), data.monthStory);
735 this.showEventModal();
736 await this.loadGame(this.currentSave.id);
737 }
738 } catch (error)
739 {
740 alert('Failed to end month');
741 console.error(error);
742 }
743 }
744
745 showEventModal ()
746 {
747 document.getElementById('eventModal').classList.remove('hidden');
748 }
749
750 hideEventModal ()
751 {
752 if (!doneTyping) return;
753 document.getElementById('eventModal').classList.add('hidden');
754 this.renderGame();
755 }
756
757 renderStorage ()
758 {
759 const foodDisplay = document.getElementById('foodDisplay');
760 const monthsLeft = this.currentSave.food_months_remaining;
761 if (monthsLeft !== undefined && monthsLeft !== null)
762 {
763 const label = Number(monthsLeft) === 1 ? 'month' : 'months';
764 foodDisplay.textContent = `Food: ${monthsLeft} ${label}`;
765 } else
766 {
767 foodDisplay.textContent = `Food: ${this.currentSave.food_count}`;
768 }
769
770 const storageItems = document.getElementById('storageItems');
771 storageItems.innerHTML = '';
772
773 if (!this.currentTribe.storage || this.currentTribe.storage.length === 0)
774 {
775 storageItems.innerHTML = '<div style="text-align: center; color: #999; padding: 10px;">No items in storage</div>';
776 return;
777 }
778
779 this.currentTribe.storage.forEach(item =>
780 {
781 const itemEl = document.createElement('div');
782 itemEl.className = 'storage-item';
783 itemEl.innerHTML = `<div class="storage-item-name">${item.name}</div>`;
784 itemEl.addEventListener('click', () => this.showItemModal(item));
785 storageItems.appendChild(itemEl);
786 });
787 }
788
789 showItemModal (item)
790 {
791 const modal = document.getElementById('itemModal');
792 document.getElementById('itemModalName').textContent = item.name;
793 document.getElementById('itemModalDescription').textContent = item.description || 'No description';
794
795 // Show stat modifications (handle both camelCase and snake_case)
796 const statMods = document.getElementById('itemModalStatMods');
797 statMods.innerHTML = '';
798
799 const modifications = item.stat_modifications || item.statModifications || {};
800 if (Object.keys(modifications).length > 0)
801 {
802 Object.entries(modifications).forEach(([stat, value]) =>
803 {
804 if (value !== 0)
805 {
806 const modEl = document.createElement('div');
807 modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`;
808 modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`;
809 statMods.appendChild(modEl);
810 }
811 });
812 } else
813 {
814 statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>';
815 }
816
817 // Restore item modal actions to storage version
818 const actions = document.querySelector('.item-modal-actions');
819 actions.innerHTML = '';
820
821 const select = document.createElement('select');
822 select.id = 'itemKoboldSelect';
823 select.className = 'kobold-select';
824 select.innerHTML = '<option value="">Select a Kobold...</option>';
825 this.currentTribe.kobolds.forEach(kobold =>
826 {
827 const option = document.createElement('option');
828 option.value = kobold.id;
829 option.textContent = kobold.name;
830 select.appendChild(option);
831 });
832
833 const giveBtn = document.createElement('button');
834 giveBtn.id = 'giveItemBtn';
835 giveBtn.className = 'primary';
836 giveBtn.textContent = 'Give Item';
837 giveBtn.disabled = true;
838
839 select.addEventListener('change', (e) =>
840 {
841 giveBtn.disabled = !e.target.value;
842 });
843
844 giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value));
845
846 actions.appendChild(select);
847 actions.appendChild(giveBtn);
848
849 modal.classList.remove('hidden');
850 }
851
852 async giveItemToKobold (item, koboldId)
853 {
854 try
855 {
856 const resp = await fetch('api/game/giveItem', {
857 method: 'POST',
858 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
859 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id })
860 });
861
862 const dataText = await resp.text();
863 const data = JSON.parse(dataText);
864 if (data.success)
865 {
866 typeText(document.getElementById('eventStory'), data.story);
867 this.showEventModal();
868 // Refresh game state
869 await this.loadGame(this.currentSave.id);
870 const kob = this.currentTribe.kobolds.find(k => k.id === koboldId);
871 } else
872 {
873 alert(data.error || 'Failed to give item');
874 }
875 } catch (err)
876 {
877 console.error(err);
878 alert('Failed to give item');
879 } finally
880 {
881 this.hideItemModal();
882 }
883 }
884
885 hideItemModal ()
886 {
887 document.getElementById('itemModal').classList.add('hidden');
888 }
889
890 hideKoboldModal ()
891 {
892 const modal = document.getElementById('koboldModal');
893 modal.classList.add('hidden');
894 }
895
896 showKoboldModal (kobold)
897 {
898 const modal = document.getElementById('koboldModal');
899 document.getElementById('koboldModalName').textContent = kobold.name;
900
901 const a = (kobold.ageCategory == "old" || kobold.ageCategory == "adult") ? "An" : "A";
902
903 if (kobold.ageCategory == "egg")
904 {
905 document.getElementById('koboldModalAge').textContent = `Not yet hatched`;
906 document.getElementById('koboldModalDescription').textContent = `An egg.`;
907 }
908 else
909 {
910 document.getElementById('koboldModalAge').textContent = `${kobold.age} years old`;
911 document.getElementById('koboldModalDescription').textContent = `${a} ${kobold.ageCategory} ${(kobold.male ? "male" : "female")} Kobold.`;
912 }
913
914 this.renderKoboldStats(kobold);
915 this.renderKoboldInventory(kobold);
916 this.renderKoboldInjuries(kobold);
917
918 // Setup tab buttons
919 document.querySelectorAll('.kobold-tab-btn').forEach(btn =>
920 {
921 btn.classList.remove('active');
922 btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab));
923 });
924 document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active');
925
926 // Hide all tabs
927 document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active'));
928 document.getElementById('koboldStatsTab').classList.add('active');
929
930 // Store current kobold for inventory actions
931 this.selectedKobold = kobold;
932
933 modal.classList.remove('hidden');
934 }
935
936 renderKoboldStats (kobold)
937 {
938 const statsGrid = document.getElementById('koboldStats');
939 statsGrid.innerHTML = '';
940
941 const stats = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
942 stats.forEach(stat =>
943 {
944 const value = kobold.stats[stat];
945 const label = this.getStatLabel(value);
946 const statEl = document.createElement('div');
947 statEl.className = 'stat-item';
948 statEl.innerHTML = `
949 <div class="stat-name">${stat}</div>
950 <div class="stat-value">${label}</div>
951 `;
952 statsGrid.appendChild(statEl);
953 });
954
955 const fatigueValue = Number(kobold.fatigue || 0);
956 const vitalityValue = Number(kobold.stats?.vitality || 0);
957 const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue);
958 const fatigueEl = document.createElement('div');
959 fatigueEl.className = 'stat-item';
960 fatigueEl.innerHTML = `
961 <div class="stat-name">energy</div>
962 <div class="stat-value">${fatigueLabel}</div>
963 `;
964 statsGrid.appendChild(fatigueEl);
965 }
966
967 renderKoboldInventory (kobold)
968 {
969 const inventory = document.getElementById('koboldInventory');
970 inventory.innerHTML = '';
971
972 if (!kobold.items || kobold.items.length === 0)
973 {
974 inventory.innerHTML = '<div class="kobold-inventory-empty">No items in inventory</div>';
975 return;
976 }
977
978 kobold.items.forEach(item =>
979 {
980 const itemEl = document.createElement('div');
981 itemEl.className = 'kobold-inventory-item';
982 itemEl.innerHTML = `<div class="kobold-item-name">${item.name}</div>`;
983 itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold));
984 inventory.appendChild(itemEl);
985 });
986 }
987
988 renderKoboldInjuries (kobold)
989 {
990 const container = document.getElementById('koboldInjuries');
991 container.innerHTML = '';
992
993 if (!kobold.injuries || kobold.injuries.length === 0)
994 {
995 container.innerHTML = '<div class="kobold-inventory-empty">No injuries</div>';
996 return;
997 }
998
999 // Mapping of injury category to required cure item (matches PHP Injury::$cureMap)
1000 const cureMap = {
1001 'wound': 'basic_medicine',
1002 'fracture': 'bone-setting',
1003 'infection': 'healing_herbs',
1004 'poison': 'antidote',
1005 'burn': 'burn_salve',
1006 'malnourished': 'food',
1007 'old-age': null
1008 };
1009
1010 kobold.injuries.forEach(injury =>
1011 {
1012 const el = document.createElement('div');
1013 el.className = 'injury-item';
1014 const name = injury.injury_type || injury.injuryType || 'Injury';
1015 const desc = injury.description || '';
1016 const severity = injury.severity ?? injury.severity ?? 1;
1017
1018 el.innerHTML = `
1019 <div class="injury-name">${name}</div>
1020 <div class="injury-desc">${desc}</div>
1021 `;
1022
1023 const actions = document.createElement('div');
1024 actions.className = 'injury-actions';
1025
1026 // malnourished has no cure button here
1027 if (injury.category !== 'malnourished' && injury.category !== 'old-age')
1028 {
1029 // Get required medicine from server or calculate from cureMap
1030 let required = injury.required_medicine || injury.requiredMedicine || null;
1031 if (!required && injury.category)
1032 {
1033 required = cureMap[injury.category] || null;
1034 }
1035
1036 if (required)
1037 {
1038 // check if kobold has item with this id
1039 const hasItem = (kobold.items || []).some(it => it.id === required);
1040 if (hasItem)
1041 {
1042 const btn = document.createElement('button');
1043 btn.className = 'primary';
1044 btn.textContent = `Cure using ${required}`;
1045 btn.addEventListener('click', async () =>
1046 {
1047 try
1048 {
1049 const resp = await fetch('api/game/cureInjury', {
1050 method: 'POST',
1051 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
1052 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required })
1053 });
1054 const dataText = await resp.text();
1055 const data = JSON.parse(dataText);
1056 if (data.success)
1057 {
1058 this.hideKoboldModal();
1059 typeText(document.getElementById('eventStory'), data.story);
1060 this.showEventModal();
1061 // Refresh game state
1062 await this.loadGame(this.currentSave.id);
1063 // reopen kobold modal after refresh
1064 const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id);
1065
1066 } else
1067 {
1068 alert(data.error || 'Failed to cure injury');
1069 }
1070 } catch (err)
1071 {
1072 console.error(err);
1073 alert('Failed to cure injury');
1074 }
1075 });
1076 actions.appendChild(btn);
1077 } else
1078 {
1079 const note = document.createElement('div');
1080 note.style.color = '#999';
1081 note.textContent = `Needs: ${required}`;
1082 actions.appendChild(note);
1083 }
1084 }
1085 }
1086
1087 el.appendChild(actions);
1088 container.appendChild(el);
1089 });
1090 }
1091
1092 showKoboldItemModal (item, kobold)
1093 {
1094 const modal = document.getElementById('itemModal');
1095 document.getElementById('itemModalName').textContent = item.name;
1096 document.getElementById('itemModalDescription').textContent = item.description || 'No description';
1097
1098 this.hideKoboldModal();
1099 // Show stat modifications (handle both camelCase and snake_case)
1100 const statMods = document.getElementById('itemModalStatMods');
1101 statMods.innerHTML = '';
1102
1103 const modifications = item.stat_modifications || item.statModifications || {};
1104 if (Object.keys(modifications).length > 0)
1105 {
1106 Object.entries(modifications).forEach(([stat, value]) =>
1107 {
1108 if (value !== 0)
1109 {
1110 const modEl = document.createElement('div');
1111 modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`;
1112 modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`;
1113 statMods.appendChild(modEl);
1114 }
1115 });
1116 } else
1117 {
1118 statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>';
1119 }
1120
1121 // Change button to return item
1122 const actions = document.querySelector('.item-modal-actions');
1123 actions.innerHTML = '';
1124
1125 const returnBtn = document.createElement('button');
1126 returnBtn.className = 'secondary';
1127 returnBtn.textContent = 'Return to Storage';
1128 returnBtn.addEventListener('click', () =>
1129 {
1130 this.hideKoboldModal();
1131 this.returnItemToStorage(item, kobold);
1132 });
1133
1134 actions.appendChild(returnBtn);
1135
1136 modal.classList.remove('hidden');
1137 this.selectedKobold = kobold;
1138 }
1139
1140 async returnItemToStorage (item, kobold)
1141 {
1142 try
1143 {
1144 const resp = await fetch('api/game/returnItem', {
1145 method: 'POST',
1146 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
1147 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id })
1148 });
1149
1150 const dataText = await resp.text();
1151 const data = JSON.parse(dataText);
1152 if (data.success)
1153 {
1154 typeText(document.getElementById('eventStory'), data.story);
1155 this.showEventModal();
1156 // Refresh game state
1157 await this.loadGame(this.currentSave.id);
1158 const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id);
1159 } else
1160 {
1161 alert(data.error || 'Failed to return item');
1162 }
1163 } catch (err)
1164 {
1165 console.error(err);
1166 alert('Failed to return item');
1167 } finally
1168 {
1169 this.hideItemModal();
1170 }
1171 }
1172
1173 switchKoboldTab (tabName)
1174 {
1175 // Hide all tabs
1176 document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active'));
1177 document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active'));
1178
1179 // Show selected tab
1180 const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab';
1181 document.getElementById(tabId).classList.add('active');
1182 document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
1183 }
1184
1185 getStatLabel (statValue)
1186 {
1187 if (statValue >= 90) return 'godlike';
1188 if (statValue >= 80) return 'divine';
1189 if (statValue >= 70) return 'master';
1190 if (statValue >= 60) return 'fantastic';
1191 if (statValue >= 50) return 'excellent';
1192 if (statValue >= 40) return 'good';
1193 if (statValue >= 30) return 'decent';
1194 if (statValue >= 20) return 'unskilled';
1195 if (statValue >= 10) return 'bad';
1196 return 'terrible';
1197 }
1198
1199 getFatigueLabel (fatigue, vitality)
1200 {
1201 const vit = Number(vitality || 0);
1202 const fat = Number(fatigue || 0);
1203 if (vit <= 0) return 'exhausted';
1204 if (fat <= 0) return 'energetic';
1205 const ratio = fat / Math.max(1, vit);
1206 if (ratio < 0.3) return 'fresh';
1207 if (ratio < 0.6) return 'tired';
1208 if (ratio < 0.85) return 'weary';
1209 return 'exhausted';
1210 }
1211
1212 hideAll ()
1213 {
1214 document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden'));
1215 }
1216
1217 capitalizeFirst (str)
1218 {
1219 return str.charAt(0).toUpperCase() + str.slice(1);
1220 }
1221}
1222
1223// Initialize app when DOM is ready
1224document.addEventListener('DOMContentLoaded', () =>
1225{
1226 window.app = new TribeGenApp();
1227});
1228
1229function typeText (element, text, minDelay = 3, maxDelay = 65)
1230{
1231 doneTyping = false;
1232 element.textContent = "";
1233 let index = 0;
1234 let timerId = null;
1235
1236 const randDelay = () =>
1237 Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;
1238
1239 const shouldStop = () =>
1240 {
1241 if (!element.isConnected) return true;
1242 if (getComputedStyle(element).display === "none") return true;
1243 return false;
1244 };
1245
1246 return new Promise((resolve) =>
1247 {
1248 function tick ()
1249 {
1250 if (shouldStop())
1251 {
1252 if (timerId) clearTimeout(timerId);
1253 doneTyping = true;
1254 resolve(false); // stopped early
1255 return;
1256 }
1257
1258 if (index >= text.length)
1259 {
1260 doneTyping = true;
1261 resolve(true); // finished normally
1262 return;
1263 }
1264
1265 element.textContent += text[index++];
1266 timerId = setTimeout(tick, randDelay());
1267 }
1268
1269 tick();
1270 });
1271}
1272