<?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">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="badge bg-primary">Heat <?= $heat_num ?></span>
                                    <strong class="ms-2"><?= htmlspecialchars($heat['heat_name'] ?: 'Heat ' . $heat_num) ?></strong>
                                </div>
                                <div>
                                    <?php if ($isCompleted): ?>
                                        <span class="badge bg-success">
                                            <i class="fas fa-check-circle"></i> Completed
                                        </span>
                                    <?php elseif ($isActive): ?>
                                        <span class="badge bg-info">
                                            <i class="fas fa-circle fa-fade"></i> LIVE
                                        </span>
                                        <span class="badge bg-secondary">
                                            Run <?= $heat['active_run'] ?>/<?= $heat['runs_count'] ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">
                                            <i class="far fa-clock"></i> Pending
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bracket-heat-body">
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="fas fa-users"></i> <?= $participant_count ?> participant<?= $participant_count !== 1 ? 's' : '' ?>
                                    &nbsp;•&nbsp;
                                    <i class="fas fa-redo"></i> <?= $heat['runs_count'] ?> run<?= $heat['runs_count'] !== 1 ? 's' : '' ?>
                                </small>
                            </div>
                            
                            <?php if ($participant_count > 0): ?>
                                <div class="bracket-participants-list">
                                    <?php 
                                    $displayLimit = 8;
                                    $count = 0;
                                    foreach ($participants as $pid): 
                                        if (isset($participants_by_id[$pid])):
                                            $p = $participants_by_id[$pid];
                                            $flag = $p['country'] ? getFlagEmoji($p['country']) : '';
                                            ?>
                                            <div class="bracket-participant-item">
                                                <?= $flag ?>
                                                <span class="badge bg-light text-dark"><?= htmlspecialchars($p['bib_number'] ?? '?') ?></span>
                                                <span><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></span>
                                            </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 class="bracket-heat-footer">
                            <button class="btn btn-sm btn-outline-primary" onclick="editHeat(<?= $heat_num ?>)">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button class="btn btn-sm btn-outline-secondary" onclick="viewHeatDetails(<?= $heat_num ?>)">
                                <i class="fas fa-eye"></i> Details
                            </button>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endforeach; ?>
</div>

<style>
.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;
    margin-bottom: 20px;
    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;
}
</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>
