<?php
/**
 * Compact Heat Bracket Template
 * For judge overlay and simplified views
 */

// Helper function for flag emoji
function getFlagEmojiCompact($countryCode) {
    if (!$countryCode || strlen($countryCode) < 2) return '🏳️';
    
    $country = strtoupper($countryCode);
    if (strlen($country) === 3) {
        $countryMap = [
            'BEL' => 'BE', 'NED' => 'NL', 'POL' => 'PL', 'LAT' => 'LV',
            'LTU' => 'LT', 'USA' => 'US', 'GBR' => 'GB', 'GER' => 'DE',
            'FRA' => 'FR', 'ESP' => 'ES', 'ITA' => 'IT', 'SUI' => 'CH',
            'AUT' => 'AT', 'CZE' => 'CZ', 'SVK' => 'SK', 'SLO' => 'SI',
            'CRO' => 'HR', 'SWE' => 'SE', 'NOR' => 'NO', 'FIN' => 'FI',
            'DEN' => 'DK', 'CAN' => 'CA', 'JPN' => 'JP', 'CHN' => 'CN',
            'KOR' => 'KR', 'AUS' => 'AU', 'NZL' => 'NZ', 'RSA' => 'ZA'
        ];
        $country = $countryMap[$country] ?? substr($country, 0, 2);
    }
    
    $country = substr($country, 0, 2);
    if (strlen($country) === 2) {
        return mb_chr(127462 + ord($country[0]) - 65) . mb_chr(127462 + ord($country[1]) - 65);
    }
    return '🏳️';
}

$levelCount = count($bracket_levels);
?>

<div class="bracket-flow-container" id="bracketFlowContainer">
    <!-- SVG for connections -->
    <svg class="bracket-connections" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 0;">
        <defs>
            <marker id="arrowhead" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                <polygon points="0 0, 10 3, 0 6" fill="#adb5bd" />
            </marker>
        </defs>
    </svg>
    
    <?php foreach ($bracket_levels as $level_idx => $level_heats): ?>
        <div class="bracket-column" data-level="<?= $level_idx ?>">
            <div class="bracket-column-header">
                <?= $level_idx === 0 ? 'QUALIFYING' : ($level_idx === $levelCount - 1 ? 'FINAL' : 'ROUND ' . ($level_idx + 1)) ?>
            </div>
            
            <?php foreach ($level_heats as $heat): ?>
                <?php
                $heat_num = $heat['heat_number'];
                $participants = $heat_participants[$heat_num] ?? [];
                $participant_count = count($participants);
                $isActive = $heat['is_active'];
                $isCompleted = false; // Can add completion logic if needed
                
                $cardClass = 'bracket-heat-card-mini';
                if ($isCompleted) $cardClass .= ' completed';
                if ($isActive) $cardClass .= ' active';
                
                $statusIcon = '';
                if ($isCompleted) {
                    $statusIcon = '<i class="fas fa-check-circle text-success bracket-heat-status-icon"></i>';
                } elseif ($isActive) {
                    $statusIcon = '<i class="fas fa-play-circle text-primary bracket-heat-status-icon"></i>';
                }
                
                // Build tooltip content
                $tooltipContent = '<strong>' . htmlspecialchars($heat['heat_name'] ?: 'Heat ' . $heat_num) . '</strong><br>';
                $tooltipContent .= 'Participants: ' . $participant_count . '<br>';
                $tooltipContent .= 'Runs: ' . $heat['runs_count'] . '<br>';
                
                if ($isActive) {
                    $tooltipContent .= '<span class="text-primary">● LIVE - Run ' . $heat['active_run'] . '/' . $heat['runs_count'] . '</span><br>';
                } elseif ($isCompleted) {
                    $tooltipContent .= '<span class="text-success">✓ Completed</span><br>';
                } else {
                    $tooltipContent .= '<span class="text-muted">Pending</span><br>';
                }
                
                if ($participant_count > 0) {
                    $tooltipContent .= '<hr style="margin:5px 0"><small>';
                    $count = 0;
                    foreach ($participants as $pid) {
                        if (isset($participants_by_id[$pid])) {
                            $p = $participants_by_id[$pid];
                            $flag = $p['country'] ? getFlagEmojiCompact($p['country']) : '';
                            $tooltipContent .= $flag . ' ' . htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) . '<br>';
                            $count++;
                            if ($count >= 5 && $participant_count > 5) {
                                $tooltipContent .= '+ ' . ($participant_count - 5) . ' more...<br>';
                                break;
                            }
                        }
                    }
                    $tooltipContent .= '</small>';
                }
                
                $tooltipContent .= '<hr style="margin:5px 0"><small class="text-muted">Click for full details</small>';
                ?>
                
                <div class="bracket-heat-compact" 
                     data-heat-id="<?= $heat_num ?>" 
                     onclick="showHeatDetail(<?= $heat_num ?>)"
                     data-bs-toggle="tooltip"
                     data-bs-placement="top"
                     data-bs-html="true"
                     title="<?= htmlspecialchars($tooltipContent) ?>">
                    <div class="<?= $cardClass ?>">
                        <div class="bracket-heat-header-mini">
                            <div class="bracket-heat-number-mini"><?= $heat_num ?></div>
                            <?= $statusIcon ?>
                        </div>
                        <div class="bracket-heat-name-mini" title="<?= htmlspecialchars($heat['heat_name'] ?: 'Heat ' . $heat_num) ?>">
                            <?= htmlspecialchars($heat['heat_name'] ?: 'Heat ' . $heat_num) ?>
                        </div>
                        <div class="bracket-heat-info-mini">
                            <span><i class="fas fa-users"></i> <?= $participant_count ?></span>
                            <span><i class="fas fa-redo"></i> <?= $heat['runs_count'] ?></span>
                        </div>
                        
                        <?php if ($isActive): ?>
                            <div class="bracket-heat-live-badge">
                                <span class="badge bg-success" style="font-size: 0.65rem;">
                                    <i class="fas fa-circle fa-fade"></i> LIVE
                                </span>
                                <span class="badge bg-info" style="font-size: 0.65rem;">
                                    Run <?= $heat['active_run'] ?>/<?= $heat['runs_count'] ?>
                                </span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endforeach; ?>
</div>

<script>
// Store heat data for detail popover
window.heatBracketData = {
    heats: {},
    participants: <?= json_encode($participants_by_id) ?>,
    connections: <?= json_encode($connections) ?>
};

// Build heats object with participant_ids array
<?php foreach ($heat_settings as $heat_num => $heat): ?>
window.heatBracketData.heats[<?= $heat_num ?>] = {
    heat_number: <?= $heat_num ?>,
    heat_name: <?= json_encode($heat['heat_name']) ?>,
    participant_ids: <?= json_encode($heat_participants[$heat_num] ?? []) ?>,
    runs_count: <?= $heat['runs_count'] ?>,
    is_active: <?= $heat['is_active'] ? 'true' : 'false' ?>,
    active_run: <?= $heat['active_run'] ?? 'null' ?>
};
<?php endforeach; ?>
</script>
