# Veilborn Chronicles Integration Guide

> _Step-by-step guide for integrating the Veilborn Chronicles engine into your
> application._

This guide provides practical examples and patterns for using the Veilborn
Chronicles API.

---

## Quick Start

### Installation

```bash
# Using npm
npm install @veilborn/core

# Using yarn
yarn add @veilborn/core

# Using pnpm
pnpm add @veilborn/core
```

### First Character

```typescript
import { createCharacterFromTemplate, PATHS } from '@veilborn/core';

// Create a Seer character
const mySeer = createCharacterFromTemplate({
  name: 'Aletheia the Truth-Seeker',
  path: 'seer',
  awakening: 'truth_sight',
  resonanceAllocation: {
    clarity: 7, // Primary for Seer
    flow: 4,
    presence: 4,
    root: 3,
    void: 5, // Secondary for Seer
  },
  backgroundChoice: 'scholar',
  startingAbilities: ['pierce_illusion', 'future_glimpse'],
});

console.log(`Created ${mySeer.name}, a level ${mySeer.level} ${mySeer.path}`);
```

---

## Character Creation Workflow

### Step 1: Choose a Path

Each Path has primary and secondary Resonances:

```typescript
import { PATHS, type PathName } from '@veilborn/core';

// Get path information
const seerPath = PATHS['seer'];
console.log(`Primary: ${seerPath.primaryResonance}`); // 'clarity'
console.log(`Secondary: ${seerPath.secondaryResonance}`); // 'void'
console.log(`Abilities: ${seerPath.abilities.length}`);

// List all paths
const pathNames: PathName[] = Object.keys(PATHS) as PathName[];
pathNames.forEach((name) => {
  const path = PATHS[name];
  console.log(`${name}: ${path.description}`);
});
```

### Step 2: Allocate Resonances

Use the point-buy system with 25 points:

```typescript
import {
  validateResonanceAllocation,
  calculatePointCost,
} from '@veilborn/core';

const allocation = {
  clarity: 6,
  flow: 5,
  presence: 4,
  root: 4,
  void: 5,
};

// Check total cost
const cost = calculatePointCost(allocation);
console.log(`Point cost: ${cost}`); // Should be 25 or less

// Validate allocation
const validation = validateResonanceAllocation(allocation);
if (!validation.valid) {
  console.error('Invalid allocation:', validation.errors);
}
```

### Step 3: Select Abilities

Choose starting abilities from your Path:

```typescript
import { PATHS, validateAbilitySelection } from '@veilborn/core';

const path = PATHS['seer'];
const tier1Abilities = path.abilities.filter((a) => a.tier === 1);

// Select 2 starting abilities
const selectedAbilities = [tier1Abilities[0].id, tier1Abilities[1].id];

const validation = validateAbilitySelection(selectedAbilities, 'seer', 1);
if (validation.valid) {
  console.log('Abilities selected successfully');
}
```

### Step 4: Create the Character

```typescript
const character = createCharacterFromTemplate({
  name: 'Kelis',
  path: 'weaver',
  awakening: 'probability_touched',
  resonanceAllocation: allocation,
  backgroundChoice: 'gambler',
  startingAbilities: selectedAbilities,
});
```

---

## Combat Integration

### Setting Up a Combat Encounter

```typescript
import { CombatManager, createCombatant, type HexCoord } from '@veilborn/core';

// Initialize combat manager
const combat = new CombatManager({
  gridWidth: 20,
  gridHeight: 15,
  tideEnabled: true,
});

// Add player characters
const playerCombatant = createCombatant({
  id: 'player-1',
  name: 'Kelis',
  team: 'player',
  position: { q: 5, r: 5 },
  stats: {
    health: 25,
    maxHealth: 25,
    defense: 3,
    attack: 4,
    movement: 4,
    initiative: 12,
  },
});
combat.addCombatant(playerCombatant);

// Add enemies
const enemyCombatant = createCombatant({
  id: 'enemy-1',
  name: 'Void Tendril',
  team: 'enemy',
  position: { q: 10, r: 8 },
  stats: {
    health: 15,
    maxHealth: 15,
    defense: 2,
    attack: 5,
    movement: 2,
    initiative: 8,
  },
});
combat.addCombatant(enemyCombatant);

// Start combat
combat.startCombat();
```

