> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mutalabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Analytics Integration

> Learn how to integrate analytics with your Muta placements

Muta provides a flexible event system that works with any analytics provider (Mixpanel, AppsFlyer, Amplitude, Firebase, etc.). Events are emitted during key user interactions, allowing you to track and analyze your placement performance.

## Tracking All Events

Use the wildcard '\*' to listen to all events:

```tsx theme={null}
import { Muta } from '@mutalabs/react-native-muta'

// Example with Mixpanel
function MixpanelTracking() {
  useEffect(() => {
    const subscription = Muta.on('*', (event) => {
      mixpanel.track(event.type, {
        placement_id: event.placementId,
        flow_name: event.flowName,
        timestamp: event.timestamp,
        ...event, // includes all event-specific properties
      })
    })

    return () => subscription.remove()
  }, [])
}

// Example with AppsFlyer
function AppsFlyerTracking() {
  useEffect(() => {
    const subscription = Muta.on('*', (event) => {
      appsflyer.logEvent(event.type, {
        placement_id: event.placementId,
        flow_name: event.flowName,
        ...event,
      })
    })

    return () => subscription.remove()
  }, [])
}
```

## Available Events

### 1. Flow Started (`flow_started`)

Emitted when a placement flow begins displaying.

```tsx theme={null}
{
  type: 'flow_started',
  timestamp: number,      // Unix timestamp in ms
  placementId: string,    // ID of the placement
  flowName?: string,      // Name of the flow (if configured)
  totalScreens: number    // Total number of screens in flow
}
```

### 2. Screen Viewed (`screen_viewed`)

Emitted when a user views a new screen in the flow.

```tsx theme={null}
{
  type: 'screen_viewed',
  timestamp: number,
  placementId: string,
  flowName?: string,
  screenIndex: number,    // Zero-based index of current screen
  totalScreens: number,   // Total number of screens in flow
  screenName?: string     // Name of the screen (if configured)
}
```

### 3. Flow Completed (`flow_completed`)

Emitted when a user successfully finishes the flow.

```tsx theme={null}
{
  type: 'flow_completed',
  timestamp: number,      // Unix timestamp in ms
  placementId: string,    // ID of the placement
  flowName?: string,      // Name of the flow (if configured)
  screenIndex: number,    // Index of final screen
  totalScreens: number,   // Total screens in flow
  screenName?: string,    // Name of final screen (if configured)
  eventData?: {           // Optional: Contains collected variables
    variables: Record<string, any>  // Variable IDs mapped to their values
  }
}
```

#### Variable Structure

When a flow completes, `eventData.variables` contains an object where:

* **Key**: Variable ID (e.g., `var_1758310510757_as20wkeo4`)
* **Value**: Object containing:
  * `id` (string): Unique variable identifier
  * `name` (string): Human-readable variable name from the Muta editor
  * `type` (string): Variable type (e.g., "text")
  * `value` (any): The collected value
  * `defaultValue` (any): The default value

**Example:**

```tsx theme={null}
Muta.on('flow_completed', (event) => {
  if (event.eventData?.variables) {
    Object.entries(event.eventData.variables).forEach(([varId, varData]) => {
      console.log(`Variable '${varData.name}': ${varData.value}`)
    })
  }
})
```

**Output:**

```
Variable 'MultipleChoice1': Family
Variable 'MultipleChoice2': Fluent
```

### 4. Flow Abandoned (`flow_abandoned`)

Emitted when a user exits the flow before completion.

```tsx theme={null}
{
  type: 'flow_abandoned',
  timestamp: number,
  placementId: string,
  flowName?: string,
  screenIndex: number,    // Index of last viewed screen
  totalScreens: number,   // Total screens in flow
  lastScreenIndex: number, // Index of last viewed screen
  screenName?: string     // Name of last viewed screen
}
```

### 5. Custom Events

Emitted when users trigger actions configured with "Emit Event" behavior in the Muta web editor.

```tsx theme={null}
{
  type: string,         // Your custom event name (e.g., 'signup_clicked', 'plan_selected')
  timestamp: number,    // Unix timestamp in ms
  placementId: string,  // ID of the placement
  flowName?: string,    // Name of the flow (if configured)
  screenIndex?: number, // Current screen index
  eventData?: any       // Custom data configured in the editor
}
```

#### Setting Up Custom Events

1. In the Muta web editor, add an "Emit Event" behavior to any element
2. Give your event a unique name (e.g., `signup_started`, `premium_selected`)
3. Optionally add custom data to pass along with the event

#### Listening for Custom Events

```tsx theme={null}
// Listen for specific custom events
Muta.on('signup_started', (event) => {
  console.log('User started signup', event.eventData)
  navigateToSignup()
})

Muta.on('plan_selected', (event) => {
  const { planType, price } = event.eventData
  trackPlanSelection(planType, price)
})
```

## Integration Examples

### Mixpanel Example

```tsx theme={null}
import { Muta } from '@mutalabs/react-native-muta'
import mixpanel from 'mixpanel-react-native'

function setupAnalytics() {
  // Track standard events
  Muta.on('flow_completed', (event) => {
    const properties = {
      flow_name: event.flowName,
      total_screens: event.totalScreens,
    }

    // Include collected variables if present
    if (event.eventData?.variables) {
      properties.variables = event.eventData.variables
    }

    mixpanel.track('Onboarding Complete', properties)
  })

  // Track custom events
  Muta.on('form_submitted', (event) => {
    mixpanel.track('Form Submitted', {
      flow_name: event.flowName,
      form_data: event.eventData,
    })
  })

  Muta.on('flow_abandoned', (event) => {
    mixpanel.track('Onboarding Abandoned', {
      flow_name: event.flowName,
      last_screen_index: event.lastScreenIndex,
      total_screens: event.totalScreens,
    })
  })
}
```

### AppsFlyer Example

```tsx theme={null}
import { Muta } from '@mutalabs/react-native-muta'
import appsFlyer from 'react-native-appsflyer'

function setupAnalytics() {
  Muta.on('*', (event) => {
    const eventName = `onboarding_${event.type}`
    appsFlyer.logEvent(eventName, {
      placement_id: event.placementId,
      flow_name: event.flowName,
      timestamp: new Date(event.timestamp).toISOString(),
      ...event,
    })
  })
}
```

## Best Practices

1. **Event Naming**: Use consistent event naming conventions across your analytics platform.

2. **Data Enrichment**: Add additional context to events when needed (e.g., user ID, app version).

3. **Error Handling**: Implement proper error handling for analytics tracking.

4. **Performance**: Consider batching events for better performance, especially for high-frequency events.

5. **Privacy**: Ensure you're not tracking sensitive information in your analytics events.
