# BUILD SEQUENCE

## How To Use This Document
- Each task is atomic (can be done in one session)
- Check off tasks as completed
- Each task has acceptance criteria
- Run tests after each task
- Commit after each task with message: "Phase X Task X.X: [description]"

When starting a new session, tell Claude Code:
> "Read docs/BUILD-SEQUENCE.md and continue from the first unchecked task."

---

## Phase 1: Fix Navigation (Day 1)

### Task 1.1: Update BottomNav ✅
- [x] File: `admin/src/components/BottomNav.jsx`
- [x] Change nav items from: [Home] [Calls] [Activate] [Inbox] [Leads]
- [x] Change nav items to: [Home] [Calls] [Inbox] [Scripts] [More]
- [x] Update icons: Home=Home, Calls=Phone, Inbox=MessageSquare, Scripts=FileText, More=MoreHorizontal
- [x] Test: All 5 nav items visible on mobile
- [x] Test: All routes work when tapped
- [x] Acceptance: Can tap each nav item, correct page loads

### Task 1.2: Create More Page ✅
- [x] File: `admin/src/pages/More.jsx`
- [x] Create sections with headers:
  - Sales Tools (Scripts, Objections, Script Stats)
  - Leads & Pipeline (All Leads, Search, Import from Sheet)
  - Activation (Activation Funnel, Stuck Leads, Bulk Actions)
  - Analytics & AI (Weekly Insights, SMS Stats, Call Stats, Activity Log)
  - Settings (Platform Sync, Voice Commands, Phone Settings, Profile)
- [x] Each item shows: icon, label, count/status badge (dynamic where possible)
- [x] Each item links to correct route
- [x] Style: Grouped sections with slate-100 bg, white cards, rounded-xl
- [x] Test: All links navigate correctly
- [x] Test: Dynamic counts load from API where available
- [x] Acceptance: Can access every feature in the app from More page

### Task 1.3: Add More Route ✅
- [x] File: `admin/src/App.jsx`
- [x] Add import: `import More from './pages/More'`
- [x] Add route: `/more` → `<More />`
- [x] Wrap in `<ProtectedRoute>` and `<AppLayout>`
- [x] Test: `/more` loads correctly from browser URL
- [x] Test: More page accessible from bottom nav
- [x] Acceptance: More page accessible from nav and direct URL

---

## Phase 2: Command Center Dashboard (Days 2-3)

### Task 2.1: Create AIStrategyCard Component ✅
- [x] File: `admin/src/components/dashboard/AIStrategyCard.jsx`
- [x] Fetch from `/api/dashboard/strategy`
- [x] Display: focus area title, reasoning (1-2 sentences), target count, potential value
- [x] Include CTA button: "START [FOCUS AREA] BLITZ"
- [x] Loading state with skeleton
- [x] Style: gradient bg (violet-600 to purple-600), white text
- [x] Test: Card renders with API data
- [x] Test: CTA button navigates to relevant page
- [x] Acceptance: Shows today's AI strategy with actionable button

### Task 2.2: Create Priority Action API Endpoint ✅
- [x] File: `src/routes/dashboard.js`
- [x] Endpoint: `GET /api/dashboard/priority-action`
- [x] Logic:
  - Get top 1 lead from call ranking (score, callbacks, hot referrals)
  - Get conversion probability for that lead
  - Get similar wins for that lead
  - Get company research if available
  - Generate AI draft message/script opener
- [x] Returns: `{ lead, probability, similarWins, companyIntel, suggestedScript }`
- [x] Test: Endpoint returns expected data structure
- [x] Test: Works with lead that has full data
- [x] Test: Works with lead that has minimal data (graceful fallback)
- [x] Acceptance: Single API call provides all data for priority card

### Task 2.3: Create PriorityActionCard Component ✅
- [x] File: `admin/src/components/dashboard/PriorityActionCard.jsx`
- [x] Fetch from `/api/dashboard/priority-action`
- [x] Display:
  - Lead name, company, score badge (with fire emoji if >80)
  - "WHY NOW" section: conversion probability, reasons (called you, similar to X, etc.)
  - "INTEL" section: 3-4 bullet points from research
  - "SCRIPT" section: personalized opener with copy button
- [x] Actions: [Call Now] (primary blue), [Skip], [SMS Instead], [Later]
- [x] Loading state with skeleton
- [x] Style: white card, emerald accent for conversion %, cyan for intel
- [x] Test: Card renders with full API data
- [x] Test: Call Now initiates call (via CallContext)
- [x] Test: Skip loads next priority lead
- [x] Acceptance: Shows #1 priority with all AI insights, Call button works

