diff --git a/src/App.js b/src/App.js index ba3b706..9a8e0bb 100644 --- a/src/App.js +++ b/src/App.js @@ -1732,21 +1732,36 @@ function InitiativeControls({ campaignId, encounter, encounterPath }) { } let nextIndex = (currentIndex + 1) % activePsInOrder.length; + let newTurnOrderIds = encounter.turnOrderIds; if (nextIndex === 0 && currentIndex !== -1) { nextRound += 1; + // Rebuild turn order by initiative at the start of each new round so that participants + // activated mid-round (appended to the end) slot into proper initiative position next round. + const activePs = encounter.participants.filter(p => p.isActive); + const sorted = sortParticipantsByInitiative(activePs, encounter.participants); + newTurnOrderIds = sorted.map(p => p.id); } + // When wrapping to a new round the next participant is first in the rebuilt order + const nextParticipant = (nextIndex === 0 && currentIndex !== -1) + ? encounter.participants.find(p => p.id === newTurnOrderIds[0]) + : activePsInOrder[nextIndex]; + + if (!nextParticipant) return; + try { await updateDoc(doc(db, encounterPath), { - currentTurnParticipantId: activePsInOrder[nextIndex].id, - round: nextRound + currentTurnParticipantId: nextParticipant.id, + round: nextRound, + turnOrderIds: newTurnOrderIds, }); - logAction(`${activePsInOrder[nextIndex].name}'s turn (Round ${nextRound})`, { encounterName: encounter.name }, { + logAction(`${nextParticipant.name}'s turn (Round ${nextRound})`, { encounterName: encounter.name }, { encounterPath, updates: { currentTurnParticipantId: encounter.currentTurnParticipantId, round: encounter.round, + turnOrderIds: [...encounter.turnOrderIds], }, }); } catch (err) {