<!-- source-hash: a64b1bda14e5000a8167e43f4d2c233d -->
Manages NATS message chunk buffering and catchup for dialog loading, ensuring chunks arriving during initial fetch are buffered, deduplicated, ordered by sequence ID, and processed without gaps or duplicates.

## Key Components

| Export | Type | Description |
|--------|------|-------------|
| `useChunkCatchup` | Hook | Main hook orchestrating chunk buffering, catchup fetching, deduplication, and ordered processing |
| `makeSeqKey` | Helper | Generates a unique tracking key from `messageType`, `chunkType`, and `sequenceId` |
| `makeBatchDedupKey` | Helper | Generates a composite deduplication key covering all relevant chunk fields |
| `getChatTypeMessageType` | Helper | Maps a `ChatType` to its corresponding `NatsMessageType` |

### Hook Return API (`UseChunkCatchupReturn`)

| Method | Description |
|--------|-------------|
| `catchUpChunks(fromSequenceId?)` | Fetches historical chunks from the API and merges with buffered NATS chunks |
| `processChunk(chunk, messageType, forceProcess?)` | Processes a single chunk, buffering it if catchup is still in progress |
| `startInitialBuffering()` | Activates the buffer so live NATS chunks are held during initial fetch |
| `isBufferingActive()` | Returns `true` if buffering is currently active |
| `resetChunkTracking()` | Clears all sequence tracking and buffer state |
| `resetAndCatchUp()` | Resets guards and re-fetches from the last known sequence — use after reconnection |
| `processedCount` | Number of successfully processed sequence keys |

## Usage Example

```typescript
const {
  catchUpChunks,
  processChunk,
  startInitialBuffering,
  resetAndCatchUp,
} = useChunkCatchup({
  dialogId: 'dialog-123',
  chatTypes: [CHAT_TYPE.CLIENT, CHAT_TYPE.ADMIN],
  fetchChunks: async (dialogId, chatType, fromSequenceId) => {
    return await api.getChunks(dialogId, chatType, fromSequenceId)
  },
  onChunkReceived: (chunk, messageType) => {
    dispatch(appendChunk({ chunk, messageType }))
  },
})

// On dialog open: buffer live chunks while fetching history
startInitialBuffering()
await catchUpChunks()

// On NATS message received:
processChunk(incomingChunk, 'message')

// On reconnect: re-fetch missed chunks from last known position
await resetAndCatchUp()
```