# @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](https://img.shields.io/badge/license-Proprietary-red.svg)](LICENSE)

## Overview

`@buzztrail-ai/engage` 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**: Just call `BuzzTrail.createConversation()`
- **Fast Loading**: Ultra-lightweight package that 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**: 32 languages built-in with auto-translation
- **Lead Capture**: Optional forms to collect visitor information before conversation
- **GDPR Compliant**: Privacy-first lead capture with consent management
- **No Technical Skills**: Works without coding knowledge (perfect for Wix users)
- **TypeScript Support**: Full type definitions included

## Table of Contents

- [Getting Started](#getting-started)
- [Quick Start](#quick-start)
- [Wix Integration Guide](#wix-integration-guide)
- [Configuration API](#configuration-api)
  - [ConversationOptions](#conversationoptions)
  - [configOverride API](#configoverride-api-reference)
- [Configuration Examples](#configuration-examples)
- [TypeScript Support](#typescript-support)
- [Browser Support](#browser-support)
- [Troubleshooting](#troubleshooting)
- [Version History](#version-history)

## 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)

**Recommended - Semver @1 (always latest v1.x):**

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

**Specific Version (for testing):**

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

**Fallback CDN (unpkg):**

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

> **Note**: The `@1` semver URL automatically updates to the latest v1.x version (e.g., v1.0.95). Use specific versions for testing, then switch to `@1` for production.

## Quick Start

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

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

<!-- 2. Add the BuzzTrail script -->
<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@1/buzztrail.umd.js"></script>

<!-- 3. Initialize BuzzTrail -->
<script>
  BuzzTrail.createConversation('buzztrail-container', {
    customerId: 'your-customer-id'
  });
</script>
```

That's it! The video conversation will appear in your container.

### With Callbacks

For more control, add callback functions:

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

<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@1/buzztrail.umd.js"></script>
<script>
  BuzzTrail.createConversation('my-container', {
    customerId: 'your-customer-id',
    onStart: () => console.log('Conversation started'),
    onEnd: () => console.log('Conversation ended'),
    onError: (error) => console.error('Error:', error)
  });
</script>
```

### NPM Usage (TypeScript/JavaScript)

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

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

BuzzTrail.createConversation('my-container', 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@1/buzztrail.umd.js"></script>
<script>
  BuzzTrail.createConversation('comp-mfy88b7h', {
    customerId: 'your-customer-id'
  });
</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**

### Finding the Correct Container ID

Each Wix page element has a unique ID. To find the correct container ID for your page:

1. Open your published Wix page in a browser
2. Open the browser's Developer Tools (F12 or right-click → Inspect)
3. In the Console tab, paste this code and press Enter:

```javascript
document.querySelectorAll('[id^="comp-"]').forEach(el => {
  console.log(`ID: ${el.id}, Size: ${el.offsetWidth}x${el.offsetHeight}px`);
});
```

4. Look for a container with dimensions around **700x500px or larger** - this is ideal for video display
5. Copy that container's ID (e.g., `comp-abc123xyz`) and use it in `createConversation()`

### 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

## Configuration API

### ConversationOptions

The main options object passed to `BuzzTrail.createConversation()`:

```typescript
interface ConversationOptions {
  // REQUIRED
  customerId: string;           // Your BuzzTrail customer ID

  // OPTIONAL CALLBACKS
  onStart?: () => void;         // Fired when conversation starts
  onEnd?: () => void;           // Fired when conversation ends
  onError?: (error: Error) => void;  // Fired on errors

  // OPTIONAL OVERRIDES (for testing/customization)
  configOverride?: Partial<CustomerConfig>;
}
```

### configOverride API Reference

The `configOverride` option allows you to override any aspect of your customer configuration at runtime. This is useful for:

- **Testing**: Try different themes, languages, or features without changing backend config
- **A/B Testing**: Test different button text, colors, or gating forms
- **Page-Specific Customization**: Different settings for different pages
- **Development/Debugging**: Enable debug logging to troubleshoot issues

#### Complete configOverride Structure

```typescript
configOverride: {
  // === CORE SETTINGS ===

  /** Override language (affects button text, form labels, etc.) */
  language?: string;  // 'en', 'es', 'de', 'fr', 'no', etc. (32 languages supported)

  /** Override conversation duration (in seconds) */
  conversation_duration_seconds?: number;  // e.g., 180, 300, 600

  /** Override redirect URL (where to send user after conversation ends) */
  redirect_url?: string;  // e.g., 'https://example.com/thank-you'

  /** Override API base URL (for testing custom backends) */
  apiBaseUrl?: string;  // Default: https://dwdytxxqcvlrmyemonxz.supabase.co/functions/v1

  /** Enable debug logging (shows all [BuzzTrail:...] logs in console) */
  debug?: boolean;  // Default: false (production mode - no logs)

  // === UI CONFIGURATION ===
  ui?: {

    // --- THEME SETTINGS ---
    theme?: {
      /** Main background color (hex) */
      backgroundColor?: string;  // e.g., '#ffffff', '#f5f5f5'

      /** Accent/brand color - used for button, highlights (hex) */
      accentColor?: string;  // e.g., '#a3e635', '#ff0000'

      /** Primary text color (hex) */
      textColor?: string;  // e.g., '#1a1a1a', '#333333'

      /** Secondary background color (hex) */
      backgroundAccent?: string;

      /** Border color (hex) */
      borderColor?: string;
    },

    // --- BUTTON SETTINGS ---
    button?: {
      /**
       * Button text
       * - Set to null to use auto-translated text based on language
       * - Set to custom string to override (e.g., 'Talk with Susan')
       */
      text?: string | null;  // e.g., 'Talk to Our AI', null for auto-translate

      /**
       * Button position relative to video panel
       * - 'center-center': Full-screen centered (default for Wix)
       * - 'bottom-right': Fixed bottom-right widget
       * - 'bottom-left': Fixed bottom-left widget
       * - 'top-right': Fixed top-right widget
       * - 'top-left': Fixed top-left widget
       */
      position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'center-center';

      /**
       * Custom button background color (overrides theme.accentColor)
       * - Leave undefined to use theme.accentColor
       * - Set to hex color to override
       */
      backgroundColor?: string;

      /** Custom button border color */
      borderColor?: string;
    },

    // --- VIDEO SETTINGS (idle avatar video) ---
    video?: {
      /** URL to avatar video (shown before conversation starts) */
      videoUrl?: string;  // e.g., 'https://video.wixstatic.com/...'

      /** URL to poster image (shown before video loads) */
      posterUrl?: string;

      /** Whether video should be muted */
      muted?: boolean;  // Default: true

      /** Whether video should loop */
      loop?: boolean;  // Default: true

      /** Whether video should autoplay */
      autoplay?: boolean;  // Default: true
    },

    // --- RESPONSIVE SETTINGS ---
    responsive?: {
      /** Desktop dimensions (screen width > 768px) */
      desktop?: {
        width?: number;   // Default: 720
        height?: number;  // Default: 405
        aspectRatio?: string;  // e.g., '16/9'
      },

      /** Tablet dimensions (screen width 481-768px) */
      tablet?: {
        width?: number;   // Default: 480
        height?: number;  // Default: 270
        aspectRatio?: string;
      },

      /** Mobile dimensions (screen width <= 480px) */
      mobile?: {
        width?: number;   // Default: 280
        height?: number;  // Default: 350
        aspectRatio?: string;  // e.g., '4/5'
      }
    }
  },

  // === GATING/LEAD CAPTURE ===
  gating?: {
    /** Enable/disable gating form */
    enabled?: boolean;  // Default: false

    /**
     * Gating mode
     * - 'standalone': Show form before conversation (current)
     * - 'pre-join': Show form in Daily.co pre-join screen (future)
     */
    mode?: 'standalone' | 'pre-join';  // Default: 'standalone'

    /**
     * Fields to collect from user
     * - Array can include: 'name', 'email', 'phone', 'company'
     */
    collectInfo?: ('name' | 'email' | 'phone' | 'company')[];  // Default: ['name', 'email']

    /**
     * Required fields (must be subset of collectInfo)
     * - These fields must be filled before form can be submitted
     */
    requiredInfo?: ('name' | 'email' | 'phone' | 'company')[];  // Default: ['name', 'email']

    /** Whether to pass collected info to Tavus conversation */
    passToConversation?: boolean;  // Default: true

    /** Email validation settings */
    emailValidation?: {
      /**
       * Block free email providers (Gmail, Yahoo, Outlook.com, etc.)
       * - Useful for B2B lead qualification
       */
      blockFreeProviders?: boolean;  // Default: true

      /** Additional email domains to block (e.g., ['competitor.com']) */
      customBlockedDomains?: string[];
    },

    /**
     * Show GDPR-compliant privacy consent checkbox
     * - Required for EU visitors per GDPR regulations
     */
    gdprCompliant?: boolean;  // Default: false

    /** Custom submit button text */
    submitButtonText?: string;  // Default: auto-translated based on language

    /**
     * Language for form labels
     * - If not set, uses main language setting
     * - 32 languages supported (same as main language option)
     */
    language?: string;

    /** Custom field labels (for custom translations or branding) */
    customLabels?: {
      name?: string;          // Default: auto-translated 'Name'
      email?: string;         // Default: auto-translated 'Email'
      phone?: string;         // Default: auto-translated 'Phone'
      company?: string;       // Default: auto-translated 'Company'
      submitButton?: string;  // Default: auto-translated 'Continue'
    }
  }
}
```

#### Supported Languages (32 total)

English (en), Spanish (es), French (fr), German (de), Italian (it), Portuguese (pt), Dutch (nl), Russian (ru), Polish (pl), Turkish (tr), Arabic (ar), Hindi (hi), Chinese Simplified (zh), Chinese Traditional (zh-TW), Japanese (ja), Korean (ko), Vietnamese (vi), Thai (th), Indonesian (id), Malay (ms), Filipino (fil), Norwegian (no), Swedish (sv), Danish (da), Finnish (fi), Greek (el), Hebrew (he), Czech (cs), Hungarian (hu), Romanian (ro), Ukrainian (uk), Bulgarian (bg)

## Configuration Examples

### Example 1: Change Language to Spanish

```javascript
BuzzTrail.createConversation('container-id', {
  customerId: 'your-customer-id',
  configOverride: {
    language: 'es'  // Button and form will auto-translate to Spanish
  }
});
```

### Example 2: Custom Theme (Red Accent Color)

```javascript
BuzzTrail.createConversation('container-id', {
  customerId: 'your-customer-id',
  configOverride: {
    ui: {
      theme: {
        accentColor: '#ff0000',  // Red button
        backgroundColor: '#ffffff',
        textColor: '#1a1a1a'
      }
    }
  }
});
```

### Example 3: Custom Button Text

```javascript
BuzzTrail.createConversation('container-id', {
  customerId: 'your-customer-id',
  configOverride: {
    ui: {
      button: {
        text: 'Talk with Susan'  // Custom button text
      }
    }
  }
});
```

### Example 4: Enable Gating Form (All Fields)

```javascript
BuzzTrail.createConversation('container-id', {
  customerId: 'your-customer-id',
  configOverride: {
    gating: {
      enabled: true,
      collectInfo: ['name', 'email', 'phone', 'company'],  // Collect all fields
      requiredInfo: ['name', 'email'],  // Only name and email required
      gdprCompliant: true  // Show GDPR consent checkbox
    }
  }
});
```

### Example 5: Production Mode (No Debug Logs)

```javascript
BuzzTrail.createConversation('container-id', {
  customerId: 'your-customer-id',
  configOverride: {
    debug: false  // Suppress all console logs (production mode)
  }
});
```

### Example 6: Debug Mode (Enable Logging)

```javascript
BuzzTrail.createConversation('container-id', {
  customerId: 'your-customer-id',
  configOverride: {
    debug: true  // Show all [BuzzTrail:...] logs for debugging
  }
});
```

### Example 7: German Language + GDPR + Business Email Only

```javascript
BuzzTrail.createConversation('container-id', {
  customerId: 'your-customer-id',
  configOverride: {
    language: 'de',  // German language
    gating: {
      enabled: true,
      collectInfo: ['name', 'email', 'company'],
      requiredInfo: ['name', 'email', 'company'],
      gdprCompliant: true,  // Show GDPR checkbox (required in EU)
      emailValidation: {
        blockFreeProviders: true  // Block Gmail, Yahoo, etc. (B2B only)
      }
    }
  }
});
```

### Example 8: Mobile-Optimized Dimensions

```javascript
BuzzTrail.createConversation('container-id', {
  customerId: 'your-customer-id',
  configOverride: {
    ui: {
      responsive: {
        mobile: {
          width: 320,
          height: 400,
          aspectRatio: '4/5'
        }
      }
    }
  }
});
```

## 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,
  VideoDimensions,
  ConversationState
} from '@buzztrail-ai/engage';
```

### Example: Type-Safe Configuration

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

const options: ConversationOptions = {
  customerId: 'acme-corp',

  configOverride: {
    language: 'es',  // TypeScript validates this is a valid language code
    ui: {
      theme: {
        accentColor: '#ff0000'  // TypeScript ensures this is a string
      }
    }
  },

  // 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);
```

## API Reference

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

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

Create a conversation in the specified container.

**Parameters:**
- `containerId` (string): DOM element ID to inject the conversation into
- `options` (ConversationOptions): Configuration options

**Returns:** `Promise<void>`

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

#### `BuzzTrail.version`

Get the package version.

```typescript
console.log(BuzzTrail.version); // "1.0.95"
```

**Note**: Starting from v1.0.92, all published bundles include a version banner comment at the top:
```javascript
/*! @buzztrail-ai/engage v1.0.95 | (c) BuzzTrail AI | https://www.buzztrail.ai */
```

## Browser Support

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

**Requirements:**
- **HTTPS Required**: Video conversations only work on secure (HTTPS) websites
- **Camera/Microphone Permissions**: Browser must support `getUserMedia` API

## Troubleshooting

### "Domain not authorized" Error

**Solution**: Contact BuzzTrail support to authorize your domain. Domain authorization is managed by BuzzTrail admins for security purposes.

### 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
- **Enable Debug Mode**: Add `configOverride: { debug: true }` to see detailed logs

### No Looping Video

- Make sure your customer config includes a `ui.video.videoUrl` property
- Check that the video URL is accessible and valid

### Logs Showing in Production

If you see `[BuzzTrail:...]` logs in production:

1. Ensure you're using v1.0.95 or later
2. Set `configOverride: { debug: false }`
3. Purge CDN cache if using `@1` semver URL:
   ```bash
   curl https://purge.jsdelivr.net/npm/@buzztrail-ai/engage@1/buzztrail.umd.js
   ```

### Form Not Translating

If gating form fields aren't translating:

1. Ensure `language` is set in `configOverride`
2. Check that `gating.language` isn't overriding the main language
3. Ensure you're using v1.0.84 or later (i18n fix)

## Version History

### Latest Releases

- **v1.0.95** (2025-10-29) - 🐛 **CRITICAL FIX** Fixed `isProduction()` to use `__DEV__` flag, debug mode now works correctly
- **v1.0.94** (2025-10-29) - ❌ **BROKEN** Attempted production mode fix but `isProduction()` always returned false
- **v1.0.93** (2025-10-29) - Skipped due to npm conflicts
- **v1.0.92** (2025-10-29) - 📋 **VERSION BANNER** All builds now include version comment at top for debugging
- **v1.0.89** (2025-10-28) - 🏗️ **ARCHITECTURE FIX** Database now single source of truth, frontend trusts backend completely
- **v1.0.88** (2025-10-28) - 🎉 **FIXED RED BUTTON** Removed DEFAULT_CONFIG.ui.button.backgroundColor blocking theme overrides
- **v1.0.86** (2025-10-27) - 🎨 Fixed button transparency + Daily iframe visibility + theme migration
- **v1.0.85** (2025-10-27) - 🎨 Button text contrast fix - bold text with shadow
- **v1.0.84** (2025-10-27) - 🎉 Fixed i18n initialization - button text now translates correctly
- **v1.0.83** (2025-10-26) - 🎨 Form contrast fix - solid white background with rounded corners
- **v1.0.82** (2025-10-26) - 🌍 Button text auto-translate attempt (completed in v1.0.84)
- **v1.0.81** (2025-10-26) - 🔒 GDPR hidden by default + removed Company from defaults
- **v1.0.80** (2025-10-26) - ✅ Submit button disabled when validation errors exist
- **v1.0.79** (2025-10-26) - ⚛️ React 18 downgrade (fixes flashing content on Wix)
- **v1.0.78** (2025-10-25) - ⚡ On-blur validation (immediate feedback when user tabs out)
- **v1.0.76** (2025-10-24) - 🔄 Schema transformation for agents array
- **v1.0.71** (2025-10-24) - 📧 Default email validation (blocks Gmail/free providers)
- **v1.0.66** (2025-10-23) - 🐛 Video URL fix (config merge bug)
- **v1.0.62** (2025-10-23) - 🧹 Removed ALL auto-init code (first working version)
- **v1.0.59** (2025-10-23) - 💰 Delays Tavus start until button click (saves credits!)
- **v1.0.52** (2025-10-22) - 🎉 Initial production release with gating form

See [CHANGELOG.md](./CHANGELOG.md) for complete version history.

## CDN Cache Management

When publishing a new version, the `@1` semver URL is cached by CDN providers. To force an immediate update:

```bash
# Purge jsdelivr CDN cache
curl https://purge.jsdelivr.net/npm/@buzztrail-ai/engage@1/buzztrail.umd.js
```

Alternatively, use a specific version for testing:
```html
<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@1.0.95/buzztrail.umd.js"></script>
```

Then switch back to `@1` for production once verified.

## Support

- **Documentation**: [docs.buzztrail.ai](https://docs.buzztrail.ai)
- **Email**: support@buzztrail.ai
- **Issues**: Report bugs or request features via your account dashboard

## License

Proprietary - BuzzTrail AI

---

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