# SportPulse Admin Tool - Product Requirements Document (PRD)

## 1. Executive Summary

### 1.1 Product Overview
SportPulse Admin Tool is a web-based administration interface for managing sports widget data across two interconnected systems:
1. **Widget Configuration API** (sportpulse-internal-apis) - Manages sports metadata, leagues, teams, widget types, and template configurations
2. **Sports Data Database** - Manages live/dynamic sports data including scores, schedules, and events

### 1.2 Objective
A unified admin dashboard that provides:
- Complete CRUD operations for all widget configuration entities
- File upload and media management
- Live sports data editing (scores, schedules, venues)
- Real-time sync with both database systems

---

## 2. System Architecture

### 2.1 High-Level Architecture

```
┌─────────────────────────────────────────────────────────────────────┐
│                     SportPulse Admin Tool (Frontend)                │
│                        React + TypeScript + SCSS                    │
└─────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────┐
│                     Admin API Server (Backend)                       │
│                     Node.js + Express + TypeScript                   │
├─────────────────────────────────────────────────────────────────────┤
│  ┌──────────────────┐    ┌──────────────────┐    ┌───────────────┐ │
│  │ Widget Config    │    │ Sports Data      │    │ File Upload   │ │
│  │ Service          │    │ Service          │    │ Service       │ │
│  └────────┬─────────┘    └────────┬─────────┘    └───────┬───────┘ │
└───────────┼───────────────────────┼──────────────────────┼─────────┘
            │                       │                      │
            ▼                       ▼                      ▼
┌───────────────────┐   ┌───────────────────┐   ┌───────────────────┐
│ Widget Config DB  │   │ Sports Data DB    │   │ Cloud Storage     │
│ (MongoDB)         │   │ (MongoDB)         │   │ (S3/CloudFlare)   │
│                   │   │                   │   │                   │
│ - Sports          │   │ - Teams           │   │ - Sport icons     │
│ - Leagues         │   │ - Players/Drivers │   │ - League logos    │
│ - Participants    │   │ - Schedules       │   │ - Team logos      │
│ - WidgetTypes     │   │ - Scores          │   │ - Thumbnails      │
│ - Templates       │   │ - Events          │   │ - Templates       │
│ - ApiKeys         │   │ - Venues          │   │                   │
└───────────────────┘   └───────────────────┘   └───────────────────┘
```

### 2.2 Database Connections

| Database | Purpose | Connection |
|----------|---------|------------|
| Widget Config DB | sportpulse-internal-apis data | `WIDGET_CONFIG_MONGODB_URI` |
| Sports Data DB | Live sports data for widgets (existing) | `SPORTS_DATA_MONGODB_URI` |

### 2.3 Project Structure Decision

**Recommended: Separate Project** - The admin tool should be a standalone project (`sportpulse-admin`) separate from the existing `sportpulse-internal-apis` for:
- **Security isolation** - Admin endpoints not exposed on public API server
- **Independent deployment** - Update admin without affecting production API
- **Access control** - Admin server can be restricted to internal network/VPN
- **Single responsibility** - Each project has clear purpose

### 2.4 Authentication

**Method: Email/Password + JWT**
- Admin users authenticate with email/password credentials
- JWT tokens for session management
- Refresh token rotation for security

---

## 3. Functional Requirements

### 3.1 Module 1: Widget Configuration Management

#### 3.1.1 Sports Management

**Features:**
| Feature | Description | Priority |
|---------|-------------|----------|
| List Sports | Display all sports with filters (active/inactive) | P0 |
| Add Sport | Create new sport with name and icon | P0 |
| Edit Sport | Update sport name, icon, active status | P0 |
| Delete Sport | Soft delete (set isActive=false) | P1 |
| Upload Sport Icon | Upload/replace sport icon image | P0 |
| Reorder Sports | Drag-and-drop ordering | P2 |

**Data Model:**
```typescript
interface Sport {
  id: number;
  sportName: string;      // slug format: "american-football"
  icon: string | null;    // URL to uploaded icon
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}
```