### Task 2.4: Create Slipping Leads API Endpoint ✅
- [x] File: `src/routes/dashboard.js`
- [x] Endpoint: `GET /api/dashboard/slipping`
- [x] Logic:
  - Find leads where last_contact_at is NULL or > 7 days ago
  - Filter to score > 50 (was hot)
  - Limit to 10
  - Calculate combined potential value
- [x] Returns: `{ leads: [...], count, totalPotential }`
- [x] Test: Returns correct leads
- [x] Test: Returns empty array if no slipping leads
- [x] Acceptance: Endpoint filters correctly

### Task 2.5: Create SlippingLeads Component ✅
- [x] File: `admin/src/components/dashboard/SlippingLeads.jsx`
- [x] Fetch from `/api/dashboard/slipping`
- [x] Display: count of slipping leads, combined potential value
- [x] Show warning icon and amber styling
- [x] Action: "Send 'Checking In' to All" button
- [x] On click: calls bulk SMS endpoint with template
- [x] Loading and success states
- [x] Test: Shows correct count
- [x] Test: Bulk SMS sends successfully
- [x] Acceptance: One tap sends SMS to all slipping leads

### Task 2.6: Create RepliesWaiting Component ✅
- [x] File: `admin/src/components/dashboard/RepliesWaiting.jsx`
- [x] Fetch from `/api/sms/conversations/prioritized?limit=3`
- [x] Display top 3 unread with:
  - Lead name, time ago
  - Message preview (truncated)
  - AI triage category badge (High Intent, Callback, Question)
  - Quick action buttons per type
- [x] Actions: [Call] for high intent, [Schedule] for callbacks, [Send Template] for questions
- [x] Link to full inbox at bottom
- [x] Test: Shows unread messages with correct categories
- [x] Test: Quick actions work
- [x] Acceptance: Can respond to message with one tap

### Task 2.7: Create TodayStats Component ✅
- [x] File: `admin/src/components/dashboard/TodayStats.jsx`
- [x] Fetch from `/api/dashboard/stats` (already exists)
- [x] Display in 4-column grid: Calls (X/15), Conversions, SMS Sent, Streak
- [x] Show progress toward daily goal for calls
- [x] Fire emoji for active streak
- [x] Compact design, fits in one row
- [x] Test: Stats load correctly
- [x] Acceptance: Clear progress indicators

### Task 2.8: Rebuild Dashboard Page ✅
- [x] File: `admin/src/pages/Dashboard.jsx`
- [x] New structure (top to bottom):
  1. Greeting header with date
  2. AIStrategyCard
  3. PriorityActionCard
  4. RepliesWaiting
  5. SlippingLeads (only if count > 0)
  6. TodayStats
- [x] Remove: Wisdom quote card, Marketplace Health, Pipeline Value, AI Insights widget, Recent Wins
- [x] Keep: Basic greeting, stats
- [x] Test: Dashboard loads with new components
- [x] Test: All cards fetch and render correctly
- [x] Acceptance: Dashboard shows actionable items, not just data

---

## Phase 3: Lead Profile Rebuild (Days 4-5)

### Task 3.1: Create LeadProfileHeader Component ✅
- [x] File: `admin/src/components/LeadProfileHeader.jsx`
- [x] Props: `lead` object
- [x] Display:
  - Name (large, bold)
  - Company (medium, slate)
  - Phone number (tappable, calls on tap)
  - Score badge with color coding (red <40, amber 40-70, green >70)
  - Conversion probability percentage
- [x] Compact design (not full screen height)
- [x] Style: white bg, subtle border-b
- [x] Test: Header shows all key info
- [x] Test: Phone number initiates call on tap
- [x] Acceptance: Phone tappable, all info visible without scroll

### Task 3.2: Create AIRecommendationCard Component ✅
- [x] File: `admin/src/components/AIRecommendationCard.jsx`
- [x] Props: `leadId`
- [x] Fetch from: `/api/activation/diagnose/:leadId` (stage diagnosis)
- [x] Fetch from: `/api/ai/similar-wins/:leadId`
- [x] Display:
  - Current stage → Next stage indicator
  - "ACTION" section: AI recommended action
  - "SIMILAR WIN" section: reference to successful conversion
  - "SCRIPT" section: personalized script with copy button
- [x] Loading skeleton
- [x] Style: violet/purple gradient header, white body
- [x] Test: Card shows AI recommendation
- [x] Test: Copy button works for script
- [x] Acceptance: Clear action with supporting context