### Processing Turns

```typescript
// Get current turn
const currentId = combat.getCurrentTurn();
const combatant = combat.getCombatant(currentId);
console.log(`Current turn: ${combatant.name}`);

// Get valid moves
const validMoves = combat.getValidMoves(currentId);
console.log(`${validMoves.length} valid movement hexes`);

// Move combatant
const targetHex: HexCoord = { q: 7, r: 6 };
if (validMoves.some((h) => h.q === targetHex.q && h.r === targetHex.r)) {
  const moveResult = combat.moveCombatant(currentId, [targetHex]);
  console.log(`Moved to (${targetHex.q}, ${targetHex.r})`);
}

// Perform an action
const action = {
  type: 'ability',
  abilityId: 'probability_shift',
  targetId: 'enemy-1',
};
const result = combat.performAction(action);

// End turn
combat.advanceTurn();
```

### Handling Status Effects

```typescript
import {
  applyStatusEffect,
  tickEffects,
  STANDARD_EFFECTS,
  hasEffect,
} from '@veilborn/core';

// Apply a status effect
let effects = [];
effects = applyStatusEffect(
  effects,
  STANDARD_EFFECTS.burning,
  'player-1', // source
  'enemy-1', // target
  1 // round number
);

// Check for effect
if (hasEffect(effects, 'burning', 'enemy-1')) {
  console.log('Enemy is burning!');
}

// Process end-of-round effects
const definitions = new Map(
  Object.entries(STANDARD_EFFECTS).map(([k, v]) => [k, v])
);
const tickResult = tickEffects(effects, 2, definitions);

// Apply tick damage
for (const tick of tickResult.ticks) {
  if (tick.damage) {
    console.log(`${tick.targetId} takes ${tick.damage} burning damage`);
  }
}

// Update effects (removes expired)
effects = tickResult.effects;
```

### Area of Effect Abilities

```typescript
import {
  getBurstArea,
  getConeArea,
  getLineArea,
  hexDistance,
} from '@veilborn/core';

// Burst ability (circular)
const fireballCenter: HexCoord = { q: 8, r: 7 };
const fireballRadius = 2;
const affectedHexes = getBurstArea(fireballCenter, fireballRadius);
console.log(`Fireball affects ${affectedHexes.length} hexes`);

// Cone ability
const breathOrigin: HexCoord = { q: 5, r: 5 };
const breathDirection: HexCoord = { q: 8, r: 7 };
const coneHexes = getConeArea(breathOrigin, breathDirection, 4, 90);
console.log(`Cone breath affects ${coneHexes.length} hexes`);

// Line ability
const lightningStart: HexCoord = { q: 2, r: 3 };
const lightningEnd: HexCoord = { q: 10, r: 3 };
const lineHexes = getLineArea(lightningStart, lightningEnd, 1);
console.log(`Lightning bolt hits ${lineHexes.length} hexes`);
```

---

## Game Session Management

### Creating a Session

```typescript
import {
  createGameSession,
  GameStateManager,
  addPlayer,
  assignCharacter,
} from '@veilborn/core';

// Create a new game session
let session = createGameSession('The Veiled Conspiracy', 'rpg', 'gm-user-123');

// Create state manager for real-time updates
const stateManager = new GameStateManager(session);

// Subscribe to state changes
const unsubscribe = stateManager.subscribe((change) => {
  console.log(`State changed: ${change.type}`, change.data);
});

// Add a player
const addResult = addPlayer(
  stateManager.getSession(),
  'player-user-456',
  'player'
);
if (!('error' in addResult)) {
  stateManager.update(() => addResult.session, 'player_joined', {
    playerId: addResult.player.id,
  });

  // Assign their character
  stateManager.update(
    (s) => assignCharacter(s, addResult.player.id, myCharacter),
    'character_updated',
    { playerId: addResult.player.id, characterId: myCharacter.id }
  );
}
```

### Managing Game Phases

```typescript
import { startGame, advanceTurn, endGame } from '@veilborn/core';

// Start the game
const startResult = startGame(stateManager.getSession());
if (!('error' in startResult)) {
  stateManager.update(() => startResult, 'phase_changed', {
    newPhase: 'playing',
  });
}

// After a player completes their turn
stateManager.update((s) => advanceTurn(s), 'turn_advanced', {});

// End the session
stateManager.update((s) => endGame(s), 'phase_changed', {
  newPhase: 'completed',
});
```

