# Phase 3E: Performance Optimization

## Changes Made

### 1. Optimized Polling Intervals
- **ConversationResource table polling**: `3s` → `15s` — reduced Livewire polling by 80%
- **Database notifications polling**: `5s` → `15s` — matched to workspace poll interval
- **Workspace JS polling**: Added `visibilitychange` listener to pause polling when tab is hidden (re-resumes when tab refocused)
- All intervals now harmonized at 15s (no duplicate/overlapping requests)

### 2. Navigation Optimization
- `selectView()` in chat-workspace.blade.php routes to Filament pages via `window.location.href`
- Navigation is already optimal — Filament handles its own pages; inline rendering would break role isolation
- CSS assets are conditionally loaded: `chat-workspace.css` only on `admin` or `admin/`

### 3. Database Indexes (new migration)
Added to `conversations`:
- `conversations_created_at_index` — speeds up reports date-range filters
- `conversations_status_index` — speeds up workspace stats + reports status breakdowns

Added to `messages`:
- `messages_created_at_index` — speeds up reports date-range filters
- `messages_direction_index` — speeds up incoming/outgoing message counts in reports

### 4. Query Optimization
- **Messages endpoint** (`/api/conversations/{id}/messages`): Already paginated at 50 per page (`->paginate(50)`)
- **Workspace data** (`/api/workspace/data`): Chats limited to 50, queue limited to 10, activity limited to 10
- **Reports queries**: Already use aggregate SQL with `SUM(CASE...)` and `selectRaw` (not N+1)
- All aggregate queries scoped by role at the query level

### 5. CSS/JS Asset Optimization
- `chat-workspace.css` only loads on workspace URLs (not all admin pages)
- Three CSS files loaded globally via `AdminPanelProvider::renderHook` — this is acceptable since they contain theme variables
- Previous cleanup reduced chat-workspace.css from 1517→1239 lines (Phase 2)

## Files Modified
- `app/Filament/Resources/ConversationResource.php:91` — polling 3s→15s
- `app/Providers/Filament/AdminPanelProvider.php:40` — notification polling 5s→15s
- `resources/views/filament/pages/chat-workspace.blade.php` — added visibility pause, interval variable
- `database/migrations/2026_05_29_130000_add_performance_indexes_to_conversations_and_messages_table.php` — 4 new indexes

## Test Results
- **67 tests, 201 assertions — all pass**
- Duration: 22.20s

## What's NOT Done (Intentionally)
- **No WebSocket/pusher**: Phase 3E explicitly excludes real-time WebSocket; polling was optimized but not replaced
- **No query-level caching**: Reports data is loaded once per page view (no polling); workspace data must be near-real-time for agent visibility
- **No JS bundling/minification**: CSS/JS are served raw — acceptable for an internal CRM with low traffic
- **No CDN**: Not applicable for local/internal deployment
