# Heat Bracket API Documentation

## Overview
Centralized API for generating heat flow bracket visualizations across different platforms (judge overlay, admin interface, etc.).

## Architecture

### API Endpoint
**File:** `api/heat_bracket_view_api.php`

**Purpose:** Server-side bracket generation with consistent logic

**Parameters:**
- `event_id` (required) - Event ID to load bracket for
- `compact` (optional) - Set to `1` for compact view, omit for full view

**Response Format:**
```json
{
  "success": true,
  "html": "<div class='bracket-flow-container'>...</div>",
  "connections": [
    {"from": 1, "to": 5},
    {"from": 2, "to": 5}
  ],
  "bracket_levels": [[1,2,3,4], [5,6], [7]]
}
```

### Templates

#### Compact Template (Judge View)
**File:** `api/heat_bracket_compact.php`

**Features:**
- Small heat cards (180px wide)
- Minimal information: heat number, name, participant count, runs
- Status indicators (active, completed)
- LIVE badge for active heats
- SVG connections with bracket-style arrows
- onclick handlers for detail popover
- Data exposed via `window.heatBracketData`

**Data Structure:**
```javascript
window.heatBracketData = {
  heats: {
    1: {
      heat_number: 1,
      heat_name: "Qualifying Round 1",
      participant_ids: [101, 102, 103],
      runs_count: 2,
      is_active: false,
      active_run: null
    }
  },
  participants: {
    101: {
      first_name: "John",
      last_name: "Doe",
      country: "USA",
      bib_number: "42"
    }
  },
  connections: [
    {from: 1, to: 5}
  ]
};
```

#### Full Template (Admin View)
**File:** `api/heat_bracket_full.php` *(to be created)*

**Features:**
- Large heat cards with full participant lists
- Flow configuration badges
- Time information
- Action buttons
- Category filters

## Integration

### Judge Score Panel
**File:** `judge/score.php`

**Implementation:**

1. **Load bracket via AJAX:**
```javascript
async function loadHeatFlowPreview() {
    const response = await fetch(`../api/heat_bracket_view_api.php?event_id=${eventId}&compact=1`);
    const data = await response.json();
    
    if (data.success) {
        container.innerHTML = '<h6>Event Heat Flow</h6>' + data.html;
        window.heatFlowConnections = data.connections;
        setTimeout(() => drawBracketConnections(data.connections), 100);
    }
}
```

2. **Draw SVG connections:**
```javascript
function drawBracketConnections(connections) {
    const svg = document.querySelector('#heatFlowPreview .bracket-connections');
    
    connections.forEach(conn => {
        const fromCard = document.querySelector(`[data-heat-id="${conn.from}"]`);
        const toCard = document.querySelector(`[data-heat-id="${conn.to}"]`);
        
        // Bracket-style path: horizontal → vertical junction → horizontal
        const midX = fromX + (toX - fromX) / 2;
        const pathData = `M ${fromX} ${fromY} L ${midX} ${fromY} L ${midX} ${toY} L ${toX} ${toY}`;
        
        const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        path.setAttribute('d', pathData);
        path.setAttribute('class', 'connection-path');
        path.setAttribute('marker-end', 'url(#arrowhead)');
        svg.appendChild(path);
    });
}
```

3. **Show heat details:**
```javascript
function showHeatDetail(heatNumber) {
    const heatData = window.heatBracketData.heats[heatNumber];
    
    // Build popover with heat info and participant list
    heatData.participant_ids.forEach(pid => {
        const p = window.heatBracketData.participants[pid];
        // Display participant info
    });
}
```

## Bracket Algorithm

### Level Building Logic

1. **Find Starting Heats:**
   - Heats with no `flow_source_heat` (empty or null)
   - These form Level 0 (QUALIFYING)

2. **Build Subsequent Levels:**
   ```php
   while (has more heats to process) {
       foreach (remaining heats) {
           // Check if source heats are in current level
           if (source_in_current_level) {
               add_to_next_level();
           }
       }
       increment_level();
   }
   ```

3. **Handle Multiple Sources:**
   - `flow_source_heat` can be JSON array: `["1", "2"]`
   - Heat advances if ALL sources are in current or earlier level

4. **Connection Generation:**
   ```php
   foreach (heat with sources) {
       foreach (source_heat) {
           connections[] = {from: source_heat, to: heat};
       }
   }
   ```

## Visual Design

### Bracket Style Connections
```
Heat 1 ─────┐
            ├──── Heat 5
Heat 2 ─────┘
```

**SVG Path Construction:**
- Horizontal line from source heat
- Vertical junction line connecting sources
- Horizontal line to destination heat
- Arrowhead marker at destination

### Column Headers
- Level 0: "QUALIFYING"
- Level 1-N: "ROUND X"
- Final Level: "FINAL"

### Heat Card States
- **Default:** Gray border, white background
- **Active:** Blue border, gradient background, LIVE badge
- **Completed:** Green border, reduced opacity, checkmark icon
- **Next Up:** Yellow star icon

## Testing

**Test File:** `test_heat_bracket_api.php`

**Features:**
- Select event ID
- Toggle compact/full mode
- View generated HTML
- See raw JSON response
- Visual bracket preview
- Connection drawing test

**Usage:**
1. Open `http://localhost/v2/test_heat_bracket_api.php`
2. Enter event ID (e.g., 1)
3. Select view mode
4. Click "Load Bracket"

## Benefits

1. **Single Source of Truth:** Bracket logic in one place
2. **Consistency:** Same rendering across platforms
3. **Maintainability:** Update once, applies everywhere
4. **Flexibility:** Easy to add new view modes via templates
5. **Performance:** Server-side generation reduces client processing
6. **Testability:** Dedicated test interface

## Future Enhancements

- [ ] Create `heat_bracket_full.php` template
- [ ] Add mobile-optimized template
- [ ] Add print-friendly template
- [ ] Cache bracket generation for performance
- [ ] Add WebSocket support for real-time updates
- [ ] Implement bracket zoom/pan controls
- [ ] Add participant photo thumbnails in cards
- [ ] Export bracket as image/PDF

## Related Files

- `judge/score.php` - Judge interface integration
- `admin/admin_heat_config.php` - Original bracket implementation (reference)
- `admin/heat_flow_api.php` - Legacy flow API (can be deprecated)
- `includes/db.php` - Database connection
- `api/heat_bracket_view_api.php` - Main API endpoint
- `api/heat_bracket_compact.php` - Compact template
- `test_heat_bracket_api.php` - Test interface
