<?php
/**
 * Full Heat Bracket Template
 * For admin view with detailed information
 */

// Helper function for flag emoji
function getFlagEmoji($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 bracket-flow-full" 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="#0d6efd" />
            </marker>
        </defs>
    </svg>
    
    <?php foreach ($bracket_levels as $level_idx => $level_heats): ?>
        <div class="bracket-column bracket-column-full" data-level="<?= $level_idx ?>">
            <div class="bracket-column-header">
                <h5 class="mb-0">
                    <?= $level_idx === 0 ? 'QUALIFYING HEATS' : ($level_idx === $levelCount - 1 ? 'FINAL' : 'ROUND ' . ($level_idx + 1)) ?>
                </h5>
            </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';
                if ($isCompleted) $cardClass .= ' completed';
                if ($isActive) $cardClass .= ' active';
                ?>
                
                <div class="bracket-heat-full" data-heat-id="<?= $heat_num ?>">
                    <div class="<?= $cardClass ?>">
                        <div class="bracket-heat-header p-1">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="badge small bg-primary">Heat <?= $heat_num ?></span>
                                    <strong class="ms-2 small"><?= htmlspecialchars($heat['heat_name'] ?: 'Heat ' . $heat_num) ?></strong>
                                </div>
                                <div>
                                    <?php if ($isCompleted): ?>
                                        <span class="badge bg-success small">
                                            <i class="fas fa-check-circle"></i> Completed
                                        </span>
                                    <?php elseif ($isActive): ?>
                                        <span class="badge bg-info small">
                                            <i class="fas fa-circle fa-fade"></i> LIVE
                                        </span>
                                        <span class="badge bg-secondary small">
                                            Run <?= $heat['active_run'] ?>/<?= $heat['runs_count'] ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary small">
                                            <i class="far fa-clock"></i> Pending
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bracket-heat-body p-1">
                            <div class="mb-2">
                                <small class="text-muted small">
                                    
                                </small>
                            </div>
                            
                            <?php if ($participant_count > 0): ?>
                                <div class="bracket-participants-list">
                                    <?php 
                                    $displayLimit = 8;
                                    $count = 0;
                                    
                                    // Get scoring method for this heat
                                    $scoring_method = $heat['runs_scoring_method'] ?? 'average';
                                    
                                    // Find the winner (highest best or average score based on scoring method)
                                    $winner_pid = null;
                                    $highest_score = -1;
                                    
                                    foreach ($participants as $pid) {
                                        if (isset($participants_by_id[$pid])) {
                                            $p = $participants_by_id[$pid];
                                            $compare_score = 0;
                                            
                                            // Handle different scoring methods
                                            if (($scoring_method === 'best' || $scoring_method === 'best_from_all') && isset($p['best_score'])) {
                                                $compare_score = $p['best_score'];
                                            } elseif (($scoring_method === 'average' || $scoring_method === 'avg') && isset($p['average_score'])) {
                                                $compare_score = $p['average_score'];
                                            }
                                            
                                            if ($compare_score > $highest_score) {
                                                $highest_score = $compare_score;
                                                $winner_pid = $pid;
                                            }
                                        }
                                    }
                                    
                                    foreach ($participants as $pid): 
                                        if (isset($participants_by_id[$pid])):
                                            $p = $participants_by_id[$pid];
                                            $flag = $p['country'] ? getFlagEmoji($p['country']) : '';
                                            $is_winner = ($pid === $winner_pid && $highest_score > 0);
                                            
                                            // Build score display
                                            $score_display = '';
                                            $heat_final_score = '';
                                            
                                            // Determine final score first
                                            if (($scoring_method === 'best' || $scoring_method === 'best_from_all') && isset($p['best_score']) && $p['best_score'] !== null) {
                                                $heat_final_score = number_format($p['best_score'], 2);
                                            } elseif (($scoring_method === 'average' || $scoring_method === 'avg') && isset($p['average_score']) && $p['average_score'] !== null) {
                                                $heat_final_score = number_format($p['average_score'], 2);
                                            }
                                            
                                            if (!empty($p['run_scores']) && is_array($p['run_scores'])) {
                                                $run_scores_parts = [];
                                                foreach ($p['run_scores'] as $run_num => $score) {
                                                    if ($score !== null && $score !== '') {
                                                        $run_scores_parts[] = "R{$run_num}: " . number_format($score, 2);
                                                    }
                                                }
                                                if (!empty($run_scores_parts)) {
                                                    $score_display = '<small class="text-muted">' . implode(' | ', $run_scores_parts);
                                                    
                                                    // Add best or average label to display
                                                    if (($scoring_method === 'best' || $scoring_method === 'best_from_all') && $heat_final_score !== '') {
                                                        $score_display .= ' | <strong class="text-success">Best: ' . $heat_final_score . '</strong>';
                                                    } elseif (($scoring_method === 'average' || $scoring_method === 'avg') && $heat_final_score !== '') {
                                                        $score_display .= ' | <strong class="text-primary">Avg: ' . $heat_final_score . '</strong>';
                                                    }
                                                    
                                                    $score_display .= '</small>';
                                                }
                                            }
                                            
                                            $item_class = 'bracket-participant-item';
                                            if ($is_winner) {
                                                $item_class .= ' heat-winner';
                                            }
                                            ?>
                                            <div class="<?= $item_class ?>">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <span class="badge bg-light text-dark"><?= htmlspecialchars($p['bib_number'] ?? '?') ?></span>
                                                        <span><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></span>
                                                        <span class="country-code"><?= $flag ?></span>
                                                        <?php if ($is_winner): ?>
                                                            <i class="fas fa-trophy text-warning ms-1" title="Heat Winner"></i>
                                                        <?php endif; ?>
                                                    </div>
                                                    <?php if ($heat_final_score !== ''): ?>
                                                        <div>
                                                            <span class="badge bg-success"><?= $heat_final_score ?></span>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                                <?php if ($score_display): ?>
                                                    <div class="mt-1">
                                                        <?= $score_display ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <?php
                                            $count++;
                                            if ($count >= $displayLimit && $participant_count > $displayLimit):
                                                ?>
                                                <div class="text-muted small">
                                                    <i class="fas fa-ellipsis-h"></i> + <?= $participant_count - $displayLimit ?> more
                                                </div>
                                                <?php break;
                                            endif;
                                        endif;
                                    endforeach;
                                    ?>
                                </div>
                            <?php else: ?>
                                <div class="text-muted small">
                                    <i class="fas fa-info-circle"></i> No participants assigned
                                </div>
                            <?php endif; ?>
                        </div>                        
                       
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endforeach; ?>
</div>

<style>
    
        .bg-primary {
    --bs-bg-opacity: 1;
 background: #B0F761;
background: linear-gradient(270deg,rgba(176, 247, 97, 1) 0%, rgba(76, 190, 201, 1) 55%, rgba(25, 162, 255, 1) 77%, rgba(52, 89, 230, 1) 100%);
}
        .bracket-view-wrapper {
            background: #ffffff;
            border-radius: 0.75rem;
            
            box-shadow: 0 0.5rem 1.5rem rgba(15, 53, 96, 0.1);
            overflow-x: auto;
        }

        .bracket-chart .team {
            font-size: 0.85rem;
            font-weight: 600;
            color: #0f3460;
        }

        .bracket-chart .score {
            font-size: 0.8rem;
            color: #344767;
        }

        .bracket-chart .match {
            border-radius: 0.5rem;
            border: 1px solid #dce4f2;
            background: #f8fbff;
            transition: box-shadow 0.2s ease, transform 0.2s ease;
        }

        .bracket-view-wrapper {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 45%, #dee2e6 100%);
            border-radius: 1.25rem;
            
            box-shadow: 0 2.5rem 4.5rem rgba(8, 20, 48, 0.12);
            position: relative;
            overflow: hidden;
        }

        .bracket-view-wrapper::before {
            content: '';
            position: absolute;
            top: -120px;
            right: -160px;
            width: 480px;
            height: 480px;
            background: radial-gradient(circle at center, rgba(76, 190, 201, 0.15), rgba(76, 190, 201, 0));
            transform: rotate(12deg);
            opacity: 0.55;
        }

        .bracket-view-wrapper::after {
            content: '';
            position: absolute;
            bottom: -180px;
            left: -140px;
            width: 420px;
            height: 420px;
            background: radial-gradient(circle at center, rgba(176, 247, 97, 0.12), rgba(176, 247, 97, 0));
            transform: rotate(-8deg);
            opacity: 0.45;
        }

        .bracket-view-body {
            position: relative;
            z-index: 1;
        }

        .bracket-view-header h4 {
            color: #0f3460;
            letter-spacing: 0.03em;
        }

        .bracket-view-header p {
            color: rgba(52, 71, 103, 0.72);
        }

        .bracket-flow-container {
            display: flex;
            gap: 3rem;
            position: relative;
            padding: 1.75rem 1.25rem;
            overflow-x: auto;
            border-radius: 1.1rem;
            background: rgba(255, 255, 255, 0.85);
            border: 1px solid rgba(52, 71, 103, 0.12);
            box-shadow: inset 0 0 0 1px rgba(52, 71, 103, 0.06);
            align-items: center;
        }

        .bracket-column {
            display: flex;
            flex-direction: column;
            gap: 1rem;
            min-width: 18rem;
        }

        .bracket-column-header {
            font-weight: 700;
            font-size: 0.75rem;
            letter-spacing: 0.28em;
            color: rgba(15, 52, 96, 0.66);
            text-align: center;
            text-transform: uppercase;
        }

        .bracket-heat-compact {
            position: relative;
            cursor: pointer;
        }

        .bracket-heat-card-mini {
            border-radius: 1rem;
            padding: 1.25rem;
            border: 1px solid rgba(255, 255, 255, 0.12);
            background: linear-gradient(170deg, rgba(61, 119, 255, 0.92) 0%, rgba(37, 87, 196, 0.92) 100%);
            box-shadow: 0 1.8rem 3.2rem rgba(9, 22, 46, 0.45);
            color: #f7fbff;
            transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
        }

        .bracket-heat-card-mini[data-round-index="1"] {
            background: linear-gradient(170deg, rgba(74, 191, 202, 0.9) 0%, rgba(17, 123, 148, 0.9) 100%);
        }

        .bracket-heat-card-mini[data-round-index="2"] {
            background: linear-gradient(170deg, rgba(147, 97, 255, 0.92) 0%, rgba(92, 63, 180, 0.92) 100%);
        }

        .bracket-heat-card-mini[data-round-index="3"] {
            background: linear-gradient(170deg, rgba(255, 132, 199, 0.9) 0%, rgba(205, 90, 178, 0.9) 100%);
        }

        .bracket-heat-card-mini:hover {
            transform: translateY(-6px);
            box-shadow: 0 2.8rem 4.8rem rgba(8, 24, 52, 0.52);
            border-color: rgba(255, 255, 255, 0.38);
        }

        .bracket-heat-card-mini.is-active {
            border-color: #39ffb6;
            box-shadow: 0 0 0 4px rgba(57, 255, 182, 0.35), 0 3.2rem 5rem rgba(10, 40, 82, 0.6);
        }

        .bracket-heat-card-mini.active {
            border-color: rgba(255, 255, 255, 0.52);
            box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.18), 0 2.8rem 4.4rem rgba(9, 30, 68, 0.56);
        }

        .heat-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 0.75rem;
            margin-bottom: 1rem;
        }

        .heat-title {
            display: flex;
            flex-direction: column;
            gap: 0.4rem;
        }

        .heat-chip {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 0.25rem 0.65rem;
            border-radius: 999px;
            font-size: 0.7rem;
            letter-spacing: 0.08em;
            text-transform: uppercase;
            background: rgba(255, 255, 255, 0.14);
            color: #f9fbff;
            font-weight: 600;
        }

        .heat-name {
            font-size: 1.05rem;
            font-weight: 700;
            color: #ffffff;
            display: flex;
            align-items: center;
            gap: 0.4rem;
        }

        .heat-name i {
            color: rgba(255, 255, 255, 0.82);
        }

        .heat-status-group {
            display: flex;
            flex-direction: column;
            gap: 0.35rem;
            align-items: flex-end;
        }

        .heat-status {
            display: inline-flex;
            align-items: center;
            gap: 0.35rem;
            padding: 0.32rem 0.65rem;
            border-radius: 999px;
            font-size: 0.7rem;
            font-weight: 600;
            letter-spacing: 0.02em;
            background: rgba(255, 255, 255, 0.18);
            color: #ffffff;
        }

        .heat-status-live {
            background: rgba(255, 76, 97, 0.28);
            color: #fff4f6;
        }

        .heat-status-run {
            background: rgba(176, 247, 97, 0.25);
            color: #f4ffec;
        }

        .bracket-heat-meta {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 0.65rem;
            font-size: 0.75rem;
            color: rgba(240, 247, 255, 0.82);
        }

        .bracket-heat-meta span {
            display: inline-flex;
            align-items: center;
            gap: 0.35rem;
            background: rgba(10, 26, 49, 0.28);
            padding: 0.32rem 0.55rem;
            border-radius: 999px;
        }

        .heat-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.35rem;
            padding: 0.32rem 0.7rem;
            border-radius: 999px;
            font-size: 0.7rem;
            font-weight: 600;
        }

        .heat-badge-auto {
            background: rgba(64, 218, 255, 0.22);
            color: #e8fbff;
        }

        .heat-badge-manual {
            background: rgba(255, 196, 119, 0.25);
            color: #fff4e7;
        }

        .bracket-heat-roster-mini {
            list-style: none;
            padding: 0;
            margin: 1.15rem 0 0;
            display: flex;
            flex-direction: column;
            gap: 0.65rem;
        }

        .bracket-heat-roster-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.55rem 0.85rem;
            border-radius: 0.75rem;
            background: rgba(10, 26, 49, 0.32);
            color: #f4f8ff;
            font-size: 0.82rem;
            gap: 0.65rem;
        }

        .bracket-heat-roster-item:first-child {
            background: rgba(12, 102, 255, 0.45);
        }

        .bracket-heat-roster-name {
            display: flex;
            align-items: center;
            gap: 0.45rem;
        }

        .bracket-heat-roster-bib {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 2.1rem;
            height: 2.1rem;
            border-radius: 0.6rem;
            background: rgba(255, 255, 255, 0.18);
            font-weight: 700;
            font-size: 0.75rem;
        }

        .bracket-heat-roster-score {
            font-variant-numeric: tabular-nums;
            font-weight: 700;
            color: #fbffde;
        }

        .bracket-heat-roster-more,
        .bracket-heat-roster-empty {
            font-size: 0.75rem;
            color: rgba(235, 243, 255, 0.75);
            padding-left: 0.35rem;
        }

        .bracket-connections {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 0;
        }

        .connection-path {
            fill: none;
            stroke: rgba(93, 208, 255, 0.45);
            stroke-width: 2.5;
        }

        .bracket-detail-card {
            border-radius: 1rem;
            background: rgba(10, 26, 49, 0.68);
            border: 1px solid rgba(255, 255, 255, 0.08);
            box-shadow: 0 1.8rem 3.2rem rgba(8, 22, 45, 0.45);
            color: #f0f6ff;
        }

        .bracket-detail-card .list-group-item {
            background: rgba(9, 20, 40, 0.55);
            border: 1px solid rgba(255, 255, 255, 0.08);
            border-radius: 0.85rem;
            margin-bottom: 0.5rem;
            padding: 0.75rem 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 0.65rem;
            color: #f6f9ff;
        }

        .bracket-detail-card .list-group-item:last-child {
            margin-bottom: 0;
        }

        .bracket-detail-card .badge {
            background: rgba(255, 255, 255, 0.16);
            color: #f8fbff;
            font-weight: 600;
            font-size: 0.75rem;
        }

        .bracket-empty-state {
            padding: 3rem 1rem;
        }