**UI Components:**
- Sports list table with search/filter
- Sport form (create/edit modal)
- Icon upload with preview
- Bulk actions (activate/deactivate)

---

#### 3.1.2 Leagues Management

**Features:**
| Feature | Description | Priority |
|---------|-------------|----------|
| List Leagues | Display leagues filtered by sport | P0 |
| Add League | Create league under a sport | P0 |
| Edit League | Update league name, logo, status | P0 |
| Delete League | Soft delete with cascade warning | P1 |
| Upload League Logo | Upload/replace league logo | P0 |
| Move League | Reassign league to different sport | P2 |

**Data Model:**
```typescript
interface League {
  id: number;
  sportId: number;
  sportName: string;      // denormalized
  leagueName: string;     // slug format: "premier-league"
  leagueLogo: string | null;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}
```

**UI Components:**
- League list with sport filter dropdown
- Hierarchical view (Sport > Leagues)
- League form with sport selector
- Logo upload with preview

---

#### 3.1.3 Participants (Teams/Players/Drivers) Management

**Features:**
| Feature | Description | Priority |
|---------|-------------|----------|
| List Participants | Display by league with type filter | P0 |
| Add Participant | Create team/player/driver | P0 |
| Edit Participant | Update all fields | P0 |
| Delete Participant | Soft delete | P1 |
| Upload Logo | Team/player photo upload | P0 |
| Multi-League Assignment | Assign participant to multiple leagues | P1 |
| Bulk Import | CSV/Excel import for teams | P2 |

**Data Model:**
```typescript
interface Participant {
  id: number;
  participantType: 'TEAM' | 'DRIVER' | 'PLAYER';
  sportId: number;
  sportName: string;
  leagueIds: number[];      // supports multiple leagues
  leagueNames: string[];
  teamName: string | null;  // for TEAM type
  fullName: string | null;  // "Los Angeles Lakers"
  shortName: string | null; // "Lakers"
  abbreviation: string | null; // "LAL" (max 10 chars)
  teamLogo: string | null;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}
```

**UI Components:**
- Participant list with type tabs (Teams/Players/Drivers)
- Multi-select league picker
- Form with conditional fields based on type
- Logo upload with cropping

---

#### 3.1.4 Widget Types Management

**Features:**
| Feature | Description | Priority |
|---------|-------------|----------|
| List Widget Types | Display by league | P0 |
| Add Widget Type | Create new widget type | P0 |
| Edit Widget Type | Update name, status | P0 |
| Delete Widget Type | With template dependency check | P1 |
| Clone Widget Type | Copy to another league | P2 |

**Data Model:**
```typescript
interface WidgetType {
  id: number;
  sportId: number;
  sportName: string;
  leagueId: number | null;  // null = sport-wide
  leagueName: string | null;
  widgetName: string;       // "live-scores", "standings"
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}
```

**UI Components:**
- Widget type list grouped by sport/league
- Form with sport/league cascading selectors
- Template count indicator per widget type

---

#### 3.1.5 Templates Management

**Features:**
| Feature | Description | Priority |
|---------|-------------|----------|
| List Templates | Display with multi-filter | P0 |
| Add Template | Create with URLs and metadata | P0 |
| Edit Template | Update all fields | P0 |
| Delete Template | Soft delete | P1 |
| Upload Thumbnails | Dark/light theme thumbnails | P0 |
| Preview Template | Inline iframe preview | P1 |
| Toggle Featured | Mark/unmark as featured | P0 |
| Bulk URL Update | Update multiple template URLs | P2 |
| Export Embed Codes | Copy/download embed codes | P1 |

**Data Model:**
```typescript
interface Template {
  id: number;
  sportId: number;
  sportName: string;
  leagueId: number | null;
  leagueName: string | null;
  participantId: number | null;
  teamName: string | null;
  widgetTypeId: number;
  widgetName: string;
  templateName: string;
  darkThemeUrl: string | null;
  lightThemeUrl: string | null;
  thumbnailDark: string | null;
  thumbnailLight: string | null;
  featured: boolean;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}
```

