# StyleScore 2025 - AI Copilot Instructions

## System Architecture Overview

StyleScore is a **live sports scoring and event management system** with a dual-architecture approach:

### Core Components
- **PHP Backend**: Event management, scoring APIs, publish system
- **JavaScript Frontend**: Real-time dashboards, judge panels, live updates  
- **MySQL Database**: Participants, scores, events, configurations
- **Static Generation**: HTML/JSON publishing for remote deployment

### Key Architectural Patterns

#### 1. API-First Design (`api/` directory)
```php
// All data operations flow through dedicated API endpoints
api/judge_score_api.php       // Scoring panel operations
api/public_dashboard_api.php  // Live dashboard data
api/summary_table_api.php     // Results formatting
```

#### 2. Static/Dynamic Dashboard Duality
- **Dynamic**: `public_event_dashboard.php` - Live server-side dashboard
- **Static**: Generated HTML + JSON APIs via `admin/publish_generators.php`
- Both use identical JavaScript but different data sources

#### 3. Real-time Update Architecture
```javascript
// Pattern: Staggered refresh cycles prevent UI thrashing  
main_refresh_interval    // 30s - Event overview data
report_refresh_offset    // 30% of main - Report cards
latest_updates_interval  // 3s - Live scoring updates
```

## Development Workflows

### Judge Scoring System
**Primary Entry**: `judge/score_panel.html` (modern API-driven)  
**Legacy**: `judge/score.php` (direct PHP, being phased out)

Key workflow:
1. Load judge context via API
2. Dynamic form generation based on event configuration
3. Figure selection system with diversity rule validation
4. Score submission with criteria breakdown

### Publishing System
**Core File**: `admin/publish_generators.php` (3400+ lines)
```bash
# Generate static dashboard for FTP deployment
php admin/publish_servers.php

# Test generation locally  
php admin/test_full_generation.php
```

### Database Schema Patterns
```sql
-- Core entities
events                  // Competition events
participants           // Athletes with photos/facts
event_participants     // Event registration link
scoring_results        // Judge scores with JSON data
result_configurations  // Report/dashboard configs
```

## Critical Code Patterns

### 1. Template Literal Handling in PHP
**Problem**: JavaScript template literals in PHP strings cause syntax issues
```php
// ❌ WRONG - Causes PHP deprecation warnings
html += `<div>${variable}</div>`;

// ✅ CORRECT - Use string concatenation  
html += '<div>' + variable + '</div>';
```

### 2. Participant Photo System
```php
// Standard pattern for participant displays
function createParticipantPhoto($participant) {
    if ($participant && $participant['photo']) {
        return '<img src="' . $participant['photo'] . '" class="participant-photo">';
    }
    $initials = strtoupper($participant['first_name'][0] . $participant['last_name'][0]);
    return '<div class="participant-photo-placeholder">' . $initials . '</div>';
}
```

### 3. API Response Format Standard
```json
{
  "success": true|false,
  "data": {...},
  "message": "Error description if applicable"
}
```

### 4. Dashboard FLIP Animation Pattern
```javascript
// First: Capture current positions
const prevRects = getRowRects(reportKey);
// Last: Update DOM
morphHtml(container, newHTML);  
// Invert & Play: Animate to new positions
playFlipAnimation(reportKey, prevRects);
```

## Database Integration Patterns

### Connection Setup
**File**: `includes/db.php`
```php
$pdo = new PDO("mysql:host=localhost;dbname=freestyle_db", $user, $pass);
// Always use prepared statements for security
```

### Score Storage Pattern
```php
// Scores stored as JSON for flexibility
"figures_json": {"Rotation": ["720", "900"]}
"criteria_scores": {"execution": 45.0, "difficulty": 40.5}
```

## Configuration Management

### Report Configurations (`result_configurations` table)
- `view_type`: 'start_list' | 'summary_table'
- `heat_number`: NULL for general, specific number for heat-specific
- `category`: Filter by participant category

### Heat Management
**Files**: `admin/heats_configure.php`, `admin/heat_management_api.php`
- Heat assignment via AJAX
- Participant distribution algorithms
- BIB number management

## Static Publishing System

### Generator Functions (`admin/publish_generators.php`)
```php
generateStaticHTMLDashboard($event_id, $temp_dir, $pdo)
generateStaticAPIFiles($event_id, $output_dir, $pdo)  
copyParticipantPhotos($event_id, $temp_dir, $pdo)
```

### FTP Deployment Pattern
1. Generate files locally in temp directory
2. Upload via FTP with connection pooling  
3. Atomic replacement of live files
4. Log all operations for debugging

## Security & Authentication

### Session Management
**File**: `includes/auth_simple.php`
- Role-based access (admin, judge, head_judge)
- Session validation on API endpoints
- CSRF protection on forms

### SQL Injection Prevention
```php
// Always use prepared statements
$stmt = $pdo->prepare("SELECT * FROM participants WHERE event_id = ?");
$stmt->execute([$event_id]);
```

## Common Debugging Approaches

### API Testing Pattern
**File**: `admin/test_api_direct.php`
```php
// Direct API endpoint testing without frontend
$response = file_get_contents("http://localhost/v2/api/judge_score_api.php?action=get_participants");
var_dump(json_decode($response, true));
```

### Dashboard Debug Mode
**Feature**: Built-in debug panel in dashboards
- Real-time API call monitoring
- Data flow visualization  
- Performance metrics

### Common Issues
1. **Template literal syntax** - Use string concatenation in PHP-generated JS
2. **Photo paths** - Verify `photos/` directory permissions
3. **API timeouts** - Check `includes/db.php` connection settings
4. **FTP errors** - Validate credentials in `admin/publish_servers.php`

## File Organization Logic

```
admin/          # Backend management, configuration
api/            # JSON endpoints for all data operations  
judge/          # Scoring interfaces (modern HTML + legacy PHP)
includes/       # Shared utilities, database, authentication
photos/         # Participant profile images
static_api/     # Generated JSON files for static publishing
assets/         # CSS, JS, images for frontend
```

## Testing Strategy

### API Testing
```bash
# Test API endpoints directly
curl "http://localhost/v2/api/public_dashboard_api.php?action=get_events_overview"

# Test static generation
php admin/test_full_generation.php
```

### Database Testing  
**Files**: `admin/test_database_structure.php`, `admin/debug_*.php`

When working on this codebase, prioritize understanding the API-first architecture and the static/dynamic publishing duality. The system supports both real-time operation and offline deployment, which drives many architectural decisions.