### Task 3.3: Create IntelSummaryCard Component ✅
- [x] File: `admin/src/components/IntelSummaryCard.jsx`
- [x] Props: `leadId`, `companyName`
- [x] Fetch from: `/api/ai/live-intel/:leadId` (already exists, returns company + person intel)
- [x] Display:
  - 4-5 key intel bullet points
  - Company info (size, industry, location)
  - Person info (job title, tenure)
  - Previous objections if any
- [x] "View Full Research" link to expand
- [x] Loading skeleton
- [x] Test: Shows intel summary
- [x] Test: Expand shows full details
- [x] Acceptance: Key facts visible, can expand for more

### Task 3.4: Create LeadActionBar Component ✅
- [x] File: `admin/src/components/LeadActionBar.jsx`
- [x] Props: `lead`, `onCall`, `onSms`, `onCallback`
- [x] Fixed position at bottom of screen
- [x] Display 3 buttons:
  - SMS (left, secondary)
  - Call (center, primary, large) - contextual label with best time
  - Callback (right, secondary)
- [x] Call button shows "Call {firstName}" or "Best: {time range}"
- [x] Style: white bg, shadow-up, safe-area padding
- [x] Test: Bar visible when scrolling page
- [x] Test: All actions work
- [x] Acceptance: ONE set of action buttons, always visible

### Task 3.5: Create SwipeableLeadProfile Component ✅
- [x] File: `admin/src/components/SwipeableLeadProfile.jsx`
- [x] Props: `currentLeadId`, `leadIds` (array from call list)
- [x] Implement swipe left/right between leads
- [x] Use react-swipeable or similar
- [x] Show position indicator: "3 of 12" in header
- [x] Preload adjacent leads for smooth transitions
- [x] Test: Swipe left goes to next lead
- [x] Test: Swipe right goes to previous lead
- [x] Test: Position indicator updates
- [x] Acceptance: Can swipe through entire call list

### Task 3.6: Rebuild LeadProfile Page ✅
- [x] File: `admin/src/pages/LeadProfile.jsx`
- [x] New structure (top to bottom):
  1. Back button + position indicator ("3 of 12")
  2. LeadProfileHeader
  3. AIRecommendationCard
  4. IntelSummaryCard
  5. Last Contact card (compact)
  6. "More" expandable section (Notes, Timeline, Platform Data, Edit)
  7. LeadActionBar (fixed bottom)
- [x] Wrap everything in SwipeableLeadProfile
- [x] Remove: duplicate button sets, tabs with buried info
- [x] Test: Profile loads with new structure
- [x] Test: All sections render
- [x] Test: Swipe works
- [x] Acceptance: All info visible, one action bar, swipeable

---

## Phase 4: SMS Command Center (Days 6-7)

### Task 4.1: Create AITriageSection Component ✅
- [x] File: `admin/src/components/inbox/AITriageSection.jsx`
- [x] Props: `category`, `conversations`, `onAction`
- [x] Display section header with category name and count
- [x] Category styling:
  - HIGH INTENT: red dot, "Call immediately"
  - CALLBACK REQUEST: amber, "Schedule"
  - QUESTIONS: blue, "Send template"
  - OTHER: slate
- [x] Each section collapsible
- [x] Test: Messages grouped correctly by category
- [x] Test: Sections collapse/expand
- [x] Acceptance: Can see messages by intent type

### Task 4.2: Create EnhancedConversationCard Component ✅
- [x] File: `admin/src/components/inbox/EnhancedConversationCard.jsx`
- [x] Props: `conversation`, `onAction`
- [x] Display:
  - Lead name, time ago, lead type badge
  - Message preview (2 lines)
  - AI insight line (e.g., "BUYING SIGNAL DETECTED")
  - Conversion probability for high intent
  - Quick action buttons per message type
- [x] Quick actions:
  - High Intent: [Call Now] [Quick Reply]
  - Callback: [Schedule] [Other Time]
  - Question: [Send Template] [Custom Reply]
- [x] Test: Card shows AI context
- [x] Test: Quick actions trigger correctly
- [x] Acceptance: Each message has relevant quick action

### Task 4.3: Add Filter Tabs to Inbox ✅
- [x] File: `admin/src/components/inbox/InboxFilterTabs.jsx`
- [x] Add tabs at top: [All] [Unread] [Needs Reply] [Hot Leads]
- [x] Tab state management
- [x] Filter logic:
  - All: no filter
  - Unread: unread_count > 0
  - Needs Reply: last message direction = inbound
  - Hot Leads: lead score > 70
- [x] Active tab styling (blue bg, white text)
- [x] Test: Tabs filter correctly
- [x] Test: Tab state persists during session
- [x] Acceptance: Can quickly find messages needing attention

