# Conversations

Conversations provides an interactive chat widget that enables real-time communication between your application and users. It supports displaying messages, collecting feedback, and managing conversation state.

**Note**: The Conversations API is lazy-loaded and may not be immediately available after initialization.

## Capabilities

### Show Conversations Widget

Displays the conversations widget on the page.

```typescript { .api }
/**
 * Shows the conversations widget
 * The widget will be displayed as a floating chat interface
 */
function show(): void;
```

**Usage Examples:**

```typescript
// Show conversations widget
posthog.conversations.show();

// Show on button click
button.addEventListener('click', () => {
    posthog.conversations.show();
});

// Show after user action
function openSupport() {
    posthog.conversations.show();
    posthog.capture('support_opened');
}
```

### Hide Conversations Widget

Hides the conversations widget from the page.

```typescript { .api }
/**
 * Hides the conversations widget
 */
function hide(): void;
```

**Usage Examples:**

```typescript
// Hide conversations widget
posthog.conversations.hide();

// Hide on close button
closeButton.addEventListener('click', () => {
    posthog.conversations.hide();
});
```

### Reset Conversations State

Resets the conversations state, clearing any cached data.

```typescript { .api }
/**
 * Resets conversations state
 * Useful when user logs out or switches accounts
 */
function reset(): void;
```

**Usage Examples:**

```typescript
// Reset on logout
function logout() {
    posthog.conversations.reset();
    posthog.reset();
}

// Reset when switching accounts
function switchAccount(newAccountId) {
    posthog.conversations.reset();
    posthog.identify(newAccountId);
}
```

## Configuration

Conversations can be enabled or disabled during initialization:

```typescript
posthog.init('<your-project-api-key>', {
    disable_conversations: false // Enable conversations (default: false)
});
```

## Types

### ConversationsRemoteConfig

```typescript { .api }
/**
 * Remote configuration for conversations loaded from PostHog
 */
interface ConversationsRemoteConfig {
    /**
     * Whether conversations are enabled
     */
    enabled?: boolean;

    /**
     * Widget appearance configuration
     */
    appearance?: {
        primaryColor?: string;
        backgroundColor?: string;
        textColor?: string;
        position?: 'left' | 'right';
    };

    /**
     * Auto-open settings
     */
    autoOpen?: boolean;

    /**
     * Welcome message
     */
    welcomeMessage?: string;
}
```

### UserProvidedTraits

```typescript { .api }
/**
 * User traits that can be provided to conversations
 */
interface UserProvidedTraits {
    /**
     * User's name
     */
    name?: string;

    /**
     * User's email
     */
    email?: string;

    /**
     * Additional custom properties
     */
    [key: string]: any;
}
```

## Best Practices

### Integration with User Support

```typescript
// Show conversations for support
function ContactSupport() {
    return (
        <button onClick={() => {
            posthog.conversations.show();
            posthog.capture('support_widget_opened');
        }}>
            Contact Support
        </button>
    );
}
```

### Conditional Display

```typescript
// Show conversations only to authenticated users
if (user.isAuthenticated) {
    posthog.identify(user.id, {
        email: user.email,
        name: user.name
    });

    // Enable conversations for authenticated users
    if (user.needsHelp) {
        posthog.conversations.show();
    }
}
```

### State Management

```typescript
// Track conversation state
let conversationsOpen = false;

function toggleConversations() {
    if (conversationsOpen) {
        posthog.conversations.hide();
        conversationsOpen = false;
    } else {
        posthog.conversations.show();
        conversationsOpen = true;
    }
}
```

## Common Patterns

### Auto-open for New Users

```typescript
// Auto-open conversations for first-time users
posthog.onFeatureFlags(() => {
    const isNewUser = !posthog.get_property('has_opened_conversations');

    if (isNewUser) {
        setTimeout(() => {
            posthog.conversations.show();
            posthog.register({ has_opened_conversations: true });
        }, 3000); // Wait 3 seconds before showing
    }
});
```

### Context-Aware Conversations

```typescript
// Show conversations with context
function showHelpForFeature(featureName: string) {
    // Set context before showing conversations
    posthog.capture('help_requested', {
        feature: featureName,
        page: window.location.pathname
    });

    posthog.conversations.show();
}
```

### Integration with Chat Button

```typescript
// Add a floating chat button
function ChatButton() {
    const [isOpen, setIsOpen] = useState(false);

    const toggleChat = () => {
        if (isOpen) {
            posthog.conversations.hide();
        } else {
            posthog.conversations.show();
        }
        setIsOpen(!isOpen);
    };

    return (
        <button
            className="chat-button"
            onClick={toggleChat}
            aria-label="Open chat"
        >
            {isOpen ? 'Close' : 'Chat'}
        </button>
    );
}
```

### User Logout Handling

```typescript
// Properly clean up conversations on logout
function handleUserLogout() {
    // Hide widget
    posthog.conversations.hide();

    // Reset conversations state
    posthog.conversations.reset();

    // Reset PostHog state
    posthog.reset();

    // Clear user session
    clearUserSession();
}
```

## Notes

- The Conversations API is loaded asynchronously and may not be available immediately after PostHog initialization
- Conversations require network connectivity to function properly
- The widget appearance and behavior can be configured in your PostHog project settings
- Conversations are automatically integrated with user identification, so identify users before showing the widget for the best experience
