# 0.1% Script System Build Plan

## Overview
Comprehensive script management system with guided call flows, objection handling, and performance tracking.

---

## Features

### SCR-1: Database + Script Library Page
**Status:** Pending

**Database Schema:**
```sql
-- Scripts table
CREATE TABLE scripts (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name VARCHAR(200) NOT NULL,
  description TEXT,
  category VARCHAR(50), -- 'cold_call', 'follow_up', 'closing', 'reactivation'
  target_type VARCHAR(20), -- 'worker', 'contractor', 'both'
  target_stage VARCHAR(50), -- platform stage this script is for

  -- Script content
  opening TEXT,
  discovery_questions JSONB, -- [{question, purpose, goodAnswers, redFlags}]
  value_props JSONB, -- [{prop, when_to_use, proof_points}]
  closing_techniques JSONB, -- [{name, script, when_to_use}]

  -- Metadata
  is_active BOOLEAN DEFAULT true,
  times_used INTEGER DEFAULT 0,
  avg_success_rate DECIMAL(5,2),
  created_by UUID,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Objections table
CREATE TABLE objections (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  objection TEXT NOT NULL,
  category VARCHAR(50), -- 'price', 'timing', 'trust', 'competition', 'authority'
  frequency INTEGER DEFAULT 0,
  responses JSONB, -- [{response, effectiveness_score, times_used}]
  scripts UUID[], -- scripts where this objection commonly appears
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Script usage tracking
CREATE TABLE script_sessions (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  script_id UUID REFERENCES scripts(id),
  lead_id UUID REFERENCES leads(id),
  started_at TIMESTAMPTZ DEFAULT NOW(),
  ended_at TIMESTAMPTZ,
  outcome VARCHAR(50), -- 'success', 'callback', 'objection', 'not_interested'
  objections_encountered UUID[], -- objection IDs
  notes TEXT,
  recording_url TEXT
);

CREATE INDEX idx_scripts_category ON scripts(category);
CREATE INDEX idx_scripts_target ON scripts(target_type, target_stage);
CREATE INDEX idx_objections_category ON objections(category);
CREATE INDEX idx_script_sessions_script ON script_sessions(script_id);
```

**Backend:**
- `GET /api/scripts` - List scripts with filters
- `GET /api/scripts/:id` - Get script details
- `POST /api/scripts` - Create script
- `PATCH /api/scripts/:id` - Update script
- `DELETE /api/scripts/:id` - Delete script

**Frontend - Script Library Page:**
- Grid of script cards
- Filter by category, target type, stage
- Sort by success rate, times used, recent
- Quick stats on each card

---

### SCR-2: Script Detail View
**Status:** Pending

**Description:** Full script view with all sections

**Sections:**
1. **Opening** - First 30 seconds
2. **Discovery Questions** - With purpose and what to listen for
3. **Value Props** - Benefit statements with proof points
4. **Objection Handlers** - Common objections for this script
5. **Closing Techniques** - Multiple close options
6. **Success Metrics** - How this script performs

**Frontend:**
- Tabbed or accordion layout
- Copy button for each section
- "Start Call with Script" button
- Edit mode for authorized users

---

### SCR-3: Script Builder
**Status:** Pending

**Description:** Create and edit scripts with guided structure

**Features:**
- Step-by-step wizard
- AI assistance for writing sections
- Preview mode
- Import from template
- Clone existing script

**AI Integration:**
- "Generate opening for [stage] [type]"
- "Suggest discovery questions for [goal]"
- "Write value prop for [pain point]"

**Backend:**
- `POST /api/scripts/ai-generate` - AI generates script section
- `POST /api/scripts/clone/:id` - Clone existing script

---

### SCR-4: Script on Call (Copilot Integration)
**Status:** Pending

**Description:** Live script guidance during calls

**Features:**
- Script panel in Call Copilot
- Current section highlighting
- Quick objection lookup
- One-click log objection
- Auto-advance through sections

**Integration Points:**
- Call Copilot page loads active script
- Script context sent to AI for suggestions
- Objections logged to script_sessions
- Post-call: prompt for outcome

**Frontend:**
- Collapsible script panel on call screen
- Section navigation
- Objection quick-search
- "Mark as handled" for objections

---

### SCR-5: Script Tracking + Analytics
**Status:** Pending

**Description:** Track script performance over time

**Metrics:**
- Success rate by script
- Avg call duration by script
- Common objections by script
- Best performing opener
- Conversion by discovery question asked

**Backend:**
- `GET /api/scripts/analytics` - Overall script stats
- `GET /api/scripts/:id/analytics` - Single script performance
- `GET /api/scripts/compare` - Compare 2+ scripts

**Frontend:**
- Analytics dashboard
- Script comparison view
- Trend charts
- Recommendation: "Script A outperforms Script B by 23%"

---

### SCR-6: Objection Library
**Status:** Pending

**Description:** Searchable database of objections and responses

**Features:**
- Search objections by keyword
- Filter by category
- Multiple responses per objection with ratings
- Community effectiveness voting
- AI-suggested responses

**Backend:**
- `GET /api/objections` - List with search/filter
- `GET /api/objections/:id` - Detail with all responses
- `POST /api/objections` - Add new objection
- `POST /api/objections/:id/responses` - Add response
- `POST /api/objections/:id/responses/:rid/rate` - Rate response

**Frontend:**
- Searchable objection list
- Objection detail modal
- "What worked" responses sorted by rating
- "Add your response" form
- Quick access from call screen

---

## File Structure

```
src/routes/scripts.js           - Scripts API
src/routes/objections.js        - Objections API
src/services/scriptAI.js        - AI generation
admin/src/pages/ScriptLibrary.jsx
admin/src/pages/ScriptDetail.jsx
admin/src/pages/ScriptBuilder.jsx
admin/src/pages/ObjectionLibrary.jsx
admin/src/components/ScriptPanel.jsx  - For call screen
supabase/script-system-migration.sql
```

---

## Build Order

1. SCR-1: Database + Script Library Page
2. SCR-2: Script Detail View
3. SCR-6: Objection Library (useful standalone)
4. SCR-4: Script on Call (Copilot integration)
5. SCR-3: Script Builder
6. SCR-5: Script Tracking + Analytics

---

## Sample Script Structure

```json
{
  "name": "Contractor Cold Call - Stripe Setup",
  "category": "reactivation",
  "target_type": "contractor",
  "target_stage": "stripe_ready",

  "opening": "Hey {{first_name}}, this is [Name] from RateRight. I noticed you started setting up your account but haven't finished connecting payments yet. Quick question - are you still looking to hire workers through the platform?",

  "discovery_questions": [
    {
      "question": "What's been holding you back from finishing the setup?",
      "purpose": "Identify blocker",
      "goodAnswers": ["Too busy", "Wasn't sure how"],
      "redFlags": ["Changed mind", "Using competitor"]
    },
    {
      "question": "When's your next project starting?",
      "purpose": "Create urgency",
      "goodAnswers": ["Soon", "Next week"],
      "redFlags": ["No projects", "Months away"]
    }
  ],

  "value_props": [
    {
      "prop": "Takes 2 minutes to connect Stripe, then you can post jobs immediately",
      "when_to_use": "If blocker is time/complexity",
      "proof_points": ["Other contractors did it in under 2 mins"]
    }
  ],

  "closing_techniques": [
    {
      "name": "Assumptive",
      "script": "Let me stay on the line while you finish - just go to Settings > Payments and I'll walk you through it",
      "when_to_use": "When they're receptive"
    }
  ]
}
```