### Task 4.4: Rebuild Inbox Page ✅
- [x] File: `admin/src/pages/Inbox.jsx`
- [x] New structure:
  1. Header with unread count
  2. Filter tabs
  3. If showing "All" with AI triage: AITriageSections
  4. If showing filtered: flat list with EnhancedConversationCards
- [x] Fetch from `/api/sms/conversations/prioritized`
- [x] Group by AI category when showing all
- [x] Test: Inbox shows AI-enhanced messages
- [x] Test: Filters work
- [x] Test: Quick actions work
- [x] Acceptance: Clear priorities, one-tap actions

---

## Phase 5: Scripts Integration (Day 8)

### Task 5.1: Add Script Display to CallList ✅
- [x] File: `admin/src/pages/CallList.jsx`
- [x] For each lead, fetch recommended script from `/api/scripts/for-lead/:leadId`
- [x] Display below lead info:
  - Script name
  - Success rate percentage
  - "Similar wins: X" count
- [x] [Preview] button to show script details
- [x] [Use Different Script] link
- [x] Test: Script shows for each lead
- [x] Test: Preview modal works
- [x] Acceptance: Can see best script before calling

### Task 5.2: Create ScriptProgressTracker Component ✅
- [x] File: `admin/src/components/ScriptProgressTracker.jsx`
- [x] Props: `scriptId`, `currentStep`
- [x] Fetch script structure from `/api/scripts/:id`
- [x] Display: horizontal step indicators
  - Steps: Opener → Discovery → Value Prop → Objections → Close
  - Checkmark for completed, arrow for current, dot for upcoming
- [x] Highlight current step with pulsing animation
- [x] Test: Progress updates when step changes
- [x] Test: Visual indicators correct
- [x] Acceptance: Can see where you are in script

### Task 5.3: Create SimilarWinCard Component ✅
- [x] File: `admin/src/components/SimilarWinCard.jsx`
- [x] Props: `similarWin` object
- [x] Display:
  - Lead name who converted
  - What worked (key factor)
  - Quote or approach used
  - "Use This Approach" button
- [x] Style: emerald border, compact
- [x] Test: Shows relevant similar win
- [x] Test: Button copies approach to clipboard
- [x] Acceptance: Can quickly reference what worked before

### Task 5.4: Enhance LiveCopilot ✅
- [x] File: `admin/src/components/LiveCopilot.jsx`
- [x] Add at top: SimilarWinCard (if similar win exists)
- [x] Add: ScriptProgressTracker below header
- [x] Enhance objection responses:
  - Show success rate percentage
  - Show "This worked on: Mike, Sarah, Tom" names
- [x] Auto-advance script progress based on transcript keywords
- [x] Test: Copilot shows enhanced data
- [x] Test: Script progress updates during call
- [x] Acceptance: More actionable coaching during calls

---

## Phase 6: Motivation System (Days 9-10)

### Task 6.1: Create Achievement System Schema
- [ ] File: `supabase/achievement-system-migration.sql`
- [ ] Create table: `user_achievements`
  - `id` UUID PRIMARY KEY
  - `user_id` UUID (references auth.users)
  - `achievement_id` VARCHAR(50)
  - `unlocked_at` TIMESTAMPTZ
- [ ] Create table: `user_xp`
  - `id` UUID PRIMARY KEY
  - `user_id` UUID (references auth.users)
  - `total_xp` INTEGER DEFAULT 0
  - `level` INTEGER DEFAULT 1
  - `current_streak` INTEGER DEFAULT 0
  - `longest_streak` INTEGER DEFAULT 0
  - `last_activity_date` DATE
- [ ] Create indexes
- [ ] Run migration
- [ ] Test: Tables created, can insert data
- [ ] Acceptance: Database ready for achievements

### Task 6.2: Create Achievements API
- [ ] File: `src/routes/achievements.js`
- [ ] Endpoints:
  - `GET /api/achievements` - list all achievements (definitions)
  - `GET /api/achievements/user` - user's unlocked achievements
  - `POST /api/achievements/check` - check and award achievements
- [ ] Define achievements in code:
  ```javascript
  const ACHIEVEMENTS = {
    'first_blood': { name: 'First Blood', desc: 'Make your first call', xp: 10 },
    'closer': { name: 'Closer', desc: 'Get your first conversion', xp: 50 },
    // ... etc
  };
  ```
- [ ] Check logic: query relevant data, compare to criteria
- [ ] Test: Achievements awarded correctly
- [ ] Test: Already-unlocked achievements not re-awarded
- [ ] Acceptance: Calling check endpoint awards appropriate achievements

