---
title: "Chat Component"
canonical_url: "https://docs.sportradar.com/resources/virtual-stadium/docs/ios/chat"
markdown_url: "https://docs.sportradar.com/resources/virtual-stadium/docs/ios/chat.md"
last_updated: "2026-10-20T09:07:17Z"
---

# Chat Component

Get started quickly with the Virtual Stadium Chat component by following this comprehensive integration guide. This guide covers the essential steps to integrate real-time messaging, bet sharing, flash bets, and AI-powered insights into your iOS application.

## Overview

To integrate the Chat component:

1. Add the ChatView component to your SwiftUI view hierarchy
2. Configure authentication with JWT tokens and channel information
3. Implement optional features (bet sharing, flash bets, insights)
4. Customize the appearance and behavior as needed
5. Handle user interactions and callbacks

This guide will walk you through each step with code examples and best practices.

***

## Basic Integration

### SwiftUI

Add the ChatView component to your SwiftUI view with minimal required configuration. This basic setup provides full chat functionality with real-time messaging.

**Required Parameters:**

**`userJWT`** `String` *required*

JWT authentication token required to initialize the UI SDK and authenticate the user.

**`channelId`** `String` *required*

The unique identifier of the chat channel to display.

**`supportedLanguage`** `SupportedLanguage` *required*

Language for localizing SDK content (e.g., `.english`, `.spanish`).

