# 🐘 Ellie AI Architecture — Handoff Guide for iScript.care

> **Purpose:** This document provides the complete blueprint for implementing the Ellie the Elephant AI mascot, help platform, and animation system on the iScript.care (US) Base44 app, modeled from the iScript.co.za (SA) implementation.

---

## Table of Contents

1. [Architecture Overview](#1-architecture-overview)
2. [File Structure & Component Map](#2-file-structure--component-map)
3. [Video Asset Library — All 101 Clips](#3-video-asset-library--all-101-clips)
4. [Core Components](#4-core-components)
5. [Performance & Concurrency Management](#5-performance--concurrency-management)
6. [Context-Aware AI Help System](#6-context-aware-ai-help-system)
7. [Reaction Trigger System](#7-reaction-trigger-system)
8. [App-Level Wiring (App.jsx)](#8-app-level-wiring-appjsx)
9. [Design Tokens & Branding](#9-design-tokens--branding)
10. [iScript.care Adaptation Notes (US Jurisdiction)](#10-iscriptcare-adaptation-notes-us-jurisdiction)
11. [Step-by-Step Implementation Checklist](#11-step-by-step-implementation-checklist)

---

## 1. Architecture Overview

Ellie is the AI elephant mascot and custodian of help/support across the entire iScript platform. The system has **five interconnected layers**:

```
┌─────────────────────────────────────────────────────────────┐
│                      APP ROOT (App.jsx)                       │
│  ┌─────────────┐  ┌──────────────────┐  ┌─────────────────┐ │
│  │ EllieProvider│  │EllieFloatingWidget│  │EllieReactionToast│ │
│  │  (Context)   │  │  (Right-side UI)  │  │  (Event Overlay) │ │
│  └──────┬──────┘  └────────┬─────────┘  └────────┬────────┘ │
│         │                    │                     │          │
│         ▼                    ▼                     ▼          │
│  ┌──────────────┐   ┌───────────────┐   ┌────────────────┐  │
│  │EllieContext  │   │EllieSupportChat│  │  EllieMascot   │  │
│  │ (global state│   │  (AI chat UI)  │  │ (video player)  │  │
│  │  + actions)  │   └───────┬───────┘  └───────┬────────┘  │
│  └──────────────┘           │                   │           │
│                             ▼                   ▼           │
│                    ┌────────────────┐  ┌──────────────────┐ │
│                    │ ellieSupportChat│  │ellieVideoGovernor│ │
│                    │ (backend fn)    │  │ (concurrency)    │ │
│                    └───────┬────────┘  └──────────────────┘ │
│                            │                               │
│                            ▼                               │
│                    ┌────────────────┐                      │
│                    │  InvokeLLM     │                      │
│                    │ (Claude/Gemini)│                      │
│                    └────────────────┘                      │
└─────────────────────────────────────────────────────────────┘
```

### Key Design Principles

- **Single mascot instance** — Only ONE Ellie video plays at any time (governor enforces this)
- **Lazy loading** — Videos load only when near viewport (IntersectionObserver)
- **Poster fallback** — Static PNG/WebP poster shown while video buffers or on slow connections
- **Context-aware** — Ellie knows which page the user is on and tailors greetings/responses
- **Channel routing** — Ellie can route conversations to WhatsApp, clinical support, or answer directly via AI
- **Inline only** — Ellie appears as contextual inline components, never as permanent floating distractions (the floating widget is dismissible and subtle)

---

## 2. File Structure & Component Map

```
src/
├── components/
│   ├── mascot/
│   │   ├── ellieActions.js          ← Master manifest: 101 actions → video/poster URLs
│   │   ├── ellieVideoGovernor.js    ← Global concurrency: only 1 video plays at a time
│   │   ├── EllieMascot.jsx          ← Video player component (lazy, poster fallback)
│   │   ├── EllieContext.jsx         ← Global state: currentAction, playAction, hide/show
│   │   └── EllieReactionToast.jsx   ← Event-triggered overlay (success/error/loading)
│   ├── ellie/
│   │   ├── EllieFloatingWidget.jsx  ← Right-side floating mascot + chat trigger
│   │   ├── EllieSupportChat.jsx     ← Context-aware AI chat UI
│   │   ├── elliePageContext.js      ← Page path → greeting + quick replies mapping
│   │   └── WhatsAppHandoff.jsx      ← WhatsApp escalation card (optional)
│   └── loyalty/
│       ├── EllieAIChat.jsx           ← Embedded AI chat (loyalty dashboard)
│       └── EllieTips.jsx             ← Daily health tip card with mascot
├── pages/
│   ├── HelpHub.jsx                  ← /help — full-page support hub with embedded Ellie
│   └── EllieMascotGallery.jsx      ← /ellie-mascot — admin gallery of all 101 clips
base44/
└── functions/
    └── ellieSupportChat/
        └── entry.ts                 ← Backend AI function (InvokeLLM + page knowledge)
```

---

## 3. Video Asset Library — All 101 Clips

All 101 Ellie video clips are hosted on the Base44 CDN and are **publicly accessible**. iScript.care can reference these URLs directly — no re-upload needed.

### URL Pattern

```
https://base44.app/api/apps/69dcbca409651991f223fd0e/files/mp/public/69dcbca409651991f223fd0e/{HASH}_ellie-{action}-{variant}.webm
```

### Phase Breakdown

| Phase | Description | Clip Count |
|-------|-------------|------------|
| Phase 1 | Core Actions (wave, idle, think, celebrate, point) | ~15 |
| Phase 2 | Vertical-Specific (scale, heart, flower, flex, meditate, shield) | ~8 |
| Phase 3 | Dashboard & Onboarding (chat listen/talk, onboarding steps) | ~10 |
| Phase 4A | Physical/Dynamic Movements (jump, spin, drag, push, gallop) | ~15 |
| Phase 4B | Emotional Expressions (sympathetic, scared, relieved, blush) | ~12 |
| Phase 4C | Trunk Gestures & UI Signals (thumbs-up, nod, wave, trumpet) | ~12 |
| Phase 4D | Playful & Character Moments (peek-a-boo, splash, stretch) | ~12 |
| Phase 5 | Loveable Gestures — Empathy & Exaggerated (27 clips) | 27 |
| **Total** | | **101** |

### How to Get All URLs

The complete manifest with all 101 video URLs, poster URLs, loop settings, durations, and context tags is in:

**`src/components/mascot/ellieActions.js`**

Each entry has this structure:
```javascript
'action-name': {
  label: 'Human-readable label',
  videoUrl: 'https://base44.app/api/apps/.../ellie-action-01.webm',
  posterUrl: 'https://base44.app/api/apps/.../ellie-action-01-poster.png',
  loop: false,           // true = loops infinitely, false = plays once
  duration: 4,           // seconds (used for auto-hide timing)
  fallbackMood: 'happy', // SVG mood (legacy, not used — poster replaces SVG)
  description: 'When to use this animation',
  contexts: ['homepage-hero', 'welcome'],  // Tags for context-based preloading
}
```

### Key Actions for US Site

| Action | Use Case | Video URL |
|--------|----------|-----------|
| `wave-happy` | Homepage hero, welcome | `.../9ad1a45d9_ellie-wave-happy-01.webm` |
| `idle-content` | Default resting state (loops) | `.../5a7c26603_ellie-idle-content-01.webm` |
| `think-curious` | AI processing, LLM loading | `.../7a83a1383_ellie-think-curious-01.webm` |
| `celebrate-joyful` | Payment success, booking confirmed | `.../d1164bce4_ellie-celebrate-joyful-01.webm` |
| `magnifying-glass-investigate` | AI chat "typing" indicator | `.../ellie-magnifying-glass-investigate-01.webm` |
| `ears-grow-huge-listening` | User typing in chat input | `.../ellie-ears-grow-huge-listening-01.webm` |
| `deep-listening` | Ellie processing user message | (Phase 5) |
| `proud-tears-of-joy` | Health milestone achieved | (Phase 5) |
| `run-hug-missed-you` | Returning user after absence | (Phase 5) |

> **Important:** Copy the **entire** `ellieActions.js` file to iScript.care verbatim. The video URLs are absolute and will work cross-domain.

---

## 4. Core Components

### 4.1 EllieMascot.jsx — Video Player

The foundational component. Renders a transparent WebM video with poster fallback.

```jsx
import EllieMascot from '@/components/mascot/EllieMascot';

// Basic usage
<EllieMascot action="wave-happy" size="md" />

// Floating (dismissible)
<EllieMascot action="celebrate-joyful" size="lg" position="bottom-right" dismissible />

// Inline in a card
<EllieMascot action="idle-content" size={96} />
```

**Props:**
- `action` (string) — Action name from `ellieActions.js` manifest (default: `'idle-content'`)
- `size` (`'sm'|'md'|'lg'` | number) — Visual size (default: `'md'` = 120px)
- `position` (`'static'|'bottom-right'|'bottom-left'|'top-right'|'top-left'`) — For floating mascot
- `autoPlay` (bool) — Auto-play when visible (default: `true`)
- `loop` (bool) — Override loop behavior from manifest
- `onClick` / `onEnded` — Callbacks
- `dismissible` (bool) — Show dismiss button when floating

**Key behaviors:**
- **IntersectionObserver** — Only loads/plays video when visible in viewport
- **Slow connection detection** — Falls back to poster image on 2G/slow-3G/save-data
- **Preload strategy** — `preload="auto"` when visible, `preload="none"` when off-screen
- **Poster frame** — PNG/WebP poster shown while video buffers, fades to video when ready

### 4.2 ellieVideoGovernor.js — Concurrency Manager

Ensures only ONE Ellie video decodes at any time. Critical for mobile performance.

```javascript
// Register a video when it mounts
const id = registerEllieVideo(videoRef.current, action);

// When this video starts playing, pause all others
pauseAllOtherEllieVideos(id);

// Unregister on unmount
unregisterEllieVideo(id);
```

**Why this matters:** Without the governor, a page with 5 Ellie mascots would try to decode 5 WebM streams simultaneously, causing frame drops and battery drain on low-end devices.

### 4.3 EllieContext.jsx — Global State Provider

Wraps the entire app. Provides `playAction()`, `hide()`, `show()`, and `preloadContext()`.

```jsx
// In App.jsx:
import { EllieProvider } from '@/components/mascot/EllieContext';

<EllieProvider>
  <Router>...</Router>
</EllieProvider>
```

```jsx
// In any component:
import { useEllie } from '@/components/mascot/EllieContext';
const { playAction } = useEllie();

// Trigger a one-time animation (auto-reverts to idle)
playAction('celebrate-joyful');

// With custom revert
playAction('proud-tears-of-joy', { revertTo: 'idle-content', autoRevert: true });
```

### 4.4 EllieReactionToast.jsx — Event-Triggered Overlay

A global overlay that shows Ellie briefly when platform events occur (payment success, errors, loading, etc.).

```jsx
// In App.jsx (rendered once at root):
import EllieReactionToast from '@/components/mascot/EllieReactionToast';
<EllieReactionToast />
```

```jsx
// In any component:
import { useEllieReaction } from '@/components/mascot/EllieReactionToast';
const { triggerReaction } = useEllieReaction();

triggerReaction('payment-success');
triggerReaction('processing', { message: 'Analyzing your assessment...' });
triggerReaction('loyalty-earned', { message: '50 Ellie points earned!' });
triggerReaction(null); // hide
```

**Reaction Map** (excerpt — see `EllieReactionToast.jsx` for full list):
| Event Type | Animation |
|------------|-----------|
| `success` | `fist-pump` |
| `payment-success` | `spin-joyful` |
| `booking-confirmed` | `excited-squeal` |
| `processing` | `drag-heavy` |
| `thinking` | `think-curious` |
| `validation-error` | `frustrated-stomp` |
| `payment-failed` | `sympathetic-caring` |
| `loyalty-earned` | `dance-groove-loop` |
| `privacy-reassurance` | `shh-secret-wink` |
| `deep-listening` | `ears-grow-huge-listening` |
| `returning-after-absence` | `run-hug-missed-you` |

---

## 5. Performance & Concurrency Management

### 5.1 Video Concurrency Governor

**File:** `src/components/mascot/ellieVideoGovernor.js`

Only one Ellie video plays at a time. When a new one starts, all others are paused. This prevents:
- Multiple simultaneous WebM decodes (kills low-end mobile)
- Battery drain from background video
- Memory pressure from multiple video elements

### 5.2 Lazy Loading Strategy

EllieMascot uses `IntersectionObserver` with `threshold: 0.1`:
- Video `src` is always set, but `preload="none"` when off-screen
- When scrolled into view, `preload` switches to `"auto"` and playback starts
- When scrolled out, video pauses

### 5.3 Slow Connection Fallback

```javascript
const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
const isSlow = conn.effectiveType === '2g' || conn.effectiveType === 'slow-2g' ||
               conn.saveData === true || conn.downlink < 1.5;
// If slow → show poster image only, skip video
```

### 5.4 Poster Frame Strategy

Every video has a corresponding poster image (PNG or WebP). The poster:
- Shows instantly while the WebM loads (perceived performance)
- Fades to the video via `opacity` transition when `onLoadedData` fires
- Serves as permanent fallback on slow connections (video element is not rendered)

### 5.5 Preload Hints

EllieContext can preload videos for a specific page context:
```javascript
const { preloadContext } = useEllie();
preloadContext('homepage-hero'); // Creates <link rel="preload"> tags
```

---

## 6. Context-Aware AI Help System

### 6.1 How It Works

1. **EllieFloatingWidget** renders on every page (right side, dismissible)
2. When clicked, Ellie plays `celebrate-joyful` then opens the chat panel
3. **EllieSupportChat** sends the user's message + current page path to the backend
4. **`ellieSupportChat` backend function** uses `InvokeLLM` (Claude) with a system prompt that includes page-specific knowledge
5. The AI returns a structured JSON response: `{ reply, routing, navigate_url, quick_replies, whatsapp_message }`
6. If routing is `whatsapp` or `clinical`, the UI shows handoff cards

### 6.2 Backend Function: `ellieSupportChat/entry.ts`

**Key architecture:**
- `PAGE_KNOWLEDGE` array — Maps URL patterns to rich page descriptions
- Each entry has: `match` (regex), `title`, `summary`, `keyDetails`, `faqs`
- The system prompt injects the matched page knowledge so Ellie knows exactly what's on the current page
- `response_json_schema` forces structured output with routing logic

**System prompt structure:**
```
You are Ellie, the AI elephant custodian of iScript Health's Help & Support platform.

CONTEXT:
- Current page: {current_page}
- User role: {user_role}
- User: {user_name} ({user_email})

CURRENT PAGE CONTEXT — "{title}":
What this page is: {summary}
Key details: {keyDetails}
Common questions about this page: {faqs}

CRITICAL: You are on the page above RIGHT NOW. Answer in context of THIS page.

YOUR ROLE:
1. Answer questions directly (in-app AI chat)
2. Route to WhatsApp for human agent escalation
3. Route to Clinical/Medical support queue
4. Suggest navigation to relevant pages
5. Provide training guidance for providers

ROUTING RULES:
- "clinical": Medical symptoms, prescription advice, emergencies
- "whatsapp": Human agent requests, complex billing disputes
- "training": How-to questions, navigation help
- "none": Can answer directly
```

**Response schema (JSON):**
```json
{
  "reply": "Ellie's response (2-4 sentences, warm, concise)",
  "routing": "none|whatsapp|clinical|training",
  "navigate_url": "/some-page or null",
  "quick_replies": ["Button 1", "Button 2"],
  "whatsapp_message": "Pre-filled WhatsApp message (when routing=whatsapp)"
}
```

### 6.3 Page Context Map: `elliePageContext.js`

Maps URL paths to context-aware greetings + quick replies. Used for the initial chat message.

```javascript
// Example entry:
{
  match: /^\/weight-loss/,
  greeting: "Interested in our weight-loss program? 🐘 I can explain the GLP-1 journey, check eligibility, or talk pricing.",
  quickReplies: ['How does GLP-1 work?', 'Am I eligible?', 'See pricing'],
}
```

### 6.4 Floating Widget: `EllieFloatingWidget.jsx`

- Renders on every page EXCEPT `/help` (which has the full embedded chat)
- Ellie "breathes" (idle-content loop) at bottom-right, elevated position
- Every 25 seconds, shows a hint bubble + waves to draw attention
- Click → plays `celebrate-joyful` → opens chat panel
- Dismissible (sessionStorage) → shows a small "Help" pill to bring Ellie back
- Tracks current page + authenticated user for context

---

## 7. Reaction Trigger System

### 7.1 How to Wire Reactions

Import the hook and call `triggerReaction()` at key moments:

```jsx
import { useEllieReaction } from '@/components/mascot/EllieReactionToast';
const { triggerReaction } = useEllieReaction();

// Payment success
triggerReaction('payment-success', { message: 'Payment successful!' });

// AI processing
triggerReaction('processing', { message: 'Analyzing your assessment...' });
// ... later when done:
triggerReaction('success', { message: 'Analysis complete!' });

// Loyalty points
triggerReaction('loyalty-earned', { message: '50 Ellie points earned!' });

// POPIA/privacy consent
triggerReaction('privacy-reassurance', { message: 'Your data is protected' });

// Clear
triggerReaction(null);
```

### 7.2 Recommended Trigger Points

| Page/Event | Reaction Key | Animation |
|------------|-------------|-----------|
| Payment success page | `payment-success` | `spin-joyful` |
| Booking confirmed | `booking-confirmed` | `excited-squeal` |
| GLP-1 assessment complete | `health-milestone-major` | `proud-tears-of-joy` |
| POPIA/privacy consent | `privacy-reassurance` | `shh-secret-wink` |
| AI analysis loading | `deep-listening` | `ears-grow-huge-listening` |
| User types in chat | `deep-listening` | (Phase 5 listening) |
| Returning user (30+ min absence) | `returning-after-absence` | `run-hug-missed-you` |
| Loyalty points earned | `loyalty-earned` | `dance-groove-loop` |
| Claim approved | `claim-approved` | `relieved-sigh` |
| Error occurred | `recoverable-error` | `stumble-recover` |
| Payment failed | `payment-failed` | `sympathetic-caring` |
| Doctor came online | `doctor-online` | `ear-flap-excited` |

---

## 8. App-Level Wiring (App.jsx)

### 8.1 Provider Wrapping

Wrap your entire app with `EllieProvider`:

```jsx
import { EllieProvider } from '@/components/mascot/EllieContext';

function App() {
  return (
    <EllieProvider>
      <AuthProvider>
        <QueryClientProvider>
          <Router>
            <AuthenticatedApp />
          </Router>
          <Toaster />
        </QueryClientProvider>
      </AuthProvider>
    </EllieProvider>
  );
}
```

### 8.2 Global Components

Render these ONCE at the app root (inside the router, after `<Routes>`):

```jsx
function AuthenticatedApp() {
  return (
    <>
      <ScrollToTop />
      <Routes>
        {/* ... all your routes ... */}
      </Routes>
      
      {/* ── Ellie Global Components ── */}
      <EllieFloatingWidget />    {/* Right-side floating mascot + chat */}
      <EllieReactionToast />     {/* Event-triggered overlay */}
    </>
  );
}
```

### 8.3 Route for Gallery (Admin)

```jsx
import EllieMascotGallery from './pages/EllieMascotGallery';

<Route path="/ellie-mascot" element={<EllieMascotGallery />} />
```

### 8.4 Route for Help Hub

```jsx
import HelpHub from './pages/HelpHub';

<Route path="/help" element={<HelpHub />} />
```

---

## 9. Design Tokens & Branding

### 9.1 Colors (iScript Brand)

```css
/* In src/index.css :root */
--iscript-lime: #A3CD3F;        /* Primary — Ellie's accent color */
--iscript-blue: #00659E;        /* Secondary — clinical/professional */
--iscript-grey: #535456;        /* Text */
--iscript-light-green: #f0f7e0; /* Backgrounds */
--iscript-light-blue: #e6f2fa;  /* Backgrounds */
```

```javascript
// In tailwind.config.js
colors: {
  lime: { DEFAULT: '#A3CD3F', light: '#f0f7e0', dark: '#7fa030' },
  'iscript-blue': { DEFAULT: '#00659E', light: '#e6f2fa', dark: '#004f7a' },
  'iscript-grey': { DEFAULT: '#535456', light: '#f4f4f4' },
}
```

### 9.2 Fonts

```css
@import url('https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=Inter:wght@300;400;500;600&display=swap');

/* Headings */
h1, h2, h3, h4, h5, h6 {
  font-family: 'Instrument Sans', sans-serif;
}

/* Body */
body {
  font-family: 'Inter', sans-serif;
}
```

### 9.3 Key CSS Utilities

```css
/* Glassmorphism card */
.glass-card {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(163, 205, 63, 0.15);
}

/* Primary buttons */
.btn-lime {
  background: #A3CD3F;
  color: white;
  font-family: 'Instrument Sans', sans-serif;
  font-weight: 600;
  border-radius: 9999px;
  padding: 14px 28px;
  box-shadow: 0 8px 24px rgba(163,205,63,0.3);
}
```

### 9.4 Logo

```
https://media.base44.com/images/public/69dcbca409651991f223fd0e/b383128db_HorizontaliScriptLogo-WithDevice-Notagline.png
```

---

## 10. iScript.care Adaptation Notes (US Jurisdiction)

### 10.1 What Stays the Same

- **All 101 video clips** — Use the same Base44 CDN URLs (they're public)
- **All component code** — Copy verbatim: EllieMascot, EllieContext, EllieReactionToast, EllieFloatingWidget, EllieSupportChat, ellieVideoGovernor, ellieActions.js, elliePageContext.js
- **Backend function** — `ellieSupportChat/entry.ts` (update PAGE_KNOWLEDGE for US pages)
- **Design tokens** — Same lime/blue branding
- **Performance architecture** — Governor, lazy loading, poster fallback, slow-connection detection

### 10.2 What Needs to Change

| Area | SA (iScript.co.za) | US (iScript.care) |
|------|---------------------|---------------------|
| Currency | ZAR (R390) | USD ($39 or similar) |
| Medical regulator | HPCSA | State medical board / DEA |
| Data protection | POPIA | HIPAA |
| Emergency number | 10177 | 911 |
| Pharmacy partner | Velobiotics / Medipost | US pharmacies (e.g. CVS, Walgreens) |
| Medical aid | Medical Aid schemes | Insurance / Medicare / Medicaid |
| Claims bureau | MediKredit | NCPDP / Change Healthcare |
| GLP-1 regulator | SAHPRA | FDA |
| WhatsApp number | +27 82 333 3333 | US number |
| ID verification | SA ID (13 digits) | SSN / State ID |
| Languages | English + 11 SA languages | English (Spanish optional) |

### 10.3 PAGE_KNOWLEDGE Updates

In `ellieSupportChat/entry.ts`, update the `PAGE_KNOWLEDGE` array to match iScript.care's page routes and US-specific details:
- Replace `R390` with USD pricing
- Replace `HPCSA` with state medical board
- Replace `POPIA` with `HIPAA`
- Replace `10177` with `911`
- Replace `SAHPRA` with `FDA`
- Update page routes to match iScript.care's URL structure

### 10.4 elliePageContext.js Updates

Update the `PAGE_CONTEXT_MAP` array:
- Change greetings to reference US services
- Update quick replies for US navigation
- Change WhatsApp number

### 10.5 WhatsApp Handoff

Update the WhatsApp number in `EllieSupportChat.jsx`:
```javascript
// Change from:
window.open(`https://wa.me/27823333333?text=...`, '_blank');
// To US number:
window.open(`https://wa.me/1XXXXXXXXXX?text=...`, '_blank');
```

---

## 11. Step-by-Step Implementation Checklist

### Phase 1: Copy Core Files (Day 1)

- [ ] Copy `src/components/mascot/ellieActions.js` (verbatim — contains all 101 video URLs)
- [ ] Copy `src/components/mascot/ellieVideoGovernor.js` (verbatim)
- [ ] Copy `src/components/mascot/EllieMascot.jsx` (verbatim)
- [ ] Copy `src/components/mascot/EllieContext.jsx` (verbatim)
- [ ] Copy `src/components/mascot/EllieReactionToast.jsx` (verbatim)
- [ ] Copy `src/components/ellie/EllieFloatingWidget.jsx` (verbatim)
- [ ] Copy `src/components/ellie/EllieSupportChat.jsx` (verbatim)
- [ ] Copy `src/components/ellie/elliePageContext.js` (update greetings for US)
- [ ] Copy `src/components/ellie/WhatsAppHandoff.jsx` (update phone number)

### Phase 2: Copy Backend Function (Day 1)

- [ ] Copy `base44/functions/ellieSupportChat/entry.ts`
- [ ] Update `PAGE_KNOWLEDGE` array for iScript.care routes & US details
- [ ] Update system prompt (HPCSA→state board, POPIA→HIPAA, 10177→911, ZAR→USD)
- [ ] Update navigation URLs to match iScript.care routes

### Phase 3: Copy Supporting Components (Day 1)

- [ ] Copy `src/components/loyalty/EllieAIChat.jsx` (embedded AI chat)
- [ ] Copy `src/components/loyalty/EllieTips.jsx` (daily tip card)
- [ ] Copy `src/pages/EllieMascotGallery.jsx` (admin gallery)
- [ ] Copy `src/pages/HelpHub.jsx` (full-page help center)

### Phase 4: Wire Into App.jsx (Day 1)

- [ ] Wrap app with `<EllieProvider>`
- [ ] Add `<EllieFloatingWidget />` after `<Routes>`
- [ ] Add `<EllieReactionToast />` after `<Routes>`
- [ ] Add routes: `/ellie-mascot` (gallery), `/help` (help hub)

### Phase 5: Design Tokens (Day 1)

- [ ] Copy color tokens from `src/index.css` (lime, blue, grey)
- [ ] Copy font imports (Instrument Sans, Inter)
- [ ] Copy Tailwind config color mappings
- [ ] Add CSS utilities (glass-card, btn-lime, etc.)

### Phase 6: Test & Verify (Day 2)

- [ ] Verify all 101 clips load on the gallery page (`/ellie-mascot`)
- [ ] Test floating widget on homepage (should breathe, wave on click, open chat)
- [ ] Test context-aware chat (ask page-specific questions)
- [ ] Test WhatsApp routing
- [ ] Test reaction triggers (payment success, etc.)
- [ ] Test on mobile (verify concurrency governor works)
- [ ] Test on slow connection (verify poster fallback)
- [ ] Lighthouse audit (verify no performance regression)

### Phase 7: US Adaptation (Day 2-3)

- [ ] Update all `PAGE_KNOWLEDGE` entries for US context
- [ ] Update `elliePageContext.js` greetings for US
- [ ] Update WhatsApp number
- [ ] Update currency (ZAR→USD)
- [ ] Update regulator references (HPCSA→state board, SAHPRA→FDA)
- [ ] Update privacy references (POPIA→HIPAA)
- [ ] Update emergency number (10177→911)
- [ ] Update routing rules for US pages

---

## Appendix A: Complete File List to Copy

```
src/components/mascot/ellieActions.js          ← 101 video URLs manifest
src/components/mascot/ellieVideoGovernor.js     ← Concurrency manager
src/components/mascot/EllieMascot.jsx          ← Video player component
src/components/mascot/EllieContext.jsx         ← Global state provider
src/components/mascot/EllieReactionToast.jsx   ← Event overlay + hook
src/components/ellie/EllieFloatingWidget.jsx   ← Floating mascot + chat
src/components/ellie/EllieSupportChat.jsx      ← AI chat UI
src/components/ellie/elliePageContext.js       ← Page→greeting map
src/components/ellie/WhatsAppHandoff.jsx      ← WhatsApp escalation card
src/components/loyalty/EllieAIChat.jsx         ← Embedded AI chat
src/components/loyalty/EllieTips.jsx            ← Daily tip card
src/pages/EllieMascotGallery.jsx               ← Admin clip gallery
src/pages/HelpHub.jsx                           ← Full-page help center
base44/functions/ellieSupportChat/entry.ts     ← Backend AI function
```

## Appendix B: Dependencies

All required npm packages (already in the Base44 default install):
- `react` (^18.2.0)
- `framer-motion` (^11.16.4) — for chat panel animations
- `lucide-react` (^0.475.0) — for icons
- `@base44/sdk` — for InvokeLLM backend calls

No additional packages needed.

## Appendix C: Key Integration Points

### Where Ellie Appears

1. **Floating widget** — Bottom-right of every page (except `/help`)
2. **Help Hub** — Full embedded chat at `/help`
3. **Patient Dashboard** — Embedded chat in the Ellie/loyalty tab
4. **Reaction toasts** — Brief overlays on events (payment, booking, errors)
5. **Inline mascots** — Contextual appearances in tips, consent pages, GLP-1 analysis

### Where Ellie Does NOT Appear

- Footer/header hero positions (removed by design — too distracting)
- Login page (platform-managed)
- As a permanent fixed mascot that can't be dismissed

---

**End of Handoff Document**

For questions about this architecture, contact the iScript.co.za development team.

🐘 *Ellie — your wise elephant friend, making healthcare accessible.*
