var doneTyping = true; // Main Game App class TribeGenApp { constructor() { this.currentUser = null; this.currentSave = null; this.currentTribe = null; this.init(); } async init () { this.setupEventListeners(); this.checkAuth(); } setupEventListeners () { // Auth Events document.getElementById('loginForm').addEventListener('submit', (e) => this.handleLogin(e)); document.getElementById('registerForm').addEventListener('submit', (e) => this.handleRegister(e)); document.getElementById('logoutBtn').addEventListener('click', () => this.handleLogout()); // Tab switching document.querySelectorAll('.tab-btn').forEach(btn => { btn.addEventListener('click', (e) => this.switchTab(e.target.dataset.tab)); }); // Main Menu document.getElementById('newGameBtn').addEventListener('click', () => this.startGameSetup()); // Game Setup document.getElementById('startGenerationBtn').addEventListener('click', () => this.generateKobolds()); document.getElementById('selectLeaderBtn').addEventListener('click', () => this.selectLeader()); document.getElementById('finishTribeBtn').addEventListener('click', () => this.finishTribe()); // Game Screen document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth()); // Modal close buttons document.querySelectorAll('.modal-close').forEach(btn => { btn.addEventListener('click', (e) => { const modal = e.target.closest('.modal'); if (modal) modal.classList.add('hidden'); }); }); document.getElementById('eventContinueBtn').addEventListener('click', () => this.hideEventModal()); } switchTab (tabName) { document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active')); document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active')); document.getElementById(tabName + 'Tab').classList.add('active'); event.target.classList.add('active'); } async checkAuth () { // Check if user is logged in const savedUser = localStorage.getItem('currentUser'); if (savedUser) { this.currentUser = JSON.parse(savedUser); this.showMainMenu(); } else { this.showAuthScreen(); } } async handleLogin (e) { e.preventDefault(); const email = document.querySelector('#loginForm input[name="email"]').value; const password = document.querySelector('#loginForm input[name="password"]').value; try { const response = await fetch('api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }); const dataJson = await response; const dataText = await dataJson.text(); const data = JSON.parse(dataText); if (data.success) { this.currentUser = data.user; localStorage.setItem('currentUser', JSON.stringify(data.user)); this.showMainMenu(); } else { this.showAuthError(data.error); } } catch (error) { this.showAuthError('Login failed'); console.error(error); } } async handleRegister (e) { e.preventDefault(); const email = document.querySelector('#registerForm input[name="email"]').value; const password = document.querySelector('#registerForm input[name="password"]').value; const passwordConfirm = document.querySelector('#registerForm input[name="passwordConfirm"]').value; if (password !== passwordConfirm) { this.showAuthError('Passwords do not match'); return; } try { const response = await fetch('api/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }); const dataRaw = await response; const dataText = await dataRaw.text(); const data = JSON.parse(dataText); if (data.success) { this.currentUser = data.user; localStorage.setItem('currentUser', JSON.stringify(data.user)); this.showMainMenu(); } else { this.showAuthError(data.error); } } catch (error) { this.showAuthError('Registration failed'); console.error(error); } } handleLogout () { this.currentUser = null; localStorage.removeItem('currentUser'); this.showAuthScreen(); } showAuthError (error) { const errorDiv = document.getElementById('authError'); errorDiv.textContent = error; errorDiv.classList.add('show'); setTimeout(() => errorDiv.classList.remove('show'), 5000); } showAuthScreen () { this.hideAll(); document.getElementById('authScreen').classList.remove('hidden'); } showMainMenu () { this.hideAll(); document.getElementById('mainMenuScreen').classList.remove('hidden'); document.getElementById('userEmail').textContent = this.currentUser.email; this.loadSaves(); } async loadSaves () { try { const response = await fetch('api/game/list', { method: 'GET', headers: { 'Authorization': `Bearer ${this.currentUser.token}` } }); const dataText = await response.text() const data = JSON.parse(dataText); const savesList = document.getElementById('savesList'); savesList.innerHTML = ''; if (data.saves && data.saves.length > 0) { data.saves.forEach(save => { const card = document.createElement('div'); card.className = 'save-card'; card.innerHTML = `