> **Info**
>
> The `userJWT`, `channelId`, and `supportedLanguage` are minimum required parameters. All other parameters are optional and default to `nil`. See [Configuration Parameters](#configuration-parameters) for additional options.

***ContentView\.swift:***

```swift
import SwiftUI
import VirtualStadiumSDK

struct ContentView: View {
    let userJWT = "<your-jwt-token>"
    let channelId = "<your-channel-id>"
    
    var body: some View {
        ChatView(
            userJWT: userJWT,
            channelId: channelId,
            matchStatusManager: nil,
            flashBetManager: nil,
            insightsManager: nil,
            supportedLanguage: .english,
            callbacksVM: nil,
            analyticsProvider: nil,
            onError: nil,
            chatSettings: ChatSettings()
        )
        .navigationTitle("Chat")
    }
}
```

***

## Configuration Parameters

The ChatView component supports various configuration options to customize appearance, behavior, and functionality.

### Required Parameters

- **`userJWT`** `String` *required* — JWT authentication token required to initialize the UI SDK and authenticate the user.
- **`channelId`** `String` *required* — The unique identifier of the chat channel to display.
- **`supportedLanguage`** `SupportedLanguage` *required* — Language code for localizing SDK content and fetching localized feeds. Available options: `.english`, `.spanish`, `.portuguese`, etc.

### Optional Parameters

- **`matchStatusManager`** `MatchStatusManager?` *optional* — Manager for controlling match status behavior. Default is `nil`. See [Match Status](#match-status).
- **`flashBetManager`** `FlashBetManager?` *optional* — Manager for handling Flash Bet events and interactions. Default is `nil`. See [Flash Bet](#flash-bet).
- **`insightsManager`** `InsightsManager?` *optional* — Manager for handling Bet insights functionality. Default is `nil`. See [Bet Insights](#bet-insights).
- **`callbacksVM`** `ChatViewCallbacksVM?` *optional* — A view model encapsulating all user interaction callbacks such as bet sharing, profile opening, tag selection, and support team contact. Default is `nil`. See [Callbacks](#callbacks).
- **`analyticsProvider`** `AnalyticsProvider?` *optional* — Provider for logging analytics events throughout the SDK. Default is `nil`.
- **`onError`** `((Error) -> Void)?` *optional* — Callback for handling SDK errors. Receives error details for logging or displaying to users.
- **`chatSettings`** `ChatSettings` *optional* — Customization settings for theming, fonts, icons, and UI behavior. Default is `ChatSettings()`. See [Chat Settings](#chat-settings).

## Callbacks

All user interaction callbacks are grouped into a single `ChatViewCallbacksVM` object and passed to `ChatView` via the `callbacksVM` parameter. This replaces the previous approach of passing individual callback parameters directly to the `ChatView` initializer.

### ChatViewCallbacksVM API

```swift
public class ChatViewCallbacksVM: ObservableObject {

    // Called when the user wants to share a bet — receives a completion handler
    // to be called with the user's bet slips. If nil, the Share Bet button is hidden.
    var onBetShareHandler: ((@escaping ([BetPayload]) -> Void) -> Void)?

    // Called when a user copies a bet from the chat
    var onCopyToBetslipHandler: ((BetPayload) -> Void)?

    // Called when the Contact Support button is tapped — if nil, the button is hidden
    var onReachSupportTeamHandler: ((InfractionReason) -> Void)?

    // Called when a user taps on another user's profile — receives the user ID
    var onOpenProfileHandler: ((String) -> Void)?

    // Called when a user taps a tag in a message
    var onTagSelectedHandler: ((Tag) -> Void)?

    public init(
        onBetShareHandler: ... = nil,
        onCopyToBetslipHandler: ... = nil,
        onReachSupportTeamHandler: ... = nil,
        onOpenProfileHandler: ... = nil,
        onTagSelectedHandler: ... = nil
    )

    public func clear()
}
```

> **Warning**
>
> **Breaking Change**
>
> In a previous version of the SDK, callbacks were passed as individual parameters directly to the `ChatView` initializer:
>
> ```swift
> // ❌ Old API — no longer supported
> ChatView(
>     userJWT: jwt,
>     channelId: channelId,
>     supportedLanguage: .english,
>     onBetShareHandler: { completion in ... },
>     onCopyToBetslip: { betPayload in ... },
>     onTagSelected: { tag in ... },
>     onReachSupportTeam: { reason in ... },
>     onOpenProfile: { userId in ... }
> )
> ```
>
> These parameters have been removed from the `ChatView` initializer. All callbacks must now be provided through `ChatViewCallbacksVM`.

### Implementation

***Callbacks Implementation:***

```swift
import SwiftUI
import VirtualStadiumSDK

struct ContentView: View {
    let jwt: String
    let channelId: String

    var body: some View {
        ChatView(
            userJWT: jwt,
            channelId: channelId,
            supportedLanguage: .english,
            callbacksVM: makeCallbacksVM()
        )
    }

    private func makeCallbacksVM() -> ChatViewCallbacksVM {
        ChatViewCallbacksVM(
            onBetShareHandler: { completion in
                /**
                 * TODO(developer): Replace with your bet slip fetching logic
                 */
                Task {
                    let betSlips = await getBetSlipsFromDatabase()
                    completion(betSlips)
                }
            },
            onCopyToBetslipHandler: { betPayload in
                /**
                 * TODO(developer): Add bet to user's bet slip
                 */
                addToBetSlip(betPayload)
                print("Bet copied to slip!")
            },
            onReachSupportTeamHandler: { reason in
                /**
                 * TODO(developer): Open support interface
                 */
                print("Opening support. Reason: \(reason)")
            },
            onOpenProfileHandler: { userId in
                /**
                 * TODO(developer): Open user profile
                 */
                print("Opening profile for user: \(userId)")
            },
            onTagSelectedHandler: { tag in
                /**
                 * TODO(developer): Handle tag selection
                 */
                print("Tag selected: \(tag.channelName)")
            }
        )
    }
}
```

1. **Step 1**

   #### Imports

   Import `SwiftUI` and `VirtualStadiumSDK`.

2. **Step 2**

   #### View & ChatView Setup

   Define the view with `jwt` and `channelId` inputs. Pass them to `ChatView` along with the `callbacksVM` returned by `makeCallbacksVM()`.

3. **Step 3**

   #### onBetShareHandler

   Called when a user taps the Share Bet button. Fetch the user's bet slips asynchronously and pass them to the `completion` handler. If this is `nil`, the Share Bet button is hidden.

4. **Step 4**

   #### onCopyToBetslipHandler

   Called when a user copies a bet from the chat. Add the received `betPayload` to the user's bet slip.

5. **Step 5**

   #### onReachSupportTeamHandler

   Called when the Contact Support button is tapped. Open your support interface with the provided infraction reason. If this is `nil`, the button is hidden.

6. **Step 6**

   #### onOpenProfileHandler

   Called when a user taps another user's profile. Navigate to the profile view using the provided `userId`.

7. **Step 7**

   #### onTagSelectedHandler

   Called when a user taps a tag in a message. Handle tag navigation or filtering using the provided `tag`.

> **Tip**
>
> **Hiding Buttons**
>
> - If `onBetShareHandler` is `nil`, the "Share Bet" button is automatically hidden from the UI.
> - If `onReachSupportTeamHandler` is `nil`, the "Contact Support" button is automatically hidden from error and infraction screens.

***

## Flash Bet

Flash Bet enables time-sensitive quick betting triggered by live match events. Users receive real-time betting opportunities with a countdown timer.

### How It Works

1. **Event Trigger** - A flash bet event is triggered from the moderation system
2. **Market Update** - Your app provides market data within 60 seconds (configurable)
3. **User Selection** - Users have limited time to select an outcome
4. **Callback** - When an outcome is selected, your callback is invoked

### FlashBetManager API

```swift
public class FlashBetManager: ObservableObject {

    // Called when a FlashBet event is received — provides the full FlashBet model
    public var onFlashBetReceived: ((FlashBet) -> Void)?

    // Called when a user selects an outcome
    public var onFlashBetOutcomeSelected: ((EventOutcome) -> Void)?

    // Publisher for updating flash bet market data — accepts a full FlashBet model
    public var updateFlashBetPublisher: PassthroughSubject<FlashBet, Never>?

    public init()
    public func clear()
}
```

> **Warning**
>
> **Deprecated API**
>
> The following properties are deprecated and will be removed in a future release. Migrate to the new API as soon as possible.
>
> ```swift
> // ❌ Deprecated — use onFlashBetReceived instead
> public var onFlashBetEventReceived: ((ReceivedEvent) -> Void)?
>
> // ❌ Deprecated — use updateFlashBetPublisher instead
> public var updateFlashBetEventPublisher: PassthroughSubject<FlashBetEventStatus, Never>?
> ```
>
> The deprecated API uses `ReceivedEvent` and `FlashBetEventStatus` which provide limited data. The new API uses the full `FlashBet` model which includes the message title, structured content, localization keys, and more.

> **Warning**
>
> **Avoid Handling Both Callbacks Simultaneously**
>
> Both `onFlashBetEventReceived` (deprecated) and `onFlashBetReceived` are triggered for the same flash bet event. Implementing both callbacks at the same time will result in the event being handled twice, causing unexpected behavior such as duplicate market updates, duplicate bet placements, or conflicting UI states.
>
> Always use only one of the two callbacks — prefer `onFlashBetReceived` for all new implementations.

***

> **Warning**
>
> **Timeout Behavior**
> If you don't provide a market within the configured timeout (default *60 seconds*) of the flash bet trigger, the flash bet will automatically be canceled and move to the next event in the queue (if any).
>
> The timeout duration can be configured via `ChatSettings.generalSettings.flashBetTimeoutDuration`.
>
> Market suspension timeout (how long a flash bet is visible) can be configured in the [moderation panel](https://moderation.vs.sportradar.com) or via the moderation API.

### Market Data Structure

```swift
public struct FlashBet {
    public let title: String
    public let message: [ContentValue]
    public let boldEventInfoSection: [String]?
    public let translationKey: String?
    public let event: Event
    public let matchEvent: MatchEvent
    public let tag: String?
    public let channelId: String?
    public let messageId: String
    public let eventDurationSeconds: Int32
    public let betStopDurationSeconds: Int32
    public var market: Market?
    public let recommendedMarket: RecommendedMarket?
}

public struct Market {
    let id: String
    let name: String
    let status: MarketStatus
    let outcomes: [EventOutcome]
}

public enum MarketStatus {
    case active      // Market is active and accepting bets
    case suspended   // Market is suspended, timer pauses
    case deactivated // Market is deactivated, outcomes disabled
}

public struct EventOutcome {
    let id: String
    let name: String
    let odds: String
}
```

***

### Implementation

***Flash Bet Implementation:***

```swift
import SwiftUI
import VirtualStadiumSDK

struct ChatWithFlashBet: View {
    let jwt: String
    let channelId: String
    
    @StateObject private var flashBetManager = FlashBetManager()
    
    var body: some View {
        NavigationView {
            ChatView(
                userJWT: jwt,
                channelId: channelId,
                flashBetManager: flashBetManager,
                supportedLanguage: .english
            )
            .navigationTitle("Chat")
        }
        .onAppear {
            setupFlashBet()
        }
    }
    
    private func setupFlashBet() {
        // Handle flash bet events
        flashBetManager.onFlashBetReceived = { flashBet in
            print("Flash bet received: \(flashBet.messageId)")
            print("Title: \(flashBet.title)")
            
            Task {
                do {
                    /**
                     * TODO(developer): Replace with your actual market fetching logic
                     */
                    let market = try await fetchFlashBetMarket(
                        eventId: flashBet.event.srEventId ?? ""
                    )
                    
                    // Update the flash bet with market data
                    var updatedFlashBet = flashBet
                    updatedFlashBet.market = market
                    flashBetManager.updateFlashBetPublisher?.send(updatedFlashBet)
                    
                } catch {
                    print("Failed to fetch flash bet market: \(error)")
                }
            }
        }
        
        // Handle outcome selection
        flashBetManager.onFlashBetOutcomeSelected = { outcome in
            placeBet(outcome: outcome)
            print("User selected outcome: \(outcome.name)")
        }
    }
    
    private func fetchFlashBetMarket(eventId: String) async throws -> Market {
        /**
         * TODO(developer): Replace with your actual API call
         */
        return Market(
            id: "market_123",
            name: "Next Goal Scorer",
            status: .active,
            outcomes: [
                EventOutcome(id: "1", name: "Player A", odd: "2.50"),
                EventOutcome(id: "2", name: "Player B", odd: "3.20")
            ]
        )
    }
    
    private func placeBet(outcome: EventOutcome) {
        /**
         * TODO(developer): Implement your bet placement logic
         */
        print("Placing bet on outcome: \(outcome.name)")
    }
}
```

1. **Step 1**

   #### Imports

   Import `SwiftUI` and `VirtualStadiumSDK`.

2. **Step 2**

   #### View Properties

   Declare `jwt` and `channelId` inputs, and initialize a `FlashBetManager` as a `@StateObject` so it persists across view updates.

3. **Step 3**

   #### ChatView with FlashBetManager

   Pass `flashBetManager` to `ChatView`. Call `setupFlashBet()` in `.onAppear` to register handlers after the view has loaded.

4. **Step 4**

   #### onFlashBetReceived

   Called when a flash bet event arrives. Fetch market data for the event asynchronously, attach it to the `FlashBet` model, and send the updated model via `updateFlashBetPublisher` so the SDK can display outcomes.

5. **Step 5**

   #### onFlashBetOutcomeSelected

   Called when the user selects an outcome. Forward the selection to your bet placement logic.

6. **Step 6**

   #### fetchFlashBetMarket

   Fetches market data for the given event ID from your backend. Replace the stub with your actual API call. Returns a `Market` with outcomes and their odds.

7. **Step 7**

   #### placeBet

   Handles the actual bet placement for the selected outcome. Replace with your sportsbook integration logic.

***

### Migrating from Deprecated API

If you are currently using the deprecated `onFlashBetEventReceived` and `updateFlashBetEventPublisher`, here is how to migrate to the new API:

***Before (Deprecated):***

```swift
flashBetManager.onFlashBetEventReceived = { receivedEvent in
    let status = FlashBetEventStatus(
        flashBetEvent: receivedEvent,
        market: market
    )
    flashBetManager.updateFlashBetEventPublisher?.send(status)
}
```

***After (New API):***

```swift
flashBetManager.onFlashBetReceived = { flashBet in
    var updatedFlashBet = flashBet
    updatedFlashBet.market = market
    flashBetManager.updateFlashBetPublisher?.send(updatedFlashBet)
}
```

The key differences are:

- `onFlashBetReceived` provides the full `FlashBet` model instead of the limited `ReceivedEvent`
- `updateFlashBetPublisher` accepts a `FlashBet` directly — simply set `market` on the existing `FlashBet` and send it, instead of wrapping it in a `FlashBetEventStatus`

***

### Market Status Management

Use market status to control flash bet behavior during different match scenarios. This allows you to pause, resume, or deactivate markets based on live events.

***Market Status Control:***

```swift
flashBetManager.onFlashBetReceived = { flashBet in
    // Store the flash bet for later updates
    currentFlashBet = flashBet
    
    // Send with active market
    var updatedFlashBet = flashBet
    updatedFlashBet.market = Market(id: "1", name: "Match Winner", status: .active, outcomes: outcomes)
    flashBetManager.updateFlashBetPublisher?.send(updatedFlashBet)
}

// Suspend the market (e.g., due to a goal)
var suspendedFlashBet = currentFlashBet
suspendedFlashBet.market = Market(id: "1", name: "Match Winner", status: .suspended, outcomes: outcomes)
flashBetManager.updateFlashBetPublisher?.send(suspendedFlashBet)

// Resume the market
var activeFlashBet = currentFlashBet
activeFlashBet.market = Market(id: "1", name: "Match Winner", status: .active, outcomes: outcomes)
flashBetManager.updateFlashBetPublisher?.send(activeFlashBet)

// Deactivate the market
var deactivatedFlashBet = currentFlashBet
deactivatedFlashBet.market = Market(id: "1", name: "Match Winner", status: .deactivated, outcomes: outcomes)
flashBetManager.updateFlashBetPublisher?.send(deactivatedFlashBet)
```

***

## Bet Insights

Bet Insights provides AI-powered betting suggestions based on Sportradar's real-time data feeds. The feature displays the most relevant markets and outcomes for the current match.

### How It Works

1. **Match Configuration** - Set a `matchId` via the moderation panel or API
2. **Automatic Fetching** - SDK fetches insights based on match state:
   - **Pre-match**: Longer refresh intervals (far future matches)
   - **Live**: \~10 second refresh intervals
   - **Post-match**: Fetching stops, insights cleared
3. **Outcome Mapping** - Your app maps SDK outcomes to your betting data
4. **Display** - SDK's algorithm selects and displays the most relevant insights

> **Info**
>
> **Important Notes**
>
> - The `onNewInsightsReceived` callback returns **all** available markets and outcomes from the feed
> - The SDK's algorithm selects which insights to display
> - Not all provided outcomes will necessarily appear on screen
> - Market and outcome IDs must match SDK identifiers for proper mapping
> - Set `useClientData = true` in `OutcomesPayload` to use your custom market/outcome names

### InsightsManager API

```swift
public class InsightsManager: ObservableObject {
    // Callback triggered when new insights are received
    public var onNewInsightsReceived: (([OutcomePayloadRequest]) -> Void)?
    
    // Callback triggered when user clicks an insight outcome
    public var onInsightOutcomeSelected: ((_ marketId: String, _ outcomeId: String) -> Void)?
    
    // Publisher for sending updated insights to display
    public var onOutcomesGenerated: PassthroughSubject<OutcomesPayload, Never>?
    
    public init()
    public func clear()
}
```

### Client Data Vs Feed Data

The `useClientData` flag in `OutcomesPayload` determines naming sources:

- **`useClientData = true`** - Use your custom market and outcome names
- **`useClientData = false`** - Use names from Sportradar's feed

Example:

- Feed data: Market "1x2", Outcome "PSG"
- Your data: Market "Match Winner", Outcome "Paris Saint Germain"

***

### Data Structures

#### OutcomePayloadRequest

The SDK provides this data for you to map to your betting system:

```swift
/**
 * Request structure from the SDK insights feed
 */
public struct OutcomePayloadRequest: Codable {
    public var eventId: String
    public var marketId: String
    public var outcomeId: String
    public var specifier: SpecifierRequest?
    
    public init(
        eventId: String,
        marketId: String,
        outcomeId: String,
        specifier: SpecifierRequest?
    )
}

public struct SpecifierRequest: Codable {
    public var name: String   // e.g., "Total Goals"
    public var value: String  // e.g., "Over 2.5"
    
    public init(name: String, value: String)
}
```

#### OutcomesPayload

Your app builds this structure to provide insights data back to the SDK:

```swift
/**
 * Payload you provide to the SDK
 */
public struct OutcomesPayload: Codable {
    public var outcomes: [ClientInsightData] = []
    public var useClientData: Bool = false
    
    public init(
        outcomes: [ClientInsightData] = [],
        useClientData: Bool = false
    )
}

public struct ClientInsightData: Codable {
    public var event: InsightEvent
    public var market: InsightMarket
    public var outcome: InsightOutcome?
    
    public init(
        event: InsightEvent,
        market: InsightMarket,
        outcome: InsightOutcome? = nil
    )
}
```

***

```swift
public struct InsightEvent: Codable {
    public var id: String
    public var teams: [InsightTeam]
    public var isLive: Bool
    public var sport: InsightSport
}

public struct InsightTeam: Codable {
    public var id: String?
    public var name: String
}

public struct InsightSport: Codable {
    public var id: String?
    public var name: String
}

public struct InsightMarket: Codable {
    public var id: String
    public var name: String
    public var status: InsightStatus
    public var specifier: InsightSpecifier?
}

public struct InsightSpecifier: Codable {
    public var value: String?
}
```

```swift
public struct InsightOutcome: Codable {
    public var id: String
    public var name: String
    public var status: InsightStatus
    public var competitor: String?
    public var oddsDecimal: Double
    public var odds: String
    public var isSelected: Bool
}

public enum InsightStatus: Codable {
    case active       // Available for betting
    case deactivated  // Temporarily deactivated
    case suspended    // Temporarily suspended
}
```

***

### Implementation

***Bet Insights Implementation:***

```swift
import SwiftUI
import VirtualStadiumSDK
import Combine

struct ChatWithInsights: View {
    let jwt: String
    let channelId: String
    
    @StateObject private var insightsManager = InsightsManager()
    @State private var cancellables = Set<AnyCancellable>()
    
    var body: some View {
        ChatView(
            userJWT: jwt,
            channelId: channelId,
            insightsManager: insightsManager,
            supportedLanguage: .english
        )
        .onAppear {
            setupInsights()
        }
    }
    
    private func setupInsights() {
        insightsManager.onNewInsightsReceived = { outcomeRequests in
            Task {
                /**
                 * TODO(developer): Replace with your actual market data fetching logic
                 */
                let clientData = try await mapInsightsData(outcomeRequests)
                
                let payload = OutcomesPayload(
                    outcomes: clientData,
                    useClientData: true
                )
                
                insightsManager.onOutcomesGenerated?.send(payload)
            }
        }
        
        insightsManager.onInsightOutcomeSelected = { marketId, outcomeId in
            addToBetSlip(marketId: marketId, outcomeId: outcomeId)
            print("Insight selected - Market: \(marketId), Outcome: \(outcomeId)")
        }
    }
    
    private func mapInsightsData(_ requests: [OutcomePayloadRequest]) async throws -> [ClientInsightData] {
        /**
         * TODO(developer): Replace with your actual API call
         */
        var clientData: [ClientInsightData] = []
        
        for request in requests {
            let marketData = try await apiClient.getMarket(
                eventId: request.eventId,
                marketId: request.marketId,
                outcomeId: request.outcomeId
            )
            
            let insight = ClientInsightData(
                event: InsightEvent(
                    id: request.eventId,
                    teams: [
                        InsightTeam(id: "team1", name: marketData.homeTeam),
                        InsightTeam(id: "team2", name: marketData.awayTeam)
                    ],
                    isLive: marketData.isLive,
                    sport: InsightSport(id: "1", name: "Soccer")
                ),
                market: InsightMarket(
                    id: request.marketId,
                    name: marketData.marketName,
                    status: .active,
                    specifier: request.specifier.map { spec in
                        InsightSpecifier(value: spec.value)
                    }
                ),
                outcome: InsightOutcome(
                    id: request.outcomeId,
                    name: marketData.outcomeName,
                    status: .active,
                    competitor: nil,
                    oddsDecimal: marketData.odds,
                    odds: String(format: "%.2f", marketData.odds),
                    isSelected: false
                )
            )
            
            clientData.append(insight)
        }
        
        return clientData
    }
    
    private func addToBetSlip(marketId: String, outcomeId: String) {
        /**
         * TODO(developer): Implement your bet slip logic
         */
        print("Adding to bet slip - Market: \(marketId), Outcome: \(outcomeId)")
    }
}
```

1. **Step 1**

   #### Imports

   Import `SwiftUI`, `VirtualStadiumSDK`, and `Combine` (needed for the `AnyCancellable` state).

2. **Step 2**

   #### View Properties

   Declare the `jwt` and `channelId` inputs. Initialize `InsightsManager` as a `@StateObject` and hold a `cancellables` set for any Combine subscriptions.

3. **Step 3**

   #### ChatView with InsightsManager

   Pass `insightsManager` to `ChatView`. Call `setupInsights()` in `.onAppear` to register callbacks after the view loads.

4. **Step 4**

   #### onNewInsightsReceived

   Called whenever the SDK fetches new insights. Map the incoming `[OutcomePayloadRequest]` to your own `[ClientInsightData]`, wrap them in an `OutcomesPayload` with `useClientData: true`, and send it via `onOutcomesGenerated` so the SDK can display them.

5. **Step 5**

   #### onInsightOutcomeSelected

   Called when a user taps an insight outcome. Forward the `marketId` and `outcomeId` to your bet slip logic.

6. **Step 6**

   #### mapInsightsData

   Fetches market data from your backend for each `OutcomePayloadRequest` and maps it to `ClientInsightData`. Build `InsightEvent`, `InsightMarket`, and `InsightOutcome` using your own data — these names and odds will be shown in the UI when `useClientData` is `true`.

7. **Step 7**

   #### addToBetSlip

   Adds the selected insight outcome to the user's bet slip. Replace with your sportsbook integration logic.

***

### Testing With Mock Data

Enable mock insights for testing without a real match. This is useful during development to test the UI and interaction flows.

```swift
let chatSettings = ChatSettings(
    generalSettings: GeneralSettings(
        useTestInsights: true
    )
)

ChatView(
    userJWT: jwt,
    channelId: channelId,
    insightsManager: insightsManager,
    supportedLanguage: .english,
    chatSettings: chatSettings
)
```

Use a mock data provider to generate test insights:
***MockInsightsProvider.swift:***

```swift
struct MockInsightsProvider {
    static func getMockInsights(
        from requests: [OutcomePayloadRequest],
        useRandomOdds: Bool = false
    ) -> OutcomesPayload {
        let clientData = requests.enumerated().map { index, request in
            let baseOdds = useRandomOdds ? Double.random(in: 1.4...3.0) : 2.5
            
            return ClientInsightData(
                event: InsightEvent(
                    id: request.eventId,
                    teams: [
                        InsightTeam(id: nil, name: "Team A"),
                        InsightTeam(id: nil, name: "Team B")
                    ],
                    isLive: true,
                    sport: InsightSport(id: "1", name: "Soccer")
                ),
                market: InsightMarket(
                    id: request.marketId,
                    name: "Market \(index + 1)",
                    status: .active,
                    specifier: request.specifier.map { spec in
                        InsightSpecifier(value: spec.value)
                    }
                ),
                outcome: InsightOutcome(
                    id: request.outcomeId,
                    name: "Outcome \(index + 1)",
                    status: .active,
                    competitor: nil,
                    oddsDecimal: baseOdds + Double(index),
                    odds: String(format: "%.2f", baseOdds + Double(index)),
                    isSelected: false
                )
            )
        }
        
        return OutcomesPayload(
            outcomes: clientData,
            useClientData: true
        )
    }
}

// Usage
insightsManager.onNewInsightsReceived = { requests in
    let mockPayload = MockInsightsProvider.getMockInsights(
        from: requests,
        useRandomOdds: true
    )
    insightsManager.onOutcomesGenerated?.send(mockPayload)
}
```

***

## Bet Sharing

Enable users to share their bet slips and copy bets from other community members. This creates a social betting experience where users can learn from and engage with each other's betting strategies.

### Implementation

> **Tip**
>
> **Hiding Share Button**
> If `onBetShareHandler` is `nil` in `ChatViewCallbacksVM`, the "Share Bet" button will be automatically hidden from the UI.

***Bet Sharing Example:***

```swift
let callbacksVM = ChatViewCallbacksVM(
    onBetShareHandler: { completion in
        /**
         * TODO(developer): Replace with your bet slip fetching logic
         */
        Task {
            let betSlips = await getBetSlipsFromDatabase()
            completion(betSlips)
        }
    },
    onCopyToBetslipHandler: { betPayload in
        // Add to user's bet slip
        addToBetSlip(betPayload)
        print("Bet copied to slip!")
    }
)

ChatView(
    userJWT: jwt,
    channelId: channelId,
    supportedLanguage: .english,
    callbacksVM: callbacksVM,
    chatSettings: ChatSettings()
)
```

***

### BetPayload Structure

```swift
public struct BetPayload {
    let id: String
    let betSlipId: String
    let betType: BetType
    let currency: String
    let combinedOdds: Odds
    let stake: Stake?
    let payout: Payout?
    let cashOut: CashOut?
    let bets: [Bet]
}

public enum BetType {
    case betBuilder
    case multiBet
    case sameGameMulti
    case single
    case none
}

public struct Odds {
    let decimalValue: Float
    let displayValue: String?
}
```

```swift
public struct Bet {
    let id: String
    let betType: BetType
    let event: BetEvent
    let markets: [BetMarket]
    let odds: Odds?
}

public struct BetEvent {
    let id: String
    let name: String?
    let teams: [Team]
}

public struct BetMarket {
    let id: String
    let name: String
    let outcomes: [Outcome]
}

public struct Outcome {
    let id: String
    let name: String
    let odds: Odds?
}
```

***

## Match Status

Control how match status affects theming for Flash Bets and Insights. The match status determines visual styling to indicate whether a match is live, pre-match, or if automatic detection is disabled.

### MatchStatusBehavior

```swift
public enum MatchStatusBehavior {
    case live       // Force live theming
    case automatic  // Automatic based on feed (default)
    case disabled   // Disable automatic status changes
}
```

### MatchStatusManager API

```swift
public class MatchStatusManager: ObservableObject {
    public var matchStatus: CurrentValueSubject<MatchStatusBehavior, Never>?
    
    public init()
    public func clear()
}
```

### Implementation

***Match Status Control:***

```swift
import SwiftUI
import VirtualStadiumSDK
import Combine

struct ChatWithMatchStatus: View {
    let jwt: String
    let channelId: String
    
    @StateObject private var matchStatusManager = MatchStatusManager()
    
    var body: some View {
        ChatView(
            userJWT: jwt,
            channelId: channelId,
            matchStatusManager: matchStatusManager,
            supportedLanguage: .english
        )
        .onAppear {
            matchStatusManager.matchStatus?.send(.live)
        }
    }
}

// Update match status dynamically
matchStatusManager.matchStatus?.send(.automatic)
matchStatusManager.matchStatus?.send(.disabled)
```

1. **Step 1**

   #### Imports

   Import `SwiftUI`, `VirtualStadiumSDK`, and `Combine`.

2. **Step 2**

   #### View Properties

   Declare `jwt` and `channelId` inputs and initialize `MatchStatusManager` as a `@StateObject`.

3. **Step 3**

   #### ChatView with MatchStatusManager

   Pass `matchStatusManager` to `ChatView`. On `.onAppear`, send the initial status — here `.live` forces live theming immediately when the view appears.

4. **Step 4**

   #### Dynamic Status Updates

   Send status updates at any time to respond to live match events. Use `.automatic` to let the SDK determine theming from the feed, or `.disabled` to stop automatic status changes entirely.

***

## Chat Settings

Customize the appearance and behavior of the Chat component through comprehensive settings options.

### ChatSettings Structure

```swift
public struct ChatSettings {
```

***Basic ChatSettings Usage:***

```swift
let chatSettings = ChatSettings(
    generalSettings: GeneralSettings(
        oddsType: .us,
        presentedInBottomSheet: false,
        flashBetTimeoutDuration: 60.0,
        useTestInsights: false
    ),
    themeSettings: ThemeSettings(
        mainColorPaletteTheme: MainColorPaletteTheme()
    )
)

ChatView(
    userJWT: jwt,
    channelId: channelId,
    supportedLanguage: .english,
    chatSettings: chatSettings
)
```

***

### GeneralSettings

Configure general behavior including odds format, presentation style, and feature flags.

```swift
public struct GeneralSettings {
    public var oddsType: OddsType
    public var presentedInBottomSheet: Bool
    public var flashBetTimeoutDuration: Double
    public var useTestInsights: Bool
    
    public init(
        oddsType: OddsType = .eu,
        presentedInBottomSheet: Bool = false,
        flashBetTimeoutDuration: Double = 60.0,
        useTestInsights: Bool = false
    )
}

public enum OddsType: String {
    case us = "us"  // American format (+150, -200)
    case uk = "uk"  // Fractional format (3/2, 1/5)
    case eu = "eu"  // Decimal format (2.50, 1.20)
}
```

***GeneralSettings Example:***

```swift
let generalSettings = GeneralSettings(
    oddsType: .us,                      // American odds format
    presentedInBottomSheet: true,        // Optimize for bottom sheet
    flashBetTimeoutDuration: 90.0,      // 90 second timeout
    useTestInsights: false               // Use real insights
)

let chatSettings = ChatSettings(
    generalSettings: generalSettings
)
```

***

### ThemeSettings

Control all color aspects of the UI including general colors, Flash Bet theming, and Insights theming. You can customize colors for both pre-match and live states.

```swift
public struct ThemeSettings {
    public var mainColorPaletteTheme: MainColorPaletteTheme
    public var textColorTheme: TextColorTheme
    public var chatViewTheme: ChatViewTheme
    public var reactionsTheme: ReactionsTheme
    public var errorAndInfoMessageTheme: ErrorAndInfoMessageTheme
    public var messageInputTheme: MessageInputTheme
    public var tabsAndNavigationTheme: TabsAndNavigationTheme
    public var betShareTheme: BetShareTheme
    public var chatMessagesTheme: ChatMessagesTheme
    public var replyAndReportMessageTheme: ReplyAndReportMessageTheme
    public var betSlipTheme: BetSlipTheme
    public var profileTheme: ProfileTheme
    public var lightInsightsTheme: LightInsightsTheme
    public var darkInsightsTheme: DarkInsightsTheme
    public var lightFlashBetTheme: LightFlashBetTheme
    public var darkFlashBetTheme: DarkFlashBetTheme
}
```

***Custom Theme Example:***

```swift
import SwiftUI

let customTheme = ThemeSettings(
    mainColorPaletteTheme: MainColorPaletteTheme(
        primaryColor: Color(hex: "1976D2"),
        secondaryColor: Color(hex: "FF6F00"),
        tertiaryColor: Color(hex: "4CAF50")
    ),
    chatViewTheme: ChatViewTheme(
        scrollToBottomBackgroundColor: Color(hex: "1976D2").opacity(0.15),
        loadingIndicatorColor: Color(hex: "1976D2")
    ),
    messageInputTheme: MessageInputTheme(
        sendMessageIconEnabledColor: Color(hex: "1976D2")
    ),
    lightInsightsTheme: LightInsightsTheme(
        seenCountBadgeBackground: Color(hex: "D32F2F"),
        closeIconColor: Color(hex: "1976D2"),
        pagerIndicatorSelected: Color(hex: "1976D2"),
        pagerIndicatorUnselected: Color(hex: "1976D2").opacity(0.2)
    ),
    lightFlashBetTheme: LightFlashBetTheme(
        flashBetCloseIconBackground: Color.white.opacity(0.2),
        flashBetExpandIconBackground: Color.white.opacity(0.2),
        flashBetOutcomeEnabledBackground: Color.white.opacity(0.2)
    )
)

let chatSettings = ChatSettings(
    themeSettings: customTheme
)
```

***

### FontSettings

Set custom fonts to match your application's branding and typography style.

```swift
public struct FontSettings {
    public let fontUltraLight: UIFont
    public let fontThin: UIFont
    public let fontLight: UIFont
    public let fontRegular: UIFont
    public let fontMedium: UIFont
    public let fontSemibold: UIFont
    public let fontBold: UIFont
    public let fontHeavy: UIFont
    public let fontBlack: UIFont
    public var inputFieldPlaceholderFont: UIFont
    
    public init(
        fontUltraLight: UIFont? = nil,
        fontThin: UIFont? = nil,
        fontLight: UIFont? = nil,
        fontRegular: UIFont? = nil,
        fontMedium: UIFont? = nil,
        fontSemibold: UIFont? = nil,
        fontBold: UIFont? = nil,
        fontHeavy: UIFont? = nil,
        fontBlack: UIFont? = nil,
        inputFieldPlaceholderFont: UIFont? = nil
    )
}
```

***Custom Font Example:***

```swift
guard let customFont = UIFont(name: "YourCustomFont-Regular", size: 16) else {
    fatalError("Failed to load custom font")
}

let fontSettings = FontSettings(
    fontRegular: customFont,
    fontMedium: UIFont(name: "YourCustomFont-Medium", size: 16),
    fontBold: UIFont(name: "YourCustomFont-Bold", size: 16),
    inputFieldPlaceholderFont: customFont
)

let chatSettings = ChatSettings(
    fontSettings: fontSettings
)
```

***

### IconSettings

Replace default icons with custom images to match your application's design system.

```swift
public struct IconSettings {
```

***Custom Icons Example:***

```swift
let iconSettings = IconSettings(
    chatIcons: ChatIconSettings(
        sendIcon: UIImage(named: "custom_send"),
        attachIcon: UIImage(named: "custom_attach"),
        replyIcon: UIImage(named: "custom_reply")
    ),
    eventIcons: EventIconSettings(
        goalIcon: UIImage(named: "custom_goal"),
        cardIcon: UIImage(named: "custom_card")
    ),
    sportIcons: SportIconSettings(
        footballIcon: UIImage(named: "custom_football"),
        basketballIcon: UIImage(named: "custom_basketball")
    )
)

let chatSettings = ChatSettings(
    iconSettings: iconSettings
)
```

***

### TranslationSettings

Customize all text strings displayed in the SDK for complete localization control.

> **Info**
>
> For the full list of `TranslationSettings` properties and default English values, see [Translations](https://docs.sportradar.com/resources/virtual-stadium/docs/ios/translations.md#available-translation-keys).

***Custom Translations Example:***

```swift
let translationSettings = TranslationSettings(
    GeneralVip: "VIP",
    GeneralReply: "Responder",
    GeneralReport: "Reportar",
    GeneralSubmit: "Enviar",
    GeneralCancel: "Cancelar",
    MessageInputPlaceholder: "Escreva uma mensagem",
    BetViewStake: "Aposta",
    BetViewReturn: "Retorno",
    ChatEmptyTitle: "Seja o primeiro!",
    ChatEmptyDescription: "O que você está pensando?"
)

let chatSettings = ChatSettings(
    translationSettings: translationSettings
)
```

***

## Complete Example

Here's a comprehensive example with all features enabled:

***ComprehensiveChatExample.swift:***

```swift
import SwiftUI
import VirtualStadiumSDK
import Combine

struct ComprehensiveChatView: View {
    let jwt: String
    let channelId: String
    
    @StateObject private var flashBetManager = FlashBetManager()
    @StateObject private var insightsManager = InsightsManager()
    @StateObject private var matchStatusManager = MatchStatusManager()
    
    @State private var showError = false
    @State private var errorMessage = ""
    @State private var showProfileSheet = false
    @State private var selectedUserId: String?
    
    var body: some View {
        NavigationView {
            ChatView(
                userJWT: jwt,
                channelId: channelId,
                matchStatusManager: matchStatusManager,
                flashBetManager: flashBetManager,
                insightsManager: insightsManager,
                supportedLanguage: .english,
                callbacksVM: makeCallbacksVM(),
                analyticsProvider: createAnalyticsProvider(),
                onError: { error in
                    errorMessage = error.localizedDescription
                    showError = true
                },
                chatSettings: createCustomSettings()
            )
            .navigationTitle("Chat")
        }
        .sheet(isPresented: $showProfileSheet) {
            if let userId = selectedUserId {
                ProfileView(userId: userId)
            }
        }
        .alert("Error", isPresented: $showError) {
            Button("OK", role: .cancel) { }
        } message: {
            Text(errorMessage)
        }
        .onAppear {
            setupManagers()
        }
    }

    private func makeCallbacksVM() -> ChatViewCallbacksVM {
        ChatViewCallbacksVM(
            onBetShareHandler: { completion in
                Task {
                    let betSlips = await getBetSlips()
                    completion(betSlips)
                }
            },
            onCopyToBetslipHandler: { betPayload in
                copyBetToSlip(betPayload)
            },
            onReachSupportTeamHandler: { reason in
                openSupport(reason: reason)
            },
            onOpenProfileHandler: { userId in
                selectedUserId = userId
                showProfileSheet = true
            },
            onTagSelectedHandler: { tag in
                handleTagSelection(tag)
            }
        )
    }
    
    private func setupManagers() {
        // Flash Bet setup
        flashBetManager.onFlashBetReceived = { flashBet in
            Task {
                let market = try? await fetchFlashBetMarket(eventId: flashBet.event.srEventId ?? "")
                var updatedFlashBet = flashBet
                updatedFlashBet.market = market
                flashBetManager.updateFlashBetPublisher?.send(updatedFlashBet)
            }
        }
        
        flashBetManager.onFlashBetOutcomeSelected = { outcome in
            placeBet(outcome: outcome)
        }
        
        // Insights setup
        insightsManager.onNewInsightsReceived = { requests in
            Task {
                let clientData = try? await mapInsightsData(requests)
                let payload = OutcomesPayload(
                    outcomes: clientData ?? [],
                    useClientData: true
                )
                insightsManager.onOutcomesGenerated?.send(payload)
            }
        }
        
        insightsManager.onInsightOutcomeSelected = { marketId, outcomeId in
            addToBetSlip(marketId: marketId, outcomeId: outcomeId)
        }
        
        // Match status setup
        matchStatusManager.matchStatus?.send(.automatic)
    }
    
    private func createAnalyticsProvider() -> AnalyticsProvider {
        return AnalyticsProvider(
            onEventReceived: { eventType in
                print("Analytics event: \(eventType)")
            },
            onBetEventReceived: { eventType, betPayload, betBuilderId in
                print("Bet analytics event: \(eventType)")
                print("Bet ID: \(betPayload.id), Type: \(betPayload.betType)")
            },
            onReactionEventReceived: { eventType, reaction in
                print("Reaction analytics event: \(eventType)")
                print("Reaction: \(reaction)")
            },
            onMessageSent: { eventType, messageType in
                print("Message sent analytics event: \(eventType)")
                print("Message type: \(messageType.rawValue)")
            }
        )
    }
    
    private func createCustomSettings() -> ChatSettings {
        let customTheme = ThemeSettings(
            mainColorPaletteTheme: MainColorPaletteTheme(
                primaryColor: Color.blue,
                secondaryColor: Color.orange
            )
        )
        
        let customFont = FontSettings(
            fontRegular: UIFont(name: "CustomFont-Regular", size: 16)
        )
        
        return ChatSettings(
            generalSettings: GeneralSettings(
                oddsType: .us,
                presentedInBottomSheet: false,
                flashBetTimeoutDuration: 60.0,
                useTestInsights: false
            ),
            themeSettings: customTheme,
            fontSettings: customFont
        )
    }
    
    private func getBetSlips() async -> [BetPayload] {
        /**
         * TODO(developer): Fetch bet slips from your backend
         */
        return []
    }
    
    private func copyBetToSlip(_ bet: BetPayload) {
        /**
         * TODO(developer): Add bet to user's bet slip
         */
        print("Copying bet to slip: \(bet.id)")
    }
    
    private func handleTagSelection(_ tag: Tag) {
        /**
         * TODO(developer): Handle tag selection
         */
        print("Tag selected: \(tag.channelName)")
    }
    
    private func openSupport(reason: InfractionReason?) {
        /**
         * TODO(developer): Open support interface
         */
        print("Opening support. Reason: \(reason?.description ?? "None")")
    }
    
    private func fetchFlashBetMarket(eventId: String) async throws -> Market {
        /**
         * TODO(developer): Fetch flash bet market from your backend
         */
        return Market(
            id: "market_123",
            name: "Next Goal Scorer",
            status: .active,
            outcomes: [
                EventOutcome(id: "1", name: "Player A", odd: "2.50"),
                EventOutcome(id: "2", name: "Player B", odd: "3.20")
            ]
        )
    }
    
    private func placeBet(outcome: EventOutcome) {
        /**
         * TODO(developer): Place bet on selected outcome
         */
        print("Placing bet on outcome: \(outcome.name)")
    }
    
    private func mapInsightsData(_ requests: [OutcomePayloadRequest]) async throws -> [ClientInsightData] {
        /**
         * TODO(developer): Map SDK insights to your betting data
         */
        var clientData: [ClientInsightData] = []
        
        for request in requests {
            let insight = ClientInsightData(
                event: InsightEvent(
                    id: request.eventId,
                    teams: [
                        InsightTeam(id: "team1", name: "Team A"),
                        InsightTeam(id: "team2", name: "Team B")
                    ],
                    isLive: true,
                    sport: InsightSport(id: "1", name: "Soccer")
                ),
                market: InsightMarket(
                    id: request.marketId,
                    name: "Match Winner",
                    status: .active,
                    specifier: request.specifier.map { InsightSpecifier(value: $0.value) }
                ),
                outcome: InsightOutcome(
                    id: request.outcomeId,
                    name: "Team A",
                    status: .active,
                    competitor: nil,
                    oddsDecimal: 2.5,
                    odds: "2.50",
                    isSelected: false
                )
            )
            
            clientData.append(insight)
        }
        
        return clientData
    }
    
    private func addToBetSlip(marketId: String, outcomeId: String) {
        /**
         * TODO(developer): Add insight outcome to bet slip
         */
        print("Adding to bet slip - Market: \(marketId), Outcome: \(outcomeId)")
    }
}

struct ProfileView: View {
    let userId: String
    
    var body: some View {
        NavigationView {
            VStack {
                Text("Profile")
                    .font(.largeTitle)
                Text("User ID: \(userId)")
                    .foregroundColor(.secondary)
            }
            .navigationTitle("User Profile")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}
```

1. **Step 1**

   #### Imports

   Import `SwiftUI`, `VirtualStadiumSDK`, and `Combine`.

2. **Step 2**

   #### View Properties

   Declare `jwt` and `channelId` inputs. Initialize all three managers — `FlashBetManager`, `InsightsManager`, and `MatchStatusManager` — as `@StateObject`s. Add state properties for error handling and profile sheet presentation.

3. **Step 3**

   #### ChatView — All Parameters

   Pass all managers, `callbacksVM`, `analyticsProvider`, `onError`, and `chatSettings` to `ChatView`. The `.sheet` modifier presents a profile view when a user profile is opened, and `.alert` displays any SDK errors. Call `setupManagers()` on `.onAppear`.

4. **Step 4**

   #### makeCallbacksVM

   Build the `ChatViewCallbacksVM` with all five callbacks: bet sharing, copy to bet slip, support contact, profile opening, and tag selection. Each delegates to a private method.

5. **Step 5**

   #### setupManagers

   Wire up all three managers in one place. For Flash Bet: fetch market data on receipt and handle outcome selection. For Insights: map incoming requests to your data and send back an `OutcomesPayload`. For Match Status: send `.automatic` to let the SDK determine theming from the feed.

6. **Step 6**

   #### createAnalyticsProvider

   Build an `AnalyticsProvider` with four event callbacks: general events, bet events (with payload and builder ID), reaction events, and message sent events. Use these to forward analytics to your own tracking system.

7. **Step 7**

   #### createCustomSettings

   Build `ChatSettings` with custom theme colors, a custom font, and general settings such as US odds format and a 60-second flash bet timeout.

8. **Step 8**

   #### Callback Implementations

   Stub implementations for `getBetSlips`, `copyBetToSlip`, `handleTagSelection`, `openSupport`, `fetchFlashBetMarket`, `placeBet`, `mapInsightsData`, and `addToBetSlip`. Replace each `TODO` with your actual backend and sportsbook integration logic.

9. **Step 9**

   #### ProfileView

   A minimal profile screen that displays the user ID. Presented as a sheet when `onOpenProfileHandler` is triggered. Replace with your own full profile UI.
