# BuzzTrail Chatbot Widget

**Embeddable AI video chatbot** - A lightweight, theme-aware chat widget that can be embedded on any website to provide AI-powered video conversations.

## 🎯 Overview

The BuzzTrail chatbot is a **React-based widget** built with **Vite** that provides embeddable AI video chat functionality. It's designed as an IIFE bundle for easy script injection into any website with theme support and responsive design.

### Key Features

- ✅ **Script Injection Ready** - Single JavaScript file for easy embedding
- ✅ **Theme System** - Multiple branded themes (Sendcloud, default, neon)
- ✅ **Responsive Design** - Works on desktop and mobile devices
- ✅ **Video Chat Interface** - Tavus AI video conversation integration
- ✅ **Scoped Styling** - CSS isolation prevents conflicts with host sites
- ✅ **Fast Loading** - Optimized bundle size (~150KB minified)
- ✅ **Hot Module Reload** - Fast development iteration

## 🚀 Quick Start

### Prerequisites

- Node.js 18+
- pnpm package manager

### Development Setup

1. **Install Dependencies**:
   ```bash
   # From project root
   pnpm install
   ```

2. **Start Development Server**:
   ```bash
   # Start chatbot development server
   pnpm run dev:chatbot

   # Server runs on http://localhost:4200
   ```

3. **Build for Production**:
   ```bash
   # Build optimized bundle
   pnpm run build:chatbot

   # Output: dist/apps/chatbot/main.js
   ```

4. **Test Theme Variations**:
   ```bash
   # Build with specific theme
   THEME=sendcloud pnpm run build:chatbot
   THEME=neon pnpm run build:chatbot
   ```

## 🏗️ Architecture

### Build System

- **Framework**: React 19 with TypeScript
- **Build Tool**: Vite with IIFE output format
- **Package Manager**: pnpm
- **Workspace**: Nx monorepo integration

### Bundle Configuration

```typescript
// Vite builds as IIFE for script injection
export default {
  build: {
    lib: {
      entry: 'src/main.tsx',
      name: 'BuzzTrailChatbot',
      formats: ['iife'],
      fileName: () => 'main.js'
    }
  }
}
```

### Key Technologies

- **React 19** - UI framework with modern hooks
- **TypeScript** - Type safety and development experience
- **Jotai** - Lightweight state management
- **Radix UI** - Accessible component primitives
- **Framer Motion** - Smooth animations and transitions
- **CSS-in-JS** - Scoped styling with theme support

### Theme System

The chatbot supports multiple themes with brand-specific styling:

```typescript
// Available themes
export type Theme = 'default' | 'sendcloud' | 'neon';

// Theme configuration
const themes = {
  sendcloud: {
    primary: '#00A3E0',
    secondary: '#F5F5F5',
    accent: '#FFB800'
  },
  default: {
    primary: '#6366F1',
    secondary: '#F8FAFC',
    accent: '#10B981'
  },
  neon: {
    primary: '#00FFFF',
    secondary: '#0A0A0A',
    accent: '#FF00FF'
  }
};
```

## 📋 Available Commands

### Development Commands

```bash
# Start development server with hot reload
pnpm run dev:chatbot

# Start with specific theme
THEME=sendcloud pnpm run dev:chatbot

# Start with logging enabled
pnpm run dev:with-logging
```

### Build Commands

```bash
# Build for production
pnpm run build:chatbot

# Build with specific theme
THEME=sendcloud pnpm run build:chatbot
THEME=neon pnpm run build:chatbot

# Build all theme variations
pnpm run build:chatbot:all
```

### Quality Commands

```bash
# Run ESLint
pnpm run lint:chatbot

# Run tests
pnpm run test:chatbot

# Type checking
pnpm run type-check
```

## 🎨 Embedding & Integration

### Basic Embedding

```html
<!-- Add to any website -->
<script src="https://your-cdn.com/buzztrail-chatbot.js"></script>
<script>
  // Initialize chatbot
  BuzzTrailChatbot.init({
    theme: 'default',
    apiKey: 'your-api-key',
    position: 'bottom-right'
  });
</script>
```

### Advanced Configuration

```javascript
BuzzTrailChatbot.init({
  // Theme configuration
  theme: 'sendcloud',

  // API configuration
  apiKey: 'your-tavus-api-key',
  apiEndpoint: 'https://your-proxy.vercel.app',

  // UI configuration
  position: 'bottom-right', // 'bottom-left', 'bottom-right'
  size: 'medium',           // 'small', 'medium', 'large'
  autoOpen: false,          // Auto-open on page load

  // Conversation configuration
  persona: 'default',       // AI persona to use
  language: 'en',          // Conversation language

  // Behavior configuration
  showOnMobile: true,       // Show on mobile devices
  respectDoNotTrack: true,  // Respect DNT header

  // Custom styling
  customCSS: '.buzztrail-widget { /* custom styles */ }',

  // Event handlers
  onOpen: () => console.log('Chatbot opened'),
  onClose: () => console.log('Chatbot closed'),
  onConversationStart: (id) => console.log('Conversation started:', id),
  onConversationEnd: (id) => console.log('Conversation ended:', id)
});
```

### WordPress Integration

```php
// Add to WordPress theme
function add_buzztrail_chatbot() {
    wp_enqueue_script(
        'buzztrail-chatbot',
        'https://your-cdn.com/buzztrail-chatbot.js',
        array(),
        '1.0.0',
        true
    );

    wp_add_inline_script('buzztrail-chatbot', '
        BuzzTrailChatbot.init({
            theme: "default",
            apiKey: "' . get_option('buzztrail_api_key') . '",
            position: "bottom-right"
        });
    ');
}
add_action('wp_enqueue_scripts', 'add_buzztrail_chatbot');
```

