import { useState, type ReactNode } from 'react'; import { Link, useNavigate, useParams } from 'react-router-dom'; import { useEncounter, useCampaign, useCampaignCharacters, useCampaignMonsters, useCampaignNpcs, useCampaignWeapons, useCampaignItems, useCampaignLocations, useAddParticipant, usePatchParticipant, useRemoveParticipant, useAdvanceRound, useNextTurn, useSetTargets, useReviveParticipant, usePatchEncounter, useSetEncounterArchived, useDeleteEncounter, useAddReward, useDeleteReward, useAwardReward, type NewReward, } from '../api/queries'; import { useCampaignSocket } from '../hooks/useCampaignSocket'; import { useAuth } from '../auth/useAuth'; import { Spinner, ErrorBanner } from '../components/Spinner'; import { NumberInput } from '../components/NumberInput'; import { HpBar } from '../components/HpBar'; import { DeathSaves } from '../components/DeathSaves'; import { TradePanel } from '../components/TradePanel'; import { useRememberCampaign } from '../lib/lastCampaign'; import { openCharacterPanel } from '../lib/characterPanel'; import { GearInForce } from '../components/CharacterPanel'; import { ABILITY_LABELS, CLASS_LABELS, COIN_LABELS, CURRENCIES, SPECIES_LABELS, extractErrorMessage, fmtMod, formatMoney, spellLevelLabel } from '../lib/format'; import { abilityModifier, scaledDamageDice, MAX_GEAR_LEVEL } from '../lib/previewCalc'; import type { Ability, CharacterSummary, Currency, Encounter, EncounterMode, EncounterParticipant, EncounterReward, Item, Weapon, } from '../api/types'; const ABILITIES: Ability[] = ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']; const CONDITIONS = [ 'Blinded', 'Charmed', 'Deafened', 'Frightened', 'Grappled', 'Incapacitated', 'Invisible', 'Paralyzed', 'Petrified', 'Poisoned', 'Prone', 'Restrained', 'Stunned', 'Unconscious', 'Concentrating', ]; // An attack on more than one target is an area attack, and harder to land: // every target's AC counts as `step` higher for each target beyond the first. // The step is the campaign's "area attack AC penalty" setting. const areaPenalty = (targetCount: number, step: number) => Math.max(0, targetCount - 1) * step; const KIND_LABELS = { CHARACTER: 'PC', MONSTER: 'Monster', NPC: 'NPC' } as const; const KIND_BADGES = { CHARACTER: 'badge-player', MONSTER: 'badge-hostile', NPC: 'badge-friendly' } as const; const MODE_LABELS: Record = { BATTLE: '⚔ Battle', QUEST: '📜 Quest' }; const STATUS_LABELS = { PLANNING: 'Planning', ACTIVE: 'In progress', COMPLETE: 'Complete' } as const; function StatChip({ label, children }: { label: string; children: ReactNode }) { return ( {label} {children} ); } // Who this combatant is, in one muted line under the name. function subline(p: EncounterParticipant): string { const info = p.characterCombatInfo; if (info) { return [ `Level ${info.level}`, info.species && SPECIES_LABELS[info.species], info.characterClass && CLASS_LABELS[info.characterClass], ] .filter(Boolean) .join(' '); } if (p.kind === 'NPC') return p.npc?.role || 'Non-player character'; if (p.monster?.challengeRating) return `Challenge ${p.monster.challengeRating}`; return ''; } function CombatantCard({ participant: p, isDM, isMine, isActive, onPatch, canRollInitiative, targetedBy, acPenalty, onTarget, onRemove, onError, }: { participant: EncounterParticipant; isDM: boolean; // The viewer's own character: its card is marked so it is easy to find. isMine: boolean; isActive: boolean; onPatch: (data: Partial) => void; // The DM for anyone; a player for their own character. The same goes for // that character's death saves. canRollInitiative: boolean; // Set while this combatant is a target: who is going for them, or '' when // nobody is on turn. targetedBy?: string; // What an area attack adds to this target's AC; 0 when they are the only one. acPenalty: number; // Marks this combatant as a target, or unmarks them. Absent for someone who // may not pick targets right now, and on the card of whoever is on turn. onTarget?: () => void; onRemove: () => void; onError: (err: unknown) => void; }) { const [hpDelta, setHpDelta] = useState(''); // Details start open for the DM (who runs the scene from this screen) and // closed for players; null = "not toggled yet", so it follows isDM once the // campaign role has loaded. const [detailsToggled, setDetailsToggled] = useState(null); const showDetails = detailsToggled ?? isDM; const info = p.characterCombatInfo; const monster = p.monster; const npc = p.npc; // A player may get a percentage in place of a monster's or NPC's numbers. const currentHp = p.currentHp ?? 0; const maxHp = p.maxHp ?? 0; const barOnly = p.maxHp == null && p.hpPercent != null; const tracksHp = barOnly || maxHp > 0; const pct = barOnly ? (p.hpPercent ?? 0) : tracksHp ? Math.max(0, Math.min(100, (currentHp / maxHp) * 100)) : 0; const isDown = tracksHp && pct <= 0; // A dying character still has something to do each turn, so its card stays lit. const isDying = info?.deathSaves.state === 'DYING'; const isTargeted = targetedBy !== undefined; // Players get a monster's name and health bar only; the stat block is the DM's. const monsterStats = monster && monster.ac !== undefined ? monster : null; const hasDetails = Boolean(info || monsterStats || npc?.dmNotes); function applyDelta(sign: 1 | -1) { const amount = Number(hpDelta); if (!amount) return; onPatch({ currentHp: currentHp + sign * amount }); setHpDelta(''); } function addCondition(condition: string) { const name = condition.trim(); if (!name || p.conditions.includes(name)) return; onPatch({ conditions: [...p.conditions, name] }); } return (
{isMine &&
★ Your character
} {isActive &&
▶ On turn
} {isTargeted && (
🎯 Targeted{targetedBy && ` by ${targetedBy}`} {acPenalty > 0 && ` · area attack, AC +${acPenalty}`}
)}
{KIND_LABELS[p.kind]} {p.character ? ( {p.displayName} ) : ( {p.displayName} )} {npc && {npc.disposition}} {p.character && (isDM || isMine) && ( )} {isDown && !info && Down} {p.hidden && ( Hidden from players )} {onTarget && ( )}
{subline(p)}
{/* Battles and quests both take initiative: who speaks or acts first matters in either. */} {canRollInitiative ? ( ) : ( {p.initiativeRoll == null ? '—' : p.initiative} )}
{tracksHp && !barOnly && ( {currentHp}/{maxHp} {info && info.tempHp > 0 && ` +${info.tempHp}`} )} {info && ( <> {info.armorClass} {info.speed} {fmtMod(info.initiativeBonus)} {info.passivePerception} {fmtMod(info.proficiencyBonus)} {info.spellcasting && {info.spellcasting.saveDC}} )} {monsterStats && ( <> {monsterStats.ac} {monsterStats.speed} {fmtMod(monsterStats.attackBonus ?? 0)} {monsterStats.damageDice && {monsterStats.damageDice}} )} {npc && npc.ac != null && {npc.ac}} {npc && npc.attackBonus != null && {fmtMod(npc.attackBonus)}} {npc && npc.damageDice && {npc.damageDice}}
{/* An NPC's description is what players are here for, so it is never tucked away. */} {npc?.description &&

{npc.description}

} {tracksHp && ( <> 0 ? (info.tempHp / maxHp) * 100 : 0} /> {isDM && (
setHpDelta(e.target.value)} style={{ width: 90 }} />
)} {info && p.character && ( )} )} {(p.conditions.length > 0 || isDM) && (
{p.conditions.map((c) => ( {c} {isDM && ( )} ))} {isDM && ( )}
)} {(hasDetails || isDM) && (
{hasDetails ? ( ) : ( )} {isDM && ( )}
)} {hasDetails && showDetails && (
{info && ( <>
{ABILITIES.map((a) => ( {info.abilities[a].final} ({fmtMod(info.abilities[a].modifier)}) ))}

Saves:{' '} {ABILITIES.map((a) => `${a} ${fmtMod(info.saves[a].bonus)}${info.saves[a].proficient ? '*' : ''}`).join(' · ')}{' '} (* proficient)

{info.weapons.length === 0 && (

No weapon equipped. A weapon has to be equipped to be used: open 🎒 Inventory to put one on.

)} {info.items.length > 0 && (

Equipped: {info.items.map((i) => `${i.name}${i.damageDice ? ` (${i.damageDice})` : ''}`).join(' · ')}

)} {info.weapons.map((w) => (
{w.name} Lv {w.level} · {w.damageDice} {fmtMod(w.damageBonus)} {w.damageType} {fmtMod(w.attackBonus)} to hit
))} {info.spells.length > 0 && (
{info.spells.map((s) => ( {s.name} ({spellLevelLabel(s.level)} {s.damageDice ? ` · ${s.damageDice}` : ''}) ))}
)} {info.spellcasting && (

Spellcasting ({ABILITY_LABELS[info.spellcasting.ability]}): save DC {info.spellcasting.saveDC} ·{' '} {fmtMod(info.spellcasting.attackBonus)} to hit

)} {info.specialAbilities &&

{info.specialAbilities}

} )} {monsterStats && ( <>
{ABILITIES.map((a) => { const score = monsterStats[`${a.toLowerCase()}Score` as 'strScore'] ?? 10; return ( {score} ({fmtMod(abilityModifier(score))}) ); })}
{monsterStats.specialTrait && (

Trait: {monsterStats.specialTrait}

)} {monsterStats.notes &&

{monsterStats.notes}

} )} {npc?.dmNotes && (

🔒 {npc.dmNotes}

)}
)}
); } // What a combatant hits with, one line per attack: a character's weapons // (the equipped ones, when any are) and damaging spells, or the single attack // of a monster or NPC. function attackLines(p: EncounterParticipant): string[] { const info = p.characterCombatInfo; if (info) { const weapons = info.weapons.map( (w) => `${w.name}: ${fmtMod(w.attackBonus)} to hit · ${w.damageDice} ${fmtMod(w.damageBonus)} ${w.damageType}` ); const spells = info.spells .filter((s) => s.damageDice) .map((s) => `${s.name}: ${s.damageDice}${info.spellcasting ? ` · ${fmtMod(info.spellcasting.attackBonus)} to hit / DC ${info.spellcasting.saveDC}` : ''}`); return [...weapons, ...spells]; } const stats = p.monster ?? p.npc; if (!stats || (stats.attackBonus == null && !stats.damageDice)) return []; return [[stats.attackBonus != null && `${fmtMod(stats.attackBonus)} to hit`, stats.damageDice].filter(Boolean).join(' · ')]; } type AreaMode = 'SPLIT' | 'EACH'; // How `amount` lands on `count` targets: all of it on each, or shared out // evenly, any remainder going one point each to the first targets picked // (7 between three is 3, 2 and 2). function shares(amount: number, count: number, mode: AreaMode): number[] { if (mode === 'EACH') return Array.from({ length: count }, () => amount); const base = Math.floor(amount / count); return Array.from({ length: count }, (_, i) => base + (i < amount % count ? 1 : 0)); } // The DM's shortcut once targets are marked: who is attacking whom, the // numbers needed to call the hit, and a box to apply the damage without // hunting for each target's card. With more than one target it is an area // attack: each AC is shown with the penalty added, the DM ticks who was hit, // and the amount is split between them or dealt to each in full. function AttackBar({ attacker, targets, acStep, onApply, onRemove, onClear, }: { attacker: EncounterParticipant | undefined; targets: EncounterParticipant[]; acStep: number; // the campaign's area attack AC penalty onApply: (changes: { participantId: string; currentHp: number }[]) => void; onRemove: (participantId: string) => void; onClear: () => void; }) { const [amount, setAmount] = useState(''); const [mode, setMode] = useState('SPLIT'); const [missed, setMissed] = useState([]); const isArea = targets.length > 1; const penalty = areaPenalty(targets.length, acStep); const tracksHp = (t: EncounterParticipant) => (t.maxHp ?? 0) > 0; const hit = targets.filter((t) => tracksHp(t) && !missed.includes(t.id)); const value = Number(amount) || 0; const portions = shares(value, hit.length, isArea ? mode : 'EACH'); const attacks = attacker ? attackLines(attacker) : []; function apply(sign: 1 | -1) { if (!value || hit.length === 0) return; onApply(hit.map((t, i) => ({ participantId: t.id, currentHp: (t.currentHp ?? 0) + sign * portions[i] }))); setAmount(''); setMissed([]); } return (
{attacker && <>{attacker.displayName} → }🎯 {isArea ? `${targets.length} targets` : targets[0].displayName}
{isArea && (

Area attack{penalty > 0 && `: every target's AC counts as ${penalty} higher (+${acStep} for each target beyond the first)`}. Untick anyone the roll missed.

)} {targets.map((t) => { const info = t.characterCombatInfo; const ac = info?.armorClass ?? t.monster?.ac ?? t.npc?.ac; const portion = portions[hit.indexOf(t)]; return (
{isArea && ( )}
{ac != null && ( {ac + penalty} {penalty > 0 && ` (${ac} +${penalty})`} )} {tracksHp(t) ? ( {t.currentHp ?? 0}/{t.maxHp} {info && info.tempHp > 0 && ` +${info.tempHp}`} ) : ( No hit points to track. )} {isArea && value > 0 && portion !== undefined && {portion}}
{isArea && ( )}
); })} {attacks.map((line) => (
⚔ {line}
))} {targets.some(tracksHp) && (
{/* Remounted when the targets change, so the cursor lands here as soon as one is marked. */} t.id).join()} autoFocus min={1} max={99999} placeholder={isArea ? 'Total' : 'Amount'} aria-label={isArea ? 'HP change for the targets hit' : `HP change for ${targets[0].displayName}`} value={amount} onChange={(e) => setAmount(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && apply(-1)} style={{ width: 90 }} /> {isArea && ( )}
)}
); } function rewardLabel(r: EncounterReward): string { if (r.type === 'GOLD') return formatMoney(r.gold ?? 0, r.currency ?? 'GOLD', true); const entry = r.type === 'WEAPON' ? r.weapon : r.item; return `${entry?.name ?? 'Removed from the pool'}${r.quantity > 1 ? ` ×${r.quantity}` : ''} · Lv ${r.level}`; } function RewardsPanel({ encounter, isDM, characters, weapons, items, onError, }: { encounter: Encounter; isDM: boolean; characters: CharacterSummary[]; weapons: Weapon[]; items: Item[]; onError: (err: unknown) => void; }) { const addReward = useAddReward(encounter.id); const deleteReward = useDeleteReward(encounter.id); const awardReward = useAwardReward(encounter.id); const [type, setType] = useState('GOLD'); const [gold, setGold] = useState(''); const [currency, setCurrency] = useState('GOLD'); const [poolId, setPoolId] = useState(''); const [quantity, setQuantity] = useState('1'); const [level, setLevel] = useState(''); const [note, setNote] = useState(''); const [recipients, setRecipients] = useState>({}); const rewards = encounter.rewards ?? []; const pool: (Weapon | Item)[] = type === 'WEAPON' ? weapons : items; const picked = pool.find((entry) => entry.id === poolId); const partySize = (encounter.participants ?? []).filter((p) => p.kind === 'CHARACTER' && p.characterId).length; if (!isDM && rewards.length === 0) return null; function handleAdd() { const shared = { note: note.trim() || undefined }; let reward: NewReward; if (type === 'GOLD') { const amount = Math.floor(Number(gold)); if (!(amount > 0)) return; reward = { type, gold: amount, currency, ...shared }; } else { if (!picked) return; const gear = { quantity: Math.max(1, Math.floor(Number(quantity)) || 1), level: level ? Number(level) : undefined, ...shared }; reward = type === 'WEAPON' ? { type, weaponId: picked.id, ...gear } : { type, itemId: picked.id, ...gear }; } addReward.mutate(reward, { onError, onSuccess: () => { setGold(''); setPoolId(''); setQuantity('1'); setLevel(''); setNote(''); }, }); } return (
Rewards
{isDM && rewards.length === 0 && (

Line up coins, weapons and items here. Players only see a reward once you award it.

)} {rewards.map((r) => (
{r.type === 'GOLD' ? '🪙' : r.type === 'WEAPON' ? '🗡' : '🎒'} {rewardLabel(r)} {isDM && ( )}
{r.note &&
{r.note}
} {r.awardedAt ? (
✓ Awarded to {r.awardedTo}
) : ( isDM && (
{r.type === 'GOLD' && ( )}
) )}
))} {isDM && (
Add a reward
{type === 'GOLD' ? ( <> setGold(e.target.value)} style={{ flex: 1, minWidth: 90 }} /> ) : ( <> {picked && ( <> setQuantity(e.target.value)} style={{ width: 64 }} /> )} )}
setNote(e.target.value)} style={{ flex: 1, minWidth: 0 }} />
)}
); } export function EncounterPage() { const { encounterId = '' } = useParams(); const { user } = useAuth(); const { data: encounter, isLoading, error } = useEncounter(encounterId); useCampaignSocket(encounter?.campaignId); useRememberCampaign(encounter?.campaignId); const { data: campaignData } = useCampaign(encounter?.campaignId); const isDM = campaignData?.campaign.role === 'DM'; const { data: characters } = useCampaignCharacters(encounter?.campaignId); const { data: monsters } = useCampaignMonsters(encounter?.campaignId, isDM); const { data: npcs } = useCampaignNpcs(encounter?.campaignId, isDM); const { data: weapons } = useCampaignWeapons(encounter?.campaignId); const { data: items } = useCampaignItems(encounter?.campaignId); const { data: locations } = useCampaignLocations(encounter?.campaignId); const addParticipant = useAddParticipant(encounterId); const patchParticipant = usePatchParticipant(encounterId); const removeParticipant = useRemoveParticipant(encounterId); const advanceRound = useAdvanceRound(encounterId); const nextTurn = useNextTurn(encounterId); const setTargets = useSetTargets(encounterId); const revive = useReviveParticipant(encounterId); const patchEncounter = usePatchEncounter(encounterId); const setArchived = useSetEncounterArchived(encounter?.campaignId ?? ''); const deleteEncounter = useDeleteEncounter(encounter?.campaignId ?? ''); const navigate = useNavigate(); const [pickType, setPickType] = useState<'character' | 'monster' | 'npc'>('character'); const [pickId, setPickId] = useState(''); const [initiative, setInitiative] = useState(''); const [formError, setFormError] = useState(null); // The DM's own screen leaves the fallen out too, until asked for. const [showDead, setShowDead] = useState(false); if (isLoading) return ; if (error || !encounter) return ; const isBattle = encounter.mode === 'BATTLE'; const participants = encounter.participants ?? []; // already in initiative order // The fallen: dead characters, and monsters and NPCs at 0 HP. Only the DM is // sent their cards, and they sit apart from those still in the fight. const standing = participants.filter((p) => !p.hidden); const outOfTheFight = participants.filter((p) => p.hidden); const fallen = encounter.fallen ?? []; const active = isBattle && encounter.status === 'ACTIVE' ? participants.find((p) => p.id === encounter.activeParticipantId) : undefined; // The viewer's own characters here, to mark and to jump to. const mine = participants.filter((p) => p.character != null && p.character.userId === user?.id); const targetIds = encounter.targetParticipantIds ?? []; const targets = targetIds.map((id) => participants.find((p) => p.id === id)).filter((p): p is EncounterParticipant => p !== undefined); // The DM marks targets whenever they like; a player while their own character is on turn. const acStep = campaignData?.campaign.areaAttackAcPenalty ?? 0; const canTarget = isDM || (active?.character != null && active.character.userId === user?.id); // A player whose own character is on turn, on their feet and able to raise the dead. const canTryRevive = active?.character != null && active.character.userId === user?.id && active.characterCombatInfo?.deathSaves.state === 'UP' && active.characterCombatInfo.canRevive; const builtCharacters = characters?.filter((c) => c.buildStage === 'COMPLETE') ?? []; const onError = (err: unknown) => setFormError(extractErrorMessage(err)); const fail = { onError }; const pickOptions: { id: string; name: string }[] = pickType === 'character' ? // The dead join no new scene until they are revived. builtCharacters.filter((c) => c.deathSaves.state !== 'DEAD' && !participants.some((p) => p.characterId === c.id)) : pickType === 'monster' ? (monsters ?? []) : (npcs ?? []).filter((n) => !participants.some((p) => p.npcId === n.id)); function handleAdd() { if (!pickId) return; setFormError(null); addParticipant.mutate( { [`${pickType}Id`]: pickId, initiativeRoll: initiative ? Number(initiative) : undefined }, { onError, onSuccess: () => setPickId('') } ); } const card = (p: EncounterParticipant) => ( patchParticipant.mutate({ participantId: p.id, ...data }, fail)} canRollInitiative={isDM || (p.character != null && p.character.userId === user?.id)} targetedBy={targetIds.includes(p.id) ? (active?.displayName ?? '') : undefined} acPenalty={areaPenalty(targets.length, acStep)} onTarget={ // Nobody targets themselves: the combatant on turn has no button. canTarget && p.id !== active?.id ? () => setTargets.mutate(targetIds.includes(p.id) ? targetIds.filter((id) => id !== p.id) : [...targetIds, p.id], fail) : undefined } onRemove={() => removeParticipant.mutate(p.id, fail)} onError={onError} /> ); // In a battle under way the turn passes down the initiative order, so // everyone above whoever is on turn has had their go this round. They drop // to "Next Round" at the bottom, which leaves the combatant on turn at the // top with those still to act beneath them. A new round puts everyone back. const turnIndex = active ? participants.indexOf(active) : -1; const hasActed = (p: EncounterParticipant) => participants.indexOf(p) < turnIndex; // A quest scene is grouped by who is there; within each group the order is // still initiative, highest first. const groups: [string, EncounterParticipant[]][] = isBattle ? [ ['Initiative order', standing.filter((p) => !hasActed(p))], ['Next Round', standing.filter(hasActed)], ] : [ ['People you meet', standing.filter((p) => p.kind === 'NPC')], ['The party', standing.filter((p) => p.kind === 'CHARACTER')], ['Creatures', standing.filter((p) => p.kind === 'MONSTER')], ]; if (showDead) groups.push(['Out of the fight, hidden from players', outOfTheFight]); return (

{isBattle ? '⚔' : '📜'} {encounter.name}

{MODE_LABELS[encounter.mode]} {STATUS_LABELS[encounter.status]} {isBattle && Round {encounter.currentRound}} {encounter.location && 📍 {encounter.location.name}} {encounter.archivedAt && Archived} {active && ▶ {active.displayName}'s turn}
← Campaign {isDM && ( <> {encounter.status === 'PLANNING' && ( )} {encounter.status === 'ACTIVE' && isBattle && ( <> )} {encounter.status === 'ACTIVE' && ( )} {encounter.status === 'COMPLETE' && ( )} )}
{formError && } {mine.length > 0 && ( )} {(isDM || encounter.description) && (
{isBattle ? 'The Scene' : 'Quest'}
{isDM ? (