# 0.1% SMS Command Center Build Plan

## Overview
Premium SMS inbox with AI-powered triage, priority sorting, smart templates, and analytics.

---

## Features

### SMS-1: Priority Inbox + AI Triage ✅ COMPLETE
**Status:** Deployed

**Backend:**
- `GET /api/sms/conversations/prioritized` - Returns conversations sorted by triage priority
- `POST /api/sms/ai-suggest` - Returns AI-suggested reply with confidence

**Triage Categories:**
| Category | Emoji | Priority | Detection |
|----------|-------|----------|-----------|
| Buying Signal | 🔥 | 100+ | metadata.buyingSignal present |
| Callback Request | ⏰ | 90 | intent=question + "call"/"callback" in message |
| Question | ❓ | 70 | metadata.intent = 'question' |
| Positive | 👋 | 50 | metadata.intent = 'positive' |
| Not Interested | ❌ | 10 | metadata.intent = 'negative' |
| Neutral | 💬 | 30 | default |

**Priority Boosters:**
- Unread: +20
- Needs Reply (last message inbound): +10

**Frontend:**
- TriageBadge component with colors
- TriageSummary filter pills with counts
- AI suggestion bar with "Use this reply" button
- Real delivery status display

---

### SMS-2: Real Delivery Status
**Status:** Pending

**Description:** Show actual delivery/read status from Twilio webhooks

**Backend:**
- Already storing status in `communications.metadata.twilioStatus`
- Webhook receives: queued → sent → delivered → read (if enabled)

**Frontend:**
- ✓ Sent (gray) - message accepted
- ✓✓ Delivered (gray) - reached device
- ✓✓ Read (blue) - opened (requires read receipts)
- ❌ Failed (red) - delivery failed

**Files to modify:**
- `admin/src/pages/Inbox.jsx` - Already displays from metadata

---

### SMS-3: Templates with Variables
**Status:** Pending

**Description:** Dynamic templates with variable substitution

**Database:**
```sql
CREATE TABLE sms_templates (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name VARCHAR(100) NOT NULL,
  category VARCHAR(50), -- 'follow_up', 'cold_outreach', 'appointment', etc.
  content TEXT NOT NULL,
  variables TEXT[], -- ['first_name', 'company', 'trade']
  is_active BOOLEAN DEFAULT true,
  use_count INTEGER DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);
```

**Variables supported:**
- `{{first_name}}` - Lead's first name
- `{{company}}` - Company name
- `{{trade}}` - Primary trade
- `{{stage}}` - Current platform stage
- `{{days_since_contact}}` - Days since last contact

**Backend:**
- `GET /api/sms/templates` - List templates (already exists)
- `POST /api/sms/templates` - Create template
- `PATCH /api/sms/templates/:id` - Update template
- `DELETE /api/sms/templates/:id` - Delete template
- `POST /api/sms/templates/:id/preview` - Preview with lead data

**Frontend:**
- Template picker in compose area
- Variable highlighting in template text
- Preview before send

---

### SMS-4: Scheduled Send
**Status:** Pending

**Description:** Queue messages to send at optimal times

**Database:**
```sql
CREATE TABLE scheduled_messages (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  lead_id UUID REFERENCES leads(id),
  content TEXT NOT NULL,
  scheduled_for TIMESTAMPTZ NOT NULL,
  status VARCHAR(20) DEFAULT 'pending', -- 'pending', 'sent', 'failed', 'cancelled'
  sent_at TIMESTAMPTZ,
  error TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_scheduled_messages_pending ON scheduled_messages(scheduled_for)
  WHERE status = 'pending';
```

**Backend:**
- `POST /api/sms/schedule` - Schedule a message
- `GET /api/sms/scheduled` - List scheduled messages
- `DELETE /api/sms/scheduled/:id` - Cancel scheduled message
- Cron job: Check every minute, send due messages

**Frontend:**
- "Schedule" button next to "Send"
- Date/time picker
- Scheduled messages list view

**Optimal send times:**
- Business hours: 9am-6pm local time
- AI suggests: Based on past response patterns

---

### SMS-5: Stats Dashboard
**Status:** Pending

**Description:** Analytics on SMS performance

**Metrics:**
- Response rate (% of outbound that got reply)
- Avg response time
- Messages sent/received by day
- Top performing templates
- Conversion by first message type

**Backend:**
- `GET /api/sms/stats` - Aggregated stats
- `GET /api/sms/stats/templates` - Template performance

**Frontend:**
- Stats cards at top of Inbox
- Charts for trends
- Template leaderboard

---

## File Structure

```
src/routes/sms.js          - SMS API endpoints
src/services/smsScheduler.js - Scheduled send cron
admin/src/pages/Inbox.jsx  - Priority Inbox UI
admin/src/api/client.js    - API client
supabase/sms-*.sql         - Migrations
```

---

## Build Order

1. ✅ SMS-1: Priority Inbox + AI Triage
2. SMS-2: Real Delivery Status (frontend polish)
3. SMS-3: Templates with Variables
4. SMS-4: Scheduled Send
5. SMS-5: Stats Dashboard