${save.name}

Month: ${save.current_month}

Season: ${save.current_season}

`; card.addEventListener('click', () => this.loadGame(save.id)); savesList.appendChild(card); }); } } catch (error) { console.error('Failed to load saves:', error); } } startGameSetup () { this.hideAll(); document.getElementById('gameSetupScreen').classList.remove('hidden'); document.getElementById('setupStep1').classList.remove('hidden'); document.getElementById('setupStep2').classList.add('hidden'); document.getElementById('setupStep3').classList.add('hidden'); } async generateKobolds () { const tribeName = document.getElementById('tribeName').value; if (!tribeName) { alert('Please enter a tribe name'); return; } try { const response = await fetch('api/game/generation', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` }, body: JSON.stringify({ saveName: tribeName, userId: this.currentUser.id }) }); const dataText = await response.text(); const data = JSON.parse(dataText); if (data.success) { this.currentSave = data.save; this.displayKobolds(data.kobolds, 'leader'); this.displayKobolds(data.kobolds, 'member'); document.getElementById('setupStep1').classList.add('hidden'); document.getElementById('setupStep2').classList.remove('hidden'); } } catch (error) { alert('Failed to generate kobolds'); console.error(error); } } displayKobolds (kobolds, type) { const container = type === 'leader' ? document.getElementById('leaderSelectionGrid') : document.getElementById('memberSelectionGrid'); container.innerHTML = ''; kobolds.forEach((kobold, index) => { const card = document.createElement('div'); card.className = 'kobold-card'; const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${kobold.id}&age=${kobold.ageCategory}`; card.innerHTML = ` Kobold sprite
${kobold.age} years
Vitality: ${kobold.stats.vitality}
`; if (type === 'member') { card.addEventListener('click', () => this.toggleMemberSelection(card, index)); } else { card.addEventListener('click', () => this.selectLeaderCard(card, index)); } container.appendChild(card); }); } async selectLeaderCard (card, index) { const leaderName = document.getElementById('leaderName').value; if (!leaderName) { alert('Please enter a leader name'); return; } document.querySelectorAll('#leaderSelectionGrid .kobold-card').forEach(c => c.classList.remove('selected')); card.classList.add('selected'); document.getElementById('selectLeaderBtn').dataset.leaderIndex = index; this.toggleMemberSelection(card, index, true); await this.selectLeader(); } toggleMemberSelection (card, index, force) { const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex; if (force || leaderIndex != index) { document.querySelectorAll('#memberSelectionGrid .kobold-card')[index].classList.toggle('selected'); const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length; document.getElementById('memberCount').textContent = `${selected} / 5 selected`; if (selected === 5) { document.getElementById('finishTribeBtn').disabled = false; } else { document.getElementById('finishTribeBtn').disabled = true; } } } async selectLeader () { const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex; const leaderName = document.getElementById('leaderName').value; if (!leaderName) { alert('Please enter a leader name'); return; } // Proceed to member selection document.getElementById('setupStep2').classList.add('hidden'); document.getElementById('setupStep3').classList.remove('hidden'); // For now, just display remaining kobolds (in real implementation, filter out leader) } async finishTribe () { const selectedMembers = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected'); const memberIndices = Array.from(selectedMembers).map(card => { return Array.from(card.parentElement.children).indexOf(card); }); // Load the game try { const response = await fetch('api/game/save', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` }, body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, leaderName: document.getElementById('leaderName').value, memberIndices: memberIndices }) }); const dataText = await response.text() const data = JSON.parse(dataText); if (data.success) { this.loadGame(this.currentSave.id); } } catch (error) { alert('Failed to finish tribe setup'); console.error(error); } } async loadGame (saveId) { try { const response = await fetch(`api/game/load?saveId=${saveId}&userId=${this.currentUser.id}`, { method: 'GET', headers: { 'Authorization': `Bearer ${this.currentUser.token}` } }); const dataText = await response.text() const data = JSON.parse(dataText); if (data.success) { this.currentSave = data.save; this.currentTribe = data.tribe; this.showGameScreen(); } } catch (error) { alert('Failed to load game'); console.error(error); } } showGameScreen () { this.hideAll(); document.getElementById('gameScreen').classList.remove('hidden'); this.renderGame(); } renderGame () { document.getElementById('tribeName').textContent = this.currentSave.name; document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`; document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season); this.renderStorage(); this.renderTribeList(); this.renderEvents(); } renderTribeList () { const list = document.getElementById('tribeList'); list.innerHTML = ''; this.currentTribe.kobolds.forEach(kobold => { const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${kobold.id}&age=${kobold.ageCategory}`; const item = document.createElement('div'); item.className = 'tribe-item'; item.innerHTML = `
${kobold.name}
${kobold.age} years
`; item.addEventListener('click', () => this.showKoboldModal(kobold)); list.appendChild(item); }); } renderEvents () { const list = document.getElementById('eventsList'); list.innerHTML = ''; const events = ['Hunting', 'Exploration', 'Farming']; events.forEach(evt => { const item = document.createElement('div'); item.className = 'event-item'; item.textContent = evt; item.addEventListener('click', () => this.showParticipantModal(evt)); list.appendChild(item); }); } async executeEvent (eventType) { // Deprecated direct execution; use participant modal instead this.showParticipantModal(eventType); } showParticipantModal (eventType) { this.currentEventType = eventType; const modal = document.getElementById('participantModal'); document.getElementById('participantModalTitle').textContent = `Select participants for ${eventType}`; const list = document.getElementById('participantsList'); list.innerHTML = ''; // Default limits and minimum age (server also enforces). Adjust per event if needed. const eventConfig = { 'Exploration': { min: 1, max: 3, minAge: 0 }, 'Hunting': { min: 1, max: 3, minAge: 0 }, 'Farming': { min: 1, max: 3, minAge: 0 } }; const config = eventConfig[eventType] || { min: 1, max: 3, minAge: 0 }; this.participantMin = config.min; this.participantMax = config.max; this.participantMinAge = config.minAge; // Helper: check if kobold is eligible const isEligible = (kobold) => { const ageCategory = (kobold.ageCategory || '').toLowerCase(); if (ageCategory === 'egg') return false; // eggs cannot participate if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend) if (kobold.age < this.participantMinAge) return false; // too young return true; }; // Render kobolds with eligibility status this.currentTribe.kobolds.forEach(kobold => { const ageCategory = (kobold.ageCategory || '').toLowerCase(); const eligible = isEligible(kobold); let reason = ''; if (ageCategory === 'egg') reason = '(eggs cannot participate)'; else if (kobold.age < this.participantMinAge) reason = `(too young, needs age ${this.participantMinAge}+)`; const row = document.createElement('div'); row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`; if (eligible) { row.innerHTML = ` `; const cb = row.querySelector('.participant-checkbox'); cb.addEventListener('change', () => this._updateParticipantButtons()); } else { row.innerHTML = `
${kobold.name} (${kobold.age}y - ${kobold.ageCategory}) ${reason}
`; } list.appendChild(row); }); document.getElementById('participantCount').textContent = `0 selected`; // cancel/start handlers const cancelBtn = document.getElementById('cancelParticipantsBtn'); const startBtn = document.getElementById('startEventBtn'); cancelBtn.onclick = () => { modal.classList.add('hidden'); }; startBtn.onclick = async () => { await this.startEventWithParticipants(); }; // initial state this._updateParticipantButtons(); modal.classList.remove('hidden'); } _updateParticipantButtons () { const list = document.getElementById('participantsList'); const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); const count = selected.length; document.getElementById('participantCount').textContent = `${count} selected`; const startBtn = document.getElementById('startEventBtn'); if (count >= (this.participantMin || 1) && count <= (this.participantMax || 3)) { startBtn.disabled = false; } else { startBtn.disabled = true; } } async startEventWithParticipants () { const modal = document.getElementById('participantModal'); const list = document.getElementById('participantsList'); const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); if (!selected || selected.length === 0) return; try { const resp = await fetch('api/game/event', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` }, body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected }) }); const dataText = await resp.text() const data = JSON.parse(dataText); if (data.success) { typeText(document.getElementById('eventStory'), data.story); this.showEventModal(); modal.classList.add('hidden'); await this.loadGame(this.currentSave.id); } else { alert(data.error || 'Failed to start event'); } } catch (err) { console.error(err); alert('Failed to start event'); } } async endMonth () { try { const response = await fetch('api/game/endMonth', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` }, body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id }) }); const dataT = await response.text(); const data = JSON.parse(dataT); if (data.success) { this.currentSave = data.save; typeText(document.getElementById('eventStory'), data.monthStory); this.showEventModal(); } } catch (error) { alert('Failed to end month'); console.error(error); } } showEventModal () { document.getElementById('eventModal').classList.remove('hidden'); } hideEventModal () { if (!doneTyping) return; document.getElementById('eventModal').classList.add('hidden'); this.renderGame(); } renderStorage () { const foodDisplay = document.getElementById('foodDisplay'); foodDisplay.textContent = `Food: ${this.currentSave.food_count}`; const storageItems = document.getElementById('storageItems'); storageItems.innerHTML = ''; if (!this.currentTribe.storage || this.currentTribe.storage.length === 0) { storageItems.innerHTML = '
No items in storage
'; return; } this.currentTribe.storage.forEach(item => { const itemEl = document.createElement('div'); itemEl.className = 'storage-item'; itemEl.innerHTML = `
${item.name}
`; itemEl.addEventListener('click', () => this.showItemModal(item)); storageItems.appendChild(itemEl); }); } showItemModal (item) { const modal = document.getElementById('itemModal'); document.getElementById('itemModalName').textContent = item.name; document.getElementById('itemModalDescription').textContent = item.description || 'No description'; // Show stat modifications (handle both camelCase and snake_case) const statMods = document.getElementById('itemModalStatMods'); statMods.innerHTML = ''; const modifications = item.stat_modifications || item.statModifications || {}; if (Object.keys(modifications).length > 0) { Object.entries(modifications).forEach(([stat, value]) => { if (value !== 0) { const modEl = document.createElement('div'); modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; modEl.innerHTML = `${this.capitalizeFirst(stat)}${value > 0 ? '+' : ''}${value}`; statMods.appendChild(modEl); } }); } else { statMods.innerHTML = '
No stat modifications
'; } // Restore item modal actions to storage version const actions = document.querySelector('.item-modal-actions'); actions.innerHTML = ''; const select = document.createElement('select'); select.id = 'itemKoboldSelect'; select.className = 'kobold-select'; select.innerHTML = ''; this.currentTribe.kobolds.forEach(kobold => { const option = document.createElement('option'); option.value = kobold.id; option.textContent = kobold.name; select.appendChild(option); }); const giveBtn = document.createElement('button'); giveBtn.id = 'giveItemBtn'; giveBtn.className = 'primary'; giveBtn.textContent = 'Give Item'; giveBtn.disabled = true; select.addEventListener('change', (e) => { giveBtn.disabled = !e.target.value; }); giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value)); actions.appendChild(select); actions.appendChild(giveBtn); modal.classList.remove('hidden'); } async giveItemToKobold (item, koboldId) { try { const resp = await fetch('api/game/giveItem', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id }) }); const dataText = await resp.text() const data = JSON.parse(dataText); if (data.success) { typeText(document.getElementById('eventStory'), data.story); this.showEventModal(); // Refresh game state await this.loadGame(this.currentSave.id); const kob = this.currentTribe.kobolds.find(k => k.id === koboldId); } else { alert(data.error || 'Failed to give item'); } } catch (err) { console.error(err); alert('Failed to give item'); } finally { this.hideItemModal(); } } hideItemModal () { document.getElementById('itemModal').classList.add('hidden'); } showKoboldModal (kobold) { const modal = document.getElementById('koboldModal'); document.getElementById('koboldModalName').textContent = kobold.name; document.getElementById('koboldModalAge').textContent = `${(kobold.male ? "male" : "female")}, ${kobold.age} years old`; document.getElementById('koboldModalDescription').textContent = `A ${kobold.ageCategory} Kobold`; this.renderKoboldStats(kobold); this.renderKoboldInventory(kobold); this.renderKoboldInjuries(kobold); // Setup tab buttons document.querySelectorAll('.kobold-tab-btn').forEach(btn => { btn.classList.remove('active'); btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab)); }); document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active'); // Hide all tabs document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); document.getElementById('koboldStatsTab').classList.add('active'); // Store current kobold for inventory actions this.selectedKobold = kobold; modal.classList.remove('hidden'); } renderKoboldStats (kobold) { const statsGrid = document.getElementById('koboldStats'); statsGrid.innerHTML = ''; const stats = ['vitality', 'intelligence', 'tinkering', 'medicine', 'crafting', 'personality', 'will']; stats.forEach(stat => { const value = kobold.stats[stat]; const label = this.getStatLabel(value); const statEl = document.createElement('div'); statEl.className = 'stat-item'; statEl.innerHTML = `
${stat}
${label}
`; statsGrid.appendChild(statEl); }); } renderKoboldInventory (kobold) { const inventory = document.getElementById('koboldInventory'); inventory.innerHTML = ''; if (!kobold.items || kobold.items.length === 0) { inventory.innerHTML = '
No items in inventory
'; return; } kobold.items.forEach(item => { const itemEl = document.createElement('div'); itemEl.className = 'kobold-inventory-item'; itemEl.innerHTML = `
${item.name}
`; itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold)); inventory.appendChild(itemEl); }); } renderKoboldInjuries (kobold) { const container = document.getElementById('koboldInjuries'); container.innerHTML = ''; if (!kobold.injuries || kobold.injuries.length === 0) { container.innerHTML = '
No injuries
'; return; } // Mapping of injury category to required cure item (matches PHP Injury::$cureMap) const cureMap = { 'wound': 'basic_medicine', 'fracture': 'bone-setting', 'infection': 'healing_herbs', 'poison': 'antidote', 'burn': 'burn_salve', 'malnourished': 'food', 'old-age': null }; kobold.injuries.forEach(injury => { const el = document.createElement('div'); el.className = 'injury-item'; const name = injury.injury_type || injury.injuryType || 'Injury'; const desc = injury.description || ''; const severity = injury.severity ?? injury.severity ?? 1; el.innerHTML = `
${name} (Severity: ${severity})
${desc}
`; const actions = document.createElement('div'); actions.className = 'injury-actions'; // malnourished has no cure button here if (injury.category !== 'malnourished') { // Get required medicine from server or calculate from cureMap let required = injury.required_medicine || injury.requiredMedicine || null; if (!required && injury.category) { required = cureMap[injury.category] || null; } if (required) { // check if kobold has item with this id const hasItem = (kobold.items || []).some(it => it.id === required); if (hasItem) { const btn = document.createElement('button'); btn.className = 'primary'; btn.textContent = `Cure using ${required}`; btn.addEventListener('click', async () => { try { const resp = await fetch('api/game/cureInjury', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required }) }); const dataText = await resp.text() const data = JSON.parse(dataText); if (data.success) { typeText(document.getElementById('eventStory'), data.story); this.showEventModal(); // Refresh game state await this.loadGame(this.currentSave.id); // reopen kobold modal after refresh const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); } else { alert(data.error || 'Failed to cure injury'); } } catch (err) { console.error(err); alert('Failed to cure injury'); } }); actions.appendChild(btn); } else { const note = document.createElement('div'); note.style.color = '#999'; note.textContent = `Needs: ${required}`; actions.appendChild(note); } } } el.appendChild(actions); container.appendChild(el); }); } showKoboldItemModal (item, kobold) { const modal = document.getElementById('itemModal'); document.getElementById('itemModalName').textContent = item.name; document.getElementById('itemModalDescription').textContent = item.description || 'No description'; // Show stat modifications (handle both camelCase and snake_case) const statMods = document.getElementById('itemModalStatMods'); statMods.innerHTML = ''; const modifications = item.stat_modifications || item.statModifications || {}; if (Object.keys(modifications).length > 0) { Object.entries(modifications).forEach(([stat, value]) => { if (value !== 0) { const modEl = document.createElement('div'); modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; modEl.innerHTML = `${this.capitalizeFirst(stat)}${value > 0 ? '+' : ''}${value}`; statMods.appendChild(modEl); } }); } else { statMods.innerHTML = '
No stat modifications
'; } // Change button to return item const actions = document.querySelector('.item-modal-actions'); actions.innerHTML = ''; const returnBtn = document.createElement('button'); returnBtn.className = 'secondary'; returnBtn.textContent = 'Return to Storage'; returnBtn.addEventListener('click', () => this.returnItemToStorage(item, kobold)); actions.appendChild(returnBtn); modal.classList.remove('hidden'); this.selectedKobold = kobold; } async returnItemToStorage (item, kobold) { try { const resp = await fetch('api/game/returnItem', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id }) }); const dataText = await resp.text() const data = JSON.parse(dataText); if (data.success) { typeText(document.getElementById('eventStory'), data.story); this.showEventModal(); // Refresh game state await this.loadGame(this.currentSave.id); const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); } else { alert(data.error || 'Failed to return item'); } } catch (err) { console.error(err); alert('Failed to return item'); } finally { this.hideItemModal(); } } switchKoboldTab (tabName) { // Hide all tabs document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active')); // Show selected tab const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab'; document.getElementById(tabId).classList.add('active'); document.querySelector(`[data-tab="${tabName}"]`).classList.add('active'); } getStatLabel (statValue) { if (statValue >= 90) return 'godlike'; if (statValue >= 80) return 'divine'; if (statValue >= 70) return 'master'; if (statValue >= 60) return 'fantastic'; if (statValue >= 50) return 'excellent'; if (statValue >= 40) return 'good'; if (statValue >= 30) return 'decent'; if (statValue >= 20) return 'unskilled'; if (statValue >= 10) return 'bad'; return 'terrible'; } hideAll () { document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden')); } capitalizeFirst (str) { return str.charAt(0).toUpperCase() + str.slice(1); } } // Initialize app when DOM is ready document.addEventListener('DOMContentLoaded', () => { window.app = new TribeGenApp(); }); function typeText (element, text, minDelay = 3, maxDelay = 65) { doneTyping = false; element.textContent = ""; let index = 0; let timerId = null; const randDelay = () => Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay; const shouldStop = () => { if (!element.isConnected) return true; if (getComputedStyle(element).display === "none") return true; return false; }; return new Promise((resolve) => { function tick () { if (shouldStop()) { if (timerId) clearTimeout(timerId); doneTyping = true; resolve(false); // stopped early return; } if (index >= text.length) { doneTyping = true; resolve(true); // finished normally return; } element.textContent += text[index++]; timerId = setTimeout(tick, randDelay()); } tick(); }); }