### Task 6.3: Create XP API
- [ ] File: `src/routes/xp.js`
- [ ] Endpoints:
  - `GET /api/xp/user` - get user's XP and level
  - `POST /api/xp/award` - award XP for action
- [ ] Level calculation:
  ```javascript
  const LEVELS = [
    { level: 1, title: 'Rookie', xpRequired: 0 },
    { level: 2, title: 'Dialer', xpRequired: 100 },
    // ... etc
  ];
  ```
- [ ] Update streak on activity (reset if > 1 day gap)
- [ ] Test: XP awarded, level calculated correctly
- [ ] Test: Streak updates correctly
- [ ] Acceptance: Actions award XP, level updates

### Task 6.4: Create AchievementBadge Component
- [ ] File: `admin/src/components/AchievementBadge.jsx`
- [ ] Props: `achievement`, `unlocked`
- [ ] Display:
  - Icon (emoji or lucide icon)
  - Name
  - Locked/unlocked state (grayscale if locked)
- [ ] Tooltip with description and XP value
- [ ] Test: Badge renders correctly
- [ ] Test: Visual distinction between locked/unlocked
- [ ] Acceptance: Clear locked/unlocked states

### Task 6.5: Create LevelProgress Component
- [ ] File: `admin/src/components/LevelProgress.jsx`
- [ ] Props: `xp`, `level`, `title`, `streak`
- [ ] Display:
  - Level number and title (e.g., "LVL 4: CLOSER")
  - XP progress bar (current/next level threshold)
  - Streak with fire emoji
- [ ] Compact enough for header placement
- [ ] Test: Progress bar accurate
- [ ] Test: Level title correct
- [ ] Acceptance: Shows progress to next level

### Task 6.6: Create CelebrationOverlay Component
- [ ] File: `admin/src/components/CelebrationOverlay.jsx`
- [ ] Props: `type` (conversion, achievement, level_up), `data`
- [ ] Animations:
  - Confetti effect (use canvas-confetti or similar)
  - Badge appear animation
  - XP counter animation
- [ ] Types:
  - Conversion: "CONVERSION! +50 XP"
  - Achievement: "ACHIEVEMENT UNLOCKED! [Badge]"
  - Level Up: "LEVEL UP! You are now a Closer"
- [ ] Auto-dismiss after 3 seconds or on tap
- [ ] Test: Animations trigger correctly
- [ ] Test: Auto-dismiss works
- [ ] Acceptance: Celebrations feel earned, not annoying

### Task 6.7: Create Stats Page
- [ ] File: `admin/src/pages/Stats.jsx`
- [ ] Sections:
  - LevelProgress (large)
  - Current streak and longest streak
  - This week stats (calls, conversions, SMS)
  - Achievements grid (all, with locked/unlocked)
- [ ] Add to App.jsx routes: `/stats`
- [ ] Link from More page
- [ ] Test: All stats load correctly
- [ ] Test: Achievements grid shows all
- [ ] Acceptance: Can see progress and all achievements

### Task 6.8: Integrate XP Awards
- [ ] Modify call logging to award XP:
  - Call made: +10 XP
  - Conversion: +50 XP
  - Streak day: +5 XP per day
- [ ] Modify CallOutcomeSheet to show XP earned
- [ ] Trigger CelebrationOverlay on conversion
- [ ] Check achievements after calls
- [ ] Test: XP awarded for actions
- [ ] Test: Celebration shows on conversion
- [ ] Acceptance: Visible feedback on XP earned

---

## Phase 7: Post-Call Coaching (Days 11-12)

### Task 7.1: Create Call Scoring API
- [ ] File: `src/routes/calls.js` or `src/services/callScoring.js`
- [ ] Endpoint: `POST /api/calls/score`
- [ ] Body: `{ callId, transcript, leadId, duration }`
- [ ] Use AI to score 5 categories (0-100 each):
  - Opener (personalization, energy)
  - Discovery (questions asked, depth)
  - Value Prop (clarity, customization)
  - Objection Handling (responses, recovery)
  - Close (directness, next steps)
- [ ] Calculate overall score (weighted average)
- [ ] Generate coaching feedback (what went well, to improve)
- [ ] Store in `call_scores` table
- [ ] Test: Scoring returns valid scores for all categories
- [ ] Test: Coaching feedback is specific, not generic
- [ ] Acceptance: Call scored on 5 dimensions with actionable feedback

### Task 7.2: Create CallScorecard Component
- [ ] File: `admin/src/components/CallScorecard.jsx`
- [ ] Props: `scores` object
- [ ] Display:
  - 5 category rows with progress bars
  - Color coding: red <50, amber 50-75, green >75
  - Short label for each (e.g., "Good energy!")
  - Overall score with star rating (1-5 stars)