## 🔧 Configuration

### Environment Variables

```bash
# API Configuration
VITE_TAVUS_API_KEY=your_api_key
VITE_API_BASE_URL=https://your-proxy.vercel.app

# Build Configuration
THEME=sendcloud              # Theme to build
NODE_ENV=production          # Environment

# Development Configuration
VITE_DEV_MODE=true          # Enable development features
VITE_DEBUG_LOGGING=true     # Enable debug logging
```

### Build Configuration

```typescript
// vite.config.ts
export default defineConfig({
  // Build as IIFE for script injection
  build: {
    lib: {
      entry: 'src/main.tsx',
      name: 'BuzzTrailChatbot',
      formats: ['iife']
    },
    rollupOptions: {
      // Embed all dependencies
      external: [],
      output: {
        assetFileNames: 'assets/[name].[ext]'
      }
    }
  },

  // CSS configuration
  css: {
    modules: {
      scopeBehaviour: 'local'
    }
  }
});
```

### Theme Development

Creating a new theme:

1. **Add Theme Configuration**:
   ```typescript
   // libs/shared/themes/src/themes.ts
   export const customTheme = {
     name: 'custom',
     colors: {
       primary: '#FF0000',
       secondary: '#00FF00',
       accent: '#0000FF'
     },
     fonts: {
       primary: '"Custom Font", sans-serif'
     }
   };
   ```

2. **Build with Theme**:
   ```bash
   THEME=custom pnpm run build:chatbot
   ```

## 🧪 Testing

### Manual Testing

1. **Development Server**: Test on `http://localhost:4200`
2. **Embedding Test**: Create HTML file with script injection
3. **Theme Testing**: Test all theme variations
4. **Responsive Testing**: Test on different screen sizes
5. **Cross-Browser Testing**: Test on Chrome, Firefox, Safari

### Automated Testing

```bash
# Run unit tests
pnpm nx test chatbot

# Run E2E tests
pnpm nx e2e chatbot

# Visual regression tests
pnpm run test:visual
```

### Performance Testing

```bash
# Bundle size analysis
pnpm run build:chatbot --analyze

# Performance profiling
pnpm run test:performance
```

## 🚀 Deployment

### CDN Deployment

1. **Build for Production**:
   ```bash
   pnpm run build:chatbot
   ```

2. **Upload to CDN**:
   ```bash
   # Upload dist/apps/chatbot/main.js to your CDN
   aws s3 cp dist/apps/chatbot/main.js s3://your-bucket/chatbot/
   ```

3. **Set Cache Headers**:
   ```
   Cache-Control: public, max-age=31536000
   Content-Type: application/javascript
   ```

### Vercel Deployment

```bash
# Deploy to Vercel
vercel deploy dist/apps/chatbot/

# Production deployment
vercel deploy dist/apps/chatbot/ --prod
```

### NPM Package

```bash
# Build and publish as NPM package
pnpm run build:chatbot
npm publish dist/apps/chatbot/
```

## 📊 Performance

### Bundle Characteristics

- **Size**: ~150KB minified and gzipped
- **Load Time**: <500ms on 3G connection
- **First Paint**: <100ms after script load
- **Interactive**: <200ms after first paint

### Optimization Features

- **Tree Shaking**: Removes unused code
- **Code Splitting**: Lazy loads components
- **Asset Optimization**: Embedded images as base64
- **CSS Purging**: Removes unused styles
- **Compression**: Gzipped output

## 🔍 Troubleshooting

### Common Issues

**Widget Not Appearing**:
- Check browser console for JavaScript errors
- Verify script is loaded: `window.BuzzTrailChatbot`
- Check CSS conflicts with host site

**Styling Conflicts**:
- Enable CSS scoping in build configuration
- Use custom CSS override options
- Check for !important conflicts

**API Errors**:
- Verify API key configuration
- Check network requests in browser dev tools
- Ensure CORS is configured on API server

**Theme Not Loading**:
- Verify theme was built correctly
- Check theme configuration in initialization
- Test with default theme first

### Debug Commands

```bash
# Development with debug logging
VITE_DEBUG_LOGGING=true pnpm run dev:chatbot

# Build with source maps
pnpm run build:chatbot --sourcemap

# Analyze bundle size
pnpm run build:chatbot --analyze
```

## 📚 Related Documentation

### Core Documentation
- [Build System Guide](../../docs/build-system-guide.md) - Vite build system details
- [Package Scripts Reference](../../docs/package-scripts-reference.md) - All available commands
- [Development Guide](../../documentation/documentation/development-guide.md) - General development setup

### Integration Guides
- [Tavus Integration Guide](../../documentation/documentation/tavus-integration-guide.md) - AI video API integration
- [UI/UX Guide](../../documentation/documentation/ui-ux-guide.md) - Component architecture and theming
- [API Integration Guide](../../documentation/documentation/api-integration-guide.md) - API patterns

### Theme Development
- [Theming Guide](../../documentation/documentation/theming.md) - Theme system details
- [Component Library](../../libs/shared/components/README.md) - Shared components

---

**Build System**: Vite (React + TypeScript)
**Output Format**: IIFE (Immediately Invoked Function Expression)
**Package Manager**: pnpm
**Bundle Size**: ~150KB minified
**Last Updated**: September 26, 2025