**UI Components:**
- Template gallery view with thumbnails
- Template list view with sortable columns
- Cascading filters (Sport > League > Widget Type > Participant)
- Dual thumbnail upload (dark/light)
- URL input with validation
- Embed code generator with copy button
- Featured badge toggle

---

### 3.2 Module 2: Sports Data Management

#### 3.2.1 Team Data Editor

**Features:**
| Feature | Description | Priority |
|---------|-------------|----------|
| Select Context | Choose sport/league to edit | P0 |
| Edit Team Info | Update fullName, shortName, abbreviation | P0 |
| Upload Team Logo | Replace team logo | P0 |
| Bulk Edit | Edit multiple teams at once | P2 |

**UI Flow:**
1. Select Sport → Select League
2. Display teams in selected league
3. Inline edit or modal edit for each team
4. Save changes to Sports Data DB

---

#### 3.2.2 Schedule/Event Management

**Features:**
| Feature | Description | Priority |
|---------|-------------|----------|
| View Schedule | Calendar or list view of events | P0 |
| Add Event | Create new matchup/event | P0 |
| Edit Event | Update date, time, venue | P0 |
| Delete Event | Remove scheduled event | P1 |
| Bulk Schedule Import | CSV import for season schedules | P2 |

**Data Model (Sports Data DB):**
```typescript
interface Event {
  id: string;
  sportId: number;
  leagueId: number;
  eventType: 'MATCHUP' | 'RACE' | 'TOURNAMENT';
  homeTeamId: number | null;
  awayTeamId: number | null;
  participants: number[];  // for non-team sports
  scheduledDate: Date;
  venue: string | null;
  status: 'SCHEDULED' | 'LIVE' | 'COMPLETED' | 'POSTPONED' | 'CANCELLED';
  createdAt: Date;
  updatedAt: Date;
}
```

**UI Components:**
- Calendar view with event dots
- List view with filters
- Event form with team/participant pickers
- Venue autocomplete

---

#### 3.2.3 Score Management

**Features:**
| Feature | Description | Priority |
|---------|-------------|----------|
| View Scores | List of events with scores | P0 |
| Edit Score | Update score for matchup | P0 |
| Period Scores | Enter scores by period/quarter/set | P1 |
| Player Stats | Individual player statistics | P2 |
| Live Score Entry | Real-time score updates | P1 |

**Data Model (Sports Data DB):**
```typescript
interface Score {
  eventId: string;
  homeScore: number | null;
  awayScore: number | null;
  periodScores: {
    period: number;
    homeScore: number;
    awayScore: number;
  }[];
  playerStats: {
    playerId: number;
    stats: Record<string, number>;
  }[];
  isFinal: boolean;
  updatedAt: Date;
}
```

**UI Components:**
- Score entry form with validation
- Period breakdown accordion
- Player stats table
- Live indicator for active games

---

### 3.3 Module 3: File Upload System

#### 3.3.1 Upload Features

| Feature | Description | Priority |
|---------|-------------|----------|
| Image Upload | Support PNG, JPG, SVG | P0 |
| Image Validation | Size limits, dimension checks | P0 |
| Image Preview | Show before upload | P0 |
| Image Cropping | Client-side crop tool | P1 |
| Bulk Upload | Multiple files at once | P2 |
| CDN Integration | Upload to S3/CloudFlare | P0 |

#### 3.3.2 Upload Specifications

| Asset Type | Recommended Size | Max Size | Formats |
|------------|------------------|----------|---------|
| Sport Icon | 64x64 px | 256KB | PNG, SVG |
| League Logo | 200x200 px | 512KB | PNG, SVG |
| Team Logo | 512x512 px | 512KB | PNG, JPG, SVG |
| Template Thumbnail | 960x540 px | 1MB | PNG, JPG, SVG |
| Template Preview | 1920x1080 px | 2MB | PNG, JPG, SVG |

#### 3.3.3 Storage Provider

**Confirmed: AWS S3**
- Store all uploaded assets in S3 bucket
- Use CloudFront CDN for fast delivery
- Organize by type: `s3://bucket/sports/`, `s3://bucket/leagues/`, etc.
- Generate unique filenames to prevent conflicts

---

### 3.4 Module 4: Data Synchronization

