# BuzzTrail Video Demo - Unified Local & Wix System

This directory contains the BuzzTrail video demo with shared components for both local development and Wix website integration, featuring auto-join Daily.co video calls and environment-specific configurations.

## 📁 Project Structure

```
buzztrail-video-demo/
├── src/
│   ├── shared-demo.js           # Shared components & auto-join logic
│   ├── local-demo.js            # Local development version
│   ├── wix-demo.js              # Wix integration version
│   └── index.html               # Local development page
├── build-wix.js                 # NX-integrated build script
├── wix-custom-code-production.html    # Production Wix build (minified)
├── wix-custom-code-dev-production.html # Development Wix build (readable)
├── .env.local                   # Local development config
├── .env.production              # Production build config
└── README.md                    # This file
```

## 🌍 Environment-Specific Behavior

### 🏠 Local Development (`localhost:8080`)
- **Video Service**: Creates real Daily.co rooms directly
- **Domain**: `buzztrail.daily.co` (your domain)
- **Auto-join**: Skips "Are you ready to join?" screen (`enable_prejoin_ui: false`)
- **API Key**: Safely stored in `.env.local` for development
- **Command**: `pnpm nx serve:buzztrail demos`

### 🌐 Production Wix
- **Video Service**: Uses real Tavus API service
- **Domain**: `tavusapi.daily.co` (Tavus domain)
- **Auto-join**: Skips pre-join screens (shared configuration)
- **Security**: No API keys exposed in public scripts
- **Command**: `pnpm nx build:wix demos`

## 🚀 Build Commands

### 🎯 Unified Development (Recommended)
```bash
# One command for everything: build + serve + preview
pnpm nx dev:buzztrail demos

# This command:
# 1. Builds production Wix version
# 2. Starts local development server
# 3. Provides both local preview AND production code ready to copy
```

### Individual Commands
```bash
# Wix Production Build
pnpm nx build:wix demos

# Local Development Server
pnpm nx serve:buzztrail demos

# Visit http://localhost:8080
```

### Direct execution
```bash
# From the demo directory
node build-wix.js
```

## 📊 Build Process

The build system:

1. **Reads** the source from `src/wix-demo.js`
2. **Minifies CSS** within template literals
3. **Minifies JavaScript** while preserving functionality
4. **Validates** character count against Wix's 15,000 limit
5. **Outputs** both production and development versions

### Character Limits
- **Wix Limit**: 15,000 characters
- **Current Build**: ~14,822 characters (99% of limit)
- **Remaining**: ~178 characters ⚠️

## 🔧 Development Workflow

### Making Changes
1. **Edit** `src/wix-demo.js` with your changes
2. **Build** using `pnpm wix`
3. **Copy** content from `wix-custom-code-built.html`
4. **Paste** into Wix Custom Code (Body - end)

### Debugging
- Use `wix-custom-code-dev.html` for readable debugging
- Check browser console for error messages
- Test with different section IDs by updating CONFIG

## 🎥 Video Integration

### Configuration Approach
Both environments use URL parameters for consistent Daily.co behavior:

```javascript
// Applied to all video room URLs
url.searchParams.set('prejoinDisabled', 'true');
url.searchParams.set('autoJoin', 'true');
url.searchParams.set('showLocalVideo', 'true');
url.searchParams.set('showParticipantsBar', 'false');
```

### Environment Differences
- **Local**: Direct Daily.co API with `enable_prejoin_ui: false`
- **Production**: BuzzTrail proxy service with URL parameter workarounds
- **Result**: Both provide smooth auto-join experience

### Leave Button Discovery
**Key Finding**: Daily Prebuilt embeds don't show leave buttons by default. Our custom "End" button provides user control when needed.

## 🚪 Advanced Leave Detection & Redirection

### Smart Leave Detection
The system includes intelligent monitoring for when users leave video calls through any method:

#### Detection Methods
1. **Custom "End Call" Button**: Immediate detection and redirect
2. **Daily.co Built-in "Leave" Button**: Advanced iframe navigation monitoring
3. **Timer Expiry**: Automatic redirect when call time limit reached

#### Iframe Navigation Monitoring
```javascript
// Intelligent cross-origin detection for Daily.co leave events
setTimeout(() => {
    let crossOriginCount = 0;
    let stableAccessCount = 0;

    // Only trigger after call is established AND sustained failures detected
    if (stableAccessCount >= 5 && crossOriginCount >= 5) {
        // User left via Daily.co controls
        endConversation();
    }
}, 15000); // Wait 15s for full setup including camera permissions
```

#### Features
- ✅ **15-second startup delay** to avoid false triggers during camera permissions
- ✅ **Stable access validation** ensures call was properly established
- ✅ **Conservative failure counting** requires 5 consecutive failures
- ✅ **2-second polling interval** for balanced responsiveness and performance

### End-of-Call Redirection
Automatic redirection occurs after any conversation end:

```javascript
function redirectAfterConversation() {
    const config = getEnvironmentConfig();
    setTimeout(() => {
        window.location.href = config.redirectUrl;
    }, 1000);
}
```

#### Redirect Destinations
- **Production Wix**: `https://www.buzztrail.ai/meet-buzz`
- **Local Development**: `http://localhost:8080/meet-buzz`
- **Timing**: 1-second delay for smooth user experience

