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

# Implementation Guide

This guide covers techniques for implementing the Chatmode embed using the standard **Bubble Code snippet** across different platforms and frameworks.

## Basic Implementation Recap

The standard method involves adding the script tag, copied from your Environment settings, to your website HTML.

1. Navigate to your `EMBED` Environment settings in Chatmode.
2. Find the **Implementation** / **Share** section.
3. Copy the **"Bubble Code"** snippet.
4. Paste the snippet into your HTML, usually before the closing `</body>` tag.

```html theme={"system"}
<!-- Example Snippet Structure - Copy the exact code from Chatmode UI! -->
<script type="module">
  import Chatmode from "https://cdn.jsdelivr.net/npm/@chatmode/embed/+esm";

  // Store the return value if you need programmatic control
  const chat = Chatmode.initBubble({
    // Required - Copied from UI
    environmentId: "YOUR_ENVIRONMENT_ID",

    // Optional - Copied from UI if set
    // iconKey: "YOUR_ICON_KEY",
    // updatedAt: TIMESTAMP,

    // Optional - Can be added/modified manually
    theme: "automatic",
  });

  // Example: Open chat via custom button
  // document.getElementById('my-help-button')?.addEventListener('click', () => chat.open());
</script>
```

This script adds the floating chat bubble to your page.

## Platform-Specific Implementations

Here's how you might add the copied script snippet in common setups:

### WordPress

#### Using a Plugin (Recommended)

1. Install and activate a plugin that allows adding code snippets to headers/footers (e.g., "WPCode", "Header Footer Code Manager", "Insert Headers and Footers").
2. Go to the plugin's settings page.
3. Create a new snippet.
4. **Paste the copied Chatmode Bubble Code snippet** into the code area.
5. Configure the snippet location to be in the **Footer**.
6. Ensure the snippet is active and save.

#### Theme File Integration (Advanced)

If using a child theme, you could edit its `footer.php` file and paste the script snippet directly before the `<?php wp_footer(); ?>` call or the closing `</body>` tag.

### React Applications

Use a `useEffect` hook in a layout component or the main App component to append the script dynamically only on the client-side. Ensure you handle cleanup.

### React / Next.js Applications (Recommended)

For modern JavaScript frameworks like React or Next.js, the recommended approach is to dynamically import the `@chatmode/embed` package within a client-side component. This ensures the embed code is loaded only when needed and integrates well with the framework's lifecycle and build process.

**Steps:**

1. **Install the package:**
   ```bash theme={"system"}
   npm install @chatmode/embed
   # or
   yarn add @chatmode/embed
   # or
   pnpm add @chatmode/embed
   ```
2. **Create a Client Component:** Create a component that will handle loading the embed. Ensure it's marked as a client component (e.g., using `"use client";` in Next.js App Router).
3. **Use `useEffect` for Initialization:** Inside the component, use a `useEffect` hook to dynamically import and initialize the bubble. Also, implement a cleanup function to remove the embed when the component unmounts.

```jsx theme={"system"}
// Example Client Component (e.g., components/ChatEmbedLoader.tsx)
"use client";

import { useEffect } from "react";
import { useTheme } from "next-themes"; // Example using next-themes

import type { BubbleControls } from "@chatmode/embed";

export function ChatEmbedLoader() {
  const { resolvedTheme } = useTheme(); // Use your theme detection logic

  useEffect(() => {
    let chatmodeBubble: BubbleControls | null = null;

    const loadEmbed = async () => {
      try {
        // Dynamically import the embed package
        const { default: Chatmode } = await import("@chatmode/embed");

        // Initialize using your Environment ID from the Chatmode UI
        // Pass the theme based on your application's logic
        chatmodeBubble = Chatmode.initBubble({
          environmentId: "YOUR_ENVIRONMENT_ID_FROM_UI", // <-- Replace this!
          theme: resolvedTheme === 'dark' ? 'dark' : 'light',
          // iconKey and updatedAt might be needed if using a custom icon
          // iconKey: "YOUR_ICON_KEY_FROM_UI",
          // updatedAt: YOUR_TIMESTAMP_FROM_UI,
        });
      } catch (error) {
        console.error("Failed to load Chatmode embed:", error);
        // Optionally, report error to a tracking service
      }
    };

    // Load the embed when the component mounts
    loadEmbed();

    // Cleanup function: Remove the embed when the component unmounts
    return () => {
      if (chatmodeBubble) {
        chatmodeBubble.remove();
        chatmodeBubble = null;
      }
    };
    // Re-run the effect if the theme changes
  }, [resolvedTheme]);

  return null; // This component doesn't render anything itself
}

// Then, import and use <ChatEmbedLoader /> in your root layout or main App component.
```

<Note>
  Replace `"YOUR_ENVIRONMENT_ID_FROM_UI"` with the actual Environment ID copied
  from your Chatmode Environment settings. Add `iconKey` and `updatedAt` if you
  are using a custom icon uploaded via the UI.
</Note>

## Advanced Considerations

### Conditional Loading

To load the chat bubble only under certain conditions, conditionally execute the JavaScript code that appends the script tag. In frameworks like React/Vue/Angular, wrap the script-appending logic within your component's conditional rendering logic.

### Performance Optimization

* **Dynamic Import (Advanced):** Instead of pasting the script content directly, you could dynamically import the `@chatmode/embed` module only when needed (e.g., after user interaction or page load completion), though this requires a more complex setup.
* **Script Location:** Placing the script tag just before `</body>` is generally good practice.

### Interaction with Parent Page

Direct interaction (calling functions like `identify`, `setContext`) is **not** supported by the standard `Chatmode.initBubble` method.

However, you **can** programmatically control the chat modal's state (open, close, toggle) using the object returned by `Chatmode.initBubble`. See the [Customization Guide](/en/embeds/customization#programmatic-control) for details.

If you need to hide the bubble itself based on page logic, you might need to resort to conditional loading (not adding the script) or CSS overrides (`display: none !important;`) targeting the bubble elements (not recommended).

## Implementation Checklist

* [ ] **Copied Bubble Code snippet** from Chatmode Environment settings.
* [ ] Snippet pasted into relevant HTML page(s) or loaded via framework component logic.
* [ ] Bubble appears correctly on desktop and mobile devices.
* [ ] Chat functionality tested by clicking the bubble and interacting.

## Troubleshooting

* **Bubble Not Appearing**: Verify the script snippet was copied correctly and completely. Check for JavaScript errors in the browser console. Ensure the Environment ID and Org ID in the snippet are correct.
* **Styling Issues**: Check for general CSS conflicts on your page. Overriding the bubble's internal styles directly is not recommended.
* **Z-index Problems**: If the bubble is hidden behind other elements, try increasing the z-index of a parent container on your page.
* **Multiple Bubbles**: Ensure the script is only loaded/initialized once per page load, especially in Single Page Applications.

## Next Steps

* Test thoroughly across different browsers and devices.
* Adjust Environment settings in Chatmode for chat interface configuration (Display Name, Picture, Colors, Initial Message).
