# Wix Code Extraction & Refactoring Analysis

**Stream A - Phase 2: Code Analysis**
**Date**: 2025-10-23
**Analyst**: Claude (Issue #172)

## Executive Summary

This document analyzes the current production Wix integration code located in `apps/demos/buzztrail-video-demo/` to prepare for extracting it into the reusable NPM package `@buzztrail-ai/engage`. The analysis identifies hardcoded values, integration patterns, security considerations, and provides a detailed refactoring plan.

## Current Implementation Overview

### Production Files Analyzed

1. **Source Files** (unminified):
   - `apps/demos/buzztrail-video-demo/src/shared-demo.js` - Core utilities and UI generation
   - `apps/demos/buzztrail-video-demo/src/wix-demo.js` - Wix-specific implementation
   - `apps/demos/buzztrail-video-demo/src/wix-combined.js` - Vite build entry point

2. **HTML Files** (production artifacts):
   - `wix-custom-code-dev-production.html` - Production ready for copy/paste to Wix
   - `wix-custom-code-norsk-unloc-production.html` - Norwegian localized version

3. **Build Configuration**:
   - `apps/demos/vite.wix.config.ts` - Vite build with aggressive minification
   - `apps/demos/project.json` - Nx build targets
   - `.env.production`, `.env.norsk-unloc` - Environment-specific configs

### Architecture Pattern

**Current Pattern**: IIFE (Immediately Invoked Function Expression) bundle
- Built with Vite + Terser for extreme minification
- Target: < 15KB gzipped (Wix custom code limit)
- Output format: Single `<script>` tag with inline JavaScript
- Deployment: Copy/paste into Wix Custom Code feature

**Integration Flow**:
1. Page loads → Script executes IIFE
2. DOM ready → Initialize BuzzTrail UI
3. User clicks "Talk to Tom" → Create Tavus conversation
4. Embed Daily.co iframe → Start video conversation
5. Timer expires or user ends call → Cleanup and redirect

## Hardcoded Values Identified

### Critical Configuration (Must Be Parameterized)

| Hardcoded Value | Location | Current Use | Should Be |
|----------------|----------|-------------|-----------|
| `comp-mfdtv4rf5` | CONFIG.sectionId | Wix element ID (English demo) | Customer config: `containerId` |
| `comp-mfy88b7h` | norsk-unloc variant | Wix element ID (Norwegian demo) | Customer config: `containerId` |
| `p527c5d8b826` | CONFIG.personaId | Tavus persona ID (Tom) | Customer config: `presenterId` |
| `p99ebcce2bfa` | norsk-unloc variant | Tavus persona ID (Tomas) | Customer config: `presenterId` |
| `rca8a38779a8` | CONFIG.replicaId | Tavus replica ID (English) | Customer config: `replicaId` |
| `rf4703150052` | norsk-unloc variant | Tavus replica ID (Norwegian) | Customer config: `replicaId` |
| `https://buzztrail-proxy.vercel.app/api` | CONFIG.proxyUrl | API proxy URL | Customer config: `apiBaseUrl` |
| `180` / `300` | CONFIG.conversationDuration | Conversation timeout (seconds) | Customer config: `maxDuration` |
| `https://www.buzztrail.ai/meet-buzz` | CONFIG.redirectUrl | Post-conversation redirect | Customer config: `redirectUrl` |
| `Talk with Tom` | CONFIG.buttonText | CTA button text | Customer config: `buttonText` |
| `Snakk med Tomas` | norsk-unloc variant | Norwegian CTA | Customer config: `buttonText` + i18n |
| `norwegian` | CONFIG.language | Language code | Customer config: `language` |
| `https://video.wixstatic.com/...` | CONFIG.videoUrl | Avatar idle video | Customer config: `videoUrl` |

### UI/Styling Hardcoded Values

| Hardcoded Value | Location | Purpose | Should Be |
|----------------|----------|---------|-----------|
| `#e7fbbc` | BUTTON_STYLES.background | Green button background | Theme config: `buttonBgColor` |
| `#a3e635` | BUTTON_STYLES.border | Green button border | Theme config: `accentColor` |
| `25%` | CSS bottom position | Button vertical position | Theme config: `buttonPosition` |
| `720px × 405px` | Video panel size | Desktop aspect ratio (16:9) | Theme config: `videoSize` |
| `480px × 270px` | Tablet breakpoint | Tablet aspect ratio (16:9) | Responsive config |
| `280px × 350px` | Mobile breakpoint | Mobile aspect ratio (4:5) | Responsive config |
| `2000` | CONFIG.initDelay | Initialization delay (ms) | Config: `initDelay` |

### API/Integration Endpoints

| Endpoint | Current Use | Notes |
|----------|-------------|-------|
| `POST /conversations/create` | Create Tavus conversation | Via proxy |
| `POST /conversations/{id}/end` | End Tavus conversation | Via proxy |
| `https://api.daily.co/v1/rooms` | Direct Daily.co (local dev only) | Fallback mode |

## Tavus SDK Integration Patterns

### Current Integration Method: **Proxy-Based**

**NOT using Tavus SDK directly** - Custom implementation via proxy:

```javascript
// Current approach (via proxy server)
const response = await fetch(`${proxyUrl}/conversations/create`, {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
        persona_id: 'p527c5d8b826',
        replica_id: 'rca8a38779a8',
        conversation_duration_seconds: 180,
        properties: { language: 'norwegian' } // Optional
    })
});

const { conversation_id, conversation_url } = await response.json();
// conversation_url is Daily.co iframe URL from Tavus
```

### Why Proxy Instead of Direct SDK?

1. **API Key Security**: Tavus API key never exposed to browser
2. **CORS Handling**: Proxy manages cross-origin requests
3. **Request Transformation**: Proxy can enrich/validate requests
4. **Cost Control**: Proxy can enforce rate limits/quotas
5. **Analytics**: Proxy logs all conversation creation events

### Proxy Server Details

**Current Proxy**: `https://buzztrail-proxy.vercel.app/api`
- Hosted on Vercel
- Handles Tavus API authentication
- Returns sanitized conversation data to client

**Expected Response Format**:
```json
{
  "conversation_id": "c1234567890",
  "conversation_url": "https://tavusapi.daily.co/room-name",
  "status": "active"
}
```

### Error Handling Pattern

```javascript
if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.error) {
    throw new Error(data.error);
}
```

## Daily.co Iframe Creation Logic

### Iframe Initialization

**Key Requirements for Camera/Microphone Permissions**:

```javascript
const iframe = document.createElement('iframe');
iframe.src = conversationUrl; // Daily.co URL from Tavus
iframe.allow = 'camera;microphone;autoplay'; // CRITICAL: Must be set programmatically
iframe.style.cssText = 'flex:1!important;width:100%!important;border:none!important';
```

### Auto-Join Parameters

The `addAutoJoinParams()` function modifies Daily.co URLs:

```javascript
export function addAutoJoinParams(roomUrl) {
    const url = new URL(roomUrl);

    // Skip pre-join screen
    url.searchParams.set('prejoinDisabled', 'true');
    url.searchParams.set('enable_prejoin_ui', 'false');
    url.searchParams.set('autoJoin', 'true');
    url.searchParams.set('skipPrejoinScreen', 'true');

    // UI controls
    url.searchParams.set('showLocalVideo', 'true');
    url.searchParams.set('showParticipantsBar', 'false');
    url.searchParams.set('showChatButton', 'true');
    url.searchParams.set('showRecordingButton', 'true');
    url.searchParams.set('showFullScreenButton', 'false');

    return url.toString();
}
```

### Theme Customization via URL Parameters

```javascript
const params = new URLSearchParams();
params.set('t', JSON.stringify({
    colors: {
        accent: '#a3e635',        // BuzzTrail green
        accentText: '#1a1a1a',    // Dark text
        background: '#ffffff',     // White background
        mainAreaBg: '#ffffff',     // White video area
        baseText: '#1a1a1a'       // Dark text
    }
}));

conversationUrl += (conversationUrl.includes('?') ? '&' : '?') + params.toString();
```

### Cross-Origin CSS Injection (Best Effort)

```javascript
iframe.addEventListener('load', () => {
    try {
        const style = iframe.contentDocument.createElement('style');
        // Hide leave buttons, participants list, settings
        style.textContent = `
            [data-testid*="leave"],
            button[title*="leave"],
            [class*="leave"],
            [data-testid*="participants"],
            [data-testid*="settings"] {
                display: none !important;
            }
        `;
        iframe.contentDocument.head.appendChild(style);
    } catch (e) {
        // Expected: CORS blocks access to iframe.contentDocument
        // Daily.co uses same-origin policy, so this fails silently
        console.log('CSS injection blocked by CORS (expected)');
    }
});
```

**Note**: CSS injection **will fail** due to CORS. Daily.co URL params are the only reliable way to control UI.

## Conversation Lifecycle Management

### State Machine

```
┌─────────────┐
│   INITIAL   │ (Video playing, button visible)
└──────┬──────┘
       │ User clicks button
       ▼
┌─────────────┐
│  STARTING   │ (Button disabled, "Starting...")
└──────┬──────┘
       │ API creates conversation
       ▼
┌─────────────┐
│   ACTIVE    │ (Iframe embedded, timer running)
└──────┬──────┘
       │ Timer expires OR user ends call
       ▼
┌─────────────┐
│   ENDING    │ (Calling /end API)
└──────┬──────┘
       │ Cleanup complete
       ▼
┌─────────────┐
│  REDIRECT   │ (Navigate to redirectUrl)
└─────────────┘
```

### Timer Implementation

```javascript
startTimer() {
    let remaining = CONFIG.conversationDuration;
    const timer = document.getElementById('buzztrail-timer');

    const tick = () => {
        updateTimer(timer, remaining); // Update UI
        remaining--;

        if (remaining >= 0) {
            this.timerInterval = setTimeout(tick, 1000);
        } else {
            this.endConversation(); // Auto-end when time's up
        }
    };

    tick();
}
```

**Timer UI Updates**:
- `> 30s remaining`: Gray background `#f0f0f0`
- `10-30s remaining`: Yellow warning `#ffc107`
- `< 10s remaining`: Red alert `#dc3545`

### Daily.co Leave Event Detection

```javascript
const messageHandler = (event) => {
    if (event.source === iframe.contentWindow &&
        event.data &&
        typeof event.data === 'object') {

        const { action, type, payload } = event.data;

        // Multiple event types for reliability
        if (action === 'left-meeting' ||
            type === 'left-meeting' ||
            action === 'meeting-ended' ||
            type === 'meeting-ended' ||
            (payload && (payload.action === 'left-meeting' ||
                        payload.action === 'meeting-ended'))) {

            window.removeEventListener('message', messageHandler);
            this.endConversation();
        }
    }
};

window.addEventListener('message', messageHandler);
```

**Why Multiple Event Types?**
- Daily.co iframe emits different event formats depending on:
  - User action (clicking leave vs. closing tab)
  - Daily.co SDK version
  - Browser differences
- Defense-in-depth: Check `action`, `type`, and `payload.action`

### Cleanup Sequence

```javascript
async endConversation() {
    try {
        // 1. Stop timer
        if (this.timerInterval) {
            clearTimeout(this.timerInterval);
            this.timerInterval = null;
        }

        // 2. Call backend to end conversation
        if (this.conversationId && this.proxyUrl) {
            await fetch(`${this.proxyUrl}/conversations/${this.conversationId}/end`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'}
            });
        }
    } finally {
        // 3. Reset state
        this.conversationId = null;
        this.conversationUrl = null;

        // 4. Remove iframe, restore video
        cleanupConversationUI(CONFIG.sectionId);
        createDemoContent(document.getElementById(CONFIG.sectionId));

        // 5. Reapply responsive styles
        if (this.applyResponsiveStyles) {
            this.applyResponsiveStyles();
        }

        // 6. Redirect after 1 second
        setTimeout(() => redirectAfterConversation(), 1000);
    }
}
```

## Wix-Specific Dependencies

### Why Wix Custom Code (Not Embed HTML or Custom Elements)?

**Problem with Wix Embed HTML**:
- Wix wraps embedded code in an `<iframe>`
- Iframes block camera/microphone permissions **even with `allow` attribute**
- This breaks Daily.co video conversations

**Solution: Custom Code Feature**:
- Script runs **directly on the page** (no wrapper iframe)
- Creates Daily.co iframe programmatically with `allow="camera;microphone;autoplay"`
- Camera/microphone permissions work correctly

### Container ID Pattern

Wix generates unique IDs for each element:
- Format: `comp-{random}`
- Example: `comp-mfdtv4rf5`, `comp-mfy88b7h`
- User must manually provide this ID to the script

**Current Approach**:
```javascript
const CONFIG = {
    sectionId: 'comp-mfdtv4rf5', // HARDCODED - must be changed per site
    // ...
};

const section = document.getElementById(CONFIG.sectionId);
```

**Future NPM Package Approach** (from PRD lines 1232-1236):
```html
<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@latest/dist/buzztrail.min.js"
        data-customer-id="acme-corp"
        data-container-id="comp-mfy88b7h">
</script>
```

### DOM Initialization Pattern

```javascript
// Check if already initialized (Wix navigates without full page reload)
if (window.buzztrailWixInitialized) {
    const existing = document.getElementById('comp-mfdtv4rf5');
    if (existing && existing.querySelector('.buzztrail-container')) {
        return; // Already initialized
    }
}
window.buzztrailWixInitialized = true;

// Wait for DOM ready
if (document.readyState !== 'loading') {
    callback();
} else {
    document.addEventListener('DOMContentLoaded', callback);
}

// Additional delay for Wix DOM stability
setTimeout(() => {
    initializeBuzzTrail();
}, CONFIG.initDelay); // 2000ms default
```

**Why the delays?**
1. `DOMContentLoaded`: Standard browser event
2. `setTimeout(2000)`: Wix-specific - ensures Wix's own scripts have finished modifying DOM
3. `500ms` in `init()`: Additional buffer before attaching event listeners

## Responsive Design Implementation

### Breakpoint Strategy

```javascript
applyResponsiveStyles() {
    if (!this.videoPanel) return;

    const w = window.innerWidth;
    const isMobile = w <= 480;
    const isTablet = w <= 768 && w > 480;

    let [width, height, ratio] = ['720px', '405px', '16/9'];

    if (isMobile) {
        [width, height, ratio] = ['280px', '350px', '4/5']; // Portrait
    } else if (isTablet) {
        [width, height, ratio] = ['480px', '270px', '16/9']; // Landscape
    }

    this.videoPanel.style.cssText += `
        width:${width}!important;
        height:${height}!important;
        aspect-ratio:${ratio}!important;
        ...
    `;
}

// Re-apply on resize
window.addEventListener('resize', this.applyResponsiveStyles.bind(this));
```

### Device Targeting

| Device | Width | Dimensions | Aspect Ratio | Use Case |
|--------|-------|------------|--------------|----------|
| Desktop | > 768px | 720×405 | 16:9 | Standard landscape |
| Tablet | 481-768px | 480×270 | 16:9 | Landscape tablets |
| Mobile | ≤ 480px | 280×350 | 4:5 | Portrait phones |

### Critical CSS Patterns

All styles use `!important` to override Wix's aggressive CSS:

```css
#comp-mfdtv4rf5 {
    visibility: visible !important;  /* Wix might hide elements */
    opacity: 1 !important;
    display: block !important;
}
```

**Why `!important` everywhere?**
- Wix injects thousands of CSS rules with high specificity
- User-added Custom Code has low specificity by default
- `!important` ensures BuzzTrail styles win the cascade

## Configuration Structure Analysis

### Current Environment-Based Config

```javascript
// shared-demo.js
export const CONFIG = {
    environment: import.meta.env.VITE_ENVIRONMENT || 'production',
    sectionId: import.meta.env.VITE_SECTION_ID || 'comp-mfdtv4rf5',
    proxyUrl: import.meta.env.VITE_PROXY_URL,
    personaId: import.meta.env.VITE_PERSONA_ID || 'p527c5d8b826',
    replicaId: import.meta.env.VITE_REPLICA_ID || 'rca8a38779a8',
    conversationDuration: parseInt(import.meta.env.VITE_CONVERSATION_DURATION) || 60,
    videoUrl: import.meta.env.VITE_VIDEO_URL || 'https://...',
    buttonText: import.meta.env.VITE_BUTTON_TEXT || 'Talk to Tom',
    redirectUrl: import.meta.env.VITE_REDIRECT_URL || 'https://...',
    dailyApiKey: import.meta.env.VITE_DAILY_API_KEY,
    dailyDomain: import.meta.env.VITE_DAILY_DOMAIN || 'tavusapi.daily.co',
    useRealTavus: import.meta.env.VITE_USE_REAL_TAVUS === 'true',
    initDelay: parseInt(import.meta.env.VITE_INIT_DELAY) || 2000,
    language: import.meta.env.VITE_LANGUAGE,
};
```

### Future Customer-Based Config (Target)

Per PRD lines 1754-1786:

```javascript
BuzzTrail.createConversation('container', {
    // CUSTOMER-SPECIFIC CONFIGURATION
    customerId: 'acme-corp',          // Unique customer identifier
    presenterId: 'p527c5d8b826',      // Tavus presenter/replica ID

    // PLATFORM-SPECIFIC CONFIGURATION
    platform: 'wix',                   // or 'wordpress', 'shopify', 'custom'

    // UI CONFIGURATION
    theme: 'acme-branded',             // Customer-specific theme
    buttonText: 'Talk to Our AI',     // Customizable CTA
    position: 'center-center',         // NEW: Full-screen centered

    // PURE TAVUS - NO OTHER FEATURES
    // (NO voiceEnabled, NO presentationEnabled - just Tavus video)

    // GATING CONFIGURATION (standalone mode for current prod)
    gating: {
        enabled: true,
        mode: 'standalone',              // NOT pre-join (current prod has no pre-join)
        collectInfo: ['name', 'email', 'phone'],
        requiredInfo: ['name', 'email'],
        passToConversation: true,

        // NEW: Language settings (i18n)
        language: 'de',                  // German example (default: 'en')
        customLabels: {                  // Optional: custom translations
            name: 'Name',
            email: 'E-Mail',
            phone: 'Telefon',
            submitButton: 'Gespräch starten'
        }
    }
});
```

## Security Considerations

### Current Security Measures

1. **API Key Protection**:
   - Tavus API key stored in proxy server (Vercel)
   - **NEVER** exposed to browser/client code
   - Daily.co API key only used in local development (not in production builds)

2. **Domain Validation** (not implemented yet):
   - Proxy should validate origin header
   - Only allow requests from authorized domains

3. **Rate Limiting** (proxy-side):
   - Prevent abuse of conversation creation API
   - Likely implemented in proxy server (not visible in client code)

4. **No Sensitive Data in Client**:
   - Configuration values are business logic (persona IDs, URLs)
   - No API keys, secrets, or PII

### Security Gaps to Address in NPM Package

1. **Origin Validation**:
   - NPM package should validate it's running on authorized domain
   - Prevent unauthorized sites from using customer's config
   - Implementation: Check `window.location.hostname` against whitelist

2. **Config Tampering**:
   - Customer config passed via script tag attributes
   - Malicious user could modify in browser DevTools
   - Mitigation: Server-side validation of customerId + presenterId pairing

3. **Iframe Sandbox**:
   - Daily.co iframe has powerful permissions (`camera;microphone;autoplay`)
   - Currently no additional sandboxing
   - Consider: Add `sandbox="allow-same-origin allow-scripts allow-forms"` if possible

4. **Content Security Policy (CSP)**:
   - Wix sites may have strict CSP
   - NPM package must work within CSP constraints
   - Test: `script-src`, `frame-src`, `connect-src` directives

## Module Breakdown for Refactoring

### Proposed Package Structure

```
libs/engage-package/src/
├── core/
│   ├── conversation-manager.ts      # Tavus conversation lifecycle
│   ├── tavus-api.ts                  # API client (via proxy)
│   └── ui-generator.ts               # HTML/CSS generation
├── config/
│   ├── safe-config.ts                # Public configs only (no secrets)
│   ├── schema.ts                     # TypeScript interfaces
│   └── validator.ts                  # Config validation
├── providers/
│   └── tavus-daily.ts                # Tavus via Daily.co (ONLY provider)
├── utils/
│   ├── responsive.ts                 # Responsive design utilities
│   ├── validation.ts                 # Input validation
│   ├── dom-utils.ts                  # DOM manipulation helpers
│   └── logger.ts                     # Compact logging (L object)
├── ui/
│   ├── button.ts                     # CTA button component
│   ├── video-panel.ts                # Avatar video panel
│   ├── iframe-embed.ts               # Daily.co iframe embed
│   └── timer.ts                      # Conversation timer
└── index.ts                          # Main entry point (IIFE export)
```

### Module Mapping from Current Code

| Current Code Block | Future Module | Rationale |
|-------------------|---------------|-----------|
| `generateBuzzTrailCSS()` | `ui-generator.ts::generateCSS()` | Pure function, no state |
| `generateBuzzTrailHTML()` | `ui-generator.ts::generateHTML()` | Pure function, no state |
| `addAutoJoinParams()` | `providers/tavus-daily.ts::buildDailyUrl()` | Daily.co-specific logic |
| `createConversationUI()` | `ui/iframe-embed.ts::createEmbed()` | UI component creation |
| `cleanupConversationUI()` | `ui/iframe-embed.ts::cleanup()` | UI component teardown |
| `updateTimer()` | `ui/timer.ts::update()` | Timer UI update |
| `BuzzTrailDemo` class | `core/conversation-manager.ts::ConversationManager` | Main orchestrator |
| `startConversation()` | `core/tavus-api.ts::createConversation()` | API call |
| `endConversation()` | `core/tavus-api.ts::endConversation()` | API call |
| `CONFIG` object | `config/safe-config.ts::getConfig()` | Configuration loader |
| `L` logger object | `utils/logger.ts::Logger` | Logging utility |
| Responsive styles logic | `utils/responsive.ts::applyResponsive()` | Breakpoint handling |

### Dependencies Between Modules

```
index.ts
  └─> core/conversation-manager.ts
        ├─> core/tavus-api.ts
        │     └─> providers/tavus-daily.ts
        ├─> core/ui-generator.ts
        │     ├─> ui/button.ts
        │     ├─> ui/video-panel.ts
        │     └─> ui/iframe-embed.ts
        ├─> ui/timer.ts
        ├─> config/safe-config.ts
        │     ├─> config/schema.ts
        │     └─> config/validator.ts
        └─> utils/
              ├─> logger.ts
              ├─> responsive.ts
              ├─> dom-utils.ts
              └─> validation.ts
```

### Code Organization Principles

1. **Separation of Concerns**:
   - UI generation separate from business logic
   - API calls separate from state management
   - Configuration separate from implementation

2. **Pure Functions Where Possible**:
   - `generateCSS()`, `generateHTML()` - no side effects
   - `buildDailyUrl()` - URL manipulation only
   - Makes testing easier

3. **Single Responsibility**:
   - Each module has one clear purpose
   - Timer module only handles timer logic
   - API client only makes HTTP requests

4. **Minimal Dependencies**:
   - No external libraries (keep bundle size < 15KB)
   - Use native browser APIs
   - TypeScript for type safety

## Refactoring Plan

### Phase C: Core Module Extraction (Streams C)

**Priority**: High (blocking for other streams)

1. **Extract Configuration System** (`config/`):
   - [ ] Create TypeScript interfaces for all config options
   - [ ] Build config validator (check required fields, types)
   - [ ] Implement default values (fallbacks)
   - [ ] Add schema documentation

2. **Extract Tavus API Client** (`core/tavus-api.ts`):
   - [ ] Move fetch logic for `/conversations/create`
   - [ ] Move fetch logic for `/conversations/{id}/end`
   - [ ] Add error handling wrapper
   - [ ] Add retry logic for transient failures
   - [ ] TypeScript interfaces for request/response

3. **Extract Daily.co Provider** (`providers/tavus-daily.ts`):
   - [ ] Move `addAutoJoinParams()` function
   - [ ] Move Daily.co theme customization
   - [ ] Add URL builder for Daily.co params
   - [ ] Document all Daily.co URL parameters

4. **Extract Logger** (`utils/logger.ts`):
   - [ ] Move `L` object (compact logger)
   - [ ] Add log levels (error, warn, info)
   - [ ] Make production logging configurable
   - [ ] Add optional external logging hooks

### Phase D: UI Module Extraction (Streams D)

**Priority**: High (parallel with Phase C)

1. **Extract UI Generator** (`core/ui-generator.ts`):
   - [ ] Move `generateBuzzTrailCSS()`
   - [ ] Move `generateBuzzTrailHTML()`
   - [ ] Parameterize all hardcoded colors/sizes
   - [ ] Add theme system (color palette, fonts)

2. **Extract Button Component** (`ui/button.ts`):
   - [ ] Create button rendering function
   - [ ] Add button state management (loading, error, ready)
   - [ ] Extract `BUTTON_STYLES` constants
   - [ ] Add hover/active states

3. **Extract Video Panel** (`ui/video-panel.ts`):
   - [ ] Create video panel HTML generator
   - [ ] Add responsive size calculator
   - [ ] Extract breakpoint logic
   - [ ] Add aspect ratio handler

4. **Extract Iframe Embed** (`ui/iframe-embed.ts`):
   - [ ] Move `createConversationUI()`
   - [ ] Move `cleanupConversationUI()`
   - [ ] Add iframe permission builder
   - [ ] Add cross-origin CSS injection (with error handling)

5. **Extract Timer** (`ui/timer.ts`):
   - [ ] Move timer countdown logic
   - [ ] Move timer UI update (`updateTimer()`)
   - [ ] Add configurable warning thresholds
   - [ ] Add timer events (onTick, onWarning, onExpire)

### Phase E: Integration & Testing

**Priority**: Critical (final phase before Streams B)

1. **Create Main Entry Point** (`index.ts`):
   - [ ] Export IIFE function (Wix compatibility)
   - [ ] Expose global `window.BuzzTrail` object
   - [ ] Add auto-init from script tag attributes
   - [ ] Add manual init API

2. **Create Conversation Manager** (`core/conversation-manager.ts`):
   - [ ] Orchestrate API client + UI modules
   - [ ] Implement conversation state machine
   - [ ] Add event listeners (message events, resize)
   - [ ] Add cleanup on navigation/unload

3. **Build & Bundle**:
   - [ ] Configure Vite for IIFE output
   - [ ] Set up Terser with size optimizations
   - [ ] Target < 15KB gzipped
   - [ ] Generate sourcemaps for debugging

4. **Testing Strategy**:
   - [ ] Unit tests for pure functions (generators, validators)
   - [ ] Integration tests for API client (mock fetch)
   - [ ] E2E tests on Wix site (real browser)
   - [ ] Size budget tests (fail if > 15KB)

### Configuration Migrations

**Before (Hardcoded)**:
```javascript
const CONFIG = {
    sectionId: 'comp-mfdtv4rf5',
    personaId: 'p527c5d8b826',
    replicaId: 'rca8a38779a8',
    // ...
};
```

**After (Customer Config)**:
```typescript
interface BuzzTrailConfig {
    customerId: string;           // NEW: 'acme-corp'
    presenterId: string;          // RENAMED: personaId → presenterId
    containerId: string;          // RENAMED: sectionId → containerId

    // Optional with defaults
    apiBaseUrl?: string;          // Default: production proxy
    maxDuration?: number;         // Default: 180s
    buttonText?: string;          // Default: 'Talk to Our AI'
    redirectUrl?: string;         // Default: same page
    theme?: ThemeConfig;          // NEW: color palette
    language?: string;            // NEW: i18n support
}
```

### Security Enhancements to Add

1. **Domain Whitelist Validation**:
```typescript
// config/validator.ts
function validateOrigin(config: BuzzTrailConfig): void {
    const allowedDomains = fetchCustomerDomains(config.customerId);
    const currentDomain = window.location.hostname;

    if (!allowedDomains.includes(currentDomain)) {
        throw new Error(`Unauthorized domain: ${currentDomain}`);
    }
}
```

2. **Config Signature Verification** (future):
```typescript
// Prevent tampering with customerId/presenterId pairing
interface SignedConfig extends BuzzTrailConfig {
    signature: string; // HMAC of config values
}
```

### Responsive Design Refactoring

**Before (inline styles)**:
```javascript
this.videoPanel.style.cssText += 'width:720px!important;height:405px!important;...';
```

**After (utility function)**:
```typescript
// utils/responsive.ts
export function getVideoDimensions(width: number): VideoDimensions {
    if (width <= 480) {
        return { width: 280, height: 350, aspectRatio: '4/5' };
    } else if (width <= 768) {
        return { width: 480, height: 270, aspectRatio: '16/9' };
    } else {
        return { width: 720, height: 405, aspectRatio: '16/9' };
    }
}
```

## Key Technical Decisions

### 1. Why IIFE Output Format?

**Reason**: Wix Custom Code requires a single `<script>` tag
- No module imports (`import/export`)
- No build step on customer side
- Self-contained bundle
- Global namespace pollution minimized with IIFE

### 2. Why Aggressive Minification?

**Reason**: Wix 15KB character limit
- Current production build: ~13KB (87% of limit)
- Terser with `passes: 3` (multiple optimization rounds)
- Remove all console logs in production
- Mangle variable names (but NOT object properties)

### 3. Why Proxy Server Instead of Direct Tavus SDK?

**Reason**: Security + Simplicity
- Keeps Tavus API key server-side
- Avoids CORS issues
- Simpler client code (just `fetch()`, no SDK)
- Easier to add rate limiting/analytics

### 4. Why Not Use React/Vue/Svelte?

**Reason**: Bundle size constraints
- React alone is ~40KB (gzipped) - 2.6x over budget
- Vanilla JS + TypeScript: ~13KB (under budget)
- No virtual DOM needed for simple UI

### 5. Why `!important` on All Styles?

**Reason**: Wix CSS specificity wars
- Wix injects thousands of high-specificity rules
- User Custom Code has low specificity
- `!important` ensures BuzzTrail styles win
- Alternative (CSS-in-JS) would increase bundle size

## Dependencies to Remove

### Current External Dependencies (in shared-demo.js)

**None** - Already pure vanilla JavaScript!

### Vite Build Dependencies (dev-only, not bundled)

- `vite` - Build tool
- `terser` - Minification
- `typescript` - Type checking
- `@nx/js` - Nx integration

**NPM Package Dependencies**: Will remain the same (zero runtime dependencies)

## Risk Analysis

### High Risk Items

1. **Bundle Size Creep**:
   - Current: ~13KB
   - Risk: Adding TypeScript interfaces/classes could increase size
   - Mitigation: Aggressive tree-shaking, regular size audits

2. **Breaking Change to Wix Sites**:
   - Risk: Refactoring could break existing production sites
   - Mitigation: Keep old code working, gradual migration path

3. **Daily.co API Changes**:
   - Risk: URL params could be deprecated
   - Mitigation: Monitor Daily.co changelog, add fallback params

### Medium Risk Items

1. **Configuration Complexity**:
   - Risk: Too many options overwhelm customers
   - Mitigation: Smart defaults, progressive disclosure

2. **Cross-Browser Compatibility**:
   - Risk: Responsive design breaks on some browsers
   - Mitigation: Test on Safari, Firefox, Chrome, Edge

3. **Wix Platform Changes**:
   - Risk: Wix updates break Custom Code feature
   - Mitigation: Monitor Wix forums, maintain test site

### Low Risk Items

1. **TypeScript Migration**:
   - Risk: Minimal (just type annotations, compiles to JS)
   - Mitigation: Test bundled output, not source code

2. **Logger Changes**:
   - Risk: Low (logging is non-critical)
   - Mitigation: Make logging optional/configurable

## Next Steps for Streams C & D

### Stream C: Core Module Extraction (16-24 hours)

**Deliverables**:
- [ ] `config/schema.ts` - TypeScript interfaces
- [ ] `config/safe-config.ts` - Config loader with defaults
- [ ] `config/validator.ts` - Validation logic
- [ ] `core/tavus-api.ts` - API client
- [ ] `providers/tavus-daily.ts` - Daily.co URL builder
- [ ] `utils/logger.ts` - Logging utility
- [ ] Unit tests for pure functions

**Blocking Dependencies**: None (can start immediately)

### Stream D: UI Module Extraction (16-24 hours)

**Deliverables**:
- [ ] `core/ui-generator.ts` - CSS/HTML generators
- [ ] `ui/button.ts` - Button component
- [ ] `ui/video-panel.ts` - Video panel component
- [ ] `ui/iframe-embed.ts` - Iframe embed logic
- [ ] `ui/timer.ts` - Timer component
- [ ] `utils/responsive.ts` - Responsive utilities
- [ ] `utils/dom-utils.ts` - DOM helpers
- [ ] Integration tests

**Blocking Dependencies**: None (can run parallel with Stream C)

### Stream E: Integration & Packaging (8-12 hours)

**Deliverables**:
- [ ] `core/conversation-manager.ts` - Main orchestrator
- [ ] `index.ts` - IIFE entry point
- [ ] Vite build configuration
- [ ] Bundle size optimization
- [ ] E2E tests on Wix
- [ ] Documentation

**Blocking Dependencies**: Streams C & D must complete first

## Build Configuration for NPM Package

### Target Output

```javascript
// dist/buzztrail.min.js (IIFE)
(function() {
    'use strict';

    window.BuzzTrail = {
        init: (config) => { /* Initialize */ },
        createConversation: (containerId, options) => { /* Create instance */ }
    };

    // Auto-init if script tag has data attributes
    const scriptTag = document.currentScript;
    if (scriptTag?.dataset.customerId) {
        // Auto-init from attributes
    }
})();
```

### Vite Configuration (libs/engage-package/)

```typescript
// vite.config.ts
export default defineConfig({
    build: {
        lib: {
            entry: 'src/index.ts',
            name: 'BuzzTrail',
            formats: ['iife'],
            fileName: () => 'buzztrail.min.js'
        },
        minify: 'terser',
        terserOptions: {
            compress: {
                drop_console: true,
                passes: 3,
                unsafe: true
            },
            mangle: {
                toplevel: true,
                properties: false // Don't break object properties
            }
        },
        rollupOptions: {
            output: {
                compact: true
            }
        }
    }
});
```

## Questions for Resolution

1. **Customer Config Storage**: Where should customer configs be stored?
   - Option A: In NPM package code (requires rebuild per customer)
   - Option B: In separate config service (fetch at runtime)
   - **Recommendation**: Option B for scalability

2. **Theme System**: How flexible should theming be?
   - Option A: Preset themes only ('professional', 'modern', etc.)
   - Option B: Full CSS customization (colors, fonts, spacing)
   - **Recommendation**: Option A for MVP, Option B for future

3. **Error Reporting**: Should errors be sent to external service?
   - Option A: Console logging only
   - Option B: Send to Sentry/LogRocket
   - **Recommendation**: Option A for MVP, Option B for production

4. **Language Support**: How many languages to support initially?
   - Current: English, Norwegian
   - Future: German, Spanish, French?
   - **Recommendation**: i18n system in place, start with EN/NO

## Conclusion

The current Wix integration code is well-structured and production-ready, but tightly coupled to specific hardcoded values. The refactoring plan breaks it into clean, testable modules that can be parameterized via customer configuration.

**Critical Success Factors**:
1. Maintain bundle size < 15KB gzipped
2. Preserve camera/microphone permissions (no Wix iframe wrapper)
3. Keep Daily.co integration working (auto-join params)
4. Ensure cross-browser compatibility

**Estimated Timeline**:
- Stream C (Core): 16-24 hours
- Stream D (UI): 16-24 hours
- Stream E (Integration): 8-12 hours
- **Total**: 40-60 hours for complete refactoring

The code is ready for extraction. Proceed to Streams C & D when ready.