## ⚙️ Configuration

The system uses shared configuration in `src/shared-demo.js`:

```javascript
export const ENV_CONFIGS = {
    production: {
        proxyUrl: 'https://buzztrail-proxy.vercel.app/api',
        useRealTavus: true,
        dailyDomain: 'tavusapi.daily.co',
        dailyApiKey: null,  // Security: Never exposed publicly
        redirectUrl: 'https://www.buzztrail.ai/meet-buzz'
    },
    local: {
        proxyUrl: null,  // Skip fake server, go directly to Daily.co
        dailyApiKey: 'your-daily-api-key',
        dailyDomain: 'buzztrail.daily.co',
        redirectUrl: 'http://localhost:8080/meet-buzz'
    }
};
```

## 🎯 Integration with Wix

### Setup Steps
1. Build production version: `pnpm wix`
2. Copy content from `wix-custom-code-production.html`
3. In Wix Editor: **Site Settings** → **Custom Code**
4. Choose **"Add Code to Pages"** → **Body - end**
5. Paste the code and save
6. Publish site

### Troubleshooting

#### Common Issues
- **Content not appearing**: Check section ID matches your Wix section (default: `comp-mfdtv4rf5`)
- **Content flashing/disappearing**: React-safe implementation prevents this with error handling
- **Camera not working**: Ensure HTTPS and proper iframe permissions

#### React-Safe Implementation (✅ Solved)
- **Problem**: Content flashing and disappearing due to React conflicts
- **Solution**: Comprehensive error handling, event isolation, delayed initialization
- **Result**: Stable content that persists through Wix's React re-renders

#### Leave Button Handling (✅ Clarified)
- **Discovery**: Daily Prebuilt hides leave buttons by default when embedded
- **Our Implementation**: Uses correct URL parameters and custom controls
- **Result**: Clean embedded experience without unwanted leave buttons

## 🏗️ Build System Features

- **NX + Vite Integration**: Full monorepo integration with modern build tools
- **Environment Variables**: VITE_ prefixed variables for environment-specific builds
- **Terser Minification**: Aggressive compression for Wix character limits
- **Unified Architecture**: Single build process with inline implementation
- **Character Validation**: Automatic limit checking with detailed reporting
- **React-Safe Output**: Handles Wix platform React conflicts

## 📋 Files Generated

### `wix-custom-code-production.html`
- **Use**: Production deployment to Wix
- **Size**: ~6,484 characters (43% of limit)
- **Environment**: Uses proxy service, relative video paths

### `wix-custom-code-local.html`
- **Use**: Local development testing
- **Size**: Similar to production (same minification)
- **Environment**: Direct Daily.co API, full video URLs

## 🔄 Development Workflow

1. ✅ **Edit**: Environment variables in `.env.production` or `.env.local`
2. ✅ **Build**: `pnpm nx build:wix demos` (builds both production + local, opens local test)
3. ✅ **Test**: Automatically opens http://localhost:8080 for testing
4. ✅ **Deploy**: Copy production HTML to Wix custom code
5. ✅ **Validate**: Automatic character limit checking

**Benefits**: Same build process for both environments, just different configs.

## 🔍 Daily.co Integration Architecture

### Environment-Specific Implementation

#### Local Development
- **Direct Daily.co API**: Full control over room configuration
- **Immediate Join**: `enable_prejoin_ui: false` works perfectly
- **Testing Environment**: Matches production behavior as closely as possible

#### Production (via Tavus)
- **Tavus API Integration**: Uses BuzzTrail proxy service
- **Limited Configuration**: Some Daily.co parameters not exposed by Tavus
- **URL Parameter Workarounds**: Applied for consistent behavior

#### Current Configuration Approach

**Local Development** (Direct Daily.co):
```javascript
properties: {
  max_participants: 2,
  enable_chat: true,
  enable_screenshare: false,
  enable_prejoin_ui: false,  // ✅ Full control
  exp: Math.floor(Date.now() / 1000) + 900
}
```

**Production** (via BuzzTrail Proxy):
```javascript
// URL parameters for consistent behavior
url.searchParams.set('prejoinDisabled', 'true');
url.searchParams.set('autoJoin', 'true');
url.searchParams.set('showLocalVideo', 'true');
url.searchParams.set('showParticipantsBar', 'false');
```

## 🔧 Implementation Notes

### Current Status
- ✅ **Unified Build System**: Both environments use same minification and build process
- ✅ **Environment Variables**: Clean separation of local vs production configs
- ✅ **Character Optimization**: Well below 15k limit with room for features
- ✅ **React-Safe**: Handles Wix platform React conflicts reliably
- ✅ **Leave Button Handling**: Uses Daily Prebuilt's default embedded behavior

### Technical Architecture
- **Local**: Direct Daily.co API with full configuration control
- **Production**: BuzzTrail proxy service for Tavus integration
- **Build Process**: Vite + NX with Terser minification
- **Source**: Single `wix-demo.js` file with environment variable injection

### Development Best Practices
1. **Test Locally First**: Use `pnpm nx build:wix demos` (automatically builds and tests locally)
2. **Verify Character Limits**: Build process provides automatic validation
3. **Check Console**: Look for initialization and error messages
4. **Production Parity**: Local build mimics production as closely as possible