#### 3.4.1 Sync Button with Confirmation

**Features:**
| Feature | Description | Priority |
|---------|-------------|----------|
| Sync Button | Global header button showing pending change count | P0 |
| Change Tracking | Track all CRUD operations across modules before sync | P0 |
| Confirmation Modal | Display categorized change summary before sync | P0 |
| Change Summary | Group changes by entity type with counts | P0 |
| Sync to API/DB | Push all pending changes to MongoDB/API on confirm | P0 |
| Clear on Success | Clear pending changes after successful sync | P0 |

**Change Tracking System:**
```typescript
type EntityType = 'sports' | 'leagues' | 'participants' | 'widgetTypes' | 'templates' | 'events' | 'scores';
type ChangeType = 'create' | 'update' | 'delete';

interface PendingChange {
  entityType: EntityType;
  changeType: ChangeType;
  entityId: string | number;
  entityName: string;
  timestamp: Date;
}
```

**UI Components:**
- Header sync button with badge showing pending change count
- Confirmation modal with categorized bullet points
- Change summary grouped by entity type (e.g., "Sports", "Leagues", "Templates")
- Icons for each change type:
  - `+` Created items
  - `✏` Updated items
  - `🗑` Deleted items
- Confirm and Cancel buttons

**Confirmation Modal Display:**
```
┌─────────────────────────────────────────────────────────────────┐
│ Confirm Sync                                              [X]   │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  You are about to sync the following changes:                   │
│                                                                 │
│  Sports (2 changes)                                             │
│    + Created "football"                                         │
│    ✏ Updated "basketball"                                       │
│                                                                 │
│  Leagues (3 changes)                                            │
│    + Created "MLS"                                              │
│    ✏ Updated "NFL"                                              │
│    🗑 Deleted "XFL"                                              │
│                                                                 │
│  Templates (1 change)                                           │
│    ✏ Updated "nba-standings-eastern"                            │
│                                                                 │
│  Events (2 changes)                                             │
│    + Created "Lakers vs Celtics"                                │
│    + Created "Patriots vs Chiefs"                               │
│                                                                 │
├─────────────────────────────────────────────────────────────────┤
│                              [Cancel]  [Confirm & Sync]         │
└─────────────────────────────────────────────────────────────────┘
```

**Behavior:**
1. All CRUD operations across pages are tracked in global state (SyncContext)
2. Sync button in header displays badge with total pending change count
3. Clicking sync button opens confirmation modal
4. Modal displays all pending changes grouped by category with numeric counts
5. Each change shows the action type icon and entity name
6. On confirm, changes are pushed to MongoDB/API system
7. On success, pending changes are cleared and user is notified
8. On failure, changes are preserved and error is displayed

---

## 4. Non-Functional Requirements

### 4.1 Performance
- Page load time: < 2 seconds
- API response time: < 500ms
- File upload: < 5 seconds for images under 1MB
- Support 100+ concurrent admin users

### 4.2 Security
- Authentication: JWT-based with refresh tokens
- Authorization: Role-based access control (RBAC)
- API Security: Rate limiting, input validation
- File Upload: Virus scanning, type validation
- Audit Logging: Track all data modifications

### 4.3 Scalability
- Horizontal scaling for API servers
- CDN for static assets
- Database indexing for query performance
- Caching layer for frequently accessed data

### 4.4 Reliability
- 99.9% uptime target
- Automated backups for both databases
- Graceful error handling
- Data validation before persistence

---

## 5. Technical Specifications

### 5.1 Frontend Stack

```
Framework: React 18+ with TypeScript
Styling: SCSS
State Management: TanStack Query (React Query) for server state
Forms: React Hook Form + Zod validation
Routing: React Router v6
File Upload: react-dropzone
Image Editing: react-image-crop
Tables: TanStack Table
Calendar: react-big-calendar or FullCalendar
Icons: Lucide React
Build Tool: Vite
```

### 5.2 Backend Stack