- [ ] Test: Scorecard renders correctly
- [ ] Test: Colors match score ranges
- [ ] Acceptance: Visual representation of call quality

### Task 7.3: Create AICoachingCard Component
- [ ] File: `admin/src/components/AICoachingCard.jsx`
- [ ] Props: `coaching` object
- [ ] Display:
  - "WHAT WENT WELL" section with checkmarks
  - "TO IMPROVE" section with specific tips
  - Each tip includes suggested phrase
- [ ] Style: emerald for positives, amber for improvements
- [ ] Test: Card shows relevant coaching
- [ ] Test: Tips are specific to the call
- [ ] Acceptance: Actionable feedback, not generic platitudes

### Task 7.4: Enhance PostCallSummarySheet
- [ ] File: `admin/src/components/PostCallSummarySheet.jsx`
- [ ] Add after outcome selection:
  1. CallScorecard (if transcript available)
  2. AICoachingCard (if transcript available)
  3. XP earned display
  4. "Focus for next call" tip
- [ ] Keep existing: outcome buttons, notes field, callback scheduling
- [ ] Show loading state while AI scores
- [ ] Test: Full review shows after call with transcript
- [ ] Test: Works gracefully without transcript (skip scoring)
- [ ] Acceptance: Comprehensive feedback, saves and moves to next

---

## Phase 8: Analytics Dashboard (Days 13-14)

### Task 8.1: Create Patterns Analysis Job
- [ ] File: `src/jobs/analyzePatterns.js`
- [ ] Logic to analyze:
  - Time patterns: best times by day/hour for answer rate
  - Script effectiveness: success rates, which work for which leads
  - Objection responses: which responses lead to conversions
  - Template performance: reply rates by template
- [ ] Store discoveries in `winning_patterns` table:
  - `id`, `pattern_type`, `description`, `data`, `confidence`, `discovered_at`
- [ ] Schedule: run weekly (or on-demand)
- [ ] Test: Job runs without error
- [ ] Test: Patterns stored correctly
- [ ] Acceptance: Patterns discovered from data

### Task 8.2: Create What's Working API
- [ ] File: `src/routes/analytics.js`
- [ ] Endpoint: `GET /api/analytics/whats-working`
- [ ] Query params: `days` (default 30)
- [ ] Returns:
  - `topScripts`: top 3 scripts by success rate with uses
  - `topResponses`: best objection responses with success rates
  - `bestTimes`: heatmap data for call times
  - `topTemplates`: SMS templates by reply rate
  - `patterns`: AI-discovered patterns
- [ ] Test: Returns comprehensive data
- [ ] Test: Empty data handled gracefully
- [ ] Acceptance: All insights in one call

### Task 8.3: Create WhatsWorkingCard Component
- [ ] File: `admin/src/components/WhatsWorkingCard.jsx`
- [ ] Props: `title`, `items`, `type`
- [ ] Display:
  - Section title with icon
  - Ranked list (1, 2, 3)
  - Each item: name, success rate, uses, trend arrow
  - AI insight at bottom if applicable
- [ ] Style: numbered circles, progress bars for rates
- [ ] Test: Card renders with data
- [ ] Test: Trend arrows correct
- [ ] Acceptance: Clear visualization of what's working

### Task 8.4: Create TimeHeatmap Component
- [ ] File: `admin/src/components/TimeHeatmap.jsx`
- [ ] Props: `data` (matrix of day x hour), `type` (contractor/worker)
- [ ] Display:
  - Grid: rows = hours (6am-8pm), columns = days (Mon-Fri)
  - Color coding: green >60%, amber 40-60%, red <40%
  - Legend
- [ ] Option to toggle between contractor and worker data
- [ ] Test: Heatmap renders correctly
- [ ] Test: Colors match thresholds
- [ ] Acceptance: Can see best times at a glance

### Task 8.5: Create Insights Page
- [ ] File: `admin/src/pages/Insights.jsx`
- [ ] Sections:
  1. Summary stats (total calls, conversion rate, period)
  2. Top Scripts (WhatsWorkingCard)
  3. Best Objection Responses (WhatsWorkingCard)
  4. Best Times to Call (TimeHeatmap)
  5. Top SMS Templates (WhatsWorkingCard)
  6. AI-Discovered Patterns (list)
- [ ] Time period selector (7, 14, 30, 90 days)
- [ ] Add to App.jsx routes: `/insights`
- [ ] Link from More page under "Analytics & AI"
- [ ] Test: Page loads with all sections
- [ ] Test: Time period filter works
- [ ] Acceptance: Comprehensive view of what's working

---