### Undo/Redo

```typescript
// Player made a mistake
if (stateManager.canUndo()) {
  stateManager.undo();
  console.log('Last action undone');
}

// Changed their mind
if (stateManager.canRedo()) {
  stateManager.redo();
  console.log('Action redone');
}
```

### Saving and Loading

```typescript
import {
  createStateSnapshot,
  restoreFromSnapshot,
  serializeSession,
  deserializeSession,
} from '@veilborn/core';

// Create a save point
const snapshot = createStateSnapshot(
  stateManager.getSession(),
  'Before boss fight'
);

// Serialize for storage
const json = serializeSession(stateManager.getSession());
localStorage.setItem('veilborn-save', json);

// Load from storage
const savedJson = localStorage.getItem('veilborn-save');
if (savedJson) {
  const loadedSession = deserializeSession(savedJson);
  const newManager = new GameStateManager(loadedSession);
}

// Restore from snapshot
const restoredSession = restoreFromSnapshot(snapshot);
```

---

## Multiplayer Integration

### Setting Up a Game Room

```typescript
import { MultiplayerService } from '@veilborn/core';

// Initialize multiplayer service
const multiplayer = new MultiplayerService({
  maxRooms: 100,
  defaultTurnTimeLimit: 120000, // 2 minutes
  spectatorDelay: 5000,
  pingInterval: 5000,
  maxReconnectAttempts: 5,
});

// Create a new room
const room = multiplayer.createRoom(
  'host-user-123',
  'GameMaster',
  'The Veiled Conspiracy',
  {
    maxPlayers: 5,
    allowSpectators: true,
    isPrivate: false,
    turnTimeLimit: 180000, // 3 minutes
    replayEnabled: true,
  }
);

console.log(`Room created with code: ${room.code}`);
```

### Joining a Room

```typescript
// Player joins with room code
const joinResult = multiplayer.joinRoom(
  'ABC123', // Room code
  'player-456', // Player ID
  'Kelis', // Display name
  false // Not as spectator
);

if (joinResult.success) {
  console.log(`Joined room: ${joinResult.room.name}`);
} else {
  console.error(`Failed to join: ${joinResult.error}`);
}

// Spectator joins
const spectatorResult = multiplayer.joinRoom(
  'ABC123',
  'spectator-789',
  'Watcher',
  true // As spectator
);
```

### Starting a Game

```typescript
// Host starts the game
const started = multiplayer.startGame(room.id, {
  phase: 'playing',
  sharedState: {
    scenario: 'The Veiled Conspiracy',
    chapter: 1,
  },
});

if (started) {
  console.log('Game started!');
}
```

### Submitting Actions

```typescript
// Player submits an action
const action = multiplayer.submitAction(room.id, 'player-456', 'ability_use', {
  abilityId: 'probability_shift',
  targetId: 'enemy-1',
  position: { q: 8, r: 7 },
});

if (action) {
  console.log(`Action ${action.id} submitted`);
}

// End turn
const turnEnded = multiplayer.endTurn(room.id, 'player-456');
```

### In-Game Communication

```typescript
// Send chat message
const chatResult = multiplayer.sendChat(
  room.id,
  'player-456',
  'Kelis',
  'I cast Probability Shift on the enemy!',
  'global'
);

// Send whisper
multiplayer.sendChat(
  room.id,
  'player-456',
  'Kelis',
  'Should I use my burst ability?',
  'whisper',
  'host-user-123'
);

// Roll dice
const diceResult = multiplayer.rollDice(
  room.id,
  'player-456',
  'Kelis',
  '2d6+4',
  'Clarity check'
);

if (!('error' in diceResult)) {
  console.log(
    `Rolled ${diceResult.dice}: [${diceResult.results.join(', ')}] + ${diceResult.modifier} = ${diceResult.total}`
  );
}

// Private roll (only visible to roller and GM)
multiplayer.rollDice(
  room.id,
  'player-456',
  'Kelis',
  '1d100',
  'Secret perception check',
  true // Private
);

// Send emote
multiplayer.sendEmote(room.id, 'player-456', 'Kelis', 'celebrate');
```

### Handling Disconnections