```
Runtime: Node.js 20+ with TypeScript
Framework: Express.js 5.x
Database ORM: Mongoose 9.x
Validation: Zod 4.x
Authentication: jsonwebtoken + bcrypt
File Upload: Multer + AWS SDK v3
Storage: AWS S3 or Cloudflare R2
API Documentation: OpenAPI 3.0 + Swagger UI
Testing: Jest + Supertest
```

### 5.3 API Endpoints

#### Widget Configuration APIs

```
# Sports
GET    /api/admin/sports
POST   /api/admin/sports
GET    /api/admin/sports/:sportId
PUT    /api/admin/sports/:sportId
DELETE /api/admin/sports/:sportId
POST   /api/admin/sports/:sportId/icon              # Upload icon

# Leagues (nested under Sports)
GET    /api/admin/sports/:sportId/leagues
POST   /api/admin/sports/:sportId/leagues
GET    /api/admin/sports/:sportId/leagues/:leagueId
PUT    /api/admin/sports/:sportId/leagues/:leagueId
DELETE /api/admin/sports/:sportId/leagues/:leagueId
POST   /api/admin/sports/:sportId/leagues/:leagueId/logo    # Upload logo

# Participants (nested under Leagues)
GET    /api/admin/leagues/:leagueId/participants
POST   /api/admin/leagues/:leagueId/participants
GET    /api/admin/leagues/:leagueId/participants/:participantId
PUT    /api/admin/leagues/:leagueId/participants/:participantId
DELETE /api/admin/leagues/:leagueId/participants/:participantId
POST   /api/admin/leagues/:leagueId/participants/:participantId/logo

# Widget Types (nested under Leagues)
GET    /api/admin/leagues/:leagueId/widget-types
POST   /api/admin/leagues/:leagueId/widget-types
GET    /api/admin/leagues/:leagueId/widget-types/:widgetTypeId
PUT    /api/admin/leagues/:leagueId/widget-types/:widgetTypeId
DELETE /api/admin/leagues/:leagueId/widget-types/:widgetTypeId

# Templates
GET    /api/admin/templates
POST   /api/admin/templates
GET    /api/admin/templates/:templateId
PUT    /api/admin/templates/:templateId
DELETE /api/admin/templates/:templateId
POST   /api/admin/templates/:templateId/thumbnail-dark
POST   /api/admin/templates/:templateId/thumbnail-light
POST   /api/admin/templates/:templateId/preview
```

#### Sports Data APIs

> **Note:** These endpoints will be updated after the Sports Data Database discovery phase is complete.

```
# Teams (Sports Data DB)
GET    /api/admin/sports-data/teams
PUT    /api/admin/sports-data/teams/:id
POST   /api/admin/sports-data/teams/:id/logo

# Events/Schedule
GET    /api/admin/sports-data/events
POST   /api/admin/sports-data/events
PUT    /api/admin/sports-data/events/:id
DELETE /api/admin/sports-data/events/:id

# Scores
GET    /api/admin/sports-data/scores
PUT    /api/admin/sports-data/scores/:eventId
```

---

## 6. User Interface Design

### 6.1 Navigation Structure

