# @buzztrail-ai/engage

AI-powered video conversations for any website platform.

[![npm version](https://badge.fury.io/js/@buzztrail-ai%2Fengage.svg)](https://www.npmjs.com/package/@buzztrail-ai/engage)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Overview

`@buzztrail-ai/engage` is a lightweight (< 15KB gzipped) package that enables AI-powered video conversations on any website platform. Add an interactive AI presenter to your site in minutes - no complex setup required.

**⚠️ Account Required**: You need an active BuzzTrail account to use this package. [Sign up at buzztrail.ai](https://buzztrail.ai) to get your customer ID and configure your AI presenter.

## Features

- **Interactive AI Presenters**: Engage website visitors with lifelike AI video conversations
- **Works Everywhere**: Wix, Webflow, WordPress, Shopify, or any custom website
- **Simple Integration**: Add one script tag - that's it
- **Fast Loading**: Ultra-lightweight (< 15KB) - won't slow down your site
- **Mobile-Friendly**: Automatically adapts to desktop, tablet, and mobile screens
- **Customizable**: Match your brand with custom colors, text, and styling
- **Multi-Language Support**: Serve global audiences with built-in translations
- **Lead Capture**: Optional forms to collect visitor information
- **No Technical Skills**: Works without coding knowledge (perfect for Wix users)

## Getting Started

### Prerequisites

1. **BuzzTrail Account**: [Sign up at buzztrail.ai](https://buzztrail.ai)
2. **Customer ID**: You'll receive this after account setup
3. **AI Presenter**: Configure your presenter in the BuzzTrail dashboard

### Installation

#### NPM (for developers)

```bash
npm install @buzztrail-ai/engage
```

```bash
yarn add @buzztrail-ai/engage
```

```bash
pnpm add @buzztrail-ai/engage
```

#### CDN (for Wix, Webflow, no-code platforms)

```html
<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@latest/dist/buzztrail.min.js"></script>
```

Or use a specific version (recommended for production):

```html
<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@1.0.0/dist/buzztrail.min.js"></script>
```

**Fallback CDN (unpkg):**

```html
<script src="https://unpkg.com/@buzztrail-ai/engage@latest/dist/buzztrail.min.js"></script>
```

## Quick Start

### CDN Usage (Wix, Webflow, etc.)

The simplest way to use BuzzTrail is via the CDN with auto-initialization:

```html
<!-- 1. Add a container element to your page -->
<div id="buzztrail-container"></div>

<!-- 2. Add the BuzzTrail script with data attributes -->
<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@latest/dist/buzztrail.min.js"
        data-customer-id="your-customer-id"
        data-container-id="buzztrail-container">
</script>
```

That's it! The script will automatically initialize when the page loads.

### Manual Initialization (JavaScript)

For more control, you can manually initialize BuzzTrail:

```html
<div id="my-container"></div>

<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@latest/dist/buzztrail.min.js"></script>
<script>
  // Wait for BuzzTrail to load
  if (window.BuzzTrail) {
    BuzzTrail.createConversation('my-container', {
      customerId: 'your-customer-id',
      platform: 'wix',
      onStart: () => console.log('Conversation started'),
      onEnd: () => console.log('Conversation ended'),
      onError: (error) => console.error('Error:', error)
    });
  }
</script>
```

### NPM Usage (TypeScript/JavaScript)

```typescript
import { createConversation } from '@buzztrail-ai/engage';
import type { ConversationOptions } from '@buzztrail-ai/engage';

const options: ConversationOptions = {
  containerId: 'my-container',
  customerId: 'acme-corp',
  platform: 'custom',
  onStart: () => {
    console.log('Conversation started');
  },
  onEnd: () => {
    console.log('Conversation ended');
  },
  onError: (error) => {
    console.error('Error:', error);
  }
};

createConversation(options);
```

## Wix Integration Guide

Wix requires special handling due to iframe permission restrictions. Follow these steps:

### Step 1: Add a Container Element

1. Open Wix Editor for your site
2. Click "Add Elements" (+) → Select "Strip" or "Box"
3. Position and size the element where you want the video conversation
4. Right-click the element → "View Properties" → Note the **Element ID** (e.g., `comp-mfy88b7h`)

### Step 2: Add BuzzTrail via Custom Code

1. Open **Settings** → **Advanced** → **Custom Code**
2. Click **"+ Add Custom Code"**
3. Paste the following code (replace `your-customer-id` and element ID):

```html
<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@latest/dist/buzztrail.min.js"
        data-customer-id="your-customer-id"
        data-container-id="comp-mfy88b7h">
</script>
```

4. Configure the snippet:
   - **Name**: BuzzTrail Engage
   - **Add to Pages**: Choose "All pages" or specific pages
   - **Place Code in**: Select **"Body - end"** (recommended)
5. Click **"Apply"**
6. **Publish your site**

### Why Custom Code (Not Embed HTML)?

- **Wix Embed HTML** wraps code in an iframe, which blocks camera/microphone permissions
- **Custom Code** runs directly on the page, allowing proper permissions
- This is the **only way** to enable video conversations on Wix

## TypeScript Support

This package includes full TypeScript type definitions. No need to install `@types` packages.

### Type Imports

```typescript
import type {
  // Configuration types
  CustomerConfig,
  UIConfig,
  ThemeConfig,
  ButtonConfig,
  VideoConfig,
  ResponsiveConfig,
  GatingConfig,
  ConversationOptions,

  // API types
  CreateConversationRequest,
  CreateConversationResponse,
  EndConversationRequest,
  EndConversationResponse,
  ApiError,

  // Video call types
  CallUrlParams,
  CallTheme,
  CallIframeConfig,
  CallPostMessageEvent,
} from '@buzztrail-ai/engage';
```

### Example: Type-Safe Configuration

```typescript
import type { ConversationOptions, CustomerConfig } from '@buzztrail-ai/engage';

const options: ConversationOptions = {
  containerId: 'my-container',
  customerId: 'acme-corp',
  platform: 'wix',

  // TypeScript will autocomplete and validate these callbacks
  onStart: () => {
    console.log('Conversation started');
  },
  onEnd: () => {
    console.log('Conversation ended');
  },
  onError: (error: Error) => {
    console.error('Error:', error.message);
  }
};

// TypeScript ensures correct option types
BuzzTrail.createConversation('my-container', options);
```

### Type Guards

The package includes type guards for runtime type checking:

```typescript
import { isApiError, isCallPostMessageEvent } from '@buzztrail-ai/engage';

try {
  await createConversation();
} catch (error) {
  if (isApiError(error)) {
    console.error(`API error: ${error.message} (${error.code})`);
  } else {
    console.error('Unknown error:', error);
  }
}

window.addEventListener('message', (event) => {
  if (isCallPostMessageEvent(event.data)) {
    if (event.data.action === 'left-meeting') {
      console.log('User left the conversation');
    }
  }
});
```

## Configuration

### Script Tag Attributes (CDN)

When using the CDN, you can configure BuzzTrail via data attributes:

| Attribute | Required | Description | Example |
|-----------|----------|-------------|---------|
| `data-customer-id` | Yes | Your BuzzTrail customer ID | `"acme-corp"` |
| `data-container-id` | Yes (Wix) | DOM element ID to inject into | `"comp-mfy88b7h"` |
| `data-position` | No | Auto-inject position (if no container ID) | `"center-center"` |
| `data-environment` | No | Environment (defaults to production) | `"production"` |

### Customer Configuration

Customer-specific configuration (persona ID, theme, etc.) is fetched from the BuzzTrail API using your `customerId`. This allows for runtime configuration changes without code updates.

Example configuration structure:

```typescript
interface CustomerConfig {
  customerId: string;              // 'acme-corp'
  presenter_id: string;            // AI presenter identifier
  conversation_duration_seconds: number;  // Max duration
  language?: string;               // 'english', 'norwegian', etc.
  ui: {
    theme: {
      backgroundColor: string;     // '#ffffff'
      accentColor: string;         // '#a3e635'
      textColor: string;           // '#1a1a1a'
    },
    button: {
      text: string;                // 'Talk to Our AI'
      position: string;            // 'center-center'
    },
    video: {
      videoUrl?: string;           // Avatar idle video
      muted?: boolean;
      loop?: boolean;
    },
    responsive: {
      desktop: { width: 720, height: 405 },
      tablet: { width: 480, height: 270 },
      mobile: { width: 280, height: 350 }
    }
  },
  gating?: {
    enabled: boolean;
    collectInfo: ['name', 'email', 'phone'],
    language: 'en',
    customLabels?: { ... }
  },
  redirect_url?: string;
}
```

## API Reference

### Global API (`window.BuzzTrail`)

#### `BuzzTrail.init(config)`

Initialize BuzzTrail with global configuration.

```typescript
BuzzTrail.init({
  environment: 'production',
  theme: 'professional',
  debug: false
});
```

#### `BuzzTrail.createConversation(containerId, options)`

Create a conversation in the specified container.

```typescript
BuzzTrail.createConversation('my-container', {
  customerId: 'acme-corp',
  platform: 'wix',
  onStart: () => {},
  onEnd: () => {},
  onError: (error) => {}
});
```

#### `BuzzTrail.destroy(containerId)`

Destroy and cleanup a conversation.

```typescript
BuzzTrail.destroy('my-container');
```

## Browser Support

- Chrome/Edge: Latest 2 versions
- Firefox: Latest 2 versions
- Safari: Latest 2 versions
- Mobile browsers: iOS Safari 14+, Chrome Android

## Security

- **API Key Protection**: All API keys are stored server-side and never exposed to the browser
- **Secure Architecture**: All API requests go through the BuzzTrail secure proxy
- **Domain Validation**: Customer configs can restrict authorized domains
- **No Sensitive Data**: Configuration values are business logic only (no secrets in client code)

## Troubleshooting

### "Domain not authorized" Error

**Solution**: Add your website domain to your BuzzTrail account settings.
1. Log in to [buzztrail.ai](https://buzztrail.ai)
2. Go to Settings → Domains
3. Add your website domain (e.g., `yourdomain.com`)

### Camera/Microphone Not Working

- **HTTPS Required**: Video conversations only work on secure (HTTPS) websites
- **Wix Users**: Use Custom Code (Settings → Advanced), NOT the Embed HTML element
- **Browser Permissions**: Users must allow camera/microphone access when prompted

### Video Not Appearing

- **Check Account**: Verify your BuzzTrail account is active
- **Check Customer ID**: Ensure you're using the correct customer ID from your dashboard
- **Check Container**: The HTML element with your container ID must exist on the page
- **Check Console**: Open browser DevTools (F12) to see any error messages

### Still Having Issues?

- **Email Support**: support@buzztrail.ai
- **Documentation**: https://docs.buzztrail.ai/engage
- **Report Bugs**: https://github.com/buzztrail-ai/engage-package/issues

## Examples

See the `/examples` directory for complete examples:

- `wix-basic.html` - Basic Wix integration
- `wix-advanced.html` - Advanced Wix with callbacks
- `webflow-example.html` - Webflow integration
- `typescript-example.ts` - TypeScript usage

## Contributing

Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.

## License

MIT © BuzzTrail AI

## Support

- **Documentation**: https://docs.buzztrail.ai/engage
- **Issues**: https://github.com/buzztrail-ai/engage-package/issues
- **Email**: support@buzztrail.ai

## Related Packages

- `@buzztrail-ai/presentation` - Add slide presentations to video conversations
- `@buzztrail-ai/experience` - Full experience with voice + slides + video

---

**Built with TypeScript** • **AI-Powered Video Conversations** • **Made for modern web platforms**