## Phase 9: AI Intelligence Layer (Days 15-16)

### Task 9.1: Create Alerts System Schema
- [ ] File: `supabase/alerts-system-migration.sql`
- [ ] Create table: `alerts`
  - `id` UUID PRIMARY KEY
  - `user_id` UUID (references auth.users)
  - `type` VARCHAR(50) (probability_drop, hot_lead_activity, etc.)
  - `lead_id` UUID (optional, references leads)
  - `data` JSONB (alert-specific data)
  - `priority` VARCHAR(20) (urgent, high, medium, low)
  - `created_at` TIMESTAMPTZ
  - `dismissed_at` TIMESTAMPTZ (null if not dismissed)
- [ ] Create indexes on user_id, created_at, dismissed_at
- [ ] Run migration
- [ ] Test: Table created, can insert alerts
- [ ] Acceptance: System can store alerts

### Task 9.2: Create Alerts API
- [ ] File: `src/routes/alerts.js`
- [ ] Endpoints:
  - `GET /api/alerts/pending` - get undismissed alerts for user
  - `POST /api/alerts/dismiss/:id` - dismiss an alert
  - `POST /api/alerts/generate` - run alert generation (internal)
- [ ] Alert generation logic (in service file):
  - Probability drop: compare current vs 48h ago
  - Hot lead activity: platform activity for score >80 leads
  - Callback due: callbacks within 15 mins
  - Slipping lead: no contact 7+ days, was hot
  - Streak at risk: no calls today, has active streak
- [ ] Test: Alerts fetched correctly
- [ ] Test: Dismiss works
- [ ] Acceptance: Can see and dismiss alerts

### Task 9.3: Enhance AlertsDropdown Component
- [ ] File: `admin/src/components/AlertsDropdown.jsx` (create or enhance)
- [ ] Fetch from `/api/alerts/pending`
- [ ] Display:
  - Bell icon with count badge
  - Dropdown with alert list
  - Each alert: icon, message, action button, dismiss X
  - Priority styling (red for urgent, amber for high)
- [ ] Action buttons trigger appropriate navigation
- [ ] Dismiss removes from list
- [ ] Test: Alerts visible with correct styling
- [ ] Test: Actions navigate correctly
- [ ] Acceptance: Proactive alerts surface important items

### Task 9.4: Create Weekly Insights API
- [ ] File: `src/routes/ai.js` (add endpoint)
- [ ] Endpoint: `GET /api/ai/weekly-summary`
- [ ] Generate with AI:
  - Wins: conversions, milestones, personal bests
  - Recommendations: specific improvements with data
  - Watch outs: declining metrics, risks
  - Focus area: priority for next week
- [ ] Store in `ai_insights` table
- [ ] Test: Summary generates correctly
- [ ] Test: Recommendations are specific, not generic
- [ ] Acceptance: Comprehensive weekly analysis

### Task 9.5: Surface Voice Commands
- [ ] File: `admin/src/components/VoiceCommandButton.jsx`
- [ ] Add mic button to:
  - Dashboard header
  - CallList header
  - During call (already in LiveCopilot)
- [ ] On tap: start listening for commands
- [ ] Show listening indicator
- [ ] File: `admin/src/pages/VoiceCommands.jsx`
- [ ] Create help page listing all commands
- [ ] Add to App.jsx routes: `/voice-commands`
- [ ] Link from More page under "Settings"
- [ ] Test: Voice commands work from all locations
- [ ] Acceptance: Can use voice for common actions

### Task 9.6: Add Weekly Insights Link
- [ ] Add to More page: "Weekly Insights" under "Analytics & AI"
- [ ] Link to `/insights` with weekly tab selected
- [ ] Or: create dedicated `/weekly-insights` page
- [ ] Test: Can access weekly insights
- [ ] Acceptance: Weekly insights discoverable

---

## Completion Checklist

### Phase 1: Navigation ✅ COMPLETE
- [x] Task 1.1: BottomNav updated
- [x] Task 1.2: More page created
- [x] Task 1.3: More route added

### Phase 2: Command Center ✅ COMPLETE
- [x] Task 2.1: AIStrategyCard
- [x] Task 2.2: Priority Action API
- [x] Task 2.3: PriorityActionCard
- [x] Task 2.4: Slipping Leads API
- [x] Task 2.5: SlippingLeads
- [x] Task 2.6: RepliesWaiting
- [x] Task 2.7: TodayStats
- [x] Task 2.8: Dashboard rebuilt

### Phase 3: Lead Profile ✅ COMPLETE
- [x] Task 3.1: LeadProfileHeader
- [x] Task 3.2: AIRecommendationCard
- [x] Task 3.3: IntelSummaryCard
- [x] Task 3.4: LeadActionBar
- [x] Task 3.5: SwipeableLeadProfile
- [x] Task 3.6: LeadProfile rebuilt