```
┌─────────────────────────────────────────────────────────────────────┐
│  SportPulse Admin                              [User] [Logout]      │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌─────────────┐  ┌─────────────────────────────────────────────┐  │
│  │ SIDEBAR     │  │ MAIN CONTENT                                │  │
│  │             │  │                                             │  │
│  │ Dashboard   │  │  [Breadcrumb: Sports > Basketball]          │  │
│  │             │  │                                             │  │
│  │ ─ CONFIG ─  │  │  ┌─────────────────────────────────────┐   │  │
│  │ Sports      │  │  │ Sport Details                       │   │  │
│  │ Leagues     │  │  │                                     │   │  │
│  │ Teams       │  │  │ Name: Basketball                    │   │  │
│  │ Widget Types│  │  │ Icon: [🏀] [Change]                 │   │  │
│  │ Templates   │  │  │ Status: ● Active                    │   │  │
│  │             │  │  │                                     │   │  │
│  │ ─ DATA ─    │  │  │ [Save] [Cancel]                     │   │  │
│  │ Schedule    │  │  └─────────────────────────────────────┘   │  │
│  │ Scores      │  │                                             │  │
│  │ Teams       │  │  ┌─────────────────────────────────────┐   │  │
│  │             │  │  │ Leagues (4)                         │   │  │
│  │ ─ SYSTEM ─  │  │  │ ┌─────┬─────────────┬────────────┐  │   │  │
│  │ API Keys    │  │  │ │ NBA │ NCAAB-DI    │ + Add      │  │   │  │
│  │ Settings    │  │  │ └─────┴─────────────┴────────────┘  │   │  │
│  │             │  │  └─────────────────────────────────────┘   │  │
│  └─────────────┘  └─────────────────────────────────────────────┘  │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

### 6.2 Key Screen Wireframes

#### Templates Gallery View
```
┌─────────────────────────────────────────────────────────────────┐
│ Templates                                    [+ Add Template]    │
├─────────────────────────────────────────────────────────────────┤
│ Filters:                                                        │
│ [Sport ▼] [League ▼] [Widget Type ▼] [Featured ▼] [Search... ] │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │ ┌──────────┐ │  │ ┌──────────┐ │  │ ┌──────────┐ │          │
│  │ │          │ │  │ │          │ │  │ │          │ │          │
│  │ │ Thumb    │ │  │ │ Thumb    │ │  │ │ Thumb    │ │          │
│  │ │          │ │  │ │          │ │  │ │          │ │          │
│  │ └──────────┘ │  │ └──────────┘ │  │ └──────────┘ │          │
│  │ NBA Standings│  │ NFL Schedule │  │ MLB Box Score│          │
│  │ ★ Featured   │  │              │  │              │          │
│  │ [Edit] [Copy]│  │ [Edit] [Copy]│  │ [Edit] [Copy]│          │
│  └──────────────┘  └──────────────┘  └──────────────┘          │
│                                                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │    ...       │  │    ...       │  │    ...       │          │
│  └──────────────┘  └──────────────┘  └──────────────┘          │
│                                                                 │
│                    [1] [2] [3] ... [10]                         │
└─────────────────────────────────────────────────────────────────┘
```

#### Score Entry Screen
```
┌─────────────────────────────────────────────────────────────────┐
│ Score Entry                                                     │
├─────────────────────────────────────────────────────────────────┤
│ Context: [NBA ▼] [2024-25 Season ▼]                            │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  Dec 30, 2024 - Lakers vs Celtics                              │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                                                         │   │
│  │   LAL  [  98  ]  vs  [  105  ]  BOS                    │   │
│  │                                                         │   │
│  │   ┌─────────────────────────────────────────────┐      │   │
│  │   │ Period │  Q1  │  Q2  │  Q3  │  Q4  │  OT   │      │   │
│  │   │  LAL   │  24  │  28  │  22  │  24  │   -   │      │   │
│  │   │  BOS   │  26  │  30  │  25  │  24  │   -   │      │   │
│  │   └─────────────────────────────────────────────┘      │   │
│  │                                                         │   │
│  │   Status: [● Final ▼]                                  │   │
│  │                                                         │   │
│  │   [Save] [Cancel]                                       │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

---

## 7. User Roles & Permissions

### 7.1 Role Definitions

| Role | Description | Permissions |
|------|-------------|-------------|
| Super Admin | Full system access | All operations + user management |
| Content Admin | Widget configuration | Full CRUD on all config entities |
| Data Editor | Sports data only | Edit scores, schedules, team info |
| Viewer | Read-only access | View all data, no modifications |

### 7.2 Permission Matrix

| Feature | Super Admin | Content Admin | Data Editor | Viewer |
|---------|-------------|---------------|-------------|--------|
| Manage Sports | ✅ | ✅ | ❌ | 👁 |
| Manage Leagues | ✅ | ✅ | ❌ | 👁 |
| Manage Teams | ✅ | ✅ | ✅ | 👁 |
| Manage Widget Types | ✅ | ✅ | ❌ | 👁 |
| Manage Templates | ✅ | ✅ | ❌ | 👁 |
| Edit Schedules | ✅ | ✅ | ✅ | 👁 |
| Edit Scores | ✅ | ✅ | ✅ | 👁 |
| Upload Files | ✅ | ✅ | ✅ | ❌ |
| Manage API Keys | ✅ | ❌ | ❌ | ❌ |
| Manage Users | ✅ | ❌ | ❌ | ❌ |