```typescript
// Check connection status
const connectedPlayers = multiplayer.connectionManager.getConnectedPlayers();
console.log(`${connectedPlayers.length} players connected`);

// Handle reconnection in your WebSocket handler
websocket.on('reconnect', (playerId) => {
  const room = multiplayer.roomManager.getPlayerRoom(playerId);
  if (room) {
    // Sync state to reconnected player
    const currentState = multiplayer.stateSyncManager.getCurrentState(room.id);
    sendToPlayer(playerId, {
      type: 'state_sync',
      state: currentState,
    });
  }
});
```

---

## Advanced Patterns

### Custom Ability Effects

```typescript
import { type AbilityDef, type StatusEffectDef } from '@veilborn/core';

// Define a custom status effect
const customEffect: StatusEffectDef = {
  id: 'thread_bound',
  name: 'Thread Bound',
  description: 'Bound by probability threads, movement is restricted',
  category: 'control',
  duration: 2,
  stackingBehavior: 'refresh',
  maxStacks: 1,
  ticksPerRound: 0,
  statModifiers: [
    { stat: 'movement', operation: 'multiply', value: 0.5, isPerStack: false },
  ],
  preventsMovement: false,
  removedBy: ['dispel', 'freedom'],
};

// Define a custom ability
const customAbility: AbilityDef = {
  id: 'binding_threads',
  name: 'Binding Threads',
  description: 'Weave threads of probability to slow enemies',
  targeting: {
    type: 'area_burst',
    range: 6,
    areaSize: 2,
    filter: {
      includeAllies: false,
      includeEnemies: true,
      includeSelf: false,
      includeNeutrals: false,
      requiresLineOfSight: true,
    },
  },
  cost: { resonance: 3 },
  tideCost: 0,
  cooldownType: 'rounds',
  cooldownDuration: 3,
  maxCharges: 0,
  statusEffects: [{ effectId: 'thread_bound', chance: 100, onlyOnHit: false }],
  isChanneled: false,
  canBeInterrupted: false,
  requiresLineOfSight: true,
  canTargetThroughAllies: false,
  requiredPath: 'weaver',
};
```

### Event-Driven Architecture

```typescript
import { EventEmitter } from 'events';

class VeilbornGame extends EventEmitter {
  private stateManager: GameStateManager;
  private combatManager: CombatManager | null = null;

  constructor(session: GameSession) {
    super();
    this.stateManager = new GameStateManager(session);

    // Forward state changes as events
    this.stateManager.subscribe((change) => {
      this.emit('stateChange', change);
      this.emit(change.type, change.data);
    });
  }

  startCombat(combatants: Combatant[]) {
    this.combatManager = new CombatManager();
    combatants.forEach((c) => this.combatManager!.addCombatant(c));
    this.combatManager.startCombat();
    this.emit('combatStarted', { combatants });
  }

  onTurnChange(callback: (data: any) => void) {
    this.on('turn_advanced', callback);
  }

  onCombatEnd(callback: () => void) {
    this.on('combatEnded', callback);
  }
}

// Usage
const game = new VeilbornGame(session);
game.onTurnChange((data) => {
  console.log('Turn changed:', data);
  updateUI();
});
```

### Persistence Layer

```typescript
interface SaveData {
  session: string;
  snapshots: StateSnapshot[];
  lastSaved: string;
}

class GamePersistence {
  private storageKey: string;

  constructor(sessionId: string) {
    this.storageKey = `veilborn-${sessionId}`;
  }

  save(session: GameSession): void {
    const data: SaveData = {
      session: serializeSession(session),
      snapshots: [],
      lastSaved: new Date().toISOString(),
    };
    localStorage.setItem(this.storageKey, JSON.stringify(data));
  }

  load(): GameSession | null {
    const raw = localStorage.getItem(this.storageKey);
    if (!raw) return null;

    try {
      const data: SaveData = JSON.parse(raw);
      return deserializeSession(data.session);
    } catch {
      return null;
    }
  }

  createCheckpoint(session: GameSession, description: string): void {
    const data = this.loadRaw();
    if (!data) return;

    const snapshot = createStateSnapshot(session, description);
    data.snapshots.push(snapshot);

    // Keep only last 10 snapshots
    if (data.snapshots.length > 10) {
      data.snapshots = data.snapshots.slice(-10);
    }

    localStorage.setItem(this.storageKey, JSON.stringify(data));
  }

  listCheckpoints(): { id: string; description: string; timestamp: string }[] {
    const data = this.loadRaw();
    if (!data) return [];

    return data.snapshots.map((s) => ({
      id: s.id,
      description: s.description,
      timestamp: s.timestamp,
    }));
  }

  restoreCheckpoint(snapshotId: string): GameSession | null {
    const data = this.loadRaw();
    if (!data) return null;

    const snapshot = data.snapshots.find((s) => s.id === snapshotId);
    if (!snapshot) return null;

    return restoreFromSnapshot(snapshot);
  }

  private loadRaw(): SaveData | null {
    const raw = localStorage.getItem(this.storageKey);
    if (!raw) return null;
    return JSON.parse(raw);
  }
}
```

