BlueGit

blue-star tribegen

Files

tribegen / web / js / app.js

app.js

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