.bracket-flow-full {
    padding: 20px;
    gap: 80px;
}

.bracket-column-full {
    min-width: 350px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.bracket-heat-card {
    background: white;
    border: 2px solid #dee2e6;
    border-radius: 8px;
   
    transition: all 0.3s ease;
}

.bracket-heat-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    transform: translateY(-2px);
}

.bracket-heat-card.active {
    border-color: #0dcaf0;
    box-shadow: 0 0 0 3px rgba(13, 202, 240, 0.1);
}

.bracket-heat-card.completed {
    border-color: #198754;
    opacity: 0.9;
}

.bracket-heat-header {
    padding: 12px 15px;
    background: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
    border-radius: 6px 6px 0 0;
}

.bracket-heat-body {
    padding: 15px;
}

.bracket-heat-footer {
    padding: 10px 15px;
    background: #f8f9fa;
    border-top: 1px solid #dee2e6;
    border-radius: 0 0 6px 6px;
    display: flex;
    gap: 8px;
}

.bracket-participants-list {
    max-height: 300px;
    overflow-y: auto;
}

.bracket-participant-item {
    padding: 6px 0;
    font-size: 0.9rem;
    border-bottom: 1px solid #f0f0f0;
}

.bracket-participant-item:last-child {
    border-bottom: none;
}

.bracket-participant-item.heat-winner {
    background: linear-gradient(90deg, rgba(255, 215, 0, 0.15) 0%, rgba(255, 215, 0, 0.05) 100%);
    border-left: 3px solid #ffd700;
    padding-left: 8px;
    margin-left: -8px;
    font-weight: 600;
}

.bracket-participant-item.heat-winner:hover {
    background: linear-gradient(90deg, rgba(255, 215, 0, 0.25) 0%, rgba(255, 215, 0, 0.08) 100%);
}
</style>

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

// Build heats object
<?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; ?>

function editHeat(heatNumber) {
    window.location.href = 'heats_configure.php?event_id=<?= $event_id ?>&heat_number=' + heatNumber;
}

function viewHeatDetails(heatNumber) {
    // Open heat details in modal or new page
    console.log('View details for heat', heatNumber);
}
</script>
