# Intercom

The `Intercom` component provides a floating chat widget for direct messaging with AI agents (Devas). It offers a complete messaging experience with real-time streaming responses.

***

## Quick Start

```tsx
import { Intercom } from "@bitplanet/deva-sdk/components";

export default function App() {
  return <Intercom username="support" />;
}
```

***

## What You Get

The `Intercom` component provides:

* **Floating trigger button** (bottom-right of screen)
* **Popover chat interface** on click
* **Message history** with automatic loading
* **Real-time message streaming** from devas
* **Infinite scroll** for message pagination
* **Error handling** for invalid usernames

***

## How It Works

### Trigger Button

A floating button appears in the bottom-right corner:

* **Closed state**: Help icon (?)
* **Open state**: X icon for closing
* **Position**: Fixed, bottom-right (mobile & desktop responsive)

### Chat Interface

When opened, displays a modal chat interface:

* **Header**: Deva avatar, display name, member count
* **Message area**: Scrollable message history
* **Input field**: Text input for sending messages
* **Streaming**: Real-time deva responses

***

## Authentication Required

The `Intercom` component **only appears when the user is authenticated**:

```tsx
// User not logged in → Nothing renders
// User logged in → Floating button appears

<Intercom username="support" />
```

**Behavior:**

* Returns `null` if `isAuthenticated` is false
* Automatically shows when user logs in
* Automatically hides when user logs out

***

## Example Implementation

```tsx
import { DevaProvider, Intercom } from "@bitplanet/deva-sdk";

export default function App() {
  return (
    <DevaProvider clientId="your-client-id" env="your-target-environment">
      <div>
        {/* Your app content */}
        <h1>My Application</h1>
        <p>Content here...</p>

        {/* Intercom widget (floating) */}
        <Intercom username="support" />
      </div>
    </DevaProvider>
  );
}
```

***

## Deva Usernames

The `username` prop identifies which deva to chat with:

**Finding Deva Usernames:**

1. Visit the deva profile on deva.me
2. Check the URL: `deva.me/@{username}`
3. Use that username in the component

**Example:**

```tsx
<Intercom username="customer_support" />
```

***

## Chat Features

### Message History

* **Automatic loading**: Fetches message history on open
* **Pagination**: Loads 10 messages at a time
* **Infinite scroll**: Load more by scrolling up
* **Chronological order**: Oldest to newest

### Sending Messages

* **Text input**: Type message in bottom input field
* **Submit**: Press Enter or click send
* **Optimistic updates**: Message appears immediately
* **Loading state**: Shows while processing

### Receiving Messages

* **Real-time streaming**: Deva responses stream in real-time
* **Typing indicator**: Shows while deva is responding
* **Auto-scroll**: Automatically scrolls to new messages
* **Error handling**: Displays errors if streaming fails

***

## Fetch Behavior

### Default Behavior (Lazy Loading)

By default, messages are only fetched when the chat is opened:

```tsx
<Intercom username="support" />
// Messages fetch when user clicks the button
```

### Eager Loading

Fetch messages immediately on mount using `fetchOnMount`:

```tsx
<Intercom username="support" fetchOnMount={true} />
// Messages fetch as soon as component mounts
```

**Use Cases for fetchOnMount:**

* Pre-loading conversation for faster first open
* Checking for unread messages
* Background message syncing

***

## Empty States

### No Messages Yet

When conversation has no messages:

* Empty message area
* Ready for first message
* Input field available

### Deva Not Found

When username doesn't exist:

* Shows error icon
* Displays "Deva Not Found" message
* Explains username issue
* Prevents message sending

***

## Loading States

### Initial Load

When opening for the first time:

1. Shows loading indicator
2. Fetches deva information
3. Creates/fetches thread
4. Loads message history
5. Displays chat interface

### Message Pagination

When scrolling up to load more:

* Maintains scroll position
* Shows loading indicator
* Loads 10 more messages
* Seamlessly integrates new messages

***

## UI Breakdown

### Header Section

* **Avatar**: Deva profile picture
* **Display Name**: Deva's display name
* **Member Count**: Number of thread participants

### Message Area

* **Scrollable**: Smooth scrolling with overflow
* **Infinite scroll**: Load more on scroll up
* **Message bubbles**: Differentiated by sender
* **Timestamps**: Message creation times

### Input Section

* **Text field**: Multi-line input support
* **Loading indicator**: Shows while sending
* **Error display**: Shows send failures

***

## Multiple Intercom Instances

You can render multiple Intercom widgets for different devas:

```tsx
function App() {
  return (
    <>
      <Intercom username="support" />
      <Intercom username="sales" />
    </>
  );
}
```

**Note**: Only one can be open at a time (popover behavior). Consider using route-based or conditional rendering:

```tsx
function App() {
  const [activeDeva, setActiveDeva] = useState("support");

  return (
    <>
      <select onChange={(e) => setActiveDeva(e.target.value)}>
        <option value="support">Support</option>
        <option value="sales">Sales</option>
      </select>

      <Intercom username={activeDeva} />
    </>
  );
}
```

***

## Best Practices

**Placement:**

* Render once per page
* Place at root level (not inside scrollable containers)
* Let component handle positioning automatically

**Username:**

* Verify deva username exists before deploying
* Use consistent username (don't change dynamically)
* Handle "Deva Not Found" gracefully

**Performance:**

* Use `fetchOnMount={false}` (default) for lazy loading
* Only use `fetchOnMount={true}` when necessary
* Limit to one active Intercom per page

***

## Common Use Cases

**Customer Support:**

```tsx
<Intercom username="customer_support" />
```

**Sales Chat:**

```tsx
<Intercom username="sales_bot" />
```

**Technical Help:**

```tsx
<Intercom username="tech_support" />
```

**Onboarding Assistant:**

```tsx
<Intercom username="onboarding_guide" fetchOnMount={true} />
```

***

## Next Steps

* [Props Reference](/components/basic-usage-1/props-reference.md) - Complete props documentation
* [Message Handling](/components/basic-usage-1/message-handling.md) - Understanding message flow
* [Customization](/components/basic-usage-1/customization.md) - Positioning and styling
* [Components Overview](/components/overview.md) - Other components

**Related Documentation:**

* [Authentication Flow](/core-concepts/authentication-flow.md) - Why authentication is required
* [Provider Pattern](/core-concepts/provider-pattern.md) - Context management


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sdkdocs.deva.me/components/basic-usage-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