---

## 8. Implementation Phases

### Phase 1: Foundation
- [ ] Project setup (frontend + backend)
- [ ] Authentication system (JWT)
- [ ] Database connections (both DBs)
- [ ] Base UI components (shadcn/ui setup)
- [ ] File upload infrastructure (S3)

### Phase 2: Widget Config CRUD
- [ ] Sports management (full CRUD + icon upload)
- [ ] Leagues management (full CRUD + logo upload)
- [ ] Participants management (full CRUD + logo upload)
- [ ] Widget Types management (full CRUD)

### Phase 3: Templates Module
- [ ] Templates list/gallery view
- [ ] Template CRUD operations
- [ ] Thumbnail uploads (dark/light)
- [ ] Embed code generator
- [ ] Template preview

### Phase 4: Sports Data Module
- [ ] Team data editor
- [ ] Schedule/event management
- [ ] Score entry system
- [ ] Calendar view

### Phase 5: Polish & Deploy
- [ ] Role-based access control
- [ ] Audit logging
- [ ] Performance optimization
- [ ] Testing & QA
- [ ] Production deployment

---

## 9. Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| Data sync conflicts | High | Implement optimistic locking |
| File upload failures | Medium | Retry logic + user feedback |
| Database connection issues | High | Connection pooling + health checks |
| Unauthorized access | Critical | JWT + RBAC + audit logs |
| Data loss | Critical | Automated backups + soft deletes |

---

## 10. Dependencies

### External Services
- **AWS S3** (confirmed) - File storage for icons, logos, thumbnails
- MongoDB Atlas or self-hosted MongoDB

### Internal Dependencies
- sportpulse-internal-apis (existing read-only API)
- Sports Data MongoDB (existing database)

### 10.1 Sports Data Database Discovery (Pre-Implementation Task)

**Important:** The Sports Data MongoDB is an existing database. Before implementation, the developer must:

1. **Document existing schema** - Connect to the Sports Data DB and document all collections:
   - Teams/Players/Drivers collection structure
   - Events/Schedule collection structure
   - Scores collection structure
   - Any other relevant collections

2. **Identify field mappings** - Map existing fields to admin UI requirements:
   - Team: fullName, shortName, abbreviation, logo fields
   - Event: date, time, venue, status fields
   - Score: home/away scores, period breakdowns

3. **Understand data relationships** - How teams link to events, how scores link to events, etc.

4. **Check for existing indexes** - Document and preserve existing indexes

**Note:** The PRD Section 3.2 (Sports Data Management) provides the *expected* data models. These should be validated and adjusted based on the actual existing database schema during the discovery phase.

---

## 11. Glossary

| Term | Definition |
|------|------------|
| Widget | Embeddable sports content (standings, scores, etc.) |
| Template | Configuration for a specific widget instance |
| Participant | Team, player, or driver in a sport |
| Widget Type | Category of widget (e.g., "live-scores", "standings") |
| Embed Code | HTML iframe snippet for embedding widgets |

---

## 12. Appendix

### A. Environment Variables

```bash
# Backend
NODE_ENV=development
PORT=3002
JWT_SECRET=your-secret-key
JWT_EXPIRES_IN=7d

# Widget Config Database
WIDGET_CONFIG_MONGODB_URI=mongodb://localhost:27017/sportpulse

# Sports Data Database
SPORTS_DATA_MONGODB_URI=mongodb://localhost:27017/sports-data

# File Storage (AWS S3 - confirmed)
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-east-1
AWS_S3_BUCKET=sportpulse-assets
AWS_CLOUDFRONT_DOMAIN=your-cloudfront-domain.cloudfront.net  # optional CDN
```

### B. References

- Existing API: `sportpulse-internal-apis` project
- OpenAPI Spec: `http://localhost:3001/openapi.yaml`
- API Docs: `http://localhost:3001/docs`