### Phase 4: SMS Inbox ✅ COMPLETE
- [x] Task 4.1: AITriageSection
- [x] Task 4.2: EnhancedConversationCard
- [x] Task 4.3: Filter Tabs
- [x] Task 4.4: Inbox rebuilt

### Phase 5: Scripts ✅ COMPLETE
- [x] Task 5.1: Script on CallList
- [x] Task 5.2: ScriptProgressTracker
- [x] Task 5.3: SimilarWinCard
- [x] Task 5.4: LiveCopilot enhanced

### Phase 6: Motivation ✓
- [ ] Task 6.1: Achievement Schema
- [ ] Task 6.2: Achievements API
- [ ] Task 6.3: XP API
- [ ] Task 6.4: AchievementBadge
- [ ] Task 6.5: LevelProgress
- [ ] Task 6.6: CelebrationOverlay
- [ ] Task 6.7: Stats Page
- [ ] Task 6.8: XP Integration

### Phase 7: Coaching ✓
- [ ] Task 7.1: Call Scoring API
- [ ] Task 7.2: CallScorecard
- [ ] Task 7.3: AICoachingCard
- [ ] Task 7.4: PostCallSummary enhanced

### Phase 8: Analytics ✓
- [ ] Task 8.1: Patterns Job
- [ ] Task 8.2: What's Working API
- [ ] Task 8.3: WhatsWorkingCard
- [ ] Task 8.4: TimeHeatmap
- [ ] Task 8.5: Insights Page

### Phase 9: AI Layer ✓
- [ ] Task 9.1: Alerts Schema
- [ ] Task 9.2: Alerts API
- [ ] Task 9.3: AlertsDropdown enhanced
- [ ] Task 9.4: Weekly Insights API
- [ ] Task 9.5: Voice Commands surfaced
- [ ] Task 9.6: Weekly Insights linked

---

## Quick Reference

### New API Endpoints
```
GET  /api/dashboard/priority-action
GET  /api/dashboard/slipping
GET  /api/achievements
GET  /api/achievements/user
POST /api/achievements/check
GET  /api/xp/user
POST /api/xp/award
POST /api/calls/score
GET  /api/calls/:id/review
GET  /api/analytics/whats-working
GET  /api/analytics/patterns
GET  /api/alerts/pending
POST /api/alerts/dismiss/:id
GET  /api/ai/weekly-summary
```

### New Database Tables
```sql
user_achievements (user_id, achievement_id, unlocked_at)
user_xp (user_id, total_xp, level, current_streak, longest_streak, last_activity_date)
call_scores (call_id, scores_json, overall, ai_feedback, created_at)
winning_patterns (id, pattern_type, description, data, confidence, discovered_at)
alerts (id, user_id, type, lead_id, data, priority, created_at, dismissed_at)
```

### New Components
```
admin/src/components/dashboard/AIStrategyCard.jsx
admin/src/components/dashboard/PriorityActionCard.jsx
admin/src/components/dashboard/RepliesWaiting.jsx
admin/src/components/dashboard/SlippingLeads.jsx
admin/src/components/dashboard/TodayStats.jsx
admin/src/components/LeadProfileHeader.jsx
admin/src/components/AIRecommendationCard.jsx
admin/src/components/IntelSummaryCard.jsx
admin/src/components/LeadActionBar.jsx
admin/src/components/SwipeableLeadProfile.jsx
admin/src/components/inbox/AITriageSection.jsx
admin/src/components/inbox/EnhancedConversationCard.jsx
admin/src/components/ScriptProgressTracker.jsx
admin/src/components/SimilarWinCard.jsx
admin/src/components/AchievementBadge.jsx
admin/src/components/LevelProgress.jsx
admin/src/components/CelebrationOverlay.jsx
admin/src/components/CallScorecard.jsx
admin/src/components/AICoachingCard.jsx
admin/src/components/WhatsWorkingCard.jsx
admin/src/components/TimeHeatmap.jsx
admin/src/components/AlertsDropdown.jsx
admin/src/components/VoiceCommandButton.jsx
```

### New Pages
```
admin/src/pages/More.jsx
admin/src/pages/Stats.jsx
admin/src/pages/Insights.jsx
admin/src/pages/VoiceCommands.jsx
```

---

## Notes

- Always test on mobile (primary use case)
- Keep components small and focused
- Use existing API endpoints where possible
- Add loading skeletons for all async data
- Handle empty states gracefully
- Commit after each task