---

## Testing Your Integration

### Unit Testing Characters

```typescript
import { describe, it, expect } from 'vitest';
import { createCharacterFromTemplate, validateCharacter } from '@veilborn/core';

describe('Character Creation', () => {
  it('should create a valid character', () => {
    const character = createCharacterFromTemplate({
      name: 'Test Seer',
      path: 'seer',
      awakening: 'truth_sight',
      resonanceAllocation: {
        clarity: 7,
        flow: 4,
        presence: 4,
        root: 3,
        void: 5,
      },
      backgroundChoice: 'scholar',
      startingAbilities: ['pierce_illusion'],
    });

    expect(character.name).toBe('Test Seer');
    expect(character.path).toBe('seer');

    const validation = validateCharacter(character);
    expect(validation.valid).toBe(true);
    expect(validation.errors).toHaveLength(0);
  });

  it('should apply path bonuses correctly', () => {
    const character = createCharacterFromTemplate({
      name: 'Test Seer',
      path: 'seer',
      awakening: 'truth_sight',
      resonanceAllocation: {
        clarity: 6, // +2 from path = 8
        flow: 4,
        presence: 4,
        root: 3,
        void: 5, // +1 from path = 6
      },
      backgroundChoice: 'scholar',
      startingAbilities: [],
    });

    expect(character.resonances.clarity).toBe(8);
    expect(character.resonances.void).toBe(6);
  });
});
```

### Integration Testing Combat

```typescript
describe('Combat System', () => {
  it('should handle a complete combat round', () => {
    const combat = new CombatManager();

    combat.addCombatant(
      createCombatant({
        id: 'player',
        name: 'Hero',
        team: 'player',
        position: { q: 0, r: 0 },
        stats: {
          health: 20,
          maxHealth: 20,
          defense: 3,
          attack: 5,
          movement: 4,
          initiative: 10,
        },
      })
    );

    combat.addCombatant(
      createCombatant({
        id: 'enemy',
        name: 'Foe',
        team: 'enemy',
        position: { q: 3, r: 0 },
        stats: {
          health: 10,
          maxHealth: 10,
          defense: 2,
          attack: 3,
          movement: 3,
          initiative: 5,
        },
      })
    );

    combat.startCombat();

    // Player's turn (higher initiative)
    expect(combat.getCurrentTurn()).toBe('player');

    // Move and attack
    combat.moveCombatant('player', [{ q: 1, r: 0 }]);
    const result = combat.performAction({
      type: 'attack',
      targetId: 'enemy',
    });

    expect(result.success).toBe(true);
    combat.advanceTurn();

    // Enemy's turn
    expect(combat.getCurrentTurn()).toBe('enemy');
  });
});
```

---

## Troubleshooting

### Common Issues

**Issue: "Invalid resonance allocation"**

- Ensure total point cost is exactly 25
- Check minimum (1) and maximum (8) constraints
- Verify all five Resonances have values

**Issue: "Player not found in session"**

- Ensure player was added with `addPlayer()` before assigning characters
- Check player ID matches exactly

**Issue: "Cannot perform actions in completed session"**

- Session phase must be 'playing'
- Use `changePhase()` to return to playing if needed

**Issue: "Room is full"**

- Check `maxPlayers` in room config
- Consider allowing spectators instead

---

_For complete API reference, see [API Reference](01-api-reference.md)_ _For SDK
documentation, see [SDK Guide](03-sdk-guide.md)_
